Wave Effort Map [AFD]

AuctionFoundry · study · 529 行 · 点赞 42 · TradingView 原页

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

Pine Script

// This Source Code Form is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Auction Foundry
//@version=6
indicator("Wave Effort Map [AFD]", "WEM [AFD]", overlay = true, max_lines_count = 16, max_labels_count = 10, behind_chart = false)
 
const int    MAX_PENDING     = 500
const float MAX_NUMBER       = 1e100
const float EQUAL_EPS        = 1e-12
const string GROUP_WAVES     = "Waves"
const string GROUP_CHART     = "Chart appearance"
const string GROUP_ALERTS    = "Alerts"
const string GROUP_TABLE     = "Comparison table"
const string TIP_ATR         = "• Bars used to measure price volatility"
const string TIP_REVERSAL    = "• ATR sets the required reversal size\n• Higher = larger reversals\n• Confirms on a later bar close"
const string TIP_DEVELOPING  = "• Gray dashed leg is still forming\n• Updates at bar close; can move\n• Not included in the comparison table"
const string TIP_LABELS      = "• Choose leg number, volume or effort\n• Volume = total reported volume\n• Off hides text; icons stay if enabled"
const string TIP_LABEL_SIZE  = "• Size of leg text and effort icons"
const string TIP_SPACING     = "• Move text away from the endpoint\n• Distance uses endpoint ATR\n• Zero keeps text at the endpoint"
const string TIP_ALERTS      = "• Alert when a complete leg finalizes\n• Only at the confirming bar close\n• Create an Any alert() function alert"
const string TIP_WIDTH       = "• Thickness of the wave lines\n• Latest leg is 1 pixel thicker"
const string TIP_GLOW        = "• Halo around completed wave lines\n• Off, Soft or Strong"
const string TIP_ICONS       = "• Volume versus the preceding leg\n• − less · = equal · ? unavailable\n• 0 means both report zero volume\n• No icon for more volume or first leg"
const string TIP_COLORS      = "• Color for this price direction\n• Applies to lines, dots, text and table\n• Darkens on light charts"
const string TIP_STYLE       = "• Line style for completed waves\n• Developing stays gray and dashed"
const string TIP_TABLE       = "• Compares the last two completed legs\n• Excludes the developing leg\n• Off hides details; warnings stay"
const string TIP_POSITION    = "• Location of the table and messages"
const string TIP_TABLE_SIZE  = "• Text size in the table and messages"
const string TIP_LAYOUT      = "• Compact: change in %\n• Detailed: unit change and %\n• Detailed adds bars and shows minutes"
 
