Auto Fib Extension - Confirmed A-B-C [AFD]

AuctionFoundry · study · 900 行 · 点赞 651 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Auction Foundry
 
//@version=6
indicator(
    title = "Auto Fib Extension - Confirmed A-B-C [AFD]",
    shorttitle = "Auto Fib Ext [AFD]",
    overlay = true,
    max_bars_back = 500,
    max_lines_count = 150,
    max_labels_count = 60,
    behind_chart = false
)
 
// Constants and tooltip copy
 
const string GROUP_SETUP = "01 · Setup"
const string GROUP_LEVELS = "02 · Levels & Colors"
const string GROUP_HTF = "03 · Higher Timeframes"
const string GROUP_STYLE = "04 · Display"
const string GROUP_PANEL = "05 · Status Panel"
const string GROUP_ALERTS = "06 · Alerts"
 
const string SIZE_SMALL = "Small"
const string SIZE_MEDIUM = "Medium"
const string SIZE_LARGE = "Large"
const string SIZE_CUSTOM = "Custom"
 
const string DIRECTION_BOTH = "Both"
const string DIRECTION_BULL = "Bullish"
const string DIRECTION_BEAR = "Bearish"
 
const string STYLE_SOLID = "Solid"
const string STYLE_DASHED = "Dashed"
const string STYLE_DOTTED = "Dotted"
 
const string GLOW_SOFT = "Soft"
const string GLOW_MEDIUM = "Medium"
const string GLOW_STRONG = "Strong"
 
const string LABEL_TINY = "Tiny"
const string LABEL_SMALL = "Small"
const string LABEL_NORMAL = "Normal"
 
const string SIDE_RIGHT = "Right"
const string SIDE_LEFT = "Left"
 
const string TEXT_RATIO = "Ratio"
const string TEXT_RATIO_PRICE = "Ratio + Price"
const string TEXT_PRICE = "Price"
 
const string PANEL_BOTTOM_CENTER = "Bottom Center"
const string PANEL_BOTTOM_LEFT = "Bottom Left"
const string PANEL_TOP_RIGHT = "Top Right"
const string PANEL_TOP_LEFT = "Top Left"
const string PANEL_MIDDLE_RIGHT = "Middle Right"
 
const int LEVEL_COUNT = 7
const int PRESET_ATR_LENGTH = 21
const int HTF_ALIGNMENT_KEYS = 500
const int MAX_OVERLAP_ZONES = 6
const int CHART_ATR_LENGTH = 14
 
const int STATE_PENDING = 0
const int STATE_ACTIVE = 1
const int STATE_INVALIDATED = 2
const int STATE_REPLACED = 3
 
const string TOOLTIP_SIZE = "• Which swings count as A-B-C legs\n• Small: 3 bars · 0.65 ATR · 15% eff.\n• Medium: 5 bars · 1.00 ATR · 20% eff.\n• Large: 7 bars · 1.25 ATR · 25% eff.\n• Custom: the three fields below"
const string TOOLTIP_STRENGTH = "• Custom Swing Size only\n• Bars on each side of a pivot\n• A pivot confirms this many bars later"
const string TOOLTIP_MIN_LEG = "• Custom Swing Size only\n• Smallest A→B move, in ATR(21)\n• 0 = off"
const string TOOLTIP_MIN_EFFICIENCY = "• Custom Swing Size only\n• A→B move ÷ sum of true ranges A→B\n• Higher rejects choppier legs"
const string TOOLTIP_DEPTH = "• C's pullback as a share of A→B\n• Max stays below 1: C never passes A"
const string TOOLTIP_DIRECTION = "• Both, bullish only or bearish only\n• Bullish: low A, high B, higher low C"
const string TOOLTIP_PAST = "• Older projections kept, faded\n• Each stops where it ended"
const string TOOLTIP_LEVEL = "• Show, ratio and color\n• Level = C + (B − A) × ratio\n• HTF layers use the same ratios"
const string TOOLTIP_BAND = "• Shades between two ratios\n• Live chart projection only\n• Off when an end is past Hide Levels"
const string TOOLTIP_LABEL_TEXT = "• Ratio, ratio + price, or price\n• ✓ = reached after C confirmed"
const string TOOLTIP_HIDE_BEYOND = "• Skips levels farther than this from\n  the last close, in ATR(14)\n• ✓, panel and alerts still count them\n• The live chart layer always keeps\n  one level; HTF layers do not\n• 0 = draw every level"
const string TOOLTIP_HTF = "• Same A-B-C rules on a higher TF\n• Chart, or not above the chart: next\n  step of 5m 15m 1H 4H D W M\n• HTF 2 equal to HTF 1 moves one step up\n• Off on range, Renko, tick and other\n  non-time charts\n• No ladder step above M: panel says\n  No higher TF\n• Updates when its HTF bar closes\n• Reached/invalid on closed chart bars"
const string TOOLTIP_HTF_STYLE = "• Line style of both HTF layers"
const string TOOLTIP_OVERLAP = "• Marks chart and HTF levels that sit\n  close together\n• Closest 6 pairs, live levels only"
const string TOOLTIP_TOLERANCE = "• How close counts as overlap\n• ATR(14) of the chart, min 2 ticks"
const string TOOLTIP_GLOW = "• Soft halo under live levels\n• Strength sets width and fade"
const string TOOLTIP_EXTEND = "• Bars live levels run past the last bar"
const string TOOLTIP_LABEL_SIZE = "• Level labels; A/B/C tags one size up"
const string TOOLTIP_LABEL_SIDE = "• Right: chart labels at line end\n• Left: chart labels at line start\n• HTF labels take the other end"
const string TOOLTIP_TINT = "• Chart tags: green bullish, red bearish\n• Off: grey; HTF tags keep layer color\n• Needs Show A-B-C Legs"
const string TOOLTIP_PRICE_TAGS = "• Live chart level prices on the scale\n• Follows level visibility and\n  Hide Levels Beyond"
const string TOOLTIP_PANEL = "• One row per layer that is on\n• C Retrace: C's pullback as a Fib of A→B\n• Fib(s) Hit: enabled levels reached\n  after C confirmed\n• Next Fib: lowest enabled ratio not hit\n• To Next Fib: price distance from\n  last close to that level (chart's\n  price units, not ticks)\n• Pending: B not yet cleared\n• Active: a close beyond B\n• Invalidated: a close beyond C"
const string TOOLTIP_PANEL_POSITION = "• Bottom Right is left out: TradingView\n  draws a badge there"
const string TOOLTIP_NEAR = "• Once per level, when a close comes\n  within this many ATR(14) of it\n• Levels not yet reached only"
const string TOOLTIP_ALERTS = "• On: HTF events join the alerts\n• Off: chart layer only\n• Use one 'Any alert() function call'\n  alert; one message per bar close"
const string TOOLTIP_LINE_STYLE = "• Chart-layer level lines\n• HTF layers use HTF Line Style"
const string TOOLTIP_LINE_WIDTH = "• Level lines on every layer\n• Glow adds its halo to this width"
const string TOOLTIP_LEGS = "• Dotted A→B and B→C lines\n• Off also hides the A, B and C tags"
const string TOOLTIP_PANEL_SIZE = "• Text size of the status panel"
const string TOOLTIP_ALERT_NEW = "• A new A-B-C, once its C confirms"
const string TOOLTIP_ALERT_CLEARED = "• First close beyond B"
const string TOOLTIP_ALERT_LEVEL = "• A bar's high or low touches an\n  enabled level not yet reached"
const string TOOLTIP_ALERT_INVALID = "• A close beyond C; its levels stop"
 
color LEG_COLOR = #CFD8DC
color PAST_COLOR = #78909C
color BULL_COLOR = #22C55E
color BEAR_COLOR = #EF4444
color BULL_TAG_COLOR = #66BB6A
color BEAR_TAG_COLOR = #E57373
 
