CQ_(9)_Phases Counter + Auto Fibonacci + Trend Pivots v2

CQuevedo345 · study · 1754 行 · 点赞 673 · TradingView 原页

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

Pine Script

//@fract
//@version=6
indicator("CQ_(9)_Phases Counter + Auto Fibonacci + Trend Pivots v2", overlay=true, max_labels_count=500, max_lines_count=500, max_boxes_count=500, explicit_plot_zorder=true, max_bars_back=4000)
 
////////////////////////////////////////////////////////////////////////////
////  SECTION 1 — ZIG ZAG TREND METRICS (ported, unused code removed)     ///
////  Source: CQ_(5)_Zig Zag Trend Metrics                                ///
////////////////////////////////////////////////////////////////////////////
 
// INPUT SETTINGS
period_basicgr = '⚙️ Phases Master Control'
period                            = input.int(45, "Period", minval=2, group = period_basicgr,
     tooltip = "Swing lookback length in bars for the main zigzag (Section 1). A bar becomes a swing high when it is the highest high of the last N bars, or a swing low when it is the lowest low. Higher values give fewer, larger swings that confirm later; lower values give more, smaller swings that react faster. This zigzag also feeds the Fibonacci section: its last settled leg (P2 → P1, the leg before the one still forming) is the one the Fibonacci levels and gauge are measured on.")
color lineUpColor                 = input(title="Color ↑", defval=#6ba583, inline="lines", group="♦︎ lines",
     tooltip = "Color of bullish zigzag legs (swing low to swing high). Pairs with the ↓ color and the Width input on the same row.")
color lineDnColor                 = input(title="↓", defval=#d75442, inline="lines", group="♦︎ lines",
     tooltip = "Color of bearish zigzag legs (swing high to swing low). Pairs with the ↑ color to its left and the Width input to its right.")
lw                                = input.int(2, "Width", [1, 2, 3, 4], inline="lines", group="♦︎ lines",
     tooltip = "Line width in pixels (1-4) of the bullish and bearish zigzag legs. Also used for the last confirmed leg when it is restyled by the ♦︎ Last Confirmed Leg options.")
bool rangeLines                   = input.bool(true, "Range Lines", inline = 'rangelines', group = "♦︎ lines",
     tooltip = "Draws thin connector lines between consecutive swing highs (high to high) and consecutive swing lows (low to low), with a faint fill between the latest pair, outlining the swing channel. Only affects lines created after the setting changes. The color is set by the swatch to its right.")
color rnglineColor                = input(title="", defval=#000000, inline="rangelines", group="♦︎ lines",
     tooltip = "Color of the high-to-high and low-to-low range lines. Only used while Range Lines is enabled.")
delta                             = input.string('Percent', '𝜟 Format', options = [ 'Percent', 'Absolute'], group = '♦︎ labels', inline = 'st',
     tooltip = "How the move size is shown on each swing label and in the statistics table. Percent: the swing's change relative to the previous opposite swing (for example +12.5%). Absolute: the raw price difference (for example +4,250). Pairs with Text Size to its right.")
txtsz                             = input.string("Small", title="Text Size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group = "♦︎ labels", inline = 'st',
     tooltip = "Size (Tiny to Huge) of the swing labels that show the HH/LH/HL/LL pattern, the move size and the bar count. Pairs with Δ Format to its left.")
bool cyclelab                     = input.bool(false, "Display Cycle", group = "♦︎ labels",
     tooltip = "Adds a second block to each swing label with the number of bars since the previous swing of the same type (the high-to-high or low-to-low cycle length), in addition to the default bar count since the opposite swing.")
showtable                         = input.bool(false, 'Show Stats table', group = '♦︎ statistics table',
     tooltip = "Shows a statistics table with the geometric average price move and duration (in bars) of recent uptrend legs and downtrend legs from this zigzag. The number of legs averaged is set by Averaging below, and the price column follows Δ Format.")
locationtable                     = input.string('Bottom Right', 'Location', ['Top Right','Top Left', 'Bottom Right', 'Bottom Left'], group = '♦︎ statistics table', inline = 'tbpr',
     tooltip = "Screen corner where the statistics table is placed. Pairs with the Size input to its right.")
sizetable                         = input.string('Normal', 'Size', ['Large', 'Normal', 'Small', 'Tiny'], group = '♦︎ statistics table', inline = 'tbpr',
     tooltip = "Text size of the statistics table. Pairs with the Location input to its left.")
avgln                             = input.int(10, "Averaging", minval=2, step=1, group = '♦︎ statistics table',
     tooltip = "Number of most recent uptrend legs and downtrend legs used for the statistics table averages (minimum 2). A geometric mean is used, so one unusually large leg skews the result less than a simple average would. Higher values give smoother, slower-changing averages.")
ts                                = txtsz == "Tiny"   ? size.tiny  :txtsz == "Small"  ? size.small :txtsz == "Normal" ? size.normal:txtsz == "Large"  ? size.large : size.huge
 
// Variables {
// LAST SWING TYPE
var string lastSwingType = ""
// SWING HIGHS
var float[] swingHighValues       = array.new_float(0)
var int[]   swingHighBarIndexes   = array.new_int(0)
var label[] swingHighLabels       = array.new_label(0)
// SWING LOWS
var float[] swingLowValues        = array.new_float(0)
var int[]   swingLowBarIndexes    = array.new_int(0)
var label[] swingLowLabels        = array.new_label(0)
// LINES
var line[]  highToHighLines       = array.new_line(0)
var line[]  lowToLowLines         = array.new_line(0)
var line[]  bullishLines          = array.new_line(0)
var line[]  bearishLines          = array.new_line(0)
// STS
var float[] highToHighPriceDiffs  = array.new_float(0)
var int[]   highToHighTimeDiffs   = array.new_int(0)
var float[] lowToLowPriceDiffs    = array.new_float(0)
var int[]   lowToLowTimeDiffs     = array.new_int(0)
 