int atrLengthInput        = input.int(14, "ATR length", minval = 2, maxval = 100, tooltip = TIP_ATR, group = GROUP_WAVES, display = display.none)
float reversalInput       = input.float(1.5, "ATR reversal multiple", minval = 0.1, maxval = 10.0, step = 0.1, tooltip = TIP_REVERSAL, group = GROUP_WAVES, display = display.none)
bool showDevelopingInput  = input.bool(true, "Show developing leg", tooltip = TIP_DEVELOPING, group = GROUP_CHART, display = display.none)
string labelContentInput  = input.string("Leg + volume", "Chart labels", options = ["Leg + volume", "Leg + effort", "Leg only", "Off"], tooltip = TIP_LABELS, group = GROUP_CHART, display = display.none)
// Keep label size editable: TradingView Reset can freeze active gates.
string labelSizeInput     = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], tooltip = TIP_LABEL_SIZE, group = GROUP_CHART, display = display.none)
int lineWidthInput        = input.int(2, "Line width", minval = 1, maxval = 4, tooltip = TIP_WIDTH, group = GROUP_CHART, display = display.none)
string glowInput          = input.string("Strong", "Wave glow", options = ["Off", "Soft", "Strong"], tooltip = TIP_GLOW, group = GROUP_CHART, display = display.none)
bool showEffortIconsInput = input.bool(true, "Show effort icons", tooltip = TIP_ICONS, group = GROUP_CHART, display = display.none)
color upColorInput        = input.color(#2962FF, "Up legs", tooltip = TIP_COLORS, group = GROUP_CHART, display = display.none)
color downColorInput      = input.color(#F23645, "Down legs", tooltip = TIP_COLORS, group = GROUP_CHART, display = display.none)
string upLineStyleInput   = input.string("Solid", "Up line style", options = ["Solid", "Dashed", "Dotted"], tooltip = TIP_STYLE, group = GROUP_CHART, display = display.none)
string downLineStyleInput = input.string("Solid", "Down line style", options = ["Solid", "Dashed", "Dotted"], tooltip = TIP_STYLE, group = GROUP_CHART, display = display.none)
bool showDetailsInput     = input.bool(true, "Show pair details", tooltip = TIP_TABLE, group = GROUP_TABLE, display = display.none)
string tablePositionInput = input.string("Top right", "Table position", options = ["Top left", "Top center", "Top right", "Middle left", "Middle center", "Middle right", "Bottom left", "Bottom center", "Bottom right"], tooltip = TIP_POSITION, group = GROUP_TABLE, display = display.none)
string tableSizeInput     = input.string("Medium", "Table size", options = ["Small", "Medium", "Large", "Extra large"], tooltip = TIP_TABLE_SIZE, group = GROUP_TABLE, display = display.none)
string tableLayoutInput   = input.string("Compact", "Table layout", options = ["Compact", "Detailed"], tooltip = TIP_LAYOUT, group = GROUP_TABLE, display = display.none)
 
float labelSpacingInput   = input.float(0.0, "Label spacing (ATR)", minval = 0.0, maxval = 3.0, step = 0.1, tooltip = TIP_SPACING, group = GROUP_CHART, display = display.none)
bool finalizationAlertsInput = input.bool(false, "Enable finalization alerts", tooltip = TIP_ALERTS, group = GROUP_ALERTS, display = display.none)
 
type Observation
    int index
    int stamp
    float hi
    float lo
    float atr
    float vol
 
type Detector
    int direction = 0
    float readyClose = na
    int anchorIndex = na
    int anchorTime = na
    float anchorPrice = na
    int extremeIndex = na
    int extremeTime = na
    float extremePrice = na
    float extremeAtr = na
    float total = 0.0
    float compensation = 0.0
    int badVolume = 0
    float endpointTotal = 0.0
    int endpointBad = 0
    int number = 0
 
type Wave
    int number
    int direction
    int startIndex
    int endIndex
    int startTime
    int endTime
    float startPrice
    float endPrice
    float vol
    float endpointAtr
 
type Bundle
    Wave wave
    line outerGlowLine
    line innerGlowLine
    line pathLine
    label noteLabel
    label startDotLabel
    label endDotLabel
    float previousVolume
    int previousNumber
 
validNumber(float value) =>
    not na(value) and math.abs(value) <= MAX_NUMBER
 
addVolume(float total, float compensation, float value) =>
    float adjusted = value - compensation
    float updated = total + adjusted
    [updated, (updated - total) - adjusted]
 
// Aggregate totals are not subject to the single-observation admission cap.
finiteValue(float value) =>
    not na(value) and not na(value - value)
 
// Preserve nonzero magnitudes outside fixed-decimal display precision.
numberText(float value) =>
    string result = "N/A"
    if finiteValue(value)
        float magnitude = math.abs(value)
        if math.sign(magnitude) == 0
            result := "0"
        else if math.sign(magnitude - 1e-10) >= 0 and magnitude < 1e9
            result := str.tostring(value, "#.##########")
        else
            float mantissa = magnitude
            int exponent = 0
            for step = 0 to 110
                if mantissa >= 1000.0
                    mantissa /= 1000.0
                    exponent += 3
                else if math.sign(mantissa - 1.0) < 0
                    mantissa *= 1000.0
                    exponent -= 3
                else
                    break
            mantissa := math.round(mantissa, 6)
            if mantissa >= 1000.0
                mantissa /= 1000.0
                exponent += 3
            result := (math.sign(value) < 0 ? "−" : "") + str.tostring(mantissa, "#.######") + "e" + str.tostring(exponent)
    result
 
volumeText(float value) =>
    not finiteValue(value) ? "Unavailable" : math.sign(value) == 0 ? "0" : math.sign(math.abs(value) - 0.01) < 0 or math.abs(value) >= 1e15 ? numberText(value) : str.tostring(value, format.volume)
 
volumeWithUnit(float value) =>
    finiteValue(value) ? volumeText(value) + " vol" : "Unavailable"
 
// Sign tests preserve differences below Pine's direct-comparison rounding.
effortRelation(float current, float previous) =>
    int relation = na
    if finiteValue(current) and finiteValue(previous)
        float difference = current - previous
        float tolerance = EQUAL_EPS * math.max(1.0, math.abs(current), math.abs(previous))
        relation := math.sign(math.abs(difference) - tolerance) <= 0 ? 0 : math.sign(difference) > 0 ? 1 : -1
    relation
 
effortText(float current, float previous) =>
    int relation = effortRelation(current, previous)
    string result = "Effort unavailable"
    if not na(relation)
        result := relation == 0 ? (math.sign(current) == 0 and math.sign(previous) == 0 ? "Both report zero volume" : "Equal effort") : relation > 0 ? "More effort" : "Less effort"
        if relation != 0
            float percent = math.sign(previous) > 0 ? math.abs((current - previous) / previous * 100.0) : na
            string changeText = not validNumber(percent) ? " · % N/A" : math.sign(percent - 0.01) < 0 ? " · <0.01%" : " · " + (percent < 1e9 ? str.tostring(percent, "#.##") : numberText(percent)) + "%"
            result += changeText
    result
 
effortIcon(float current, float previous) =>
    int relation = effortRelation(current, previous)
    na(relation) ? "?" : relation == 0 ? (math.sign(current) == 0 and math.sign(previous) == 0 ? "0" : "=") : relation > 0 ? "" : "−"
 
elapsedText(int startTime, int endTime) =>
    float seconds = (endTime - startTime) / 1000.0
    int days = math.floor(seconds / 86400.0)
    seconds -= days * 86400.0
    int hours = math.floor(seconds / 3600.0)
    seconds -= hours * 3600.0
    int minutes = math.floor(seconds / 60.0)
    seconds -= minutes * 60.0
    string result = days > 0 ? str.tostring(days) + "d" : ""
    if hours > 0
        result += (result != "" ? " " : "") + str.tostring(hours) + "h"
    if minutes > 0
        result += (result != "" ? " " : "") + str.tostring(minutes) + "m"
    if math.sign(seconds) > 0 or result == ""
        result += (result != "" ? " " : "") + str.tostring(seconds, "#.###") + "s"
    result
 
// Exact rational reconstruction accepts grid prices without tolerating off-grid values.
gridIndex(float price, int minMove, int priceScale) =>
    float result = na
    if finiteValue(price) and minMove > 0 and priceScale > 0 and minMove <= 9007199254740992 and priceScale <= 9007199254740992
        float quotient = price / float(minMove) * float(priceScale)
        if finiteValue(quotient) and math.abs(quotient) <= 281474976710656.0
            float index = math.round(quotient, 0)
            float numerator = index * float(minMove)
            if math.abs(numerator) <= 9007199254740992.0 and math.sign(price - numerator / float(priceScale)) == 0
                result := index
    result
 
distanceTicks(float startPrice, float endPrice, int minMove, int priceScale) =>
    float startIndex = gridIndex(startPrice, minMove, priceScale)
    float endIndex = gridIndex(endPrice, minMove, priceScale)
    float ticks = math.abs(endIndex - startIndex)
    not na(ticks) and math.abs(ticks * float(minMove)) <= 9007199254740992.0 ? ticks : na
 
priceDistanceText(float startPrice, float endPrice, int minMove, int priceScale) =>
    float ticks = distanceTicks(startPrice, endPrice, minMove, priceScale)
    (na(ticks) ? "≈" + numberText(math.abs(endPrice - startPrice)) : numberText(ticks * float(minMove) / float(priceScale))) + " pts"
 
percentText(float difference, float previous) =>
    string result = "N/A"
    if finiteValue(difference) and finiteValue(previous) and math.sign(previous) > 0
        float percent = math.abs(difference / previous * 100.0)
        if validNumber(percent)
            result := math.sign(difference) == 0 ? "0%" : (math.sign(difference) > 0 ? "+" : "−") + (math.sign(percent - 0.01) < 0 ? "<0.01" : percent < 1e9 ? str.tostring(percent, "#.##") : numberText(percent)) + "%"
    result
 
signedUnits(float value, string unit) =>
    (math.sign(value) > 0 ? "+" : math.sign(value) < 0 ? "−" : "") + (unit == "vol" ? volumeText(math.abs(value)) : unit == "min" ? (math.sign(value) != 0 and math.sign(math.abs(value) - 0.01) < 0 ? "<0.01" : str.tostring(math.abs(value), "#.##")) : numberText(math.abs(value))) + " " + (unit == "bars" and math.abs(value) == 1 ? "bar" : unit)
 
comparisonText(float current, float previous, string unit, bool detailed, bool volumeMetric = false) =>
    float difference = current - previous
    if volumeMetric and effortRelation(current, previous) == 0
        difference := 0.0
    string result = percentText(difference, previous)
    if detailed
        float value = unit == "min" ? difference / 60000.0 : difference
        result := finiteValue(value) ? signedUnits(value, unit) + "\n" + result : "N/A"
    result
 
// Raw fallback reports uncertainty instead of snapping distinct adjusted prices.
priceComparison(float startLatest, float endLatest, float startPrevious, float endPrevious, int minMove, int priceScale, bool detailed) =>
    float latestTicks = distanceTicks(startLatest, endLatest, minMove, priceScale)
    float previousTicks = distanceTicks(startPrevious, endPrevious, minMove, priceScale)
    bool onGrid = not na(latestTicks) and not na(previousTicks)
    float latest = onGrid ? latestTicks : math.abs(endLatest - startLatest)
    float previous = onGrid ? previousTicks : math.abs(endPrevious - startPrevious)
    float difference = latest - previous
    float uncertainty = 2.220446049250313e-16 * (math.abs(startLatest) + math.abs(endLatest) + math.abs(startPrevious) + math.abs(endPrevious) + latest + previous + math.abs(difference))
    bool resolved = onGrid or (math.sign(uncertainty) > 0 and math.sign(math.abs(difference) - uncertainty) > 0)
    string result = "Precision limited"
    if resolved
        string prefix = onGrid ? "" : "≈"
        result := prefix + percentText(difference, previous)
        if detailed
            float points = onGrid ? difference * float(minMove) / float(priceScale) : difference
            result := prefix + signedUnits(points, "pts") + "\n" + result
    result
 
labelSize() =>
    labelSizeInput == "Tiny" ? size.tiny : labelSizeInput == "Normal" ? size.normal : size.small
 
tableSize() =>
    tableSizeInput == "Small" ? 9 : tableSizeInput == "Large" ? 16 : tableSizeInput == "Extra large" ? 20 : 11
 
tablePosition() =>
    switch tablePositionInput
        "Top left" => position.top_left
        "Top center" => position.top_center
        "Top right" => position.top_right
        "Middle left" => position.middle_left
        "Middle center" => position.middle_center
        "Bottom left" => position.bottom_left
        "Bottom right" => position.bottom_right
        "Middle right" => position.middle_right
        => position.bottom_center
 
themeAccent(color baseColor) =>
    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
    lightChart ? color.new(color.from_gradient(55, 0, 100, baseColor, chart.fg_color), color.t(baseColor)) : baseColor
 
legColor(int direction) =>
    themeAccent(direction > 0 ? upColorInput : downColorInput)
 
labelFill(color tone) =>
    color.t(tone) >= 100 ? color.new(chart.bg_color, 100) : color.new(color.from_gradient(14, 0, 100, chart.bg_color, color.new(tone, 0)), color.t(tone))
 
legStyle(int direction) =>
    string selected = direction > 0 ? upLineStyleInput : downLineStyleInput
    selected == "Dashed" ? line.style_dashed : selected == "Dotted" ? line.style_dotted : line.style_solid
 
glowColor(color tone, bool outer, bool latest) =>
    float opacity = glowInput == "Strong" ? (outer ? 14.0 : 30.0) : (outer ? 6.0 : 15.0)
    color.new(tone, 100.0 - (100.0 - color.t(tone)) * opacity / 100.0 * (latest ? 1.0 : 0.65))
 
waveTooltip(Wave wave, float previousVolume, int previousNumber) =>
    string comparison = na(previousNumber) ? "No previous leg" : effortText(wave.vol, previousVolume)
    "• " + comparison + "\n• Elapsed: " + elapsedText(wave.startTime, wave.endTime)
 
deleteBundle(Bundle bundle) =>
    line.delete(bundle.outerGlowLine)
    line.delete(bundle.innerGlowLine)
    line.delete(bundle.pathLine)
    label.delete(bundle.noteLabel)
    label.delete(bundle.startDotLabel)
    label.delete(bundle.endDotLabel)
 
pairCell(table panelTable, int column, int row, string value, color tone, bool heading = false, bool figure = false) =>
    color background = color.from_gradient(heading ? 10 : column == 0 ? 5 : 0, 0, 100, chart.bg_color, chart.fg_color)
    table.cell(panelTable, column, row, value, text_color = tone, text_size = tableSize(), text_halign = figure ? text.align_right : text.align_left, bgcolor = background, text_font_family = figure ? font.family_monospace : font.family_default, text_formatting = heading or column == 0 ? text.format_bold : text.format_none)
 
float atrValue = ta.atr(atrLengthInput)
bool supportedChart = chart.is_standard and not timeframe.isticks
bool priceValid = validNumber(open) and validNumber(high) and validNumber(low) and validNumber(close) and math.sign(high - low) >= 0 and math.sign(high - open) >= 0 and math.sign(high - close) >= 0 and math.sign(low - open) <= 0 and math.sign(low - close) <= 0
bool atrValid = validNumber(atrValue) and math.sign(atrValue) > 0
bool volumeValid = validNumber(volume) and math.sign(volume) >= 0
var Detector detector = Detector.new()
var array<Observation> pendingArray = array.new<Observation>()
var int previousIndex = na
var int previousTime = na
var int resetCount = 0
var string lastReset = "None"
bool resetNow = false
Wave finalized = na
 
if barstate.isconfirmed
    bool ordered = na(previousIndex) or (bar_index > previousIndex and time > previousTime)
    bool dataValid = priceValid and not na(time) and not na(time_close) and time_close > time and ordered
    if not supportedChart or not dataValid or (not atrValid and not na(detector.readyClose))
        resetNow := true
        lastReset := not supportedChart ? "Use standard time-based candles" : not dataValid ? "Invalid price/time; restarted" : "Invalid ATR; restarted"
        0 // Unify side-effect branch return types.
    else if atrValid
        if detector.direction == 0
            if not na(detector.readyClose) and math.sign(close - detector.readyClose) != 0
                detector.direction := math.sign(close - detector.readyClose) > 0 ? 1 : -1
                detector.extremeIndex := bar_index
                detector.extremeTime := time
                detector.extremePrice := detector.direction > 0 ? high : low
                detector.extremeAtr := atrValue
            detector.readyClose := close
            0
        else
            [updatedTotal, updatedCompensation] = addVolume(detector.total, detector.compensation, volumeValid ? volume : 0.0)
            detector.total := updatedTotal
            detector.compensation := updatedCompensation
            detector.badVolume += volumeValid ? 0 : 1
            bool newExtreme = detector.direction > 0 ? math.sign(high - detector.extremePrice) > 0 : math.sign(low - detector.extremePrice) < 0
            if newExtreme
                detector.extremeIndex := bar_index
                detector.extremeTime := time
                detector.extremePrice := detector.direction > 0 ? high : low
                detector.extremeAtr := atrValue
                detector.endpointTotal := detector.total
                detector.endpointBad := detector.badVolume
                array.clear(pendingArray)
                0
            else if array.size(pendingArray) >= MAX_PENDING
                resetNow := true
                lastReset := "500-bar pending suffix exceeded; restarted"
                0
            else
                array.push(pendingArray, Observation.new(bar_index, time, high, low, atrValue, volumeValid ? volume : na))
                bool reversal = detector.direction > 0 ? math.sign(close - (detector.extremePrice - detector.extremeAtr * reversalInput)) <= 0 : math.sign(close - (detector.extremePrice + detector.extremeAtr * reversalInput)) >= 0
                if reversal
                    if not na(detector.anchorIndex)
                        detector.number += 1
                        finalized := Wave.new(detector.number, detector.direction, detector.anchorIndex, detector.extremeIndex, detector.anchorTime, detector.extremeTime, detector.anchorPrice, detector.extremePrice, detector.endpointBad == 0 ? detector.endpointTotal : na, detector.extremeAtr)
                    detector.anchorIndex := detector.extremeIndex
                    detector.anchorTime := detector.extremeTime
                    detector.anchorPrice := detector.extremePrice
                    detector.direction := -detector.direction
                    detector.total := 0.0
                    detector.compensation := 0.0
                    detector.badVolume := 0
                    detector.extremeIndex := na
                    for observation in pendingArray
                        [suffixTotal, suffixCompensation] = addVolume(detector.total, detector.compensation, na(observation.vol) ? 0.0 : observation.vol)
                        detector.total := suffixTotal
                        detector.compensation := suffixCompensation
                        detector.badVolume += na(observation.vol) ? 1 : 0
                        bool better = na(detector.extremeIndex) or (detector.direction > 0 ? math.sign(observation.hi - detector.extremePrice) > 0 : math.sign(observation.lo - detector.extremePrice) < 0)
                        if better
                            detector.extremeIndex := observation.index
                            detector.extremeTime := observation.stamp
                            detector.extremePrice := detector.direction > 0 ? observation.hi : observation.lo
                            detector.extremeAtr := observation.atr
                            detector.endpointTotal := detector.total
                            detector.endpointBad := detector.badVolume
                    while array.size(pendingArray) > 0 and array.get(pendingArray, 0).index <= detector.extremeIndex
                        array.shift(pendingArray)
                0
            0
        0
    if resetNow
        detector := Detector.new()
        array.clear(pendingArray)
        resetCount += 1
    previousIndex := resetNow ? na : bar_index
    previousTime := resetNow ? na : time
 
var array<Bundle> bundlesArray = array.new<Bundle>()
var line developingLine = na
var label developingLabel = na
var table pairTable = na
var int tableMode = -1
 
if resetNow
    for bundle in bundlesArray
        deleteBundle(bundle)
    array.clear(bundlesArray)
    line.delete(developingLine)
    label.delete(developingLabel)
    developingLine := na
    developingLabel := na
 
if not na(finalized)
    int priorCount = array.size(bundlesArray)
    Wave priorWave = priorCount > 0 ? array.get(bundlesArray, priorCount - 1).wave : na
    float previousVolume = not na(priorWave) ? priorWave.vol : na
    int previousNumber = not na(priorWave) ? priorWave.number : na
    if priorCount == 2
        deleteBundle(array.shift(bundlesArray))
    color tone = legColor(finalized.direction)
    line outerGlowLine = na
    line innerGlowLine = na
    if glowInput != "Off"
        outerGlowLine := line.new(finalized.startTime, finalized.startPrice, finalized.endTime, finalized.endPrice, xloc = xloc.bar_time, color = glowColor(tone, true, true), style = legStyle(finalized.direction), width = lineWidthInput + 18)
        innerGlowLine := line.new(finalized.startTime, finalized.startPrice, finalized.endTime, finalized.endPrice, xloc = xloc.bar_time, color = glowColor(tone, false, true), style = legStyle(finalized.direction), width = lineWidthInput + 9)
    line pathLine = line.new(finalized.startTime, finalized.startPrice, finalized.endTime, finalized.endPrice, xloc = xloc.bar_time, color = tone, style = legStyle(finalized.direction), width = lineWidthInput + 1)
    label noteLabel = na
    string finalizedIcon = showEffortIconsInput and not na(previousNumber) ? effortIcon(finalized.vol, previousVolume) : ""
    if labelContentInput != "Off" or finalizedIcon != ""
        noteLabel := label.new(finalized.endTime, finalized.endPrice + finalized.direction * finalized.endpointAtr * labelSpacingInput, "", xloc = xloc.bar_time, color = labelFill(tone), style = finalized.direction > 0 ? label.style_label_down : label.style_label_up, textcolor = tone, size = labelSize(), tooltip = waveTooltip(finalized, previousVolume, previousNumber))
    label startDotLabel = label.new(finalized.startTime, finalized.startPrice, "", xloc = xloc.bar_time, color = tone, style = label.style_circle, size = size.tiny)
    label endDotLabel = label.new(finalized.endTime, finalized.endPrice, "", xloc = xloc.bar_time, color = tone, style = label.style_circle, size = size.tiny)
    array.push(bundlesArray, Bundle.new(finalized, outerGlowLine, innerGlowLine, pathLine, noteLabel, startDotLabel, endDotLabel, previousVolume, previousNumber))
    for [slot, bundle] in bundlesArray
        bool latest = slot == array.size(bundlesArray) - 1
        color bundleTone = legColor(bundle.wave.direction)
        line.set_width(bundle.pathLine, lineWidthInput + (latest ? 1 : 0))
        line.set_color(bundle.pathLine, bundleTone)
        if not na(bundle.outerGlowLine)
            line.set_color(bundle.outerGlowLine, glowColor(bundleTone, true, latest))
            line.set_color(bundle.innerGlowLine, glowColor(bundleTone, false, latest))
        if not na(bundle.noteLabel)
            string icon = showEffortIconsInput and not na(bundle.previousNumber) ? effortIcon(bundle.wave.vol, bundle.previousVolume) : ""
            string role = latest ? "Latest · Leg " : "Leg "
            string caption = labelContentInput != "Off" ? role + str.tostring(slot + 1) : ""
            string detail = labelContentInput == "Leg + volume" ? volumeWithUnit(bundle.wave.vol) : labelContentInput == "Leg + effort" ? (na(bundle.previousNumber) ? "No previous leg" : effortText(bundle.wave.vol, bundle.previousVolume) + (latest ? " vs Leg 1" : "\nvs earlier leg (off chart)")) : ""
            label.set_text(bundle.noteLabel, icon + (icon != "" and caption != "" ? "  " : "") + caption + (detail != "" ? "\n" + detail : ""))
            label.set_textcolor(bundle.noteLabel, bundleTone)
            label.set_color(bundle.noteLabel, labelFill(bundleTone))
            label.set_tooltip(bundle.noteLabel, waveTooltip(bundle.wave, bundle.previousVolume, bundle.previousNumber))
            label.set_text_formatting(bundle.noteLabel, latest ? text.format_bold : text.format_none)
 
if barstate.islast
    bool developingReady = supportedChart and not na(detector.anchorIndex) and showDevelopingInput
    if developingReady
        color developingTone = color.from_gradient(65, 0, 100, chart.bg_color, chart.fg_color)
        if na(developingLine)
            developingLine := line.new(detector.anchorTime, detector.anchorPrice, detector.extremeTime, detector.extremePrice, xloc = xloc.bar_time, color = developingTone, style = line.style_dashed, width = 1)
        line.set_xy1(developingLine, detector.anchorTime, detector.anchorPrice)
        line.set_xy2(developingLine, detector.extremeTime, detector.extremePrice)
        if labelContentInput != "Off"
            if na(developingLabel)
                developingLabel := label.new(detector.extremeTime, detector.extremePrice, "", xloc = xloc.bar_time, color = labelFill(developingTone), style = detector.direction > 0 ? label.style_label_down : label.style_label_up, textcolor = developingTone, size = labelSize())
            label.set_xy(developingLabel, detector.extremeTime, detector.extremePrice + detector.direction * detector.extremeAtr * labelSpacingInput)
            label.set_style(developingLabel, detector.direction > 0 ? label.style_label_down : label.style_label_up)
            string developingDetail = labelContentInput == "Leg + volume" ? " · " + volumeWithUnit(detector.endpointBad == 0 ? detector.endpointTotal : na) : ""
            label.set_text(developingLabel, "Developing" + developingDetail)
            label.set_tooltip(developingLabel, "• Elapsed: " + elapsedText(detector.anchorTime, detector.extremeTime))
        0
    else
        line.delete(developingLine)
        label.delete(developingLabel)
        developingLine := na
        developingLabel := na
        0
 
    int count = array.size(bundlesArray)
    string stateText = ""
    if not supportedChart
        stateText := "Unsupported chart; standard time-based candles required."
    else if count == 0
        string phase = na(detector.readyClose) ? "Waiting for ATR data." : detector.direction == 0 ? "Waiting for a changed close." : na(detector.anchorIndex) ? "Waiting for the first reversal anchor." : "The first complete leg is forming."
        stateText := (resetCount > 0 ? lastReset + "\n" : "") + phase
    int nextMode = stateText != "" ? 1 : showDetailsInput ? (tableLayoutInput == "Compact" ? 2 : 3) : 0
    if nextMode != tableMode
        if not na(pairTable)
            table.delete(pairTable)
        pairTable := na
        if nextMode != 0
            pairTable := table.new(tablePosition(), 4, nextMode == 1 ? 2 : nextMode == 2 ? 4 : 5, bgcolor = chart.bg_color, frame_color = color.from_gradient(30, 0, 100, chart.bg_color, chart.fg_color), frame_width = 1, border_color = color.from_gradient(12, 0, 100, chart.bg_color, chart.fg_color), border_width = 1)
            if nextMode == 1
                table.merge_cells(pairTable, 0, 0, 3, 0)
                table.merge_cells(pairTable, 0, 1, 3, 1)
        tableMode := nextMode
    if not na(pairTable)
        color muted = color.from_gradient(65, 0, 100, chart.bg_color, chart.fg_color)
        pairCell(pairTable, 0, 0, "Wave effort", chart.fg_color, true)
        if tableMode == 1
            pairCell(pairTable, 0, 1, stateText, chart.fg_color)
        else
            Wave latestWave = array.get(bundlesArray, count - 1).wave
            color effortTone = legColor(latestWave.direction)
            pairCell(pairTable, 0, 1, "Effort (volume)", effortTone)
            pairCell(pairTable, 0, 2, "Result (price)", effortTone)
            pairCell(pairTable, 0, 3, tableMode == 2 ? "Time (d/h/m/s)" : "Time (min)", effortTone)
            pairCell(pairTable, 3, 0, tableMode == 3 ? "Change\nUnits / %" : "Change (%)", effortTone, true)
            for [slot, bundle] in bundlesArray
                bool latest = slot == count - 1
                int column = latest ? 1 : 2
                Wave wave = bundle.wave
                string heading = (latest ? "Latest" : "Previous") + "\n" + (wave.direction > 0 ? "Up" : "Down") + " · Leg " + str.tostring(slot + 1)
                pairCell(pairTable, column, 0, heading, legColor(wave.direction), true)
                pairCell(pairTable, column, 1, volumeWithUnit(wave.vol), finiteValue(wave.vol) ? legColor(wave.direction) : muted, figure = true)
                pairCell(pairTable, column, 2, priceDistanceText(wave.startPrice, wave.endPrice, syminfo.minmove, syminfo.pricescale), legColor(wave.direction), figure = true)
                pairCell(pairTable, column, 3, tableMode == 2 ? elapsedText(wave.startTime, wave.endTime) : str.tostring((wave.endTime - wave.startTime) / 60000.0, "#.##") + " min", legColor(wave.direction), figure = true)
                if tableMode == 3
                    pairCell(pairTable, column, 4, str.tostring(wave.endIndex - wave.startIndex) + (wave.endIndex - wave.startIndex == 1 ? " bar" : " bars"), legColor(wave.direction), figure = true)
            if count == 2
                Wave previousWave = array.get(bundlesArray, 0).wave
                pairCell(pairTable, 3, 1, comparisonText(latestWave.vol, previousWave.vol, "vol", tableMode == 3, true), finiteValue(latestWave.vol) and finiteValue(previousWave.vol) ? effortTone : muted, figure = true)
                pairCell(pairTable, 3, 2, priceComparison(latestWave.startPrice, latestWave.endPrice, previousWave.startPrice, previousWave.endPrice, syminfo.minmove, syminfo.pricescale, tableMode == 3), effortTone, figure = true)
                pairCell(pairTable, 3, 3, comparisonText(latestWave.endTime - latestWave.startTime, previousWave.endTime - previousWave.startTime, "min", tableMode == 3), effortTone, figure = true)
                if tableMode == 3
                    pairCell(pairTable, 3, 4, comparisonText(latestWave.endIndex - latestWave.startIndex, previousWave.endIndex - previousWave.startIndex, "bars", true), effortTone, figure = true)
            else
                pairCell(pairTable, 2, 0, "Previous\nNone yet", muted, true)
                for row = 1 to (tableMode == 2 ? 3 : 4)
                    pairCell(pairTable, 2, row, "—", muted, figure = true)
                    pairCell(pairTable, 3, row, "N/A", muted, figure = true)
            if tableMode == 3
                pairCell(pairTable, 0, 4, "Bars (count)", effortTone)
 
// Events describe the confirming close, while the measured endpoint can be earlier.
if finalizationAlertsInput and barstate.isconfirmed and not na(finalized)
    Bundle latestBundle = array.get(bundlesArray, array.size(bundlesArray) - 1)
    string comparison = na(latestBundle.previousNumber) ? "No previous complete leg" : effortText(finalized.vol, latestBundle.previousVolume) + " vs preceding complete leg"
    alert("Wave Effort Map | " + (syminfo.prefix == "" ? "" : syminfo.prefix + ":") + syminfo.ticker + " | " + timeframe.period + " | " + (finalized.direction > 0 ? "Up" : "Down") + " leg finalized | " + volumeWithUnit(finalized.vol) + " | " + comparison, alert.freq_once_per_bar_close)

← 返回列表