// Inputs
 
string swingSizeInput = input.string(SIZE_MEDIUM, "Swing Size", options = [SIZE_SMALL, SIZE_MEDIUM, SIZE_LARGE, SIZE_CUSTOM], tooltip = TOOLTIP_SIZE, group = GROUP_SETUP, display = display.none)
int pivotStrengthInput = input.int(7, "Custom Pivot Strength", minval = 2, maxval = 50, tooltip = TOOLTIP_STRENGTH, group = GROUP_SETUP, display = display.none)
float minimumLegInput = input.float(1.25, "Custom Minimum Leg (ATR)", minval = 0.0, maxval = 20.0, step = 0.05, tooltip = TOOLTIP_MIN_LEG, group = GROUP_SETUP, display = display.none)
float minimumEfficiencyInput = input.float(0.25, "Custom Minimum Efficiency", minval = 0.0, maxval = 1.0, step = 0.05, tooltip = TOOLTIP_MIN_EFFICIENCY, group = GROUP_SETUP, display = display.none)
float depthMinimumInput = input.float(0.236, "C Depth (min, max)", minval = 0.0, maxval = 0.99, step = 0.001, inline = "depth", group = GROUP_SETUP, display = display.none)
float depthMaximumInput = input.float(0.886, "", minval = 0.0, maxval = 0.99, step = 0.001, tooltip = TOOLTIP_DEPTH, inline = "depth", group = GROUP_SETUP, display = display.none)
string directionInput = input.string(DIRECTION_BOTH, "Direction", options = [DIRECTION_BOTH, DIRECTION_BULL, DIRECTION_BEAR], tooltip = TOOLTIP_DIRECTION, group = GROUP_SETUP, display = display.none)
 