var float[] bullishPriceDiffs     = array.new_float(0)
var float[] bullishPrcDiffs       = array.new_float(0)
var int[]   bullishTimeDiffs      = array.new_int(0)
var float[] bearishPriceDiffs     = array.new_float(0)
var float[] bearishPrcDiffs       = array.new_float(0)
var int[]   bearishTimeDiffs      = array.new_int(0)
//}
pH = 0 == ta.highestbars(high, period) ? high : na
pL = 0 == ta.lowestbars(low, period) ? low  : na
// Adds a new swing high point, calculates differences (same-type and cross-type), creates a label, and draws connecting lines{
f_addHighSwingPoint(highValue, barIndex) =>
    // Calculate opposite-type differences (with most recent low)
    oppPriceDiff  = (array.size(swingLowValues) > 0) ? highValue - array.get(swingLowValues, 0) : 0.0
    oppPctDiff = (array.size(swingLowValues) > 0) ? oppPriceDiff / array.get(swingLowValues, 0) * 100 : 0.0
    oppTimeDiff   = (array.size(swingLowBarIndexes) > 0) ? barIndex - array.get(swingLowBarIndexes, 0) : 0
    sameTimeDiff  = (array.size(swingHighBarIndexes) > 0) ? barIndex - array.get(swingHighBarIndexes, 0) : 0
    patternH = ""
    if array.size(swingHighValues) > 0
        patternH := (highValue > array.get(swingHighValues, 0)) ? "ʜʜ" : "ʟʜ"
    labelText = ""
    if array.size(swingLowValues) > 0
        textx = delta=="Percent"?(str.tostring(oppPctDiff, format.percent)):str.tostring(oppPriceDiff, "#.##")
        labelText := str.tostring(patternH) + "\n+" + textx  + "\n⏱" + str.tostring(oppTimeDiff)
    if array.size(swingHighValues) > 0 and cyclelab
        labelText := labelText +  "\nʜɪɢʜ ᴄʏᴄʟᴇ\n"  + "⏱" + str.tostring(sameTimeDiff)
    // Create label at swing high point
    newLabel = label.new(barIndex, highValue, labelText, textcolor = #6ba583,
                  style=label.style_label_down, color=color.new(#000000, 100), size=ts, text_formatting = text.format_bold)
    // Store swing high data
    array.unshift(swingHighValues, highValue)
    array.unshift(swingHighBarIndexes, barIndex)
    array.unshift(swingHighLabels, newLabel)
    // Draw lin connection betwn cons swing highs
    // if previous high exists
    if array.size(swingHighValues) > 1
        prevBar   = array.get(swingHighBarIndexes, 1)
        prevValue = array.get(swingHighValues, 1)
        newLine = rangeLines?line.new(prevBar, prevValue, barIndex, highValue, color=rnglineColor, width=1, style = line.style_solid):na
        array.unshift(highToHighLines, newLine)
        // Calculate and store differences for this high-to-high line
        priceDiff = highValue - prevValue
        timeDiff  = barIndex - prevBar
        array.unshift(highToHighPriceDiffs, priceDiff)
        array.unshift(highToHighTimeDiffs, timeDiff)
    // Draw bullish line if the last swing was 
    // (from a low to this high)
    if array.size(swingLowValues) > 0 and lastSwingType != "high"
        prevLowBar   = array.get(swingLowBarIndexes, 0)
        prevLowValue = array.get(swingLowValues, 0)
        newBullishLine = line.new(prevLowBar, prevLowValue, barIndex, highValue, color=lineUpColor, width=lw, style = line.style_solid)
        array.unshift(bullishLines, newBullishLine)
        bullishPdiff = highValue - prevLowValue
        bullishTdiff = barIndex - prevLowBar
        array.unshift(bullishPriceDiffs, bullishPdiff)
        array.unshift(bullishPrcDiffs, oppPctDiff)
        array.unshift(bullishTimeDiffs, bullishTdiff)
//}
// Updates the current swing high point 
// if a new candidate is more extreme, recalculates differences, 
// updates the label text, and updates connecting lines{
f_updateHighSwingPoint(highValue, barIndex) =>
    if highValue > array.get(swingHighValues, 0)
        array.set(swingHighValues, 0, highValue)
        array.set(swingHighBarIndexes, 0, barIndex)
        oppPriceDiff  = (array.size(swingLowValues) > 0) ? highValue - array.get(swingLowValues, 0) : 0.0
        oppPctDiff = (array.size(swingLowValues) > 0) ? oppPriceDiff / array.get(swingLowValues, 0) * 100 : 0.0
        oppTimeDiff   = (array.size(swingLowBarIndexes) > 0) ? barIndex - array.get(swingLowBarIndexes, 0) : 0
        sameTimeDiff  = (array.size(swingHighBarIndexes) > 1) ? barIndex - array.get(swingHighBarIndexes, 1) : 0
        labelText = ""
        patternH = ""
        if array.size(swingHighValues) > 1
            patternH := (highValue > array.get(swingHighValues, 1)) ? "ʜʜ" : "ʟʜ"
        if array.size(swingLowValues) > 0
            textx = delta=="Percent"?(str.tostring(oppPctDiff, format.percent)):str.tostring(oppPriceDiff, "#.##")
            labelText := str.tostring(patternH) + "\n+"+ textx + "\n⏱" + str.tostring(oppTimeDiff)
        if array.size(swingHighValues) > 1 and cyclelab
            labelText := labelText + "\nʜɪɢʜ ᴄʏᴄʟᴇ\n" + "⏱" + str.tostring(sameTimeDiff)
        // Update label for current swing high
        lbl = array.get(swingHighLabels, 0)
        label.set_xy(lbl, barIndex, highValue)
        label.set_text(lbl, labelText)
        // Update high-to-high connection if it exists 
        if array.size(swingHighValues) > 1 and array.size(highToHighLines) > 0
            prevBar = array.get(swingHighBarIndexes, 1)
            prevValue = array.get(swingHighValues, 1)
            line.set_xy1(array.get(highToHighLines, 0), array.get(swingHighBarIndexes, 1), array.get(swingHighValues, 1))
            line.set_xy2(array.get(highToHighLines, 0), barIndex, highValue)
            // Upd stored diffs for high-to-high connection
            array.set(highToHighPriceDiffs, 0, highValue - prevValue)
            array.set(highToHighTimeDiffs, 0, barIndex - prevBar)
        // Upd bullish connection
        if array.size(swingLowValues) > 0 and array.size(bullishLines) > 0
            prevLowBar = array.get(swingLowBarIndexes, 0)
            prevLowValue = array.get(swingLowValues, 0)
            line.set_xy1(array.get(bullishLines, 0), prevLowBar, prevLowValue)
            line.set_xy2(array.get(bullishLines, 0), barIndex, highValue)
            array.set(bullishPriceDiffs, 0, highValue - prevLowValue)
            array.set(bullishPrcDiffs, 0, (highValue - prevLowValue)/prevLowValue * 100)
            array.set(bullishTimeDiffs, 0, barIndex - prevLowBar)
    0.
//}
// Adds a new swing low point, calculates differences (same-type and cross-type),creates a label, and draws connecting lines{
f_addLowSwingPoint(lowValue, barIndex) =>
    // Calculate opposite-type differences (with most recent high)
    oppPriceDiff  = (array.size(swingHighValues) > 0) ? lowValue - array.get(swingHighValues, 0) : 0.0
    oppPctDiff = (array.size(swingHighValues) > 0) ? oppPriceDiff / array.get(swingHighValues, 0) * 100 : 0.0
    oppTimeDiff   = (array.size(swingHighBarIndexes) > 0) ? barIndex - array.get(swingHighBarIndexes, 0) : 0
    sameTimeDiff  = (array.size(swingLowBarIndexes) > 0) ? barIndex - array.get(swingLowBarIndexes, 0) : 0
    labelText = ""
    patternL = ""
    if array.size(swingLowValues) > 0
        patternL := (lowValue < array.get(swingLowValues, 0)) ? "ʟʟ" : "ʜʟ"
    if array.size(swingHighValues) > 0
        textx = delta=="Percent"?(str.tostring(oppPctDiff, format.percent)):str.tostring(oppPriceDiff, "#.##")
        labelText := str.tostring(patternL) + "\n" + textx + "\n⏱" + str.tostring(oppTimeDiff)
    if array.size(swingLowValues) > 0 and cyclelab
        labelText := labelText + "\nʟᴏᴡ ᴄʏᴄʟᴇ\n"  + "⏱" + str.tostring(sameTimeDiff)
    // Create label at swing low point
    newLabel = label.new(barIndex, lowValue, labelText, textcolor = #d75442,
                  style=label.style_label_up, color=color.new(#000000, 100), size=ts, text_formatting = text.format_bold)
    // Store swing low data
    array.unshift(swingLowValues, lowValue)
    array.unshift(swingLowBarIndexes, barIndex)
    array.unshift(swingLowLabels, newLabel)
    // connection line betwn consecutive swing lows
    if array.size(swingLowValues) > 1 
        prevBar   = array.get(swingLowBarIndexes, 1)
        prevValue = array.get(swingLowValues, 1)
        newLine = rangeLines?line.new(prevBar, prevValue, barIndex, lowValue, color=rnglineColor, width=1, style = line.style_solid):na
        array.unshift(lowToLowLines, newLine)
        // Calculate and store differences for this low-to-low line
        priceDiff = lowValue - prevValue
        timeDiff  = barIndex - prevBar
        array.unshift(lowToLowPriceDiffs, priceDiff)
        array.unshift(lowToLowTimeDiffs, timeDiff)
    // Draw bearish line if the last swing was of the opposite type (from a high to this low)
    if array.size(swingHighValues) > 0 and lastSwingType != "low"
        prevHighBar   = array.get(swingHighBarIndexes, 0)
        prevHighValue = array.get(swingHighValues, 0)
        newBearishLine = line.new(prevHighBar, prevHighValue, barIndex, lowValue, color=lineDnColor, width=lw, style = line.style_solid)
        array.unshift(bearishLines, newBearishLine)
        bearishPdiff = lowValue - prevHighValue
        bearishTdiff = barIndex - prevHighBar
        array.unshift(bearishPriceDiffs, bearishPdiff)
        array.unshift(bearishPrcDiffs, oppPctDiff)
        array.unshift(bearishTimeDiffs, bearishTdiff)
//}
// Updates the current swing low point if a new is more extreme, recalculates differences, updates the lab text, and connecting lines{
f_updateLowSwingPoint(lowValue, barIndex) =>
    if lowValue < array.get(swingLowValues, 0)
        array.set(swingLowValues, 0, lowValue)
        array.set(swingLowBarIndexes, 0, barIndex)
        oppPriceDiff  = (array.size(swingHighValues) > 0) ? lowValue - array.get(swingHighValues, 0) : 0.0
        oppPctDiff = (array.size(swingHighValues) > 0) ? oppPriceDiff / array.get(swingHighValues, 0) * 100 : 0.0
        oppTimeDiff   = (array.size(swingHighBarIndexes) > 0) ? barIndex - array.get(swingHighBarIndexes, 0) : 0
        sameTimeDiff  = (array.size(swingLowBarIndexes) > 1) ? barIndex - array.get(swingLowBarIndexes, 1) : 0
        labelText = ""
        patternL = ""
        if array.size(swingLowValues) > 1
            patternL := (lowValue < array.get(swingLowValues, 1)) ? "ʟʟ" : "ʜʟ"
        if array.size(swingHighValues) > 0
            textx = delta=="Percent"?(str.tostring(oppPctDiff, format.percent)):str.tostring(oppPriceDiff, "#.##")
            labelText := str.tostring(patternL)+ "\n"+ textx + "\n⏱" + str.tostring(oppTimeDiff)
        if array.size(swingLowValues) > 1 and cyclelab
            labelText := labelText + "\nʟᴏᴡ ᴄʏᴄʟᴇ\n"  + "⏱" + str.tostring(sameTimeDiff)
        // Update label for current swing low
        lbl = array.get(swingLowLabels, 0)
        label.set_xy(lbl, barIndex, lowValue)
        label.set_text(lbl, labelText)
        // Update low-to-low connection if it exists
        if array.size(swingLowValues) > 1 and array.size(lowToLowLines) > 0
            prevBar = array.get(swingLowBarIndexes, 1)
            prevValue = array.get(swingLowValues, 1)
            line.set_xy1(array.get(lowToLowLines, 0), prevBar, prevValue)
            line.set_xy2(array.get(lowToLowLines, 0), barIndex, lowValue)
            array.set(lowToLowPriceDiffs, 0, lowValue - prevValue)
            array.set(lowToLowTimeDiffs, 0, barIndex - prevBar)
        // Update bearish connection if exists
        if array.size(swingHighValues) > 0 and array.size(bearishLines) > 0
            prevHighBar = array.get(swingHighBarIndexes, 0)
            prevHighValue = array.get(swingHighValues, 0)
            line.set_xy1(array.get(bearishLines, 0), prevHighBar, prevHighValue)
            line.set_xy2(array.get(bearishLines, 0), barIndex, lowValue)
            array.set(bearishPriceDiffs, 0, lowValue - prevHighValue)
            array.set(bearishPrcDiffs, 0, (lowValue - prevHighValue)/prevHighValue * 100)
            array.set(bearishTimeDiffs, 0, barIndex - prevHighBar)
    0.
//}
if array.size(highToHighLines) > 0 and array.size(lowToLowLines) > 0
    linefill.new(array.get(highToHighLines, 0), array.get(lowToLowLines, 0), color.rgb(0, 0, 0, 95))
// Process pivs {
var int direction = 0
direction := (not na(pH) and na(pL)) ? 1 : (not na(pL) and na(pH)) ? -1 : direction
 
if direction==1
    if lastSwingType != "high"
        f_addHighSwingPoint(pH, bar_index)
        lastSwingType := "high"
    else
        f_updateHighSwingPoint(pH, bar_index)
 
if direction==-1
    if lastSwingType != "low"
        f_addLowSwingPoint(pL, bar_index)
        lastSwingType := "low"
    else
        f_updateLowSwingPoint(pL, bar_index)
//}
// Function for geometric averaging {
f_geometric_avg(_source, _condition, _length) =>
    var float geom_avg = na
    var float[] valuesArray = array.new_float()
    if _condition
        if _source > 0
            array.push(valuesArray, _source)
            while array.size(valuesArray) > _length
                array.shift(valuesArray)
        n = array.size(valuesArray)
        if n > 0
            logSum = 0.0
            for val in valuesArray
                logSum += math.log(val)
            geom_avg := math.exp(logSum / n)
        else
            geom_avg := na
    geom_avg
var float sourcebull = na
var float sourcebear = na
var int sourcebullt = na
var int sourcebeart = na
 
if array.size(bullishPriceDiffs)>0 and array.size(bullishPrcDiffs)>0
    sourcebull := delta=="Percent"?array.get(bullishPrcDiffs, 0) : array.get(bullishPriceDiffs, 0)
    sourcebullt:=array.get(bullishTimeDiffs, 0)
conditionbull = lastSwingType=="low" and lastSwingType[1]== "high" 
rma_valuebull = f_geometric_avg(sourcebull, conditionbull, avgln)
rma_valuebullt = f_geometric_avg(sourcebullt, conditionbull, avgln)
if array.size(bearishPriceDiffs)>0 and array.size(bearishPrcDiffs)>0
    sourcebear := delta=="Percent"?array.get(bearishPrcDiffs, 0) : array.get(bearishPriceDiffs, 0)
    sourcebeart:=array.get(bearishTimeDiffs, 0) 
conditionbear = lastSwingType=="high" and lastSwingType[1] == "low" 
rma_valuebear = f_geometric_avg(math.abs(sourcebear), conditionbear, avgln)
rma_timebear = f_geometric_avg(sourcebeart, conditionbear, avgln)
//}
//Table{
var table_loc = locationtable == 'Top Right' ? position.top_right : locationtable == 'Bottom Right' ? position.bottom_right : locationtable == 'Top Left' ? position.top_left  : position.bottom_left
var table_size = sizetable == 'Large' ? size.large : sizetable == 'Normal' ? size.normal : sizetable == 'Small' ? size.small : size.tiny
var table = showtable ? table.new(table_loc, 16, 16, #2a2e39, #1e1e1e, 2, #1f232f, 2) : na
table_cell(column, row, txt) =>
    table.cell(table, column, row, txt, 0, 0, #ffffff, text_size = table_size)
if barstate.islast and showtable
    table_cell(0, 0, "STATISTICS TABLE")
    table_cell(0, 1, "ɢᴇᴏᴍᴇᴛʀɪᴄ\nᴀᴠᴇʀᴀɢɪɴɢ")
    table_cell(1, 1, "𝞓 ᴘʀɪᴄᴇ")
    table_cell(2, 1, "𝞓 ᴛɪᴍᴇ")
    table_cell(0, 2, 'ᴜᴘᴛʀᴇɴᴅ')
    table_cell(0, 3, 'ᴅᴏᴡɴᴛʀᴇɴᴅ')
    table_cell(1, 2, "+"+str.tostring(rma_valuebull, delta=="Percent"?format.percent:format.mintick))
    table_cell(1, 3, "-"+str.tostring(rma_valuebear, delta=="Percent"?format.percent:format.mintick))
    table_cell(2, 2, str.tostring(rma_valuebullt, format.mintick))
    table_cell(2, 3, str.tostring(rma_timebear, format.mintick))
    table.cell_set_text_font_family(table, 0,0, font.family_monospace)
    table.cell_set_text_formatting(table, 1, 1, text.format_bold)
    table.cell_set_text_formatting(table, 2, 1, text.format_bold)
    table.cell_set_text_formatting(table, 0, 2, text.format_bold)
    table.cell_set_text_formatting(table, 0, 3, text.format_bold)
    table.cell_set_text_color(table, 0, 1, color.gray)
    table.cell_set_text_size(table, 0, 1, size.small)
    table.merge_cells(table, 0,0,2,0)
//}
 
////////////////////////////////////////////////////////////////////////////
////  SECTION 2 — FIBONACCI RETRACEMENT + GAUGE                           ///
////  Ported from CQ_(8)_Auto Fibonacci Retracement.                      ///
////  Fed by the zigzag's LAST SETTLED LEG P2 → P1 (Section 1) — the leg  ///
////  before the one still forming, so both pivots are frozen and the    ///
////  levels never shift while P0 keeps stretching. The current move     ///
////  (P1 → P0 → close) is the retracement being measured.               ///
////  The retracement math is direction-agnostic                         ///
////  (0% = newest pivot P1, 100% = older pivot P2), so:                 ///
////    • settled leg BEARISH (ends at a Low)  → retracement reads as a   ///
////      BULLISH bounce measured up from that low                       ///
////    • settled leg BULLISH (ends at a High) → retracement reads as a   ///
////      BEARISH pullback measured down from that high                  ///
////  "Invert Fibonacci Direction" swaps the anchors (0% = older pivot,  ///
////  100% = newest pivot), turning the ladder into a projection in the  ///
////  direction of the leg.                                              ///
////////////////////////////////////////////////////////////////////////////
 
var COLOR_TRANSP = color.rgb(255, 255, 255, 100)
var basicgr      = '⚙️ Master Control'
 
show_indicator = input.bool(true, '⚡ Enable Fibonacci Gauge', group = '🪙 F i b o n a c c i  R e t r a c e m e n t',
     tooltip = "Master switch for the Fibonacci levels, extensions, gauge and their labels. When off, nothing from this section is drawn; the zigzag and the last-leg highlight are unaffected.")
fb_invert      = input.bool(false, '⇅ Invert Fibonacci Direction', group = '🪙 F i b o n a c c i  R e t r a c e m e n t',
     tooltip = "Off (default): 0% sits on the NEWEST pivot (P1) of the last settled leg and 100% on the OLDER pivot (P2), so the levels read as a retracement of that leg, and the gauge measures the current move away from P1.\nOn: 0% sits on the OLDER pivot and 100% on the NEWEST pivot, so the levels (and the 125%-200% extensions) read as a projection in the direction of the leg. The gauge and label colors are swapped to match that tendency, and the gauge is measured from the leg start with its extreme label tracking the continuation side.")
 
// ─── CLOSE PRICE PLOT ──────────────────────────────────────────────────────────
plot_gr = 'Close Price Plot'
 
show_close_plot  = input.bool  (false,        'Show Line Graph', group = plot_gr,
     tooltip = "Plots the close price as an extra series on the chart, styled by the Color, Width and Style inputs below. Useful as a clean price trace over candles or on a line chart.")
close_plot_color = input.color (color.blue, 'Color'          , inline = 'pltclose', group = plot_gr,
     tooltip = "Color of the close price plot. Pairs with Width to its right.")
close_plot_width = input.int   (1,            'Width'          , minval = 1, maxval = 10, inline = 'pltclose', group = plot_gr,
     tooltip = "Line width (1-10) of the close price plot. Pairs with Color to its left.")
 
_close_plot_style_raw = input.string('Line', 'Style',
     options = ['Line', 'Stepline', 'Histogram', 'Cross', 'Area', 'Columns', 'Circles'],
     group   = plot_gr,
     tooltip = "Plot style of the close price series: Line, Stepline, Histogram, Cross, Area, Columns or Circles.")
 
close_plot_style = switch _close_plot_style_raw
    'Line'      => plot.style_line
    'Stepline'  => plot.style_stepline
    'Histogram' => plot.style_histogram
    'Cross'     => plot.style_cross
    'Area'      => plot.style_area
    'Columns'   => plot.style_columns
    'Circles'   => plot.style_circles
    => plot.style_line
 
plot(show_close_plot ? close : na, title = 'Close', color = close_plot_color, linewidth = close_plot_width, style = close_plot_style)
// ─────────────────────────────────────────────────────────────────────────────
 
fb250 = input(true, '25% ', inline = 'fbl', group = basicgr,
     tooltip = "Shows or hides the 25% level between the 0% and 100% lines of the last settled leg. A hidden level is also left out of the Dynamic Proximity Shading ranking, so the remaining levels are ranked without it.")
fb400 = input(true, '40% ', inline = 'fbl', group = basicgr,
     tooltip = "Shows or hides the 40% level between the 0% and 100% lines of the last settled leg. A hidden level is also left out of the Dynamic Proximity Shading ranking, so the remaining levels are ranked without it.")
fb500 = input(true, '50% ', inline = 'fbl', group = basicgr,
     tooltip = "Shows or hides the 50% level between the 0% and 100% lines of the last settled leg. A hidden level is also left out of the Dynamic Proximity Shading ranking, so the remaining levels are ranked without it.")
fb600 = input(true, '60% ', inline = 'fbl', group = basicgr,
     tooltip = "Shows or hides the 60% level between the 0% and 100% lines of the last settled leg. A hidden level is also left out of the Dynamic Proximity Shading ranking, so the remaining levels are ranked without it.")
fb750 = input(true, '75% ', inline = 'fbl', group = basicgr,
     tooltip = "Shows or hides the 75% level between the 0% and 100% lines of the last settled leg. A hidden level is also left out of the Dynamic Proximity Shading ranking, so the remaining levels are ranked without it.")
fb900 = input(true, '90%',  inline = 'fbl', group = basicgr,
     tooltip = "Shows or hides the 90% level between the 0% and 100% lines of the last settled leg. A hidden level is also left out of the Dynamic Proximity Shading ranking, so the remaining levels are ranked without it.")
 
// ─── EXTENSION LEVEL SELECTION ────────────────────────────────────────────────
// User picks which extension levels are allowed on the chart, and WHEN they are
// shown (see "Show Extensions" below).
fbx_m25  = input(true, '-25% ',  inline = 'fbxlo', group = basicgr,
     tooltip = "Allows the -25% extension level, which lies beyond the 0% line on the side away from 100%. With Invert Fibonacci Direction off (default), 0% is the newest pivot (P1), so it extends past it in the settled leg's own direction; with Invert on, 0% is the leg start, so this level sits behind the leg. When a checked level is actually drawn is controlled by Show Extensions below.")
fbx_m50  = input(true, '-50% ',  inline = 'fbxlo', group = basicgr,
     tooltip = "Allows the -50% extension level, which lies beyond the 0% line on the side away from 100%. With Invert Fibonacci Direction off (default), 0% is the newest pivot (P1), so it extends past it in the settled leg's own direction; with Invert on, 0% is the leg start, so this level sits behind the leg. When a checked level is actually drawn is controlled by Show Extensions below.")
fbx_m100 = input(true, '-100% ', inline = 'fbxlo', group = basicgr,
     tooltip = "Allows the -100% extension level, which lies beyond the 0% line on the side away from 100%. With Invert Fibonacci Direction off (default), 0% is the newest pivot (P1), so it extends past it in the settled leg's own direction; with Invert on, 0% is the leg start, so this level sits behind the leg. When a checked level is actually drawn is controlled by Show Extensions below.")
fbx_m150 = input(true, '-150% ', inline = 'fbxlo', group = basicgr,
     tooltip = "Allows the -150% extension level, which lies beyond the 0% line on the side away from 100%. With Invert Fibonacci Direction off (default), 0% is the newest pivot (P1), so it extends past it in the settled leg's own direction; with Invert on, 0% is the leg start, so this level sits behind the leg. When a checked level is actually drawn is controlled by Show Extensions below.")
fbx_m160 = input(true, '-160% ', inline = 'fbxlo', group = basicgr,
     tooltip = "Allows the -160% extension level, which lies beyond the 0% line on the side away from 100%. With Invert Fibonacci Direction off (default), 0% is the newest pivot (P1), so it extends past it in the settled leg's own direction; with Invert on, 0% is the leg start, so this level sits behind the leg. When a checked level is actually drawn is controlled by Show Extensions below.")
fbx_m200 = input(true, '-200%',  inline = 'fbxlo', group = basicgr,
     tooltip = "Allows the -200% extension level, which lies beyond the 0% line on the side away from 100%. With Invert Fibonacci Direction off (default), 0% is the newest pivot (P1), so it extends past it in the settled leg's own direction; with Invert on, 0% is the leg start, so this level sits behind the leg. When a checked level is actually drawn is controlled by Show Extensions below.")
fbx_125  = input(true, '125% ',  inline = 'fbxhi', group = basicgr,
     tooltip = "Allows the 125% extension level, which lies beyond the 100% line on the side away from 0%. With Invert Fibonacci Direction off (default), 100% is the leg start (P2), so this level marks a retracement that has gone past the whole settled leg; with Invert on, 100% is the newest pivot, so it projects the leg further in its own direction. When a checked level is actually drawn is controlled by Show Extensions below.")
fbx_150  = input(true, '150% ',  inline = 'fbxhi', group = basicgr,
     tooltip = "Allows the 150% extension level, which lies beyond the 100% line on the side away from 0%. With Invert Fibonacci Direction off (default), 100% is the leg start (P2), so this level marks a retracement that has gone past the whole settled leg; with Invert on, 100% is the newest pivot, so it projects the leg further in its own direction. When a checked level is actually drawn is controlled by Show Extensions below.")
fbx_160  = input(true, '160% ',  inline = 'fbxhi', group = basicgr,
     tooltip = "Allows the 160% extension level, which lies beyond the 100% line on the side away from 0%. With Invert Fibonacci Direction off (default), 100% is the leg start (P2), so this level marks a retracement that has gone past the whole settled leg; with Invert on, 100% is the newest pivot, so it projects the leg further in its own direction. When a checked level is actually drawn is controlled by Show Extensions below.")
fbx_200  = input(true, '200%',   inline = 'fbxhi', group = basicgr,
     tooltip = "Allows the 200% extension level, which lies beyond the 100% line on the side away from 0%. With Invert Fibonacci Direction off (default), 100% is the leg start (P2), so this level marks a retracement that has gone past the whole settled leg; with Invert on, 100% is the newest pivot, so it projects the leg further in its own direction. When a checked level is actually drawn is controlled by Show Extensions below.")
 
fbx_mode = input.string('When Reached', 'Show Extensions', options = ['When Reached', 'Always', 'Never'], group = basicgr,
     tooltip = "Controls when the checked extension levels above are drawn.\n• When Reached: a level appears only once price has pushed past the level just inside it (cascading, no gaps).\n• Always: every checked level is drawn at all times, whether or not price has reached it.\n• Never: all extension levels are hidden; only the 0%-100% retracement levels are drawn.")
 
// ─── DYNAMIC LEVEL SHADING ─────────────────────────────────────────────────────
shade_gr = '── Dynamic Level Shading ──'
dyn_shade_enable = input.bool(true, 'Enable Dynamic Proximity Shading', group = shade_gr,
     tooltip = "Fades each Fibonacci level's line and label based on how close that level's price sits to the current close — including the extension levels beyond 0%-100% (-200% through 200%). The 0% and 100% pivot lines/labels always stay fully opaque.")
pct_near = input.int(100, 'Nearest Levels Opacity %', minval = 0, maxval = 100, group = shade_gr,
     tooltip = 'Opacity used for the level immediately above the current price and the level immediately below it.')
pct_mid  = input.int(70, 'Next Levels Opacity %', minval = 0, maxval = 100, group = shade_gr,
     tooltip = 'Opacity used for the second-nearest level above the current price and the second-nearest level below it.')
pct_far  = input.int(40, 'Remaining Levels Opacity %', minval = 0, maxval = 100, group = shade_gr,
     tooltip = 'Opacity used for every other level, beyond the two nearest on each side of the current price.')
 
// ─── COLOR SETTINGS ───────────────────────────────────────────────────────────
view_gr = 'Color Settings'
 
col_bull = input.color(color.rgb(255, 138,  61), 'BEARISH (▲ Now Bullish Tendency / Last Leg: BEARISH)',  inline = 'theme', group = view_gr,
     tooltip = "Theme color for the Fibonacci lines, gauge and (if Use Trend Colors for Labels is on) labels. With Invert Fibonacci Direction off (default) it is used when the last settled leg is BULLISH; with Invert on the two theme colors swap and it is used when the last settled leg is BEARISH. Pairs with the other theme color to its right.")
col_bear = input.color(color.rgb( 38, 166, 154), 'BULLISH (▼ Now Bearish Tendency / Last Leg: BULLISH)', inline = 'theme', group = view_gr,
     tooltip = "Theme color for the Fibonacci lines, gauge and (if Use Trend Colors for Labels is on) labels. With Invert Fibonacci Direction off (default) it is used when the last settled leg is BEARISH; with Invert on the two theme colors swap and it is used when the last settled leg is BULLISH. Pairs with the other theme color to its left.")
 
lbl_use_theme_color = input.bool(true, 'Use Trend Colors for Labels', inline = 'lblcol0', group = view_gr,
     tooltip = "When on, the Fibonacci level labels, the gauge extreme label and the level percentages use the same theme color as the lines. Turn off to color the labels independently with the Label ▲ and Label ▼ swatches to the right.")
lbl_col_bull         = input.color(color.rgb(255, 138,  61), 'Label ▲', inline = 'lblcol0', group = view_gr,
     tooltip = "Label color used when Use Trend Colors for Labels is off, in the same situations as the BEARISH (▲) theme color: last settled leg BULLISH with Invert off, or BEARISH with Invert on.")
lbl_col_bear         = input.color(color.rgb( 38, 166, 154), 'Label ▼', inline = 'lblcol0', group = view_gr,
     tooltip = "Label color used when Use Trend Colors for Labels is off, in the same situations as the BULLISH (▼) theme color: last settled leg BEARISH with Invert off, or BULLISH with Invert on.")
 
_lbl_side_raw = input.string('Right', 'Label Side (vs Gauge)', options = ['Left', 'Right'], inline = 'lblside0', group = view_gr,
     tooltip = "Places the Fibonacci level labels to the Left or Right of the gauge tick marks. Left right-aligns the text so it ends at the gauge; Right left-aligns it so it starts at the gauge.")
lbl_style     = _lbl_side_raw == 'Left' ? label.style_label_right : label.style_label_left
lbl_align     = _lbl_side_raw == 'Left' ? text.align_right        : text.align_left
 
fb_guide_draw           = input.bool (true, 'Gauge ⁞▌',                              inline = 'gauge', group = view_gr,
     tooltip = "Draws the gauge at the right edge: an outer grey box spanning the highest and lowest price reached since the settled leg's newest pivot (P1), extended to include the gauge anchor, an inner colored bar from the anchor to the current close, a label with the extreme price and its % change, and a profit label showing close minus the 0% price. With Invert off (default), the anchor is P1 and the extreme label tracks the retracement side; with Invert on, the anchor is the leg start (P2) and it tracks the continuation side.")
fb_guide_highlight_bull = input.color(color.rgb( 38, 166, 154, 40), 'Bullish Highlight ▲', inline = 'gauge', group = view_gr,
     tooltip = "Color of the close marker on the gauge's inner bar when the BULLISH (▼) theme color is active: last settled leg BEARISH with Invert off, or BULLISH with Invert on.")
fb_guide_highlight_bear = input.color(color.rgb(255, 138,  61, 40), 'Bearish Highlight ▼', inline = 'gauge', group = view_gr,
     tooltip = "Color of the close marker on the gauge's inner bar when the BEARISH (▲) theme color is active: last settled leg BULLISH with Invert off, or BEARISH with Invert on.")
 
// ─── LAYOUT ───────────────────────────────────────────────────────────────────
fb_gauge_position = input.int (defval = 60, title = 'Gauge X-Offset',            inline = 'pos', group = view_gr,
     tooltip = "Horizontal offset in bars of the gauge, its tick marks and the level labels, measured from the current bar. Negative values move everything left; positive values move it right into the empty space past the last bar. Ignored while Gauge at Leg End is on.")
fb_line_lenght    = input.int (defval =  1, minval = 1, maxval = 9,
                                title = 'Level Tick Length (Right)',              inline = 'pos', group = view_gr,
     tooltip = "Length in bars (1-9) of the short tick mark drawn to the right of the gauge at each Fibonacci level.")
fb_pivot_width    = input.int (defval =  3, minval = 1, maxval = 10,
                                title = '0% / 100% Line Width',                   group = view_gr,
     tooltip = "Line width in pixels (1-10) of the 0% and 100% Fibonacci lines (the two pivot lines of the last settled leg). All other levels stay at width 1.")
draw_simplelabel  = input.bool(true, 'Show Price on Labels',                      inline = 'lbl', group = view_gr,
     tooltip = "Adds the level's price under its percentage on each Fibonacci label. Turn off to show only the percentages.")
 
_lbl_size_raw = input.string('Small', 'Label Size',
     options = ['Tiny', 'Small', 'Normal', 'Large', 'Huge'],
     inline  = 'lbl', group = view_gr,
     tooltip = "Size (Tiny to Huge) of the Fibonacci level labels, the gauge extreme label and the profit label.")
 
fb_lbl_size = switch _lbl_size_raw
    'Tiny'   => size.tiny
    'Small'  => size.small
    'Normal' => size.normal
    'Large'  => size.large
    'Huge'   => size.huge
    => size.small
 
show_evt_labels = input.bool(true, 'Show Entry / Target Labels (Left of Gauge)', group = view_gr,
     tooltip = "Adds tiny tags on the left side of the gauge. Entries: 40% = Early Entry 1, 50% = Early Entry 2, 60% = Entry Event 1, 100% = Entry Event 2. Targets: 125% = Target 1, 160% = Target 2, 200% = Target 3. They use the same color and proximity shading as their level's label, and only appear while that level is shown (target tags follow Show Extensions). Hover a tag for its zone (up to the next tag; beyond 200% for Target 3), distance from close, whether price has reached it, and how many bars (and roughly how long) price has closed inside its zone since the leg end (P1).")
 
gauge_at_line_end = input.bool(false, 'Gauge at Leg End  (vs Current Bar)', group = view_gr,
     tooltip = "Positions the gauge and level labels exactly at the end bar of the last settled leg (its newest pivot, P1), where the retracement begins, instead of at the current bar. The older-pivot line stops just before the gauge, while the P1 line and the inner levels run from the gauge to the current bar. While on, Gauge X-Offset is ignored.")
// ─────────────────────────────────────────────────────────────────────────────
 
// ─── LAST CONFIRMED LEG STYLE ──────────────────────────────────────────────────
lastleg_gr        = '♦︎ Last Confirmed Leg'
dash_last_leg     = input.bool(true, "Dash Last Leg", inline = 'lastleg1', group = lastleg_gr,
     tooltip = "Restyles the zigzag's last settled leg (P2 → P1, the leg the Fibonacci levels are measured on) as a dashed line so it stands out. When a new leg takes over, the previous one goes back to solid.")
mark_last_leg     = input.bool(true, "Mark Start/End (Hollow Circles)", inline = 'lastleg1', group = lastleg_gr,
     tooltip = "Draws hollow circle markers at the start and end pivots (P2 and P1) of the last settled leg. Their size is set by Circle Size below.")
 
_lastleg_size_raw = input.string('Normal', 'Circle Size',
     options = ['Tiny', 'Small', 'Normal', 'Large', 'Huge'],
     group   = lastleg_gr,
     tooltip = "Size (Tiny to Huge) of the hollow circle markers at both ends of the last settled leg. Only has an effect while Mark Start/End is enabled.")
 
lastleg_mark_size = switch _lastleg_size_raw
    'Tiny'   => size.tiny
    'Small'  => size.small
    'Normal' => size.normal
    'Large'  => size.large
    'Huge'   => size.huge
    => size.normal
// ─────────────────────────────────────────────────────────────────────────────
 
// ─── LEG BRIDGE: pull the zigzag's last SETTLED leg (P2 → P1) into the Fib engine ─
// The newest zigzag leg (P1 → P0) can still stretch while price keeps making new
// extremes, so it is skipped. The leg before it has both pivots frozen:
//   lastSwingType == "high" → newest leg is bullish (L0 → H0, still forming);
//                             settled leg = bearishLines[0]  (H1 → L0)
//   lastSwingType == "low"  → newest leg is bearish (H0 → L0, still forming);
//                             settled leg = bullishLines[0]  (L1 → H0)
var line  fb_lineLast   = na
var float fb_pLast      = 0.0
var int   fb_iLast      = 0
var bool  fb_isHighLast = false
 
fb_new_line = false
 
if lastSwingType == "high" and array.size(bearishLines) > 0
    // settled leg is BEARISH (high → low): retracement reads BULLISH (bounce up from P1 low)
    fb_new_line   := fb_lineLast != array.get(bearishLines, 0)
    fb_lineLast   := array.get(bearishLines, 0)
    fb_pLast      := array.get(swingLowValues, 0)
    fb_iLast      := array.get(swingLowBarIndexes, 0)
    fb_isHighLast := false
 
if lastSwingType == "low" and array.size(bullishLines) > 0
    // settled leg is BULLISH (low → high): retracement reads BEARISH (pullback down from P1 high)
    fb_new_line   := fb_lineLast != array.get(bullishLines, 0)
    fb_lineLast   := array.get(bullishLines, 0)
    fb_pLast      := array.get(swingHighValues, 0)
    fb_iLast      := array.get(swingHighBarIndexes, 0)
    fb_isHighLast := true
 
// ─── FIB DIRECTION: 0% / 100% anchor prices ───────────────────────────────────
// Normal:   0% = newest pivot (fb_pLast), 100% = older pivot (leg start)
// Inverted: 0% = older pivot (leg start), 100% = newest pivot (fb_pLast)
fb_p0   = fb_invert ? line.get_y1(fb_lineLast) : fb_pLast
fb_p100 = fb_invert ? fb_pLast : line.get_y1(fb_lineLast)
 
// ─── LAST CONFIRMED LEG HIGHLIGHT (dashed style + hollow circle markers) ──────
// Restyles the zigzag's own settled leg line in place (it's the same object as
// bearishLines[0]/bullishLines[0]) so it visually stands out from older legs.
// When a new leg takes over, the previous one is reverted back to its normal
// solid zigzag style before the new one gets dashed.
var line  hl_activeLine  = na   // the line currently wearing the highlight
var label hl_circleStart = na
var label hl_circleEnd   = na
var bool  hl_visible     = false
 
if (dash_last_leg or mark_last_leg) and not na(fb_lineLast)
    // a new leg just took over: put the previous leg back to its normal solid style
    if fb_new_line and not na(hl_activeLine) and hl_activeLine != fb_lineLast
        _prevLegColor = fb_isHighLast ? lineDnColor : lineUpColor  // superseded leg was the opposite type
        line.set_style(hl_activeLine, line.style_solid)
        line.set_width(hl_activeLine, lw)
        line.set_color(hl_activeLine, _prevLegColor)
 
    _hlColor = fb_isHighLast ? lineUpColor : lineDnColor
 
    if dash_last_leg
        line.set_style(fb_lineLast, line.style_dashed)
        line.set_width(fb_lineLast, lw)
        line.set_color(fb_lineLast, _hlColor)
 
    if mark_last_leg
        if na(hl_circleStart)
            hl_circleStart := label.new(line.get_x1(fb_lineLast), line.get_y1(fb_lineLast), '◯',
                 style = label.style_label_center, color = color.new(#000000, 100),
                 textcolor = _hlColor, size = lastleg_mark_size)
            hl_circleEnd   := label.new(line.get_x2(fb_lineLast), line.get_y2(fb_lineLast), '◯',
                 style = label.style_label_center, color = color.new(#000000, 100),
                 textcolor = _hlColor, size = lastleg_mark_size)
 
        label.set_xy       (hl_circleStart, line.get_x1(fb_lineLast), line.get_y1(fb_lineLast))
        label.set_textcolor(hl_circleStart, _hlColor)
        label.set_size      (hl_circleStart, lastleg_mark_size)
 
        label.set_xy       (hl_circleEnd, line.get_x2(fb_lineLast), line.get_y2(fb_lineLast))
        label.set_textcolor(hl_circleEnd, _hlColor)
        label.set_size      (hl_circleEnd, lastleg_mark_size)
    else if hl_visible
        // markers turned off: remove them
        label.delete(hl_circleStart)
        label.delete(hl_circleEnd)
        hl_circleStart := na
        hl_circleEnd   := na
 
    hl_activeLine := fb_lineLast
    hl_visible    := true
 
if not (dash_last_leg or mark_last_leg) and hl_visible
    // feature turned off entirely: revert the line and remove the circles
    if not na(hl_activeLine)
        _revertColor = fb_isHighLast ? lineUpColor : lineDnColor
        line.set_style(hl_activeLine, line.style_solid)
        line.set_width(hl_activeLine, lw)
        line.set_color(hl_activeLine, _revertColor)
    if not na(hl_circleStart)
        label.delete(hl_circleStart)
        label.delete(hl_circleEnd)
        hl_circleStart := na
        hl_circleEnd   := na
    hl_visible := false
 
 
// bars → approximate duration string on the chart timeframe (used by the entry-label tooltips)
f_dur(_bars) =>
    _s = _bars * timeframe.in_seconds()
    _d = math.floor(_s / 86400)
    _h = math.floor((_s % 86400) / 3600)
    _m = math.floor((_s % 3600) / 60)
    _d > 0 ? str.tostring(_d) + 'd ' + str.tostring(_h) + 'h' : _h > 0 ? str.tostring(_h) + 'h ' + str.tostring(_m) + 'm' : str.tostring(_m) + 'm'
 
// zone upper bound (as leg fraction) for each tagged level; na = unbounded
// Early Entry 1 40→50 · Early Entry 2 50→60 · Entry Event 1 60→100 · Entry Event 2 100→125
// Target 1 125→160 · Target 2 160→200 · Target 3 beyond 200
f_tagZoneHi(_lvl) =>
    _lvl == 0.40 ? 0.50 : _lvl == 0.50 ? 0.60 : _lvl == 0.60 ? 1.00 : _lvl == 1.00 ? 1.25 : _lvl == 1.25 ? 1.60 : _lvl == 1.60 ? 2.00 : na
 
// Tooltip for entry/target tags: level insight + time spent in its zone since P1.
// Everything is measured as a fraction "t" of the settled leg (t = 0 at the 0% price,
// 1 at the 100% price), so it works in both Invert modes. Scans every bar from P1
// (leg end) to now, capped at 3999. Call on the last bar only.
f_tagTip(_name, _lvl, _price, _legEndX) =>
    _den = fb_p100 - fb_p0
    string _tip = ''
    if _den != 0
        float _zHi     = f_tagZoneHi(_lvl)
        _n             = math.min(math.max(bar_index - _legEndX, 0), 3999)
        _runMin        = 1e10
        _runMax        = -1e10
        _firstTouchAgo = -1
        _inZone        = 0
        _streak        = 0
        _lastInAgo     = -1
        for i = _n to 0
            _tH = (high[i] - fb_p0) / _den
            _tL = (low[i]  - fb_p0) / _den
            _runMin := math.min(_runMin, _tH, _tL)
            _runMax := math.max(_runMax, _tH, _tL)
            if _firstTouchAgo < 0 and _runMin <= _lvl and _runMax >= _lvl
                _firstTouchAgo := i
            _tC = (close[i] - fb_p0) / _den
            _in = na(_zHi) ? _tC >= _lvl : _tC >= _lvl and _tC <= _zHi
            if _in
                _inZone    += 1
                _streak    += 1
                _lastInAgo := i
            else
                _streak := 0
 
        _tNow      = (close - fb_p0) / _den
        _dist      = _price - close
        _distPct   = _dist / close * 100
        _barsTotal = _n + 1
        _share     = float(_inZone) / _barsTotal * 100
        _zLoPx     = fb_p0 + _den * _lvl
        _zoneTxt   = na(_zHi)
             ? 'beyond ' + str.tostring(_lvl * 100, '0') + '% (' + str.tostring(_zLoPx, '$0,000') + ')'
             : str.tostring(_lvl * 100, '0') + '% → ' + str.tostring(_zHi * 100, '0') + '%  (' + str.tostring(_zLoPx, '$0,000') + ' – ' + str.tostring(fb_p0 + _den * _zHi, '$0,000') + ')'
        _statusTxt = _firstTouchAgo >= 0
             ? 'Reached · first touch ' + str.tostring(_firstTouchAgo) + ' bars ago (≈' + f_dur(_firstTouchAgo) + ')'
             : 'Not reached yet'
        _streakTxt = _streak > 0
             ? 'In zone now · ' + str.tostring(_streak) + ' bars in a row (≈' + f_dur(_streak) + ')'
             : _lastInAgo >= 0
                 ? 'Outside zone · last close in zone ' + str.tostring(_lastInAgo) + ' bars ago'
                 : 'No close in this zone since P1'
        _tip := str.replace_all(_name, '\n', ' ') + ' · ' + str.tostring(_lvl * 100, '0') + '% · ' + str.tostring(_price, '$0,000')
             + '\nZone: ' + _zoneTxt
             + '\nClose ' + str.tostring(close, '$0,000') + ' · retraced ' + str.tostring(_tNow * 100, '0.0') + '% of leg'
             + '\nDistance: ' + (_dist >= 0 ? '+' : '') + str.tostring(_dist, '$#,##0') + ' (' + (_dist >= 0 ? '+' : '') + str.tostring(_distPct, '0.00') + '%) ' + (_dist >= 0 ? 'above close' : 'below close')
             + '\nStatus: ' + _statusTxt
             + '\nSince P1 (' + str.tostring(_barsTotal) + ' bars, ≈' + f_dur(_barsTotal) + '): ' + str.tostring(_inZone) + ' closes in zone (' + str.tostring(_share, '0') + '%)'
             + '\n' + _streakTxt
    _tip
 
fb_retracement(_show, _fib_level, _switch, _shadeTrans = 0.0) =>
    if not show_indicator
        bool(na)
    else
        _clrHigh  = fb_invert ? not fb_isHighLast : fb_isHighLast  // inverted mode swaps the tendency colors
        _col      = _clrHigh ? col_bull : col_bear  // Reverse colors to correspond tendency
        _lbl_col  = lbl_use_theme_color ? _col : (_clrHigh ? lbl_col_bull : lbl_col_bear)
        _gauge_hl = _clrHigh ? fb_guide_highlight_bear : fb_guide_highlight_bull
 
        _price             = fb_p0 + (fb_p100 - fb_p0) * _fib_level
        _position          = bar_index - line.get_x2(fb_lineLast)
        _gAnchor           = fb_p0  // gauge anchor: newest pivot normally, older pivot (leg start) when inverted
        _fbr_max_highest   = math.max(ta.highest(high, nz(math.max(1, _position), 1)), fb_pLast, _gAnchor)
        _fbr_min_lowest    = math.min(ta.lowest (low,  nz(math.max(1, _position), 1)), fb_pLast, _gAnchor)
 
        // gauge x: leg end / P1 (offset ignored) when Gauge at Leg End is on, else current bar + offset
        _legEndX = line.get_x2(fb_lineLast)
        _gauge_x = gauge_at_line_end ? _legEndX : bar_index + fb_gauge_position
 
        if _switch == 'auto' and not na(fb_lineLast)
            fibo_id_auto     = line.new(line.get_x2(fb_lineLast), _price, bar_index + 6, _price,
                                 style = line.style_solid,
                                 color = color.new(_col, _shadeTrans),
                                 width = 1, extend = extend.none)
            fibo_id_ext_auto = line.new(_gauge_x - 2, _price, _gauge_x + 1, _price,
                                 color = color.new(_col, _shadeTrans), width = 1, extend = extend.none)
            fb_label_auto    = label.new(x = _gauge_x, y = _price,
                                 text      = str.tostring(math.round(_fib_level, 02), '000%') + (draw_simplelabel ? '\n' + str.tostring(_price, ' $00,000') : ''),
                                 textcolor = color.new(_lbl_col, _shadeTrans),
                                 style     = lbl_style,
                                 textalign = lbl_align,
                                 color     = #00000000,
                                 size      = fb_lbl_size)
            line.delete (fibo_id_auto[1])
            line.delete (fibo_id_ext_auto[1])
            label.delete(fb_label_auto[1])
            if not _show
                line.delete (fibo_id_auto)
                line.delete (fibo_id_ext_auto)
                label.delete(fb_label_auto)
 
            // ── TARGET LABELS (left side of the gauge, tiny text) ───────────────────
            _tgtTxt = _fib_level == 1.25 ? 'Target 1' : _fib_level == 1.60 ? 'Target 2' : _fib_level == 2.00 ? 'Target 3' : ''
            if _tgtTxt != ''
                var label fb_tgt_label = na
                if show_evt_labels and _show
                    if na(fb_tgt_label)
                        fb_tgt_label := label.new(_gauge_x, _price, _tgtTxt,
                             style     = label.style_label_right,
                             textalign = text.align_right,
                             color     = #00000000,
                             size      = size.tiny)
                    label.set_xy       (fb_tgt_label, _gauge_x, _price)
                    label.set_text     (fb_tgt_label, _tgtTxt)
                    label.set_textcolor(fb_tgt_label, color.new(_lbl_col, _shadeTrans))
                    if barstate.islast
                        label.set_tooltip(fb_tgt_label, f_tagTip(_tgtTxt, _fib_level, _price, _legEndX))
                else if not na(fb_tgt_label)
                    label.delete(fb_tgt_label)
                    fb_tgt_label := na
 
        if _show and _switch == ''
            var fibo_id     = line.new(fb_iLast, _price, bar_index, _price, color = color.new(_col, 0), width = 2, extend = extend.none, style = line.style_solid)  // Extremes lihes
            var fibo_id_ext = line.new(fb_iLast, _price, bar_index, _price, color = color.new(_col, 0), width = 2, extend = extend.none, style = line.style_solid)
            var fb_label    = label.new(x = bar_index, y = _price, text = '',
                                 textcolor = COLOR_TRANSP,
                                 style     = lbl_style,
                                 textalign = lbl_align,
                                 color     = color.rgb(0, 0, 0, 100),
                                 size      = fb_lbl_size)
 
 
            if not na(fb_lineLast)
                // 0% and 100% (the leg's own pivots) always stay fully opaque; every
                // other core level fades per the proximity ranking computed below.
                _lvlTrans = _fib_level == 0.0 or _fib_level == 1.0 ? 0.0 : _shadeTrans
                // the level sitting on the OLDER pivot starts its line at the leg's start bar
                _olderLvl = fb_invert ? 0.0 : 1.0
 
                _isPivotLvl = _fib_level == 0.0 or _fib_level == 1.0
                _lineX1     = _fib_level == _olderLvl ? line.get_x1(fb_lineLast) : _legEndX
                // Gauge at Leg End: only the older-pivot line stops before the gauge; the P1
                // line and inner levels start at the gauge (P1 bar) and run to the current bar.
                // Current Bar mode: both pivot lines stop just before the gauge (original).
                _lineX2     = gauge_at_line_end ? (_fib_level == _olderLvl ? math.max(_lineX1, _gauge_x - 2) : bar_index) : (_isPivotLvl ? _gauge_x - 2 : bar_index)
                line.set_xy1   (fibo_id, _lineX1, _price)
                line.set_xy2   (fibo_id, _lineX2, _price)
                line.set_color (fibo_id, color.new(_col, _lvlTrans))
                line.set_style (fibo_id, _fib_level == 0.0 or _fib_level == 1.0 ? line.style_solid : line.style_dotted)
                line.set_width (fibo_id, _fib_level == 0.0 or _fib_level == 1.0 ? fb_pivot_width : 1)
 
                line.set_xy1  (fibo_id_ext, _gauge_x - 1, _price)
                line.set_xy2  (fibo_id_ext, _gauge_x + fb_line_lenght, _price)
                line.set_color(fibo_id_ext, color.new(_col, _lvlTrans))
                line.set_width(fibo_id_ext, _fib_level == 0.0 or _fib_level == 1.0 or _fib_level == 0.60 ? 2 : 1)
 
                label.set_xy       (fb_label, _gauge_x, _price)
                label.set_text     (fb_label, str.tostring(math.round(_fib_level, 02), '00%') + (draw_simplelabel ? '\n' + str.tostring(_price, '$0,000') : ''))
                label.set_tooltip  (fb_label, str.tostring(((_price - fb_p0) / fb_p0) * 100, format.percent) + ' ' + str.tostring(math.round(_price - fb_p0, 0), '$00,000') + ' from 00% ' + str.tostring(math.round(fb_p0, 0), '$00,000'))
                label.set_textcolor(fb_label, color.new(_lbl_col, _lvlTrans))
                label.set_size     (fb_label, fb_lbl_size)
 
                // ── ENTRY LABELS (left side of the gauge, tiny text) ────────────────────
                _evtTxt = _fib_level == 0.40 ? 'Early\nEntry 1' : _fib_level == 0.50 ? 'Early\nEntry 2' : _fib_level == 0.60 ? 'Entry\nEvent 1' : _fib_level == 1.0 ? 'Entry\nEvent 2' : ''
                if _evtTxt != ''
                    var label fb_evt_label = na
                    if show_evt_labels
                        if na(fb_evt_label)
                            fb_evt_label := label.new(_gauge_x, _price, _evtTxt,
                                 style     = label.style_label_right,
                                 textalign = text.align_right,
                                 color     = #00000000,
                                 size      = size.tiny)
                        label.set_xy       (fb_evt_label, _gauge_x, _price)
                        label.set_text     (fb_evt_label, _evtTxt)
                        label.set_textcolor(fb_evt_label, color.new(_lbl_col, _lvlTrans))
 
                        if barstate.islast
                            label.set_tooltip(fb_evt_label, f_tagTip(_evtTxt, _fib_level, _price, _legEndX))
                    else if not na(fb_evt_label)
                        label.delete(fb_evt_label)
                        fb_evt_label := na
 
                // ── GAUGE (outer box = max/min extreme, inner box = close vs. pivot) ──────
                if _fib_level == 1.0
                    var box   fibo_box_max       = na
                    var line  fibo_line_max      = na
                    var line  fibo_line_min      = na
                    var box   fibo_box_ext       = na
                    var line  fibo_line_ext      = na
                    var label fibo_extreme_label = na
                    var bool  fibo_gauge_visible = false   // tracks whether the gauge is currently drawn
 
                    if fb_guide_draw
                        _extreme_price = _clrHigh ? _fbr_min_lowest : _fbr_max_highest
                        _extreme_chg   = (_extreme_price - _gAnchor) / _gAnchor * 100
                        _extreme_sign  = _extreme_chg >= 0 ? '▲ ' : '▼ '
                        _extreme_txt   = _extreme_sign
                                       + str.tostring(_extreme_price, '$0,000')
                                       + '\n' + str.tostring(math.round(_extreme_chg, 2), '0.0') + '%'
 
                        if not fibo_gauge_visible
                            // outer box: highest/lowest extreme reached since the pivot
                            fibo_box_max  := box.new (bar_index, close, bar_index, _gAnchor,
                                                  border_color = color.new(_col, 50),
                                                  border_width = 1,
                                                  border_style = line.style_dotted,
                                                  bgcolor      = color.new(color.black, 80),
                                                  text         = 'AFR',
                                                  text_valign  = text.align_top,
                                                  text_size    = size.tiny,
                                                  text_color   = color.white)
                            fibo_line_max := line.new(bar_index, close, bar_index, _gAnchor, color = color.white, width = 1)
                            fibo_line_min := line.new(bar_index, close, bar_index, _gAnchor, color = _col, width = 1)
                            // inner box: current close vs. the 0% pivot price
                            fibo_box_ext  := box.new (bar_index, close, bar_index, _gAnchor,
                                                  border_color = color.new(_col, 70),
                                                  border_width = 5,   // Gauge width
                                                  bgcolor      = color.new(_col, 70))
                            fibo_line_ext := line.new(bar_index, close, bar_index, _gAnchor, color = _gauge_hl, width = 4)
                            fibo_extreme_label := label.new(
                                                  x         = _gauge_x - 2,
                                                  y         = _extreme_price,
                                                  text      = _extreme_txt,
                                                  textcolor = color.new(_lbl_col, 0),
                                                  style     = label.style_label_right,
                                                  textalign = text.align_right,
                                                  color     = color.new(_col, 90),
                                                  size      = fb_lbl_size)
                            fibo_gauge_visible := true
 
                        // outer box: max/min extreme
                        box.set_lefttop     (fibo_box_max,  _gauge_x - 1, _fbr_max_highest)
                        box.set_rightbottom (fibo_box_max,  _gauge_x + 1, _fbr_min_lowest)
                        box.set_border_color(fibo_box_max,  color.rgb(73, 73, 73, 30))
                        box.set_bgcolor     (fibo_box_max,  color.rgb(73, 73, 73, 50))
                        box.set_text_color  (fibo_box_max,  color.white)
                        line.set_xy1        (fibo_line_max, _gauge_x - 1, _fbr_max_highest)
                        line.set_xy2        (fibo_line_max, _gauge_x + 1, _fbr_max_highest)
                        line.set_xy1        (fibo_line_min, _gauge_x - 1, _fbr_min_lowest)
                        line.set_xy2        (fibo_line_min, _gauge_x + 1, _fbr_min_lowest)
                        line.set_color      (fibo_line_min, _col)
                        // inner box: current close vs. pivot
                        box.set_lefttop     (fibo_box_ext,  _gauge_x,     close)
                        box.set_rightbottom (fibo_box_ext,  _gauge_x,     _gAnchor)
                        box.set_border_color(fibo_box_ext,  color.new(_col, 50))
                        box.set_bgcolor     (fibo_box_ext,  color.new(_col, 70))
                        line.set_xy1        (fibo_line_ext, _gauge_x,     close)
                        line.set_xy2        (fibo_line_ext, _gauge_x,     close)
                        line.set_color      (fibo_line_ext, _gauge_hl)
 
                        // update every bar / left label position
                        label.set_xy       (fibo_extreme_label, _gauge_x - 0, _extreme_price)
                        label.set_text     (fibo_extreme_label, _extreme_txt)
                        label.set_textcolor(fibo_extreme_label, color.new(_lbl_col, 0))
                        label.set_color    (fibo_extreme_label, color.new(_col, 90))
                        label.set_size     (fibo_extreme_label, fb_lbl_size)
                        label.set_style    (fibo_extreme_label, label.style_label_right)
                        label.set_textalign(fibo_extreme_label, text.align_right)
 
                    if not fb_guide_draw and fibo_gauge_visible
                        // toggle just turned off: remove the gauge instead of leaving it frozen on screen
                        box.delete  (fibo_box_max)
                        line.delete (fibo_line_max)
                        line.delete (fibo_line_min)
                        box.delete  (fibo_box_ext)
                        line.delete (fibo_line_ext)
                        label.delete(fibo_extreme_label)
                        fibo_gauge_visible := false
 
                // ── PROFIT LABEL AT 0% PIVOT ────────────────────────────────────────────
                if _fib_level == 0.0
                    var label fibo_prof_label   = na
                    var bool  fibo_prof_visible = false
 
                    if fb_guide_draw
                        _profit_txt = str.tostring(math.round(close - fb_p0, 0), '$0,000')
                        if not fibo_prof_visible
                            fibo_prof_label   := label.new(bar_index, close, _profit_txt, size = fb_lbl_size)
                            fibo_prof_visible := true
                        label.set_xy       (fibo_prof_label, _gauge_x + 4, close - 100)
                        label.set_text     (fibo_prof_label, _profit_txt)
                        label.set_tooltip  (fibo_prof_label,
                                            str.tostring(((close - fb_p0) / fb_p0) * 100,
                                            format.percent) + ' ' + _profit_txt + ' from 00% ' + str.tostring(math.round(fb_p0, 0), '$00,000'))
                        label.set_color    (fibo_prof_label, color.new(_col, 100))
                        label.set_textcolor(fibo_prof_label, color.white)
                        label.set_size     (fibo_prof_label, fb_lbl_size)
                        label.set_style    (fibo_prof_label, label.style_label_right)
                        label.set_textalign(fibo_prof_label, text.align_right)
 
                    if not fb_guide_draw and fibo_prof_visible
                        // toggle just turned off: remove the label instead of leaving it frozen on screen
                        label.delete(fibo_prof_label)
                        fibo_prof_visible := false
 
        bool(na)  // explicit, consistent return type across both top-level branches
 
// ─── EXTENSION VISIBILITY (user-selected timing) ──────────────────────────────
// "Show Extensions" decides WHEN checked extension levels are drawn:
//   When Reached → cascading "reached" gates below (a level appears only once
//                  price has pushed through the level immediately inside it,
//                  so all levels up to the current extreme show with no gaps)
//   Always       → every checked level is drawn regardless of price
//   Never        → no extension levels are drawn
// Cascading gates used by "When Reached":
//   Below 0%:  -25% needs price past   0% (pivot)
//              -50% needs price past -25%
//             -100% needs price past -50%
//             -150% needs price past -100%
//             -160% needs price past -150%
//             -200% needs price past -160%
//   Above 100%: 125% needs price past 100% (pivot)
//               150% needs price past 125%
//               160% needs price past 150%
//               200% needs price past 160%
fb_height    = fb_p100 - fb_p0
fb_k_low_cr  = ta.lowest (low,  2)
fb_k_high_cr = ta.highest(high, 2)
 
f_ext_reached(_m, _aboveHundred) =>
    _lvl     = fb_p0 + fb_height * _m
    _useHigh = _aboveHundred ? fb_height > 0 : fb_height < 0
    _useHigh ? fb_k_high_cr > _lvl : fb_k_low_cr < _lvl
 
fb_under_0    = f_ext_reached( 0.000, false)   // gates -25%
fb_under_1000 = f_ext_reached(-0.250, false)   // gates -50%
fb_under_1500 = f_ext_reached(-0.500, false)   // gates -100%
fb_under_2000 = f_ext_reached(-1.000, false)   // gates -150%
fb_under_m160 = f_ext_reached(-1.500, false)   // gates -160%
fb_under_m1   = f_ext_reached(-1.600, false)   // gates -200%
 
fb_over_1250  = f_ext_reached( 1.000, true)    // gates 125%
fb_over_1500  = f_ext_reached( 1.250, true)    // gates 150%
fb_over_1600  = f_ext_reached( 1.500, true)    // gates 160%
fb_over_2000  = f_ext_reached( 1.600, true)    // gates 200%
 
// Final per-level visibility = mode enabled AND user selection AND (Always OR
// price-reached gate). The gates stay price-based, so unchecking an inner level
// never blocks outer levels.
fb_ext_on     = fbx_mode != 'Never'
fb_ext_always = fbx_mode == 'Always'
 
fb_show_m25  = fb_ext_on and fbx_m25  and (fb_ext_always or fb_under_0)
fb_show_m50  = fb_ext_on and fbx_m50  and (fb_ext_always or fb_under_1000)
fb_show_m100 = fb_ext_on and fbx_m100 and (fb_ext_always or fb_under_1500)
fb_show_m150 = fb_ext_on and fbx_m150 and (fb_ext_always or fb_under_2000)
fb_show_m160 = fb_ext_on and fbx_m160 and (fb_ext_always or fb_under_m160)
fb_show_m200 = fb_ext_on and fbx_m200 and (fb_ext_always or fb_under_m1)
fb_show_125  = fb_ext_on and fbx_125  and (fb_ext_always or fb_over_1250)
fb_show_150  = fb_ext_on and fbx_150  and (fb_ext_always or fb_over_1500)
fb_show_160  = fb_ext_on and fbx_160  and (fb_ext_always or fb_over_1600)
fb_show_200  = fb_ext_on and fbx_200  and (fb_ext_always or fb_over_2000)
 
// ─── DYNAMIC LEVEL SHADING (all fib levels, core + extensions) ────────────────
// Fades each level's line/label by how close that level's price sits to the
// current close. 0% and 100% (the leg's own pivots) are exempt — always fully
// opaque — and handled directly inside fb_retracement(). Every other level
// participates in one shared near/mid/far ranking: the six toggleable core
// levels (25/40/50/60/75/90%) AND the ten extension levels beyond the
// 0%-100% range (-200/-160/-150/-100/-50/-25/125/150/160/200%). An extension level
// only enters the ranking while its own "fb_show_" condition (mode + user
// selection + reached gate, mirroring the draw calls below) is true, matching
// how a toggled-off core level is already excluded.
trans_0   = 0.0
trans_100 = 0.0
trans_25  = 0.0
trans_40  = 0.0
trans_50  = 0.0
trans_60  = 0.0
trans_75  = 0.0
trans_90  = 0.0
trans_m25  = 0.0
trans_m50  = 0.0
trans_m100 = 0.0
trans_m150 = 0.0
trans_m160 = 0.0
trans_m200 = 0.0
trans_125  = 0.0
trans_150  = 0.0
trans_160  = 0.0
trans_200  = 0.0
 
if dyn_shade_enable and not na(fb_lineLast)
    _endpoint  = fb_p100
    lvl_prices = array.new_float(0)
    lvl_slots  = array.new_int(0)   // 0=25%,1=40%,2=50%,3=60%,4=75%,5=90%,
                                     // 6=-25%,7=-50%,8=-100%,9=-150%,10=-200%,11=125%,12=150%,13=200%,
                                     // 14=-160%,15=160%
    if fb250
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * 0.25)
        array.push(lvl_slots, 0)
    if fb400
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * 0.40)
        array.push(lvl_slots, 1)
    if fb500
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * 0.50)
        array.push(lvl_slots, 2)
    if fb600
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * 0.60)
        array.push(lvl_slots, 3)
    if fb750
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * 0.75)
        array.push(lvl_slots, 4)
    if fb900
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * 0.90)
        array.push(lvl_slots, 5)
    // Extension levels — each gated by the same mode + selection + "reached"
    // condition its draw call below uses, so a level not currently shown doesn't skew the ranking.
    if fb_show_m25
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * -0.25)
        array.push(lvl_slots, 6)
    if fb_show_m50
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * -0.50)
        array.push(lvl_slots, 7)
    if fb_show_m100
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * -1.00)
        array.push(lvl_slots, 8)
    if fb_show_m150
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * -1.50)
        array.push(lvl_slots, 9)
    if fb_show_m160
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * -1.60)
        array.push(lvl_slots, 14)
    if fb_show_m200
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * -2.00)
        array.push(lvl_slots, 10)
    if fb_show_125
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * 1.25)
        array.push(lvl_slots, 11)
    if fb_show_150
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * 1.50)
        array.push(lvl_slots, 12)
    if fb_show_160
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * 1.60)
        array.push(lvl_slots, 15)
    if fb_show_200
        array.push(lvl_prices, fb_p0 + (_endpoint - fb_p0) * 2.00)
        array.push(lvl_slots, 13)
 
    idxAbove = array.new_int(0)
    idxBelow = array.new_int(0)
    pxAbove  = array.new_float(0)
    pxBelow  = array.new_float(0)
    for i = 0 to array.size(lvl_prices) - 1
        p = array.get(lvl_prices, i)
        if p >= close
            array.push(idxAbove, i)
            array.push(pxAbove, p)
        else
            array.push(idxBelow, i)
            array.push(pxBelow, p)
 
    trans_by_slot = array.new_float(16, 100 - pct_far)
 
    if array.size(idxAbove) > 0
        ordAbove = array.sort_indices(pxAbove, order.ascending)    // nearest to close first
        for r = 0 to array.size(ordAbove) - 1
            li   = array.get(idxAbove, array.get(ordAbove, r))
            slot = array.get(lvl_slots, li)
            pct  = r == 0 ? pct_near : r == 1 ? pct_mid : pct_far
            array.set(trans_by_slot, slot, 100 - pct)
 
    if array.size(idxBelow) > 0
        ordBelow = array.sort_indices(pxBelow, order.descending)   // nearest to close first
        for r = 0 to array.size(ordBelow) - 1
            li   = array.get(idxBelow, array.get(ordBelow, r))
            slot = array.get(lvl_slots, li)
            pct  = r == 0 ? pct_near : r == 1 ? pct_mid : pct_far
            array.set(trans_by_slot, slot, 100 - pct)
 
    trans_25   := array.get(trans_by_slot, 0)
    trans_40   := array.get(trans_by_slot, 1)
    trans_50   := array.get(trans_by_slot, 2)
    trans_60   := array.get(trans_by_slot, 3)
    trans_75   := array.get(trans_by_slot, 4)
    trans_90   := array.get(trans_by_slot, 5)
    trans_m25  := array.get(trans_by_slot, 6)
    trans_m50  := array.get(trans_by_slot, 7)
    trans_m100 := array.get(trans_by_slot, 8)
    trans_m150 := array.get(trans_by_slot, 9)
    trans_m200 := array.get(trans_by_slot, 10)
    trans_125  := array.get(trans_by_slot, 11)
    trans_150  := array.get(trans_by_slot, 12)
    trans_200  := array.get(trans_by_slot, 13)
    trans_m160 := array.get(trans_by_slot, 14)
    trans_160  := array.get(trans_by_slot, 15)
 
// ─── DRAW ─────────────────────────────────────────────────────────────────────
fb_retracement(fb_show_m200  , -2.000, 'auto', trans_m200)
fb_retracement(fb_show_m160  , -1.600, 'auto', trans_m160)
fb_retracement(fb_show_m150  , -1.500, 'auto', trans_m150)
fb_retracement(fb_show_m100  , -1.000, 'auto', trans_m100)
fb_retracement(fb_show_m50   , -0.500, 'auto', trans_m50)
fb_retracement(fb_show_m25   , -0.250, 'auto', trans_m25)
fb_retracement(true          ,  0.000, '', trans_0)
fb_retracement(fb250         ,  0.250, '', trans_25)
fb_retracement(fb400         ,  0.400, '', trans_40)
fb_retracement(fb500         ,  0.500, '', trans_50)
fb_retracement(fb600         ,  0.600, '', trans_60)
fb_retracement(fb750         ,  0.750, '', trans_75)
fb_retracement(fb900         ,  0.900, '', trans_90)
fb_retracement(true          ,  1.000, '', trans_100)
fb_retracement(fb_show_125   ,  1.250, 'auto', trans_125)
fb_retracement(fb_show_150   ,  1.500, 'auto', trans_150)
fb_retracement(fb_show_160   ,  1.600, 'auto', trans_160)
fb_retracement(fb_show_200   ,  2.000, 'auto', trans_200)
 