bool showLevel1Input = input.bool(false, "Level 1", inline = "level1", group = GROUP_LEVELS, display = display.none)
float level1Input = input.float(0.618, "", minval = 0.0, maxval = 10.0, step = 0.001, inline = "level1", group = GROUP_LEVELS, display = display.none)
color level1ColorInput = input.color(#B0BEC5, "", tooltip = TOOLTIP_LEVEL, inline = "level1", group = GROUP_LEVELS, display = display.none)
bool showLevel2Input = input.bool(true, "Level 2", inline = "level2", group = GROUP_LEVELS, display = display.none)
float level2Input = input.float(1.000, "", minval = 0.0, maxval = 10.0, step = 0.001, inline = "level2", group = GROUP_LEVELS, display = display.none)
color level2ColorInput = input.color(#4FC3F7, "", tooltip = TOOLTIP_LEVEL, inline = "level2", group = GROUP_LEVELS, display = display.none)
bool showLevel3Input = input.bool(true, "Level 3", inline = "level3", group = GROUP_LEVELS, display = display.none)
float level3Input = input.float(1.272, "", minval = 0.0, maxval = 10.0, step = 0.001, inline = "level3", group = GROUP_LEVELS, display = display.none)
color level3ColorInput = input.color(#81C784, "", tooltip = TOOLTIP_LEVEL, inline = "level3", group = GROUP_LEVELS, display = display.none)
bool showLevel4Input = input.bool(true, "Level 4", inline = "level4", group = GROUP_LEVELS, display = display.none)
float level4Input = input.float(1.618, "", minval = 0.0, maxval = 10.0, step = 0.001, inline = "level4", group = GROUP_LEVELS, display = display.none)
color level4ColorInput = input.color(#FFD54F, "", tooltip = TOOLTIP_LEVEL, inline = "level4", group = GROUP_LEVELS, display = display.none)
bool showLevel5Input = input.bool(false, "Level 5", inline = "level5", group = GROUP_LEVELS, display = display.none)
float level5Input = input.float(2.000, "", minval = 0.0, maxval = 10.0, step = 0.001, inline = "level5", group = GROUP_LEVELS, display = display.none)
color level5ColorInput = input.color(#FFB74D, "", tooltip = TOOLTIP_LEVEL, inline = "level5", group = GROUP_LEVELS, display = display.none)
bool showLevel6Input = input.bool(true, "Level 6", inline = "level6", group = GROUP_LEVELS, display = display.none)
float level6Input = input.float(2.618, "", minval = 0.0, maxval = 10.0, step = 0.001, inline = "level6", group = GROUP_LEVELS, display = display.none)
color level6ColorInput = input.color(#FF8A65, "", tooltip = TOOLTIP_LEVEL, inline = "level6", group = GROUP_LEVELS, display = display.none)
bool showLevel7Input = input.bool(false, "Level 7", inline = "level7", group = GROUP_LEVELS, display = display.none)
float level7Input = input.float(3.618, "", minval = 0.0, maxval = 10.0, step = 0.001, inline = "level7", group = GROUP_LEVELS, display = display.none)
color level7ColorInput = input.color(#F06292, "", tooltip = TOOLTIP_LEVEL, inline = "level7", group = GROUP_LEVELS, display = display.none)
bool showBandInput = input.bool(true, "Highlight Band", inline = "band", group = GROUP_LEVELS, display = display.none)
float bandFromInput = input.float(1.272, "", minval = 0.0, maxval = 10.0, step = 0.001, inline = "band", group = GROUP_LEVELS, display = display.none)
float bandToInput = input.float(1.618, "", minval = 0.0, maxval = 10.0, step = 0.001, inline = "band", group = GROUP_LEVELS, display = display.none)
color bandColorInput = input.color(color.new(#FFD54F, 88), "", tooltip = TOOLTIP_BAND, inline = "band", group = GROUP_LEVELS, display = display.none)
string labelTextInput = input.string(TEXT_RATIO, "Label Text", options = [TEXT_RATIO, TEXT_RATIO_PRICE, TEXT_PRICE], tooltip = TOOLTIP_LABEL_TEXT, group = GROUP_LEVELS, display = display.none)
float hideBeyondInput = input.float(10.0, "Hide Levels Beyond (ATR)", minval = 0.0, maxval = 100.0, step = 0.5, tooltip = TOOLTIP_HIDE_BEYOND, group = GROUP_LEVELS, display = display.none)
 
bool showHtf1Input = input.bool(true, "HTF 1", inline = "htf1", group = GROUP_HTF, display = display.none)
string htf1TimeframeInput = input.timeframe("", "", inline = "htf1", group = GROUP_HTF, display = display.none)
color htf1ColorInput = input.color(#B39DDB, "", tooltip = TOOLTIP_HTF, inline = "htf1", group = GROUP_HTF, display = display.none)
bool showHtf2Input = input.bool(true, "HTF 2", inline = "htf2", group = GROUP_HTF, display = display.none)
string htf2TimeframeInput = input.timeframe("240", "", inline = "htf2", group = GROUP_HTF, display = display.none)
color htf2ColorInput = input.color(#4DD0E1, "", tooltip = TOOLTIP_HTF, inline = "htf2", group = GROUP_HTF, display = display.none)
string htfLineStyleInput = input.string(STYLE_DASHED, "HTF Line Style", options = [STYLE_SOLID, STYLE_DASHED, STYLE_DOTTED], tooltip = TOOLTIP_HTF_STYLE, group = GROUP_HTF, display = display.none)
bool showOverlapInput = input.bool(true, "HTF Overlap", inline = "overlap", group = GROUP_HTF, display = display.none)
color overlapColorInput = input.color(#FF4081, "", tooltip = TOOLTIP_OVERLAP, inline = "overlap", group = GROUP_HTF, display = display.none)
float overlapToleranceInput = input.float(0.25, "Overlap Tolerance (ATR)", minval = 0.0, maxval = 2.0, step = 0.05, tooltip = TOOLTIP_TOLERANCE, group = GROUP_HTF, display = display.none)
 
string lineStyleInput = input.string(STYLE_SOLID, "Line Style", options = [STYLE_SOLID, STYLE_DASHED, STYLE_DOTTED], tooltip = TOOLTIP_LINE_STYLE, group = GROUP_STYLE, display = display.none)
int lineWidthInput = input.int(1, "Line Width", minval = 1, maxval = 4, tooltip = TOOLTIP_LINE_WIDTH, group = GROUP_STYLE, display = display.none)
bool glowInput = input.bool(true, "Glow", inline = "glow", group = GROUP_STYLE, display = display.none)
string glowStrengthInput = input.string(GLOW_MEDIUM, "", options = [GLOW_SOFT, GLOW_MEDIUM, GLOW_STRONG], tooltip = TOOLTIP_GLOW, inline = "glow", group = GROUP_STYLE, display = display.none)
int extendRightInput = input.int(30, "Extend Right (bars)", minval = 0, maxval = 300, tooltip = TOOLTIP_EXTEND, group = GROUP_STYLE, display = display.none)
string labelSizeInput = input.string(LABEL_SMALL, "Label Size", options = [LABEL_TINY, LABEL_SMALL, LABEL_NORMAL], tooltip = TOOLTIP_LABEL_SIZE, group = GROUP_STYLE, display = display.none)
string labelSideInput = input.string(SIDE_RIGHT, "Label Position", options = [SIDE_RIGHT, SIDE_LEFT], tooltip = TOOLTIP_LABEL_SIDE, group = GROUP_STYLE, display = display.none)
bool showLegsInput = input.bool(true, "Show A-B-C Legs", tooltip = TOOLTIP_LEGS, group = GROUP_STYLE, display = display.none)
bool tintTagsInput = input.bool(true, "Direction-Tinted Tags", tooltip = TOOLTIP_TINT, group = GROUP_STYLE, display = display.none)
int pastProjectionsInput = input.int(0, "Past Projections", minval = 0, maxval = 5, tooltip = TOOLTIP_PAST, group = GROUP_STYLE, display = display.none)
bool showPriceTagsInput = input.bool(true, "Price-Scale Tags", tooltip = TOOLTIP_PRICE_TAGS, group = GROUP_STYLE, display = display.none)
 
bool showPanelInput = input.bool(true, "Status Panel", tooltip = TOOLTIP_PANEL, group = GROUP_PANEL, display = display.none)
string panelPositionInput = input.string(PANEL_BOTTOM_CENTER, "Panel Position", options = [PANEL_BOTTOM_CENTER, PANEL_BOTTOM_LEFT, PANEL_TOP_RIGHT, PANEL_TOP_LEFT, PANEL_MIDDLE_RIGHT], tooltip = TOOLTIP_PANEL_POSITION, group = GROUP_PANEL, display = display.none)
string panelSizeInput = input.string(LABEL_SMALL, "Panel Size", options = [LABEL_TINY, LABEL_SMALL, LABEL_NORMAL], tooltip = TOOLTIP_PANEL_SIZE, group = GROUP_PANEL, display = display.none)
 
bool alertNewInput = input.bool(true, "New A-B-C", tooltip = TOOLTIP_ALERT_NEW, group = GROUP_ALERTS, display = display.none)
bool alertClearedInput = input.bool(true, "B Cleared", tooltip = TOOLTIP_ALERT_CLEARED, group = GROUP_ALERTS, display = display.none)
bool alertLevelInput = input.bool(true, "Level Reached", tooltip = TOOLTIP_ALERT_LEVEL, group = GROUP_ALERTS, display = display.none)
bool alertInvalidInput = input.bool(true, "Invalidated", tooltip = TOOLTIP_ALERT_INVALID, group = GROUP_ALERTS, display = display.none)
bool alertNearInput = input.bool(false, "Near Level (ATR)", inline = "near", group = GROUP_ALERTS, display = display.none)
float nearAtrInput = input.float(0.5, "", minval = 0.05, maxval = 5.0, step = 0.05, tooltip = TOOLTIP_NEAR, inline = "near", group = GROUP_ALERTS, display = display.none)
bool alertHtfInput = input.bool(true, "Include HTF Layers", tooltip = TOOLTIP_ALERTS, group = GROUP_ALERTS, display = display.none)
 
// Effective settings
 
int effectiveStrength = switch swingSizeInput
    SIZE_SMALL => 3
    SIZE_MEDIUM => 5
    SIZE_LARGE => 7
    => pivotStrengthInput
float effectiveMinimumLeg = switch swingSizeInput
    SIZE_SMALL => 0.65
    SIZE_MEDIUM => 1.00
    SIZE_LARGE => 1.25
    => minimumLegInput
float effectiveMinimumEfficiency = switch swingSizeInput
    SIZE_SMALL => 0.15
    SIZE_MEDIUM => 0.20
    SIZE_LARGE => 0.25
    => minimumEfficiencyInput
float effectiveDepthMinimum = math.min(depthMinimumInput, depthMaximumInput)
float effectiveDepthMaximum = math.max(depthMinimumInput, depthMaximumInput)
int directionFilter = directionInput == DIRECTION_BULL ? 1 : directionInput == DIRECTION_BEAR ? -1 : 0
 
// Types
 
type Projection
    float aPrice
    int aTime
    float bPrice
    int bTime
    float cPrice
    int cTime
    int direction
    int state = 0
    int startTime
    int cutoffTime
    array<bool> reached
    array<bool> near
 
// Pivot, geometry and color helpers
 
strictPivotHigh(int strength) =>
    float candidate = high[strength]
    bool result = not na(candidate)
    for offset = 1 to strength
        float rightNeighbor = high[strength - offset]
        float leftNeighbor = high[strength + offset]
        if na(leftNeighbor) or na(rightNeighbor) or leftNeighbor >= candidate or rightNeighbor >= candidate
            result := false
            break
    result
 
strictPivotLow(int strength) =>
    float candidate = low[strength]
    bool result = not na(candidate)
    for offset = 1 to strength
        float rightNeighbor = low[strength - offset]
        float leftNeighbor = low[strength + offset]
        if na(leftNeighbor) or na(rightNeighbor) or leftNeighbor <= candidate or rightNeighbor <= candidate
            result := false
            break
    result
 
fadeColor(color baseColor, float opacityFactor) =>
    float baseOpacity = 100.0 - color.t(baseColor)
    float boundedFactor = math.max(0.0, math.min(100.0, opacityFactor))
    color.new(baseColor, int(math.round(100.0 - baseOpacity * boundedFactor / 100.0)))
 
channelLuminance(float channel) =>
    float scaled = channel / 255.0
    scaled <= 0.04045 ? scaled / 12.92 : math.pow((scaled + 0.055) / 1.055, 2.4)
relativeLuminance(color value) =>
    0.2126 * channelLuminance(color.r(value)) + 0.7152 * channelLuminance(color.g(value)) + 0.0722 * channelLuminance(color.b(value))
contrastTextColor(color backgroundColor) =>
    float luminance = relativeLuminance(backgroundColor)
    (luminance + 0.05) / (relativeLuminance(#111827) + 0.05) >= (relativeLuminance(#F8FAFC) + 0.05) / (luminance + 0.05) ? #111827 : #F8FAFC
 
lineStyleOf(string styleName) =>
    switch styleName
        STYLE_DASHED => line.style_dashed
        STYLE_DOTTED => line.style_dotted
        => line.style_solid
 
labelSizeOf(string sizeName) =>
    switch sizeName
        LABEL_TINY => size.tiny
        LABEL_NORMAL => size.normal
        => size.small
 
tagSizeOf(string sizeName) =>
    switch sizeName
        LABEL_TINY => size.small
        LABEL_NORMAL => size.large
        => size.normal
 
panelPositionOf(string positionName) =>
    switch positionName
        PANEL_TOP_RIGHT => position.top_right
        PANEL_TOP_LEFT => position.top_left
        PANEL_MIDDLE_RIGHT => position.middle_right
        PANEL_BOTTOM_LEFT => position.bottom_left
        => position.bottom_center
 
nextHigherSeconds(int seconds) =>
    int monthSeconds = timeframe.in_seconds("M")
    seconds < 300 ? 300 : seconds < 900 ? 900 : seconds < 3600 ? 3600 : seconds < 14400 ? 14400 : seconds < 86400 ? 86400 : seconds < 604800 ? 604800 : seconds < monthSeconds ? monthSeconds : na
 
timeframeLabel(string timeframeValue) =>
    string resolved = timeframeValue == "" ? timeframe.period : timeframeValue
    int seconds = timeframe.in_seconds(resolved)
    string result = resolved
    if nz(seconds) > 0 and not str.contains(resolved, "D") and not str.contains(resolved, "W") and not str.contains(resolved, "M") and not str.contains(resolved, "S")
        int minutes = int(math.floor(seconds / 60))
        result := minutes >= 60 and minutes % 60 == 0 ? str.tostring(int(math.floor(minutes / 60))) + "H" : str.tostring(minutes) + "m"
    result
 
levelPrice(Projection projection, float ratio) =>
    math.round_to_mintick(projection.cPrice + (projection.bPrice - projection.aPrice) * ratio)
 
// A-B-C engine: one instance per call site (chart and each HTF request).
abcState(bool commit, int strength, int atrLength, float minimumLeg, float minimumEfficiency, float depthMinimum, float depthMaximum, int allowedDirection) =>
    float pathTotal = ta.cum(ta.tr(true))
    float atrValue = ta.atr(atrLength)
    bool highPivot = strictPivotHigh(strength)
    bool lowPivot = strictPivotLow(strength)
 
    var int pivotCount = 0
    var int oldSide = 0
    var float oldPrice = na
    var int oldTime = na
    var float oldPath = na
    var int midSide = 0
    var float midPrice = na
    var int midTime = na
    var float midPath = na
    var float midAtr = na
    var int newSide = 0
    var float newPrice = na
    var int newTime = na
    var float newPath = na
    var float newAtr = na
 
    var float aPrice = na
    var int aTime = na
    var float bPrice = na
    var int bTime = na
    var float cPrice = na
    var int cTime = na
    var int legDirection = 0
 
    if commit
        int eventSide = 0
        if highPivot and lowPivot
            eventSide := newSide == 1 ? -1 : newSide == -1 ? 1 : 0
        else if highPivot
            eventSide := 1
        else if lowPivot
            eventSide := -1
 
        if eventSide != 0
            float eventPrice = eventSide == 1 ? high[strength] : low[strength]
            int eventTime = time[strength]
            float eventPath = pathTotal[strength]
            float eventAtr = atrValue[strength]
            bool evaluate = false
            if pivotCount > 0 and newSide == eventSide
                bool moreExtreme = eventSide == 1 ? eventPrice > newPrice : eventPrice < newPrice
                if moreExtreme
                    newPrice := eventPrice
                    newTime := eventTime
                    newPath := eventPath
                    newAtr := eventAtr
                    evaluate := pivotCount >= 3
            else
                oldSide := midSide
                oldPrice := midPrice
                oldTime := midTime
                oldPath := midPath
                midSide := newSide
                midPrice := newPrice
                midTime := newTime
                midPath := newPath
                midAtr := newAtr
                newSide := eventSide
                newPrice := eventPrice
                newTime := eventTime
                newPath := eventPath
                newAtr := eventAtr
                pivotCount := math.min(pivotCount + 1, 3)
                evaluate := pivotCount >= 3
 
            if evaluate
                int candidateDirection = midSide == 1 ? 1 : -1
                float impulse = (midPrice - oldPrice) * candidateDirection
                float pullback = (midPrice - newPrice) * candidateDirection
                float path = math.abs(midPath - oldPath)
                bool measurable = impulse > 0.0 and pullback > 0.0 and not na(midAtr) and midAtr > 0.0 and not na(path) and path > 0.0
                float legAtr = measurable ? impulse / midAtr : na
                float efficiency = measurable ? math.min(1.0, impulse / path) : na
                float depth = measurable ? pullback / impulse : na
                bool directionAllowed = allowedDirection == 0 or allowedDirection == candidateDirection
                bool qualified = measurable and directionAllowed and legAtr >= minimumLeg and efficiency >= minimumEfficiency and depth >= depthMinimum and depth <= depthMaximum and depth < 1.0
                if qualified
                    aPrice := oldPrice
                    aTime := oldTime
                    bPrice := midPrice
                    bTime := midTime
                    cPrice := newPrice
                    cTime := newTime
                    legDirection := candidateDirection
 
    [aPrice, aTime, bPrice, bTime, cPrice, cTime, legDirection]
 
// Values from the last closed HTF bar: lookahead_on with [1].
confirmedAbcState(int strength, int atrLength, float minimumLeg, float minimumEfficiency, float depthMinimum, float depthMaximum, int allowedDirection) =>
    [aPrice, aTime, bPrice, bTime, cPrice, cTime, legDirection] = abcState(true, strength, atrLength, minimumLeg, minimumEfficiency, depthMinimum, depthMaximum, allowedDirection)
    [aPrice[1], aTime[1], bPrice[1], bTime[1], cPrice[1], cTime[1], legDirection[1]]
 
// Maps each HTF bar's open time to the chart bar that printed its high and its low.
htfAlignment(bool enabled, string requestTimeframe) =>
    var map<int, int> highTimes = map.new<int, int>()
    var map<int, int> lowTimes = map.new<int, int>()
    // A ring of the newest HTF_ALIGNMENT_KEYS bucket keys; the next slot holds the oldest. Like
    // the keys and maps (all var), the slot rolls back on each realtime tick.
    var array<int> bucketKeys = array.new_int(HTF_ALIGNMENT_KEYS)
    var array<int> ringSlot = array.from(0)
    var float bucketHigh = na
    var float bucketLow = na
    int bucketTime = enabled ? time(requestTimeframe) : na
    if enabled and not na(bucketTime)
        // A chart bar is filed under the HTF bar it opened in.
        bool bucketStart = na(bucketTime[1]) or bucketTime != bucketTime[1] or na(bucketHigh)
        if bucketStart
            bucketHigh := high
            bucketLow := low
            if not map.contains(highTimes, bucketTime)
                int slot = array.get(ringSlot, 0)
                int expiredKey = array.get(bucketKeys, slot)
                if not na(expiredKey)
                    map.remove(highTimes, expiredKey)
                    map.remove(lowTimes, expiredKey)
                array.set(bucketKeys, slot, bucketTime)
                array.set(ringSlot, 0, (slot + 1) % HTF_ALIGNMENT_KEYS)
            map.put(highTimes, bucketTime, time)
            map.put(lowTimes, bucketTime, time)
        else
            if high > bucketHigh
                bucketHigh := high
                map.put(highTimes, bucketTime, time)
            if low < bucketLow
                bucketLow := low
                map.put(lowTimes, bucketTime, time)
    [highTimes, lowTimes]
 
alignedTime(map<int, int> times, int htfTime) =>
    na(htfTime) ? na : nz(map.get(times, htfTime), htfTime)
 
directionWord(int direction) =>
    direction == 1 ? "Bullish" : "Bearish"
 
ratioText(float ratio) =>
    str.tostring(ratio, "0.###")
 
// Fractional ticks (1/32) print with the tick's own decimals.
tickDecimalsFormat() =>
    int decimals = 0
    float step = syminfo.mintick
    while decimals < 10 and math.abs(step - math.floor(step + 0.5)) > 1e-9
        step := step * 10
        decimals += 1
    decimals == 0 ? "0" : "0." + str.repeat("0", decimals)
 
priceFormatOf() =>
    float shown = str.tonumber(str.tostring(syminfo.mintick, format.mintick))
    na(shown) or math.abs(shown - syminfo.mintick) <= syminfo.mintick * 1e-6 ? format.mintick : tickDecimalsFormat()
 
var string priceFormat = priceFormatOf()
 
priceText(float price) =>
    str.tostring(price, priceFormat)
 
depthOf(Projection projection) =>
    float impulse = math.abs(projection.bPrice - projection.aPrice)
    impulse > 0.0 ? math.abs(projection.bPrice - projection.cPrice) / impulse : na
 
eventHead(string layerName, int direction) =>
    layerName + " · " + directionWord(direction) + " A-B-C · "
 
newEventText(string layerName, int direction, float aPrice, float bPrice, float cPrice) =>
    float impulse = math.abs(bPrice - aPrice)
    string depthPart = impulse > 0.0 ? " · depth " + ratioText(math.abs(bPrice - cPrice) / impulse) : ""
    eventHead(layerName, direction) + "new · A " + priceText(aPrice) + " · B " + priceText(bPrice) + " · C " + priceText(cPrice) + depthPart
 
newProjection(float aPrice, int aTime, float bPrice, int bTime, float cPrice, int cTime, int direction) =>
    Projection.new(aPrice, aTime, bPrice, bTime, cPrice, cTime, direction, STATE_PENDING, time, na, array.new_bool(LEVEL_COUNT, false), array.new_bool(LEVEL_COUNT, false))
 
stepProjection(Projection projection, array<float> ratios, array<bool> visible, string layerName, bool alertsEnabled, float nearDistance, array<string> events) =>
    if not na(projection) and na(projection.cutoffTime) and time > projection.startTime
        string head = eventHead(layerName, projection.direction)
        if projection.state == STATE_PENDING and (projection.direction == 1 ? close > projection.bPrice : close < projection.bPrice)
            projection.state := STATE_ACTIVE
            if alertsEnabled and alertClearedInput
                array.push(events, head + "B cleared at " + priceText(close))
        for levelIndex = 0 to LEVEL_COUNT - 1
            if array.get(visible, levelIndex) and not array.get(projection.reached, levelIndex)
                float ratio = array.get(ratios, levelIndex)
                float target = levelPrice(projection, ratio)
                bool touched = projection.direction == 1 ? high >= target : low <= target
                if touched
                    array.set(projection.reached, levelIndex, true)
                    if alertsEnabled and alertLevelInput
                        array.push(events, head + ratioText(ratio) + " reached at " + priceText(target))
                else if alertsEnabled and alertNearInput and not array.get(projection.near, levelIndex) and not na(nearDistance) and math.abs(close - target) <= nearDistance
                    array.set(projection.near, levelIndex, true)
                    array.push(events, head + "near " + ratioText(ratio) + " at " + priceText(target) + ", close " + priceText(close))
        bool brokeC = projection.direction == 1 ? close < projection.cPrice : close > projection.cPrice
        if brokeC
            projection.state := STATE_INVALIDATED
            projection.cutoffTime := time
            if alertsEnabled and alertInvalidInput
                array.push(events, head + "invalidated, close beyond C at " + priceText(close))
    true
 
// Engines and timeframe selection
 
var array<float> levelRatios = array.from(level1Input, level2Input, level3Input, level4Input, level5Input, level6Input, level7Input)
var array<bool> levelVisible = array.from(showLevel1Input, showLevel2Input, showLevel3Input, showLevel4Input, showLevel5Input, showLevel6Input, showLevel7Input)
var array<color> levelColors = array.from(level1ColorInput, level2ColorInput, level3ColorInput, level4ColorInput, level5ColorInput, level6ColorInput, level7ColorInput)
 
[chartA, chartATime, chartB, chartBTime, chartC, chartCTime, chartDirection] = abcState(barstate.isconfirmed, effectiveStrength, PRESET_ATR_LENGTH, effectiveMinimumLeg, effectiveMinimumEfficiency, effectiveDepthMinimum, effectiveDepthMaximum, directionFilter)
 
// Non-time charts (range, Renko, Kagi, PnF, Line Break, tick) get no HTF layers.
bool clockChart = not (chart.is_range or chart.is_renko or chart.is_kagi or chart.is_pnf or chart.is_linebreak or timeframe.isticks)
int chartSeconds = nz(timeframe.in_seconds())
// Non-time charts report a nominal period, so the bar width is the median of 50 spans.
int medianSpan = ta.median(time - time[1], 50)
int barMilliseconds = clockChart and chartSeconds > 0 ? chartSeconds * 1000 : math.max(nz(medianSpan, nz(time - time[1])), 1000)
int htf1InputSeconds = nz(timeframe.in_seconds(htf1TimeframeInput))
bool htf1AsSet = htf1InputSeconds > chartSeconds
int htf1Seconds = htf1AsSet ? htf1InputSeconds : nextHigherSeconds(chartSeconds)
int htf2InputSeconds = nz(timeframe.in_seconds(htf2TimeframeInput))
int htf2Candidate = htf2InputSeconds > chartSeconds ? htf2InputSeconds : nextHigherSeconds(chartSeconds)
bool htf2SameAsHtf1 = showHtf1Input and htf2Candidate == htf1Seconds
bool htf2AsSet = htf2InputSeconds > chartSeconds and not htf2SameAsHtf1
int htf2Seconds = htf2SameAsHtf1 ? nextHigherSeconds(htf1Seconds) : htf2Candidate
bool htf1Higher = clockChart and not na(htf1Seconds)
bool htf2Higher = clockChart and not na(htf2Seconds)
bool useHtf1 = showHtf1Input and htf1Higher
bool useHtf2 = showHtf2Input and htf2Higher
string htf1Request = not useHtf1 ? timeframe.period : htf1AsSet ? htf1TimeframeInput : timeframe.from_seconds(htf1Seconds)
string htf2Request = not useHtf2 ? timeframe.period : htf2AsSet ? htf2TimeframeInput : timeframe.from_seconds(htf2Seconds)
string htf1Name = useHtf1 ? timeframeLabel(timeframe.from_seconds(htf1Seconds)) : "HTF 1"
string htf2Name = useHtf2 ? timeframeLabel(timeframe.from_seconds(htf2Seconds)) : "HTF 2"
string chartName = clockChart ? "Chart " + timeframeLabel(timeframe.period) : "Chart"
 
[htf1A, htf1ATime, htf1B, htf1BTime, htf1C, htf1CTime, htf1Direction] = request.security(syminfo.tickerid, htf1Request, confirmedAbcState(effectiveStrength, PRESET_ATR_LENGTH, effectiveMinimumLeg, effectiveMinimumEfficiency, effectiveDepthMinimum, effectiveDepthMaximum, directionFilter), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[htf2A, htf2ATime, htf2B, htf2BTime, htf2C, htf2CTime, htf2Direction] = request.security(syminfo.tickerid, htf2Request, confirmedAbcState(effectiveStrength, PRESET_ATR_LENGTH, effectiveMinimumLeg, effectiveMinimumEfficiency, effectiveDepthMinimum, effectiveDepthMaximum, directionFilter), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
 
[htf1HighTimes, htf1LowTimes] = htfAlignment(useHtf1, htf1Request)
[htf2HighTimes, htf2LowTimes] = htfAlignment(useHtf2, htf2Request)
 
float chartAtr = ta.atr(CHART_ATR_LENGTH)
var float closedClose = na
var float closedAtr = na
if barstate.isconfirmed
    closedClose := close
    closedAtr := chartAtr
 
// Projection lifecycle, confirmed chart bars only
 
var array<Projection> chartProjections = array.new<Projection>()
var Projection htf1Projection = na
var Projection htf2Projection = na
var int lastChartCTime = na
var int lastChartBTime = na
var int lastHtf1CTime = na
var int lastHtf1BTime = na
var int lastHtf2CTime = na
var int lastHtf2BTime = na
 
if barstate.isconfirmed
    array<string> events = array.new_string()
    float nearDistance = chartAtr * nearAtrInput
    int chartCount = array.size(chartProjections)
    if chartCount > 0
        stepProjection(array.get(chartProjections, chartCount - 1), levelRatios, levelVisible, chartName, true, nearDistance, events)
    if useHtf1
        stepProjection(htf1Projection, levelRatios, levelVisible, htf1Name, alertHtfInput, nearDistance, events)
    if useHtf2
        stepProjection(htf2Projection, levelRatios, levelVisible, htf2Name, alertHtfInput, nearDistance, events)
 
    bool chartChanged = not na(chartCTime) and (na(lastChartCTime) or chartCTime != lastChartCTime or chartBTime != lastChartBTime)
    if chartChanged
        if chartCount > 0
            Projection previous = array.get(chartProjections, chartCount - 1)
            if na(previous.cutoffTime)
                previous.cutoffTime := time
                previous.state := STATE_REPLACED
        array.push(chartProjections, newProjection(chartA, chartATime, chartB, chartBTime, chartC, chartCTime, chartDirection))
        while array.size(chartProjections) > pastProjectionsInput + 1
            array.shift(chartProjections)
        lastChartCTime := chartCTime
        lastChartBTime := chartBTime
        if alertNewInput
            array.push(events, newEventText(chartName, chartDirection, chartA, chartB, chartC))
 
    bool htf1Changed = useHtf1 and not na(htf1CTime) and (na(lastHtf1CTime) or htf1CTime != lastHtf1CTime or htf1BTime != lastHtf1BTime)
    if htf1Changed
        int dir = htf1Direction
        htf1Projection := newProjection(htf1A, alignedTime(dir == 1 ? htf1LowTimes : htf1HighTimes, htf1ATime), htf1B, alignedTime(dir == 1 ? htf1HighTimes : htf1LowTimes, htf1BTime), htf1C, alignedTime(dir == 1 ? htf1LowTimes : htf1HighTimes, htf1CTime), dir)
        lastHtf1CTime := htf1CTime
        lastHtf1BTime := htf1BTime
        if alertNewInput and alertHtfInput
            array.push(events, newEventText(htf1Name, dir, htf1A, htf1B, htf1C))
 
    bool htf2Changed = useHtf2 and not na(htf2CTime) and (na(lastHtf2CTime) or htf2CTime != lastHtf2CTime or htf2BTime != lastHtf2BTime)
    if htf2Changed
        int dir = htf2Direction
        htf2Projection := newProjection(htf2A, alignedTime(dir == 1 ? htf2LowTimes : htf2HighTimes, htf2ATime), htf2B, alignedTime(dir == 1 ? htf2HighTimes : htf2LowTimes, htf2BTime), htf2C, alignedTime(dir == 1 ? htf2LowTimes : htf2HighTimes, htf2CTime), dir)
        lastHtf2CTime := htf2CTime
        lastHtf2BTime := htf2BTime
        if alertNewInput and alertHtfInput
            array.push(events, newEventText(htf2Name, dir, htf2A, htf2B, htf2C))
 
    if array.size(events) > 0
        alert("AFX · " + syminfo.ticker + "\n" + array.join(events, "\n"), alert.freq_once_per_bar_close)
 
// Drawings, rebuilt on the last bar
 
var array<line> drawnLines = array.new<line>()
var array<label> drawnLabels = array.new<label>()
var array<linefill> drawnFills = array.new<linefill>()
color panelBackground = color.from_gradient(8, 0, 100, chart.bg_color, chart.fg_color)
color panelText = chart.fg_color
color panelMuted = color.from_gradient(70, 0, 100, chart.bg_color, chart.fg_color)
bool lightChart = color.r(chart.bg_color) * 0.299 + color.g(chart.bg_color) * 0.587 + color.b(chart.bg_color) * 0.114 >= 128.0
themeAccent(color baseColor) =>
    lightChart ? color.new(color.from_gradient(55, 0, 100, baseColor, chart.fg_color), color.t(baseColor)) : baseColor
labelTextColor(color baseColor, float factor) =>
    fadeColor(themeAccent(baseColor), lightChart ? 70.0 + 0.3 * factor : 40.0 + 0.6 * factor)
labelFillColor(color baseColor) =>
    color.t(baseColor) >= 100 ? color.new(chart.bg_color, 100) : color.new(color.from_gradient(lightChart ? 12 : 18, 0, 100, chart.bg_color, color.new(baseColor, 0)), 10)
onChart(color baseColor) =>
    color.from_gradient(100 - color.t(baseColor), 0, 100, chart.bg_color, color.new(baseColor, 0))
var table statusPanel = showPanelInput ? table.new(panelPositionOf(panelPositionInput), 7, 4, bgcolor = panelBackground, frame_color = color.new(#64748B, 72), frame_width = 1, border_width = 0) : na
 
clearDrawings() =>
    while array.size(drawnFills) > 0
        linefill.delete(array.pop(drawnFills))
    while array.size(drawnLines) > 0
        line.delete(array.pop(drawnLines))
    while array.size(drawnLabels) > 0
        label.delete(array.pop(drawnLabels))
 
glowWidth() =>
    switch glowStrengthInput
        GLOW_SOFT => 2
        GLOW_STRONG => 6
        => 4
 
glowOpacity() =>
    switch glowStrengthInput
        GLOW_SOFT => 20.0
        GLOW_STRONG => 40.0
        => 30.0
 
isLive(Projection projection) =>
    not na(projection) and not na(projection.cTime) and na(projection.cutoffTime)
 
withinReach(float price) =>
    hideBeyondInput <= 0.0 or na(closedAtr) or na(closedClose) or math.abs(price - closedClose) <= hideBeyondInput * closedAtr
 
nextRatio(Projection projection) =>
    float bestRatio = na
    if isLive(projection)
        for levelIndex = 0 to LEVEL_COUNT - 1
            float ratio = array.get(levelRatios, levelIndex)
            if array.get(levelVisible, levelIndex) and not array.get(projection.reached, levelIndex) and (na(bestRatio) or ratio < bestRatio)
                bestRatio := ratio
    bestRatio
 
farthestVisibleRatio() =>
    float bestRatio = na
    for levelIndex = 0 to LEVEL_COUNT - 1
        float ratio = array.get(levelRatios, levelIndex)
        if array.get(levelVisible, levelIndex) and (na(bestRatio) or ratio > bestRatio)
            bestRatio := ratio
    bestRatio
 
drawnLevel(Projection projection, int levelIndex, float price, bool keepOne) =>
    float keptRatio = keepOne and isLive(projection) ? nz(nextRatio(projection), farthestVisibleRatio()) : na
    withinReach(price) or (not na(keptRatio) and array.get(levelRatios, levelIndex) == keptRatio)
 
levelLabelText(string prefix, float ratio, float price, bool reached) =>
    string body = switch labelTextInput
        TEXT_RATIO => prefix + ratioText(ratio)
        TEXT_PRICE => prefix + priceText(price)
        => prefix + ratioText(ratio) + " · " + priceText(price)
    body + (reached ? " ✓" : "")
 
drawTag(int x, float y, string tagText, bool isHigh, color fillColor, color textColor, string tagTooltip) =>
    array.push(drawnLabels, label.new(x, y, tagText, xloc = xloc.bar_time, style = isHigh ? label.style_label_down : label.style_label_up, color = fillColor, textcolor = textColor, size = tagSizeOf(labelSizeInput), tooltip = tagTooltip))
 
// Right: the label starts where the line ends. Left: it ends where the line starts. Never on the line.
// Owner 2026-10-30: HTF labels take the other end, so a chart label and an HTF label never stack.
drawLevelLabel(int lineStart, int lineEnd, float price, string labelText, color baseColor, bool chartLayer) =>
    bool atEnd = (labelSideInput == SIDE_RIGHT) == chartLayer
    array.push(drawnLabels, label.new(atEnd ? lineEnd : lineStart, price, labelText, xloc = xloc.bar_time, style = atEnd ? label.style_label_left : label.style_label_right, color = labelFillColor(baseColor), textcolor = labelTextColor(baseColor, 100.0), size = labelSizeOf(labelSizeInput)))
 
drawTags(Projection projection, color layerColor, string prefix, bool newest) =>
    if showLegsInput and not na(projection) and not na(projection.cTime) and not na(projection.aTime) and not na(projection.bTime)
        bool live = na(projection.cutoffTime)
        bool bullish = projection.direction == 1
        if live or newest
            color legBase = na(layerColor) ? (lightChart ? PAST_COLOR : LEG_COLOR) : layerColor
            color tagBase = na(layerColor) and tintTagsInput ? (bullish ? BULL_TAG_COLOR : BEAR_TAG_COLOR) : legBase
            // Owner 2026-10-30: an invalidated projection's tags are dim text with no box, "1H · A"; only C carries ✕.
            color tagColor = live ? tagBase : color.new(chart.bg_color, 100)
            color tagText = live ? contrastTextColor(onChart(tagBase)) : labelTextColor(tagBase, 60.0)
            string tagPrefix = live or prefix == "" ? prefix : str.trim(prefix) + " · "
            float depth = depthOf(projection)
            string cText = live ? prefix + "C" + (na(depth) ? "" : " · " + ratioText(depth)) : tagPrefix + "C ✕"
            string cTooltip = live and not na(depth) ? "C pulled back " + str.tostring(depth * 100.0, "0.#") + "% of the A→B move" : live ? "" : "Invalidated: a bar closed beyond C"
            drawTag(projection.aTime, projection.aPrice, tagPrefix + "A", not bullish, tagColor, tagText, "")
            drawTag(projection.bTime, projection.bPrice, tagPrefix + "B", bullish, tagColor, tagText, "")
            drawTag(projection.cTime, projection.cPrice, cText, not bullish, tagColor, tagText, cTooltip)
    true
 
drawProjection(Projection projection, color layerColor, string prefix, int rightEdge, bool allowBand, bool newest) =>
    // An older projection that price invalidated draws nothing; the newest keeps its legs and tags.
    if not na(projection) and not na(projection.cTime) and (newest or projection.state != STATE_INVALIDATED)
        bool live = na(projection.cutoffTime)
        bool chartLayer = na(layerColor)
        int xEnd = live ? rightEdge : projection.cutoffTime
        float stateFactor = not live ? 35.0 : projection.state == STATE_PENDING ? 65.0 : 100.0
        // Owner 2026-10-30: an invalidated projection keeps its faded tags but draws no levels.
        bool showLevels = projection.state != STATE_INVALIDATED
        bool bullish = projection.direction == 1
        if showLegsInput and not na(projection.aTime) and not na(projection.bTime)
            color legBase = chartLayer ? (lightChart ? PAST_COLOR : LEG_COLOR) : layerColor
            color legColor = fadeColor(legBase, live ? 70.0 : 30.0)
            array.push(drawnLines, line.new(projection.aTime, projection.aPrice, projection.bTime, projection.bPrice, xloc = xloc.bar_time, color = legColor, style = line.style_dotted, width = 1))
            array.push(drawnLines, line.new(projection.bTime, projection.bPrice, projection.cTime, projection.cPrice, xloc = xloc.bar_time, color = legColor, style = line.style_dotted, width = 1))
        for levelIndex = 0 to LEVEL_COUNT - 1
            float ratio = array.get(levelRatios, levelIndex)
            float price = levelPrice(projection, ratio)
            if showLevels and array.get(levelVisible, levelIndex) and drawnLevel(projection, levelIndex, price, chartLayer)
                color baseColor = chartLayer ? array.get(levelColors, levelIndex) : layerColor
                color coreColor = live ? fadeColor(baseColor, stateFactor) : fadeColor(PAST_COLOR, stateFactor)
                if live and glowInput
                    array.push(drawnLines, line.new(projection.cTime, price, xEnd, price, xloc = xloc.bar_time, color = fadeColor(baseColor, glowOpacity() * stateFactor / 100.0), width = lineWidthInput + glowWidth()))
                array.push(drawnLines, line.new(projection.cTime, price, xEnd, price, xloc = xloc.bar_time, color = coreColor, style = lineStyleOf(chartLayer ? lineStyleInput : htfLineStyleInput), width = lineWidthInput))
                if live
                    drawLevelLabel(projection.cTime, xEnd, price, levelLabelText(prefix, ratio, price, array.get(projection.reached, levelIndex)), baseColor, chartLayer)
        float bandLowPrice = levelPrice(projection, bandFromInput)
        float bandHighPrice = levelPrice(projection, bandToInput)
        if allowBand and live and showBandInput and bandFromInput != bandToInput and withinReach(bandLowPrice) and withinReach(bandHighPrice)
            line bandLow = line.new(projection.cTime, bandLowPrice, xEnd, bandLowPrice, xloc = xloc.bar_time, color = color.new(#000000, 100))
            line bandHigh = line.new(projection.cTime, bandHighPrice, xEnd, bandHighPrice, xloc = xloc.bar_time, color = color.new(#000000, 100))
            array.push(drawnLines, bandLow)
            array.push(drawnLines, bandHigh)
            array.push(drawnFills, linefill.new(bandLow, bandHigh, bandColorInput))
    true
 
collectOverlaps(Projection chartProjection, Projection htfProjection, array<float> distances, array<float> lowPrices, array<float> highPrices, array<int> startTimes, float tolerance) =>
    if isLive(chartProjection) and isLive(htfProjection)
        for chartIndex = 0 to LEVEL_COUNT - 1
            float chartPrice = levelPrice(chartProjection, array.get(levelRatios, chartIndex))
            if array.get(levelVisible, chartIndex) and drawnLevel(chartProjection, chartIndex, chartPrice, true)
                for htfIndex = 0 to LEVEL_COUNT - 1
                    float htfPrice = levelPrice(htfProjection, array.get(levelRatios, htfIndex))
                    if array.get(levelVisible, htfIndex) and drawnLevel(htfProjection, htfIndex, htfPrice, false)
                        float distance = math.abs(chartPrice - htfPrice)
                        if distance <= tolerance
                            array.push(distances, distance)
                            array.push(lowPrices, math.min(chartPrice, htfPrice) - tolerance * 0.5)
                            array.push(highPrices, math.max(chartPrice, htfPrice) + tolerance * 0.5)
                            array.push(startTimes, math.max(chartProjection.cTime, htfProjection.cTime))
    true
 
renderOverlaps(array<float> distances, array<float> lowPrices, array<float> highPrices, array<int> startTimes, int rightEdge) =>
    if array.size(distances) > 0
        array<int> ranking = array.sort_indices(distances, order.ascending)
        int zoneCount = math.min(array.size(ranking), MAX_OVERLAP_ZONES)
        for zoneIndex = 0 to zoneCount - 1
            int pairIndex = array.get(ranking, zoneIndex)
            float lowPrice = array.get(lowPrices, pairIndex)
            float highPrice = array.get(highPrices, pairIndex)
            int startTime = array.get(startTimes, pairIndex)
            line zoneLow = line.new(startTime, lowPrice, rightEdge, lowPrice, xloc = xloc.bar_time, color = color.new(#000000, 100))
            line zoneHigh = line.new(startTime, highPrice, rightEdge, highPrice, xloc = xloc.bar_time, color = color.new(#000000, 100))
            array.push(drawnLines, zoneLow)
            array.push(drawnLines, zoneHigh)
            array.push(drawnFills, linefill.new(zoneLow, zoneHigh, fadeColor(overlapColorInput, 45.0)))
            if glowInput
                float midPrice = (lowPrice + highPrice) * 0.5
                array.push(drawnLines, line.new(startTime, midPrice, rightEdge, midPrice, xloc = xloc.bar_time, color = fadeColor(overlapColorInput, math.min(100.0, glowOpacity() * 1.8)), width = lineWidthInput + glowWidth() + 2))
    true
 
stateText(Projection projection, bool enabled, bool higher) =>
    string result = "Waiting"
    if not enabled
        result := "Off"
    else if not higher
        result := clockChart ? "No higher TF" : "Time charts"
    else if not na(projection)
        result := switch projection.state
            STATE_ACTIVE => "Active"
            STATE_INVALIDATED => "Invalidated"
            STATE_REPLACED => "Replaced"
            => "Pending"
    result
 
nextLevelText(Projection projection) =>
    float bestRatio = nextRatio(projection)
    na(bestRatio) ? "—" : ratioText(bestRatio)
 
toNextText(Projection projection) =>
    float bestRatio = nextRatio(projection)
    na(bestRatio) or na(closedClose) ? "—" : priceText(math.abs(levelPrice(projection, bestRatio) - closedClose))
 
reachedText(Projection projection) =>
    int shown = 0
    int hit = 0
    if not na(projection) and not na(projection.cTime)
        for levelIndex = 0 to LEVEL_COUNT - 1
            if array.get(levelVisible, levelIndex)
                shown += 1
                if array.get(projection.reached, levelIndex)
                    hit += 1
    na(projection) or shown == 0 ? "—" : str.tostring(hit) + "/" + str.tostring(shown)
 
depthText(Projection projection) =>
    float depth = na(projection) ? na : depthOf(projection)
    na(depth) ? "—" : ratioText(depth)
 
panelCell(int column, int row, string cellText, color textColor) =>
    table.cell(statusPanel, column, row, cellText, text_color = textColor, text_size = labelSizeOf(panelSizeInput), text_halign = column == 1 ? text.align_center : text.align_left)
 
setPanelRow(int row, string layerName, color nameColor, Projection projection, bool enabled, bool higher) =>
    bool shown = enabled and higher
    bool hasDirection = shown and not na(projection)
    string arrow = hasDirection ? (projection.direction == 1 ? "▲" : "▼") : ""
    color arrowColor = themeAccent(hasDirection and projection.direction == 1 ? BULL_COLOR : BEAR_COLOR)
    color rowText = shown ? panelText : panelMuted
    panelCell(0, row, layerName, nameColor)
    panelCell(1, row, arrow, arrowColor)
    panelCell(2, row, stateText(projection, enabled, higher), rowText)
    panelCell(3, row, shown ? depthText(projection) : "—", rowText)
    panelCell(4, row, shown ? reachedText(projection) : "—", rowText)
    panelCell(5, row, shown ? nextLevelText(projection) : "—", rowText)
    panelCell(6, row, shown ? toNextText(projection) : "—", rowText)
 
if barstate.islast
    clearDrawings()
    int rightEdge = time + extendRightInput * barMilliseconds
    int chartCount = array.size(chartProjections)
    if showOverlapInput and chartCount > 0
        Projection chartLive = array.get(chartProjections, chartCount - 1)
        float overlapTolerance = math.max(nz(closedAtr * overlapToleranceInput, 0.0), syminfo.mintick * 2.0)
        array<float> overlapDistances = array.new_float()
        array<float> overlapLows = array.new_float()
        array<float> overlapHighs = array.new_float()
        array<int> overlapStarts = array.new_int()
        if useHtf1
            collectOverlaps(chartLive, htf1Projection, overlapDistances, overlapLows, overlapHighs, overlapStarts, overlapTolerance)
        if useHtf2
            collectOverlaps(chartLive, htf2Projection, overlapDistances, overlapLows, overlapHighs, overlapStarts, overlapTolerance)
        renderOverlaps(overlapDistances, overlapLows, overlapHighs, overlapStarts, rightEdge)
    if chartCount > 0
        for projectionIndex = 0 to chartCount - 1
            bool newestChart = projectionIndex == chartCount - 1
            drawProjection(array.get(chartProjections, projectionIndex), na, "", rightEdge, newestChart, newestChart)
    if useHtf1
        drawProjection(htf1Projection, htf1ColorInput, htf1Name + " ", rightEdge, false, true)
    if useHtf2
        drawProjection(htf2Projection, htf2ColorInput, htf2Name + " ", rightEdge, false, true)
    if chartCount > 0
        for projectionIndex = 0 to chartCount - 1
            drawTags(array.get(chartProjections, projectionIndex), na, "", projectionIndex == chartCount - 1)
    if useHtf1
        drawTags(htf1Projection, htf1ColorInput, htf1Name + " ", true)
    if useHtf2
        drawTags(htf2Projection, htf2ColorInput, htf2Name + " ", true)
 
    if not na(statusPanel)
        Projection chartCurrent = chartCount > 0 ? array.get(chartProjections, chartCount - 1) : na
        panelCell(0, 0, "Layer", panelMuted)
        panelCell(1, 0, "Dir", panelMuted)
        panelCell(2, 0, "State", panelMuted)
        panelCell(3, 0, "C Retrace", panelMuted)
        panelCell(4, 0, "Fib(s) Hit", panelMuted)
        panelCell(5, 0, "Next Fib", panelMuted)
        panelCell(6, 0, "To Next Fib", panelMuted)
        setPanelRow(1, chartName, panelText, chartCurrent, true, true)
        int nextRow = 2
        if showHtf1Input
            setPanelRow(nextRow, htf1Name, themeAccent(htf1ColorInput), htf1Projection, true, htf1Higher)
            nextRow += 1
        if showHtf2Input
            setPanelRow(nextRow, htf2Name, themeAccent(htf2ColorInput), htf2Projection, true, htf2Higher)
 
// Price-scale tags: the live chart levels' prices on the right axis, last bar only.
priceTag(int levelIndex) =>
    float result = na
    int chartCount = array.size(chartProjections)
    if showPriceTagsInput and barstate.islast and chartCount > 0
        Projection live = array.get(chartProjections, chartCount - 1)
        float price = isLive(live) ? levelPrice(live, array.get(levelRatios, levelIndex)) : na
        if array.get(levelVisible, levelIndex) and not na(price) and drawnLevel(live, levelIndex, price, true)
            result := price
    result
 
plot(priceTag(0), "Level 1 tag", color = array.get(levelColors, 0), display = display.price_scale, editable = false)
plot(priceTag(1), "Level 2 tag", color = array.get(levelColors, 1), display = display.price_scale, editable = false)
plot(priceTag(2), "Level 3 tag", color = array.get(levelColors, 2), display = display.price_scale, editable = false)
plot(priceTag(3), "Level 4 tag", color = array.get(levelColors, 3), display = display.price_scale, editable = false)
plot(priceTag(4), "Level 5 tag", color = array.get(levelColors, 4), display = display.price_scale, editable = false)
plot(priceTag(5), "Level 6 tag", color = array.get(levelColors, 5), display = display.price_scale, editable = false)
plot(priceTag(6), "Level 7 tag", color = array.get(levelColors, 6), display = display.price_scale, editable = false)

← 返回列表