////////////////////////////////////////////////////////////////////////////
////  SECTION 3 — TREND PIVOTS                                            ///
////  Ported from CQ_(5)_Trend Pivots [Anan]                              ///
////  (based on "Trend Pivots [Anan]" © Mohamed3nan — MPL 2.0)            ///
////  This source code is subject to the terms of the Mozilla Public      ///
////  License 2.0 at https://mozilla.org/MPL/2.0/                        ///
////                                                                       ///
////  Independent pivot-high/low engine (ta.pivothigh/ta.pivotlow) that   ///
////  classifies each confirmed pivot as HH/LH/HL/LL, with optional       ///
////  arrow markers, labels, a smoothed center line, support/resistance   ///
////  extensions, and fractal-break arrows/alerts. All identifiers below  ///
////  are prefixed tp_ to keep this section's namespace fully isolated    ///
////  from Sections 1 & 2 (both of which already use "period"/"bull"/     ///
////  "bear"/pivot-style variables under different names/case).           ///
////////////////////////////////////////////////////////////////////////////
 
tp_basicgr = '⚙️ Trend Pivots Master Control'
show_trendpivots = input.bool(true, '⚡ Enable Trend Pivots', group = tp_basicgr,
     tooltip = "Master switch for the visuals of the Trend Pivots section: arrow heads, pivot labels, center line, Bull/Bear labels, support/resistance and fractal-break arrows. The TP Fractal Break alerts keep evaluating even when this is off.")
 
tp_Period    = input.int(defval = 5, title = 'Pivot Point Period', minval = 1, group = tp_basicgr,
     tooltip = "Bars required on each side of a bar for it to count as a pivot high or low (ta.pivothigh / ta.pivotlow). A pivot is only confirmed this many bars after it forms, so its marker appears N bars late and is drawn back on the pivot bar. Higher values give fewer, more significant pivots. Independent of the zigzag Periods in the other sections.")
tp_showPPA   = input(defval = true, title = 'Show Pivot Points Arrow Heads', group = tp_basicgr,
     tooltip = "Plots a small triangle at each confirmed pivot: red down-triangles above the bar for pivot highs (HH and LH), green up-triangles below the bar for pivot lows (HL and LL).")
tp_showPPL   = input(defval = false, title = 'Show Pivot Points Labels', group = tp_basicgr,
     tooltip = "Draws a label at each confirmed pivot classifying it as HH (higher high), LH (lower high), HL (higher low) or LL (lower low) compared with the previous pivot of the same type. Size, colors and text/arrow mode are set in the Trend Pivots Label Style group.")
tp_showCL    = input(defval = false, title = 'Show Pivot Points Center Line', group = tp_basicgr,
     tooltip = "Plots a stepped center line: a weighted running average of pivot prices (2/3 previous center, 1/3 newest pivot), updated on each new pivot. It is teal while below hl2 (price above it) and red while above. The Bull/Bear labels are based on it.")
tp_showLabels= input(defval = false, title = 'Show Bull/Bear Labels', group = tp_basicgr,
     tooltip = "Shows a Bull label when the close crosses above the center line and a Bear label when it crosses below. Uses the center line calculation whether or not the line itself is displayed.")
tp_showSR    = input(defval = false, title = 'Show Support/Resistance Level Extensions', group = tp_basicgr,
     tooltip = "Plots circles at the most recent pivot low (support, teal) and pivot high (resistance, orange), held until a new pivot of that type forms and shifted back by the Pivot Point Period so they line up with the pivot bars.")
tp_showFB    = input(false, title = 'Show Fractal Break Arrows', group = tp_basicgr,
     tooltip = "Plots a green up-triangle when a bar opens at or below the last pivot high and closes above it, and a red down-triangle when a bar opens at or above the last pivot low and closes below it. The TP Fractal Break alerts fire on the same conditions regardless of this setting.")
 
// ── 🏷️ Pivot Label Style ──────────────────────────────
tp_ppl_sizeStr = input.string(defval = 'Tiny', title = 'Pivot Label Text Size', options = ['Auto', 'Tiny', 'Small', 'Normal', 'Large', 'Huge'], group = '🏷️ Trend Pivots Label Style',
     tooltip = "Size of the HH/LH/HL/LL pivot labels. Auto lets TradingView scale them with the chart. Only used while Show Pivot Points Labels is enabled.")
tp_useArrows    = input.bool(defval = false, title = 'Show Directional Arrows Instead of Text (↗ ↘)', group = '🏷️ Trend Pivots Label Style',
     tooltip = "Replaces the HH/LH/HL/LL text on the pivot labels with arrows: ↗ for HH and HL, ↘ for LH and LL. Colors still follow the per-type colors below.")
tp_col_HH = input.color(defval = color.aqua, title = 'HH Color (Higher High)', inline = 'tphh', group = '🏷️ Trend Pivots Label Style',
     tooltip = "Text color of HH (higher high) pivot labels: a pivot high above the previous pivot high.")
tp_col_LH = input.color(defval = color.rgb(150, 235, 235), title = 'LH Color (Lower High)', inline = 'tplh', group = '🏷️ Trend Pivots Label Style',
     tooltip = "Text color of LH (lower high) pivot labels: a pivot high below the previous pivot high.")
tp_col_LL = input.color(defval = color.red, title = 'LL Color (Lower Low)', inline = 'tpll', group = '🏷️ Trend Pivots Label Style',
     tooltip = "Text color of LL (lower low) pivot labels: a pivot low below the previous pivot low.")
tp_col_HL = input.color(defval = color.rgb(255, 150, 150), title = 'HL Color (Higher Low)', inline = 'tphl', group = '🏷️ Trend Pivots Label Style',
     tooltip = "Text color of HL (higher low) pivot labels: a pivot low above the previous pivot low.")
 
/////////////////////////////////
float tp_pivotHigh = na
float tp_pivotLow  = na
tp_pivotHigh := ta.pivothigh(tp_Period, tp_Period)
tp_pivotLow  := ta.pivotlow(tp_Period, tp_Period)
 
/////////////////////////////////
// Higher Highs, Lower Highs, Higher Lows, Lower Lows  //
tp_valuewhen_1 = ta.valuewhen(bool(tp_pivotHigh), high[tp_Period], 1)
tp_valuewhen_2 = ta.valuewhen(bool(tp_pivotHigh), high[tp_Period], 0)
tp_higherhigh  = na(tp_pivotHigh) ? na : tp_valuewhen_1 < tp_valuewhen_2 ? tp_pivotHigh : na
tp_lowerhigh   = na(tp_pivotHigh) ? na : tp_valuewhen_1 > tp_valuewhen_2 ? tp_pivotHigh : na
tp_valuewhen_5 = ta.valuewhen(bool(tp_pivotLow), low[tp_Period], 1)
tp_valuewhen_6 = ta.valuewhen(bool(tp_pivotLow), low[tp_Period], 0)
tp_higherlow   = na(tp_pivotLow) ? na : tp_valuewhen_5 < tp_valuewhen_6 ? tp_pivotLow : na
tp_lowerlow    = na(tp_pivotLow) ? na : tp_valuewhen_5 > tp_valuewhen_6 ? tp_pivotLow : na
 
// Higher Highs, Lower Highs, Higher Lows, Lower Lows  //
///////////////////////////////// "ʟʟ" : "ʜʜ" : "ʟʜ" : "ʜʟ"
plotshape(show_trendpivots and tp_showPPA ? tp_higherhigh : na, title = 'TP ʜʜ', style = shape.triangledown, location = location.abovebar, size = size.tiny, color = color.rgb(255, 0, 0), text = 'ʜʜ', textcolor = color.rgb(255, 0, 0, 100), offset = -tp_Period)
plotshape(show_trendpivots and tp_showPPA ? tp_higherlow : na, title = 'TP ʜʟ', style = shape.triangleup, location = location.belowbar, size = size.tiny, color = color.rgb(0, 255, 8), text = 'ʜʟ', textcolor = color.rgb(0, 255, 8, 100), offset = -tp_Period)
plotshape(show_trendpivots and tp_showPPA ? tp_lowerhigh : na, title = 'TP ʟʜ', style = shape.triangledown, location = location.abovebar, size = size.tiny, color = color.rgb(255, 0, 0), text = 'ʟʜ', textcolor = color.rgb(255, 0, 0, 100), offset = -tp_Period)
plotshape(show_trendpivots and tp_showPPA ? tp_lowerlow : na, title = 'TP ʟʟ', style = shape.triangleup, location = location.belowbar, size = size.tiny, color = color.rgb(0, 255, 8), text = 'ʟʟ', textcolor = color.rgb(0, 255, 8, 100), offset = -tp_Period)
/////////////////////////////////
// Pivot Point Labels (customizable size, color, and text/arrow style)
// Uses label.new() instead of plotshape() — labels are drawing objects, not
// compiled plots, so they don't count toward the 64-plot limit, and their
// "size"/"text" arguments accept dynamic (series) values instead of requiring
// compile-time consts. This lets size + text/arrow mode stay fully dynamic
// with a single code path per pivot type (no per-size duplication needed).
tp_ppl_size = switch tp_ppl_sizeStr
    'Auto'   => size.auto
    'Tiny'   => size.tiny
    'Small'  => size.small
    'Normal' => size.normal
    'Large'  => size.large
    'Huge'   => size.huge
    => size.tiny
 
tp_txt_HH = tp_useArrows ? '↗' : 'ʜʜ'
tp_txt_LH = tp_useArrows ? '↘' : 'ʟʜ'
tp_txt_LL = tp_useArrows ? '↘' : 'ʟʟ'
tp_txt_HL = tp_useArrows ? '↗' : 'ʜʟ'
 
if show_trendpivots and tp_showPPL and not na(tp_higherhigh)
    label.new(x = bar_index - tp_Period, y = tp_higherhigh, text = tp_txt_HH, xloc = xloc.bar_index, yloc = yloc.price, style = label.style_none, textcolor = tp_col_HH, size = tp_ppl_size, textalign = text.align_center)
 
if show_trendpivots and tp_showPPL and not na(tp_higherlow)
    label.new(x = bar_index - tp_Period, y = tp_higherlow, text = tp_txt_HL, xloc = xloc.bar_index, yloc = yloc.price, style = label.style_none, textcolor = tp_col_HL, size = tp_ppl_size, textalign = text.align_center)
 
if show_trendpivots and tp_showPPL and not na(tp_lowerhigh)
    label.new(x = bar_index - tp_Period, y = tp_lowerhigh, text = tp_txt_LH, xloc = xloc.bar_index, yloc = yloc.price, style = label.style_none, textcolor = tp_col_LH, size = tp_ppl_size, textalign = text.align_center)
 
if show_trendpivots and tp_showPPL and not na(tp_lowerlow)
    label.new(x = bar_index - tp_Period, y = tp_lowerlow, text = tp_txt_LL, xloc = xloc.bar_index, yloc = yloc.price, style = label.style_none, textcolor = tp_col_LL, size = tp_ppl_size, textalign = text.align_center)
/////////////////////////////////
 
float tp_center = na
tp_center := tp_center[1]
float tp_lastpp = bool(tp_pivotHigh) ? tp_pivotHigh : bool(tp_pivotLow) ? tp_pivotLow : na
if bool(tp_lastpp)
    if na(tp_center)
        tp_center := tp_lastpp
        tp_center
    else
        tp_center := (tp_center + tp_center + tp_lastpp) / 3
        tp_center
 
 
plot(show_trendpivots and tp_showCL ? tp_center : na, color = show_trendpivots and tp_showCL ? tp_center < hl2 ? color.new(color.teal, 25) : color.new(color.red, 25) : na, title = 'TP Center Line', style = plot.style_stepline, linewidth = 2)
/////////////////////////////////
 
float tp_resistance = na
float tp_support    = na
tp_support    := bool(tp_pivotLow) ? tp_pivotLow : tp_support[1]
tp_resistance := bool(tp_pivotHigh) ? tp_pivotHigh : tp_resistance[1]
 
plot(show_trendpivots and tp_showSR and bool(tp_support) ? tp_support : na, title = 'TP Support', color = show_trendpivots and tp_showSR and bool(tp_support) ? color.new(color.teal, 50) : na, style = plot.style_circles, offset = -tp_Period)
plot(show_trendpivots and tp_showSR and bool(tp_resistance) ? tp_resistance : na, title = 'TP Resistance', color = show_trendpivots and tp_showSR and bool(tp_resistance) ? color.new(color.orange, 50) : na, style = plot.style_circles, offset = -tp_Period)
 
 
/////////////////////////////////
tp_bsignal = close > tp_center[1] and close[1] < tp_center[2]
tp_ssignal = close < tp_center[1] and close[1] > tp_center[2]
plotshape(show_trendpivots and tp_bsignal and tp_showLabels ? tp_center[1] : na, title = 'TP Bull', text = 'Bull', location = location.belowbar, style = shape.labelup, size = size.tiny, color = color.new(color.teal, 50), textcolor = color.new(color.white, 50))
plotshape(show_trendpivots and tp_ssignal and tp_showLabels ? tp_center[1] : na, title = 'TP Bear', text = 'Bear', location = location.abovebar, style = shape.labeldown, size = size.tiny, color = color.new(color.orange, 50), textcolor = color.new(color.white, 50))
/////////////////////////////////
 
//  Fractal Break Alerts
tp_pvthis = 0.0
tp_pvtlos = 0.0
tp_pvthis := na(tp_pivotHigh) ? tp_pvthis[1] : high[tp_Period]
tp_pvtlos := na(tp_pivotLow) ? tp_pvtlos[1] : low[tp_Period]
 
tp_bull = false
tp_bear = false
tp_bull := close > tp_pvthis and open <= tp_pvthis
tp_bear := close < tp_pvtlos and open >= tp_pvtlos
 
plotshape(show_trendpivots and tp_showFB and tp_bull ? 1 : na, title = 'TP BUY Arrow', color = color.new(color.green, 0), style = shape.triangleup, location = location.belowbar)
plotshape(show_trendpivots and tp_showFB and tp_bear ? -1 : na, title = 'TP SELL Arrow', color = color.new(color.red, 0), style = shape.triangledown, location = location.abovebar)
/////////////////////////////////
 
// Alerts//
alertcondition(tp_bull or tp_bear, title = 'TP Fractal Break Arrow', message = 'Alert')
alertcondition(tp_bull, title = 'TP Fractal Break BULL', message = 'BULL')
alertcondition(tp_bear, title = 'TP Fractal Break BEAR', message = 'BEAR')
 
////////////////////////////////////////////////////////////////////////////
////  END SECTION 3 — TREND PIVOTS                                       ///
////////////////////////////////////////////////////////////////////////////
 
////////////////////////////////////////////////////////////////////////////
////  SECTION 4 — PHASE COUNTER + ADAPTIVE PROJECTION                    ///
////  Ported from CQ_(9)_Phases Counter + Adaptive Projection v2.        ///
////  Fully independent pivot engine (own ZigZag Period), separate from  ///
////  Section 1's swing engine and Section 3's pivot-high/low engine —   ///
////  the same "independent section" pattern already used for Sections  ///
////  1 and 3 in this file. Ports the ZigZag leg rendering, the Adaptive ///
////  Projection, and the permanent 1-5 Leg Numbering system anchored to ///
////  per-timeframe timestamps. The source script's Phase Statistics     ///
////  table is intentionally NOT included, along with everything that    ///
////  existed only to feed it (per-pivot ATR tracking, leg High/Low/Bars ///
////  bookkeeping). All identifiers are prefixed pc_ to keep this        ///
////  section's namespace fully isolated from Sections 1-3.              ///
////////////////////////////////////////////////////////////////////////////
 
// 🌀 ZIGZAG SETTINGS
pc_grp_zz = "🌀 Phase Counter — ZigZag"
pc_period = input.int(45, 'Period', 10, 100, group = pc_grp_zz,
     tooltip = "ZigZag lookback length in bars. A bar becomes a pivot high (or pivot low) only when it is the highest high (or lowest low) of the last N bars, and pivots of alternating direction are connected into legs. Higher values give fewer, larger, smoother legs that confirm later; lower values give more, smaller, noisier legs that react faster. This one setting drives everything else in this section: leg drawing, phase numbering, and the Adaptive Projection averages.")
 
pc_bull_color = input.color(color.rgb(0, 137, 123), 'Bullish Leg', inline = 'pczzcol', group = pc_grp_zz,
     tooltip = "Color of ZigZag legs that travel upward (price ended the leg higher than it started), including the live Active leg while price is above its starting pivot. Also colors the start/end circle markers of those legs. Pairs with the Bearish Leg color to its right.")
pc_bear_color = input.color(color.rgb(255, 153, 0), 'Bearish Leg', inline = 'pczzcol', group = pc_grp_zz,
     tooltip = "Color of ZigZag legs that travel downward (price ended the leg lower than it started), including the live Active leg while price is below its starting pivot. Also colors the start/end circle markers of those legs. Pairs with the Bullish Leg color to its left.")
 
pc_confirmed_style = input.string('Solid', 'Confirmed Style', ['Solid', 'Dashed', 'Dotted'], inline = 'pczzstyle', group = pc_grp_zz,
     tooltip = "Line style (Solid, Dashed or Dotted) for confirmed, fully settled ZigZag legs. The two most recent legs are styled separately: see Unconfirmed Leg Style and Active Leg Style below. Pairs with the Width input to its right.")
pc_width = input.int(2, 'Width', 1, 8, inline = 'pczzstyle', group = pc_grp_zz,
     tooltip = "Line width in pixels (1-8) shared by every ZigZag leg: confirmed, unconfirmed and active. Pairs with the Confirmed Style input to its left.")
 
pc_active_leg_style = input.string('Dotted', 'Active Leg Style', ['Solid', 'Dashed', 'Dotted'], group = pc_grp_zz,
     tooltip = "Line style of the Active leg: the still-forming leg drawn from the most recent pivot to the current price on the last bar. It moves with every price update until a new pivot forms and it becomes the Unconfirmed leg.")
pc_unconfirmed_leg_style = input.string('Dashed', 'Unconfirmed Leg Style', ['Solid', 'Dashed', 'Dotted'], group = pc_grp_zz,
     tooltip = "Line style of the Unconfirmed leg: the most recent completed pivot-to-pivot leg. Its end pivot can still shift while price keeps making new extremes, so it is styled apart from the older, settled legs, which use the Confirmed Style.")
 
pc_show_leg_markers = input.bool(true, 'Mark Active Leg Start/End', inline = 'pclegmark', group = pc_grp_zz,
     tooltip = "Draws a small circle marker at both ends of the Active leg (its starting pivot and the current price), colored to match the leg's direction. The marker size is chosen by the selector to its right.")
pc_marker_size_choice = input.string('Small', '', options = ['Tiny', 'Small', 'Normal', 'Large', 'Huge'], inline = 'pclegmark', group = pc_grp_zz,
     tooltip = "Size (Tiny to Huge) of the circle markers drawn on the Active leg. Only has an effect while Mark Active Leg Start/End is enabled.")
 
pc_show_prev_leg_markers = input.bool(true, 'Mark Unconfirmed Leg Start/End', inline = 'pclegmark2', group = pc_grp_zz,
     tooltip = "Draws a small circle marker at both ends of the Unconfirmed leg (the most recent completed pivot-to-pivot leg), colored to match that leg's direction. The marker size is chosen by the selector to its right.")
pc_prev_marker_size_choice = input.string('Normal', '', options = ['Tiny', 'Small', 'Normal', 'Large', 'Huge'], inline = 'pclegmark2', group = pc_grp_zz,
     tooltip = "Size (Tiny to Huge) of the circle markers drawn on the Unconfirmed leg. Only has an effect while Mark Unconfirmed Leg Start/End is enabled.")
 
pc_f_drawLeg(arr, x1, y1, x2, y2, col, pw, sty) =>
    pc_line_style = sty == 'Solid' ? line.style_solid : sty == 'Dashed' ? line.style_dashed : line.style_dotted
    pc_ml = line.new(x1 = x1, y1 = y1, x2 = x2, y2 = y2, xloc = xloc.bar_time, color = col, width = pw, style = pc_line_style)
    array.push(arr, pc_ml)
 
pc_f_labelSize(sel) =>
    sel == "Tiny" ? size.tiny : sel == "Small" ? size.small : sel == "Normal" ? size.normal : sel == "Large" ? size.large : size.huge
 
float pc_ph = ta.highestbars(high, pc_period) == 0 ? high : na
float pc_pl = ta.lowestbars(low, pc_period) == 0 ? low : na
 
pc_isPh = not na(pc_ph)
pc_isPl = not na(pc_pl)
 
var pc_dir = 0
pc_prev_dir = pc_dir
pc_dir := pc_isPh and not pc_isPl ? 1 : pc_isPl and not pc_isPh ? -1 : pc_dir
pc_dc = pc_dir != pc_prev_dir ? 1 : 0
 
var pc_z = array.new_float(0)
 
pc_add_to_zigzag(p, v, b) =>
    array.unshift(p, b)
    array.unshift(p, v)
 
pc_update_zigzag(p, v, b, d) =>
    if array.size(p) == 0
        pc_add_to_zigzag(p, v, b)
    else if (d == 1 and v > array.get(p, 0)) or (d == -1 and v < array.get(p, 0))
        array.set(p, 0, v)
        array.set(p, 1, b)
    0.
 
if pc_isPh or pc_isPl
    if pc_dc != 0
        pc_add_to_zigzag(pc_z, pc_dir == 1 ? pc_ph : pc_pl, time)
    else if not(pc_isPh and pc_isPl)
        pc_update_zigzag(pc_z, pc_dir == 1 ? pc_ph : pc_pl, time, pc_dir)
 
var array<line> pc_zigzag_lines = array.new_line()
var array<label> pc_prev_leg_markers = array.new_label()
if array.size(pc_z) >= 4
    while array.size(pc_zigzag_lines) > 0
        line.delete(array.pop(pc_zigzag_lines))
    while array.size(pc_prev_leg_markers) > 0
        label.delete(array.pop(pc_prev_leg_markers))
 
    pc_last_valid = array.size(pc_z) - 4
    if pc_last_valid >= 0
        for i = 0 to pc_last_valid by 2
            pc_x1 = int(array.get(pc_z, i + 1))
            pc_y1 = array.get(pc_z, i)
            pc_x2 = int(array.get(pc_z, i + 3))
            pc_y2 = array.get(pc_z, i + 2)
            pc_leg_color = pc_y1 > pc_y2 ? pc_bull_color : pc_bear_color
            pc_leg_style = i == 0 ? pc_unconfirmed_leg_style : pc_confirmed_style
            pc_f_drawLeg(pc_zigzag_lines, pc_x1, pc_y1, pc_x2, pc_y2, pc_leg_color, pc_width, pc_leg_style)
 
            if i == 0 and pc_show_prev_leg_markers
                pc_prev_marker_size = pc_f_labelSize(pc_prev_marker_size_choice)
                pc_prev_start_marker = label.new(pc_x1, pc_y1, "◯",
                     xloc = xloc.bar_time,
                     style = label.style_label_center,
                     color = color.new(color.white, 100),
                     textcolor = pc_leg_color,
                     size = pc_prev_marker_size)
                pc_prev_end_marker = label.new(pc_x2, pc_y2, "◯",
                     xloc = xloc.bar_time,
                     style = label.style_label_center,
                     color = color.new(color.white, 100),
                     textcolor = pc_leg_color,
                     size = pc_prev_marker_size)
                array.push(pc_prev_leg_markers, pc_prev_start_marker)
                array.push(pc_prev_leg_markers, pc_prev_end_marker)
 
pc_grp_proj = "📈 Phase Counter — Adaptive Projection"
pc_show_projection = input.bool(true, "Show Projection", group = pc_grp_proj,
     tooltip = "Master switch for the Adaptive Projection: two lines drawn forward from the current price. Segment 1 continues the current leg until it reaches the average length of past legs in the same direction (skipped if the leg is already longer than that average). Segment 2 then reverses, using the average length and average slope of past legs in the opposite direction. The averages are taken from every ZigZag leg in this section's history, so the projection adapts as more legs form. The projection never extends more than 500 bars ahead.")
pc_proj_bull_color = input.color(color.rgb(0, 137, 123), 'Bullish Projection', inline = 'pcprojcol', group = pc_grp_proj,
     tooltip = "Color of projection segments that move upward. Segment 1 uses this color when the current leg is bullish; Segment 2 uses it when the projected reversal is upward (current leg bearish). Pairs with the Bearish Projection color to its right.")
pc_proj_bear_color = input.color(color.rgb(255, 153, 0), 'Bearish Projection', inline = 'pcprojcol', group = pc_grp_proj,
     tooltip = "Color of projection segments that move downward. Segment 1 uses this color when the current leg is bearish; Segment 2 uses it when the projected reversal is downward (current leg bullish). Pairs with the Bullish Projection color to its left.")
pc_proj_style = input.string("Dotted", "Style", options = ["Solid", "Dashed", "Dotted"], inline = 'pcproj', group = pc_grp_proj,
     tooltip = "Line style (Solid, Dashed or Dotted) of both projection segments. Pairs with the Width input to its right.")
pc_proj_width = input.int(1, "Width", 1, 5, inline = 'pcproj', group = pc_grp_proj,
     tooltip = "Line width in pixels (1-5) of both projection segments. Pairs with the Style input to its left.")
 
var float pc_avg_bearish_length = 0.0
var float pc_avg_bullish_length = 0.0
var float pc_avg_bearish_slope = 0.0
var float pc_avg_bullish_slope = 0.0
 
if array.size(pc_z) >= 4
    pc_bearish_lengths = array.new_float(0)
    pc_bullish_lengths = array.new_float(0)
    pc_bearish_slopes = array.new_float(0)
    pc_bullish_slopes = array.new_float(0)
    i = 0
    while i < array.size(pc_z) - 2
        pc_yA = array.get(pc_z, i)
        pc_xA = array.get(pc_z, i + 1)
        pc_yB = array.get(pc_z, i + 2)
        pc_xB = array.get(pc_z, i + 3)
        if pc_xA != pc_xB
            pc_segment_direction = pc_yA > pc_yB ? 1 : -1
            pc_segment_length = math.abs(pc_yA - pc_yB)
            pc_segment_slope = (pc_yA - pc_yB) / (pc_xA - pc_xB)
            if pc_segment_direction == -1
                array.push(pc_bearish_lengths, pc_segment_length)
                array.push(pc_bearish_slopes, pc_segment_slope)
            else
                array.push(pc_bullish_lengths, pc_segment_length)
                array.push(pc_bullish_slopes, pc_segment_slope)
        i += 2
    pc_avg_bearish_length := array.size(pc_bearish_lengths) > 0 ? array.avg(pc_bearish_lengths) : 0
    pc_avg_bullish_length := array.size(pc_bullish_lengths) > 0 ? array.avg(pc_bullish_lengths) : 0
    pc_avg_bearish_slope := array.size(pc_bearish_slopes) > 0 ? array.avg(pc_bearish_slopes) : 0
    pc_avg_bullish_slope := array.size(pc_bullish_slopes) > 0 ? array.avg(pc_bullish_slopes) : 0
 
pc_grp_leg = "🔢 Phase Counter — Leg Numbering"
 
pc_anchor_time_1h = input.time(timestamp("2024-01-01 00:00"), "Pivot⚓ (1H)", group = pc_grp_leg, inline = 'pc1H',
     tooltip = "Date and time of a pivot whose phase number you have verified on the 1H timeframe. When the counter seeds itself it snaps to the ZigZag pivot closest in time to this timestamp, uses it as the numbering reference, then labels every other pivot 1-5 in a repeating cycle forward and backward from it. Only used when the active anchor timeframe is 1h (set by Anchor Timeframe Selection / Anchor Timeframe (Manual)); the other timeframes' anchors are ignored. Choose a real swing pivot you can identify on the chart, and re-check it if you change this section's ZigZag Period, since a different Period may produce different pivots.")
pc_last_verified_leg_1h = input.int(1, "", minval = 1, maxval = 5, group = pc_grp_leg, inline = 'pc1H',
     tooltip = "Phase number (1-5) assigned to the 1H anchor pivot above. Neighboring pivots continue the repeating 1-2-3-4-5 cycle in both directions (older pivots count down, newer ones count up, wrapping from 5 back to 1), and newly confirmed pivots keep extending the count automatically. Only used when the active anchor timeframe is 1h.")
 
pc_anchor_time_4h = input.time(timestamp("2026-08-01T11:00:00-0500"), "Pivot⚓ (4H)", group = pc_grp_leg, inline = 'pc4H',
     tooltip = "Date and time of a pivot whose phase number you have verified on the 4H timeframe. When the counter seeds itself it snaps to the ZigZag pivot closest in time to this timestamp, uses it as the numbering reference, then labels every other pivot 1-5 in a repeating cycle forward and backward from it. Only used when the active anchor timeframe is 4h (set by Anchor Timeframe Selection / Anchor Timeframe (Manual)); the other timeframes' anchors are ignored. Choose a real swing pivot you can identify on the chart, and re-check it if you change this section's ZigZag Period, since a different Period may produce different pivots.")
pc_last_verified_leg_4h = input.int(1, "", minval = 1, maxval = 5, group = pc_grp_leg, inline = 'pc4H',
     tooltip = "Phase number (1-5) assigned to the 4H anchor pivot above. Neighboring pivots continue the repeating 1-2-3-4-5 cycle in both directions (older pivots count down, newer ones count up, wrapping from 5 back to 1), and newly confirmed pivots keep extending the count automatically. Only used when the active anchor timeframe is 4h.")
 
pc_anchor_time_1d = input.time(timestamp("2026-05-05 19:00"), "Pivot⚓ (1D)", group = pc_grp_leg, inline = 'pc1D',
     tooltip = "Date and time of a pivot whose phase number you have verified on the 1D timeframe. When the counter seeds itself it snaps to the ZigZag pivot closest in time to this timestamp, uses it as the numbering reference, then labels every other pivot 1-5 in a repeating cycle forward and backward from it. Only used when the active anchor timeframe is 1d (set by Anchor Timeframe Selection / Anchor Timeframe (Manual)); the other timeframes' anchors are ignored. Choose a real swing pivot you can identify on the chart, and re-check it if you change this section's ZigZag Period, since a different Period may produce different pivots.")
pc_last_verified_leg_1d = input.int(5, "", minval = 1, maxval = 5, group = pc_grp_leg, inline = 'pc1D',
     tooltip = "Phase number (1-5) assigned to the 1D anchor pivot above. Neighboring pivots continue the repeating 1-2-3-4-5 cycle in both directions (older pivots count down, newer ones count up, wrapping from 5 back to 1), and newly confirmed pivots keep extending the count automatically. Only used when the active anchor timeframe is 1d.")
 
pc_anchor_time_1w = input.time(timestamp("2024-01-01 00:00"), "Pivot⚓ (1W)", group = pc_grp_leg, inline = 'pc1W',
     tooltip = "Date and time of a pivot whose phase number you have verified on the 1W timeframe. When the counter seeds itself it snaps to the ZigZag pivot closest in time to this timestamp, uses it as the numbering reference, then labels every other pivot 1-5 in a repeating cycle forward and backward from it. Only used when the active anchor timeframe is 1w (set by Anchor Timeframe Selection / Anchor Timeframe (Manual)); the other timeframes' anchors are ignored. Choose a real swing pivot you can identify on the chart, and re-check it if you change this section's ZigZag Period, since a different Period may produce different pivots.")
pc_last_verified_leg_1w = input.int(1, "", minval = 1, maxval = 5, group = pc_grp_leg, inline = 'pc1W',
     tooltip = "Phase number (1-5) assigned to the 1W anchor pivot above. Neighboring pivots continue the repeating 1-2-3-4-5 cycle in both directions (older pivots count down, newer ones count up, wrapping from 5 back to 1), and newly confirmed pivots keep extending the count automatically. Only used when the active anchor timeframe is 1w.")
 
pc_anchor_time_1m = input.time(timestamp("2024-01-01 00:00"), "Pivot⚓ (1M)", group = pc_grp_leg, inline = 'pc1M',
     tooltip = "Date and time of a pivot whose phase number you have verified on the 1M timeframe. When the counter seeds itself it snaps to the ZigZag pivot closest in time to this timestamp, uses it as the numbering reference, then labels every other pivot 1-5 in a repeating cycle forward and backward from it. Only used when the active anchor timeframe is 1m (set by Anchor Timeframe Selection / Anchor Timeframe (Manual)); the other timeframes' anchors are ignored. Choose a real swing pivot you can identify on the chart, and re-check it if you change this section's ZigZag Period, since a different Period may produce different pivots.")
pc_last_verified_leg_1m = input.int(1, "", minval = 1, maxval = 5, group = pc_grp_leg, inline = 'pc1M',
     tooltip = "Phase number (1-5) assigned to the 1M anchor pivot above. Neighboring pivots continue the repeating 1-2-3-4-5 cycle in both directions (older pivots count down, newer ones count up, wrapping from 5 back to 1), and newly confirmed pivots keep extending the count automatically. Only used when the active anchor timeframe is 1m.")
 
pc_f_tfMatches(sel) =>
    switch sel
        "1h" => timeframe.isintraday and timeframe.multiplier == 60
        "4h" => timeframe.isintraday and timeframe.multiplier == 240
        "1d" => timeframe.isdaily and timeframe.multiplier == 1
        "1w" => timeframe.isweekly and timeframe.multiplier == 1
        "1m" => timeframe.ismonthly and timeframe.multiplier == 1
        => false
 
pc_f_detectTf() =>
    timeframe.isintraday and timeframe.multiplier == 60 ? "1h" :
     timeframe.isintraday and timeframe.multiplier == 240 ? "4h" :
     timeframe.isdaily and timeframe.multiplier == 1 ? "1d" :
     timeframe.isweekly and timeframe.multiplier == 1 ? "1w" :
     timeframe.ismonthly and timeframe.multiplier == 1 ? "1m" :
     "none"
 
pc_anchor_tf_mode = input.string("Automatic", "Anchor Timeframe Selection", options = ["Manual", "Automatic"], group = pc_grp_leg,
     tooltip = "Manual: the 'Anchor Timeframe' picker below chooses which saved anchor/leg# setup is active, regardless of what timeframe the chart is actually on — this section only displays when the chart happens to match your pick. Automatic: the script detects the chart's current timeframe itself and switches to that timeframe's saved anchor/leg# automatically, so the same indicator instance keeps working as you flip between 1h/4h/1d/1w/1m charts with no manual switching. On a timeframe outside those 5 presets, Automatic has no saved anchor to use and this section stays silent, same as an unmatched Manual pick.")
pc_anchor_tf_manual = input.string("1h", "Anchor Timeframe (Manual)", options = ["1h", "4h", "1d", "1w", "1m"], group = pc_grp_leg,
     tooltip = "Only used when Anchor Timeframe Selection above is set to Manual. The chart timeframe this anchor/leg-numbering setup was built for. Picking a timeframe here selects which anchor time above is active, and this section (labels + anchor marker) only displays when the chart is actually on this timeframe — so the same indicator instance stays silent and uncluttered on every other timeframe instead of numbering pivots that don't correspond to this setup.")
 
pc_detected_tf = pc_f_detectTf()
pc_anchor_tf = pc_anchor_tf_mode == "Automatic" ? pc_detected_tf : pc_anchor_tf_manual
 
pc_anchor_time = switch pc_anchor_tf
    "1h" => pc_anchor_time_1h
    "4h" => pc_anchor_time_4h
    "1d" => pc_anchor_time_1d
    "1w" => pc_anchor_time_1w
    "1m" => pc_anchor_time_1m
    => pc_anchor_time_1h
 
pc_tf_matches = pc_f_tfMatches(pc_anchor_tf)
 
pc_last_verified_leg = switch pc_anchor_tf
    "1h" => pc_last_verified_leg_1h
    "4h" => pc_last_verified_leg_4h
    "1d" => pc_last_verified_leg_1d
    "1w" => pc_last_verified_leg_1w
    "1m" => pc_last_verified_leg_1m
    => pc_last_verified_leg_1h
 
pc_show_anchor_marker = input.bool(true, "Mark Anchor Pivot", group = pc_grp_leg,
     tooltip = "Draws a small ⚓ marker on the pivot that was snapped to as the anchor, so you can confirm the right point was picked.")
pc_char_style = input.string("①②③④⑤", "Numbering Style", options = ["①②③④⑤", "❶❷❸❹❺", "Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ", "1️⃣2️⃣3️⃣4️⃣5️⃣", "₍₁₎ ₍₂₎ ₍₃₎ ₍₄₎ ₍₅₎", "⑴ ⑵ ⑶ ⑷ ⑸"], group = pc_grp_leg,
     tooltip = "Glyph set used for phase numbers 1-5 on the chart labels. Some sets (especially the keycap style and the subscript / parenthesized styles) render at different sizes or shapes depending on your OS, browser and font, so pick the one that looks best on your setup.")
pc_size_choice = input.string("Huge", "Label Size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = pc_grp_leg,
     tooltip = "Size (Tiny to Huge) of the phase-number labels drawn on the chart.")
 
pc_auto_dir_color = input.bool(true, "Auto-Color by Leg Direction", group = pc_grp_leg,
     tooltip = "When enabled, each label's background and text use the Bullish/Bearish Label colors set below, based on whether that leg's price rose or fell from the prior one (background shown faded per the Fade % below). Disable to use the custom colors below instead.")
pc_label_bull_color = input.color(color.rgb(0, 137, 123), 'Bullish Label Color', inline = 'pclblcol', group = pc_grp_leg,
     tooltip = "Color for bullish phases (legs that rise from their pivot to the next). Colors the number label text and its faded background when Auto-Color by Leg Direction is on. Pairs with the Bearish Label Color to its right.")
pc_label_bear_color = input.color(color.rgb(255, 153, 0), 'Bearish Label Color', inline = 'pclblcol', group = pc_grp_leg,
     tooltip = "Color for bearish phases (legs that fall from their pivot to the next). Colors the number label text and its faded background when Auto-Color by Leg Direction is on. Pairs with the Bullish Label Color to its left.")
pc_manual_bg_color = input.color(color.rgb(54, 58, 69, 50), "Custom Label Background Color", group = pc_grp_leg,
     tooltip = "Background color of the number labels when Auto-Color by Leg Direction is off. Label Background Fade % below is applied on top and overrides any transparency set in this color picker.")
pc_manual_txt_color = input.color(color.rgb(255, 255, 255, 50), "Custom Label Text Color", group = pc_grp_leg,
     tooltip = "Text color of the number labels when Auto-Color by Leg Direction is off. Any transparency set in this color picker is kept as-is.")
pc_bg_fade_pct = input.int(90, "Label Background Fade %", minval = 0, maxval = 100, group = pc_grp_leg,
     tooltip = "Transparency of the number label background: 0 is fully opaque, 100 is fully transparent (only the number glyph shows). Applies to both the automatic direction colors and the custom background color, overriding the transparency of the picked color.")
pc_label_pos = input.string("Leg Midpoint", "Label Position", options = ["Pivot", "Leg Midpoint"], group = pc_grp_leg,
     tooltip = "Pivot: label sits on the pivot point itself (original behavior). Leg Midpoint: label sits halfway (in both time and price) along the leg this pivot starts — the leg connecting it to the next numbered pivot. The newest numbered label tracks the leg's live in-progress endpoint until that leg is confirmed, so it walks smoothly toward the eventual midpoint instead of jumping once the leg freezes.")
 
pc_lbl_size = pc_f_labelSize(pc_size_choice)
 
pc_f_legChar(num, style) =>
    style1 = array.from("①", "②", "③", "④", "⑤")
    style2 = array.from("❶", "❷", "❸", "❹", "❺")
    style3 = array.from("Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ")
    style4 = array.from("1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣")
    style5 = array.from("₍₁₎", "₍₂₎", "₍₃₎", "₍₄₎", "₍₅₎")
    style6 = array.from("⑴", "⑵", "⑶", "⑷", "⑸")
    chosen = style == "①②③④⑤" ? style1 : style == "❶❷❸❹❺" ? style2 : style == "Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ" ? style3 : style == "1️⃣2️⃣3️⃣4️⃣5️⃣" ? style4 : style == "₍₁₎ ₍₂₎ ₍₃₎ ₍₄₎ ₍₅₎" ? style5 : style6
    array.get(chosen, num - 1)
 
var array<int>   pc_leg_bar_arr   = array.new_int(0)
var array<float> pc_leg_price_arr = array.new_float(0)
var array<int>   pc_leg_num_arr   = array.new_int(0)
 
var bool  pc_seeded             = false
var int   pc_last_recorded_bar  = na
var int   pc_last_assigned_num  = na
var label pc_anchor_label       = na
var int   pc_anchor_bar_saved   = na
var float pc_anchor_price_saved = na
var bool  pc_anchor_is_high     = false
 
if barstate.islast and not pc_seeded and array.size(pc_z) >= 4
    pc_num_pairs = int(array.size(pc_z) / 2)
 
    pc_anchor_idx = 2
    pc_best_diff = float(na)
    for i = 1 to pc_num_pairs - 1
        pc_t = array.get(pc_z, i * 2 + 1)
        pc_diff = math.abs(pc_t - pc_anchor_time)
        if na(pc_best_diff) or pc_diff < pc_best_diff
            pc_best_diff := pc_diff
            pc_anchor_idx := i * 2
 
    pc_neighbor_idx = pc_anchor_idx + 2 <= array.size(pc_z) - 2 ? pc_anchor_idx + 2 : (pc_anchor_idx - 2 >= 0 ? pc_anchor_idx - 2 : pc_anchor_idx)
    pc_anchor_is_high := array.get(pc_z, pc_anchor_idx) > array.get(pc_z, pc_neighbor_idx)
 
    for idx = (pc_num_pairs - 1) * 2 to 2 by 2
        pc_num = 0
        if idx > pc_anchor_idx
            pc_step_back = int((idx - pc_anchor_idx) / 2)
            pc_num := ((pc_last_verified_leg - 1 - pc_step_back) % 5 + 5) % 5 + 1
        else
            pc_step_fwd = int((pc_anchor_idx - idx) / 2)
            pc_num := (pc_last_verified_leg - 1 + pc_step_fwd) % 5 + 1
        array.push(pc_leg_bar_arr, int(array.get(pc_z, idx + 1)))
        array.push(pc_leg_price_arr, array.get(pc_z, idx))
        array.push(pc_leg_num_arr, pc_num)
 
    pc_anchor_bar_saved := int(array.get(pc_z, pc_anchor_idx + 1))
    pc_anchor_price_saved := array.get(pc_z, pc_anchor_idx)
 
    pc_last_recorded_bar := int(array.get(pc_z, 3))
    pc_last_assigned_num := array.get(pc_leg_num_arr, array.size(pc_leg_num_arr) - 1)
    pc_seeded := true
 
if pc_seeded and array.size(pc_z) >= 4
    pc_frozen_bar = int(array.get(pc_z, 3))
    if pc_frozen_bar != pc_last_recorded_bar
        pc_frozen_px = array.get(pc_z, 2)
        pc_next_num = pc_last_assigned_num % 5 + 1
        array.push(pc_leg_bar_arr, pc_frozen_bar)
        array.push(pc_leg_price_arr, pc_frozen_px)
        array.push(pc_leg_num_arr, pc_next_num)
        pc_last_assigned_num := pc_next_num
        pc_last_recorded_bar := pc_frozen_bar
 
var array<label> pc_leg_labels = array.new_label()
if barstate.islast
    while array.size(pc_leg_labels) > 0
        label.delete(array.pop(pc_leg_labels))
    label.delete(pc_anchor_label)
    pc_anchor_label := na
 
    if pc_tf_matches
        if array.size(pc_leg_num_arr) > 0
            pc_last_leg_i = array.size(pc_leg_num_arr) - 1
            for i = 0 to pc_last_leg_i
                pc_bx  = array.get(pc_leg_bar_arr, i)
                pc_px  = array.get(pc_leg_price_arr, i)
                pc_num2 = array.get(pc_leg_num_arr, i)
 
                pc_dir_color = i == pc_last_leg_i ? pc_label_bull_color : (array.get(pc_leg_price_arr, i + 1) > pc_px ? pc_label_bull_color : pc_label_bear_color)
                pc_bg_col  = pc_auto_dir_color ? color.new(pc_dir_color, pc_bg_fade_pct) : color.new(pc_manual_bg_color, pc_bg_fade_pct)
                pc_txt_col = pc_auto_dir_color ? pc_dir_color : pc_manual_txt_color
 
                pc_next_x = i < pc_last_leg_i ? array.get(pc_leg_bar_arr, i + 1) : time
                pc_next_y = i < pc_last_leg_i ? array.get(pc_leg_price_arr, i + 1) : close
                pc_lbl_x = pc_label_pos == "Leg Midpoint" ? int(math.round((pc_bx + pc_next_x) / 2.0)) : pc_bx
                pc_lbl_y = pc_label_pos == "Leg Midpoint" ? (pc_px + pc_next_y) / 2.0 : pc_px
 
                pc_lbl = label.new(pc_lbl_x, pc_lbl_y, pc_f_legChar(pc_num2, pc_char_style),
                     xloc = xloc.bar_time,
                     style = label.style_label_center,
                     color = pc_bg_col,
                     textcolor = pc_txt_col,
                     size = pc_lbl_size)
                array.push(pc_leg_labels, pc_lbl)
 
        if pc_show_anchor_marker and not na(pc_anchor_bar_saved)
            pc_anchor_buf = ta.atr(20) * 2
            pc_anchor_y = pc_anchor_is_high ? pc_anchor_price_saved + pc_anchor_buf : pc_anchor_price_saved - pc_anchor_buf
            pc_anchor_style = pc_anchor_is_high ? label.style_label_down : label.style_label_up
            pc_anchor_label := label.new(pc_anchor_bar_saved, pc_anchor_y, "⚓" + str.tostring(pc_last_verified_leg) + " " + pc_anchor_tf,
                 xloc = xloc.bar_time,
                 style = pc_anchor_style,
                 color = color.new(color.blue, 0),
                 textcolor = color.white,
                 size = size.small)
 
var array<line> pc_current_leg_lines = array.new_line()
var array<label> pc_current_leg_markers = array.new_label()
var float pc_last_pivot_y = na
var int pc_last_pivot_x = na
if array.size(pc_z) >= 2
    while array.size(pc_current_leg_lines) > 0
        line.delete(array.pop(pc_current_leg_lines))
    while array.size(pc_current_leg_markers) > 0
        label.delete(array.pop(pc_current_leg_markers))
    pc_last_pivot_y := array.get(pc_z, 0)
    pc_last_pivot_x := int(array.get(pc_z, 1))
    pc_live_leg_color = close > pc_last_pivot_y ? pc_bull_color : pc_bear_color
    pc_f_drawLeg(pc_current_leg_lines, pc_last_pivot_x, pc_last_pivot_y, time, close, pc_live_leg_color, pc_width, pc_active_leg_style)
 
    if pc_show_leg_markers
        pc_marker_size = pc_f_labelSize(pc_marker_size_choice)
        pc_start_marker = label.new(pc_last_pivot_x, pc_last_pivot_y, "◯",
             xloc = xloc.bar_time,
             style = label.style_label_center,
             color = color.new(color.white, 100),
             textcolor = pc_live_leg_color,
             size = pc_marker_size)
        pc_end_marker = label.new(time, close, "◯",
             xloc = xloc.bar_time,
             style = label.style_label_center,
             color = color.new(color.white, 100),
             textcolor = pc_live_leg_color,
             size = pc_marker_size)
        array.push(pc_current_leg_markers, pc_start_marker)
        array.push(pc_current_leg_markers, pc_end_marker)
 
var int pc_current_direction = 0
var float pc_current_length = 0.0
var float pc_current_slope = 0.0
if not na(pc_last_pivot_x)
    pc_current_direction := close > pc_last_pivot_y ? 1 : -1
    pc_current_length := math.abs(close - pc_last_pivot_y)
    pc_dx = math.max(1.0, float(time - pc_last_pivot_x))
    pc_current_slope := (close - pc_last_pivot_y) / pc_dx
 
var line pc_extension_line1 = na
var line pc_extension_line2 = na
if array.size(pc_z) >= 2 and pc_show_projection and not na(pc_current_slope)
    line.delete(pc_extension_line1)
    line.delete(pc_extension_line2)
    pc_start_x = time
    pc_start_y = close
    pc_ms_per_bar = timeframe.in_seconds() * 1000
    pc_max_future_ms = 500 * pc_ms_per_bar
    pc_max_x = pc_start_x + pc_max_future_ms
    pc_last_zigzag_length = pc_current_length
    pc_projection_length1 = pc_current_direction == 1 ? (pc_avg_bullish_length > pc_last_zigzag_length ? pc_avg_bullish_length - pc_last_zigzag_length : 0) : (pc_avg_bearish_length > pc_last_zigzag_length ? pc_avg_bearish_length - pc_last_zigzag_length : 0)
    pc_abs_slope_current = math.max(1e-10, math.abs(pc_current_slope))
    pc_proj_line_style = pc_proj_style == 'Solid' ? line.style_solid : pc_proj_style == 'Dashed' ? line.style_dashed : line.style_dotted
    if pc_projection_length1 > 0
        pc_raw_dx1 = int(math.round(pc_projection_length1 / pc_abs_slope_current))
        pc_dx1 = math.max(1, math.min(pc_raw_dx1, pc_max_x - pc_start_x))
        pc_end_x1 = pc_start_x + pc_dx1
        pc_end_y1 = pc_start_y + pc_current_slope * pc_dx1
        pc_seg1_color = pc_current_direction == 1 ? pc_proj_bull_color : pc_proj_bear_color
        pc_extension_line1 := line.new(x1 = pc_start_x, y1 = pc_start_y, x2 = pc_end_x1, y2 = pc_end_y1, xloc = xloc.bar_time, extend = extend.none, color = pc_seg1_color, width = pc_proj_width, style = pc_proj_line_style)
        pc_projection_length2 = pc_current_direction == 1 ? pc_avg_bearish_length : pc_avg_bullish_length
        pc_projection_slope2 = pc_current_direction == 1 ? pc_avg_bearish_slope : pc_avg_bullish_slope
        pc_abs_slope2 = math.max(1e-10, math.abs(pc_projection_slope2))
        pc_raw_dx2 = int(math.round(pc_projection_length2 / pc_abs_slope2))
        pc_dx2 = math.max(1, math.min(pc_raw_dx2, pc_max_x - pc_end_x1))
        pc_end_x2 = pc_end_x1 + pc_dx2
        pc_end_y2 = pc_end_y1 + pc_projection_slope2 * pc_dx2
        pc_seg2_color = pc_current_direction == 1 ? pc_proj_bear_color : pc_proj_bull_color
        pc_extension_line2 := line.new(x1 = pc_end_x1, y1 = pc_end_y1, x2 = pc_end_x2, y2 = pc_end_y2, xloc = xloc.bar_time, extend = extend.none, color = pc_seg2_color, width = pc_proj_width, style = pc_proj_line_style)
    else
        pc_projection_length2 = pc_current_direction == 1 ? pc_avg_bearish_length : pc_avg_bullish_length
        pc_projection_slope2 = pc_current_direction == 1 ? pc_avg_bearish_slope : pc_avg_bullish_slope
        pc_abs_slope2 = math.max(1e-10, math.abs(pc_projection_slope2))
        pc_raw_dx2 = int(math.round(pc_projection_length2 / pc_abs_slope2))
        pc_dx2 = math.max(1, math.min(pc_raw_dx2, pc_max_x - pc_start_x))
        pc_end_x2 = pc_start_x + pc_dx2
        pc_end_y2 = pc_start_y + pc_projection_slope2 * pc_dx2
        pc_seg2_color = pc_current_direction == 1 ? pc_proj_bear_color : pc_proj_bull_color
        pc_extension_line2 := line.new(x1 = pc_start_x, y1 = pc_start_y, x2 = pc_end_x2, y2 = pc_end_y2, xloc = xloc.bar_time, extend = extend.none, color = pc_seg2_color, width = pc_proj_width, style = pc_proj_line_style)
 
////////////////////////////////////////////////////////////////////////////
////  END SECTION 4 — PHASE COUNTER + ADAPTIVE PROJECTION                ///
////////////////////////////////////////////////////////////////////////////
 
//EOF

← 返回列表