TD Levels + Targets V1

Rmayso · study · 416 行 · 点赞 9 · TradingView 原页

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

Pine Script

//@version=6
indicator("TD Levels + Targets V1", shorttitle="TD Levels + Targets", overlay=true, max_lines_count=350, max_labels_count=350)
// Master visibility switches - first controls in Settings.
gMaster = "00 - Quick Controls"
masterLevels = input.bool(true, "Show TD Levels", group=gMaster)
masterTargets = input.bool(true, "Show TD Targets", group=gMaster)
// V30: TD session levels computed on a fixed extended-hours 1-minute feed.
// For intraday charts >= 1 minute, the most recently completed 1-minute observation
// is sampled. On historical higher-timeframe bars, values update at bar boundaries.
// Today's levels extended into the past are visual references, not historical knowledge.
// ----- Viewing presets and custom visibility -----
viewChart = false
viewShort = true
viewLong = false
viewTDOnly = false
// Presets control default feature visibility. Each section also has its own toggle.
// No separate checkbox bank in Viewing Mode.
viewTD = true
f_lineStyle(string selected) =>
    selected == "Dotted" ? line.style_dotted : selected == "Dashed" ? line.style_dashed : line.style_solid
// ----- Inputs -----
gTD = "01 - TD Levels"
showAllTD = masterLevels and viewTD
showPDH = input.bool(true, "PDH", group=gTD)
showPDL = input.bool(true, "PDL", group=gTD)
showPDO = input.bool(true, "PDO", group=gTD)
showPDC = input.bool(true, "PDC", group=gTD)
showPMH = input.bool(true, "PMH", group=gTD)
showPML = input.bool(true, "PML", group=gTD)
showOPEN = input.bool(true, "OPEN", group=gTD)
showPWH = input.bool(false, "Previous Week High", group=gTD)
showPWL = input.bool(false, "Previous Week Low", group=gTD)
gDisplay = "01 - TD Levels Display"
labelStyle = input.string("Bubble", "Label Style", options=["Bubble", "Text Only", "No Labels"], group=gDisplay)
tdBubbleOpacity = input.int(78, "Bubble Transparency", minval=0, maxval=100, group=gDisplay, tooltip="Borderless filled TD label. 100 is transparent.")
labelPosition = input.string("At Line End", "Label Position", options=["At Line End", "Right Edge", "Lines to Price Scale"], group=gDisplay)
rightEdgeInset = input.int(2, "Right Edge Text Inset (bars)", minval=0, maxval=30, group=gDisplay, tooltip="Distance of the label right edge from the rightmost visible bar. Lower values move labels closer to the price scale.")
tdLineStyle = input.string("Solid", "TD Line Style", options=["Solid", "Dotted", "Dashed"], group=gDisplay)
showPrices = input.bool(true, "Show Prices in Labels", group=gDisplay)
labelOffset = input.int(2, "TD Label Right Offset (bars)", minval=1, maxval=100, group=gDisplay)
tdLabelGapBars = input.int(3, "TD Line-to-Label Gap (bars)", minval=1, maxval=30, group=gDisplay, tooltip="Stops the TD level line before its text or bubble. Increase if long labels still overlap the line at your chart zoom.")
autoTFSpacing = input.bool(false, "Auto Timeframe Label Spacing", group=gDisplay, tooltip="Automatically adapts TD horizontal offsets for 1-5m, 10-16m, 30-78m, 2-4h and 8h-D. Turn off to use manual offsets.")
spacingFineTune = input.int(0, "Auto Spacing Fine Tune (bars)", minval=-10, maxval=30, group=gDisplay, tooltip="Add or subtract bars from the automatic offsets. The TD spacing is preserved.")
// Automatic layout groups, preserving manual settings when disabled.
float tfMinutes = timeframe.in_seconds(timeframe.period) / 60.0
int autoTdBars = tfMinutes <= 5 ? 20 : tfMinutes <= 16 ? 15 : tfMinutes <= 78 ? 12 : tfMinutes <= 240 ? 10 : 8
int autoGapBars = tfMinutes <= 5 ? 4 : tfMinutes <= 16 ? 4 : tfMinutes <= 78 ? 5 : tfMinutes <= 240 ? 10 : 6
int tdOffsetEffective = autoTFSpacing ? math.max(2, autoTdBars + spacingFineTune) : labelOffset
int tdGapEffective = autoTFSpacing ? autoGapBars : tdLabelGapBars
lineWidth = input.int(1, "Major Line Width", minval=1, maxval=4, group=gDisplay)
extensionMode = input.string("Previous 1 Week", "Line Extension", options=["Current Day Only", "Previous Trading Day", "Previous 1 Week", "Previous 2 Weeks", "Previous 3 Weeks", "Previous 1 Month", "Previous 1 Year"], group=gDisplay)
labelSpacingPct = input.float(0.18, "Minimum Label Separation (%)", minval=0, maxval=2, step=0.02, group=gDisplay)
// Colors are independent, with matched defaults.
gColors = "01 - TD Level Colors"
cPDH = input.color(color.rgb(239,83,80), "PDH", group=gColors)
cPDL = input.color(color.rgb(239,83,80), "PDL", group=gColors)
cPDO = input.color(color.rgb(66,133,244), "PDO", group=gColors)
cPDC = input.color(color.rgb(66,133,244), "PDC", group=gColors)
cPMH = input.color(color.rgb(0,188,212), "PMH", group=gColors)
cPML = input.color(color.rgb(0,188,212), "PML", group=gColors)
cOPEN = input.color(color.rgb(255,214,0), "OPEN", group=gColors)
cPWH = input.color(color.rgb(171,71,188), "PWH", group=gColors)
cPWL = input.color(color.rgb(126,87,194), "PWL", group=gColors)
// ----- Sessions -----
string tz = "America/New_York"
string extTicker = ticker.modify(syminfo.tickerid, session=session.extended)
string regTicker = ticker.modify(syminfo.tickerid, session=session.regular)
[pdh,pdl,pdo,pdc,prevDayStart,currentDayStart] = request.security(regTicker,"D",[high[1],low[1],open[1],close[1],time[1],time],gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on)
[pwh,pwl,week1,week2,week3] = request.security(regTicker,"W",[high[1],low[1],time[1],time[2],time[3]],gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on)
// Accumulate on the SAME fixed 1m extended-hours source for every chart timeframe.
// The accumulator resets on a New York calendar date change.
f_session() =>
    var float pmh = na
    var float pml = na
    var float opn = na
    var int storedDay = na
    int dayKey = year(time,tz)*10000 + month(time,tz)*100 + dayofmonth(time,tz)
    if na(storedDay) or dayKey != storedDay
        pmh := na
        pml := na
        opn := na
        storedDay := dayKey
    bool pre = not na(time("1","0400-0930:1234567",tz))
    bool firstRegular = hour(time,tz) == 9 and minute(time,tz) == 30
    if pre
        pmh := na(pmh) ? high : math.max(pmh,high)
        pml := na(pml) ? low : math.min(pml,low)
    if firstRegular
        opn := open
    [pmh,pml,opn,dayKey]
// The one-minute accumulator is sampled consistently on each chart bar.
// Intraday charts above 1m will show the final available 1m snapshot per bar.
[pmHigh,pmLow,todayOpen,sessionDay] = request.security(extTicker,"1",f_session(),gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_off)
// ----- Calendar anchors -----
f_monthBack(int anchor) =>
    int yy = year(anchor,tz)
    int mm = month(anchor,tz)
    int dd = dayofmonth(anchor,tz)
    int ty = mm == 1 ? yy-1 : yy
    int tm = mm == 1 ? 12 : mm-1
    int last = dayofmonth(timestamp(tz,ty,tm+1,0,12,0),tz)
    timestamp(tz,ty,tm,math.min(dd,last),0,0)
f_yearBack(int anchor) =>
    int yy = year(anchor,tz)-1
    int mm = month(anchor,tz)
    int dd = dayofmonth(anchor,tz)
    int last = dayofmonth(timestamp(tz,yy,mm+1,0,12,0),tz)
    timestamp(tz,yy,mm,math.min(dd,last),0,0)
var array<line> tdLines = array.new<line>(9,na)
var array<label> tdLabels = array.new<label>(9,na)
f_draw(int i, bool enabled, float price, string name, color clr, int leftTime, float labelY) =>
    line ln = array.get(tdLines,i)
    label lb = array.get(tdLabels,i)
    if enabled and not na(price) and not na(leftTime)
        int barMs = math.max(60000,int(nz(timeframe.in_seconds(timeframe.period),60)*1000))
        // Bubble and text-only labels use identical x coordinates.
        // Unlabeled levels extend to the price-scale edge.
        bool edgeMode = labelStyle == "No Labels" or labelPosition == "Lines to Price Scale"
        int barGapMs = math.max(1, tdOffsetEffective) * barMs
        int edge = chart.right_visible_bar_time
        // Reference V35 behavior: level ends at the latest candle and the
        // label begins just beyond it. Other modes remain available.
        int xLabel = labelPosition == "Right Edge" ? edge - rightEdgeInset * barMs : edgeMode ? edge : time_close + labelOffset * barMs
        int xRight = edgeMode ? edge : labelPosition == "At Line End" ? time_close : math.max(leftTime + 1, xLabel - (tdGapEffective + (showPrices ? 10 : 5)) * barMs)
        if na(ln)
            ln := line.new(leftTime,price,xRight,price,xloc=xloc.bar_time,color=clr,width=lineWidth,style=f_lineStyle(tdLineStyle))
            array.set(tdLines,i,ln)
        else
            line.set_xy1(ln,leftTime,price)
            line.set_xy2(ln,xRight,price)
            line.set_color(ln,clr)
            line.set_width(ln,lineWidth)
            line.set_style(ln,f_lineStyle(tdLineStyle))
        if labelStyle == "No Labels"
            if not na(lb)
                label.delete(lb)
                array.set(tdLabels,i,na)
        else
            string txt = showPrices ? name+" "+str.tostring(price,format.mintick) : name
            // Use the same left-anchored label geometry for both styles.
            // Text Only removes the fill, not the alignment.
            string sty = label.style_label_left
            color bg = labelStyle == "Bubble" ? color.new(clr,tdBubbleOpacity) : color.new(clr,100)
            if na(lb)
                lb := label.new(xLabel,labelY,txt,xloc=xloc.bar_time,style=sty,color=bg,textcolor=clr,size=size.small,textalign=labelPosition == "Right Edge" ? text.align_right : text.align_left)
                array.set(tdLabels,i,lb)
            else
                label.set_xloc(lb,xLabel,xloc.bar_time)
                label.set_y(lb,labelY)
                label.set_text(lb,txt)
                label.set_style(lb,sty)
                label.set_color(lb,bg)
                label.set_textcolor(lb,clr)
                label.set_textalign(lb,labelPosition == "Right Edge" ? text.align_right : text.align_left)
    else
        if not na(ln)
            line.delete(ln)
            array.set(tdLines,i,na)
        if not na(lb)
            label.delete(lb)
            array.set(tdLabels,i,na)
if barstate.islast
    int leftAnchor = switch extensionMode
        "Current Day Only" => currentDayStart
        "Previous Trading Day" => prevDayStart
        "Previous 1 Week" => week1
        "Previous 2 Weeks" => week2
        "Previous 3 Weeks" => week3
        "Previous 1 Month" => na(currentDayStart) ? na : f_monthBack(currentDayStart)
        "Previous 1 Year" => na(currentDayStart) ? na : f_yearBack(currentDayStart)
        => week1
    array<float> levels = array.from(pwh,pwl,pdh,pdl,pdo,pdc,pmHigh,pmLow,todayOpen)
    array<bool> enabled = array.from(showAllTD and showPWH,showAllTD and showPWL,showAllTD and showPDH,showAllTD and showPDL,showAllTD and showPDO,showAllTD and showPDC,showAllTD and showPMH,showAllTD and showPML,showAllTD and showOPEN)
    array<float> ys = array.new<float>(9,na)
    array<int> order = array.new<int>()
    for i=0 to 8
        if array.get(enabled,i) and not na(array.get(levels,i))
            array.push(order,i)
    int n = array.size(order)
    if n>1
        for i=1 to n-1
            int key = array.get(order,i)
            int j=i-1
            while j>=0 and array.get(levels,array.get(order,j))>array.get(levels,key)
                array.set(order,j+1,array.get(order,j))
                j-=1
            array.set(order,j+1,key)
    float lastY=na
    if n>0
        for k=0 to n-1
            int i=array.get(order,k)
            float p=array.get(levels,i)
            float gap=math.max(syminfo.mintick*3,p*labelSpacingPct/100)
            float y=na(lastY)?p:math.max(p,lastY+gap)
            array.set(ys,i,y)
            lastY:=y
    f_draw(0,array.get(enabled,0),pwh,"PWH",cPWH,leftAnchor,array.get(ys,0))
    f_draw(1,array.get(enabled,1),pwl,"PWL",cPWL,leftAnchor,array.get(ys,1))
    f_draw(2,array.get(enabled,2),pdh,"PDH",cPDH,leftAnchor,array.get(ys,2))
    f_draw(3,array.get(enabled,3),pdl,"PDL",cPDL,leftAnchor,array.get(ys,3))
    f_draw(4,array.get(enabled,4),pdo,"PDO",cPDO,leftAnchor,array.get(ys,4))
    f_draw(5,array.get(enabled,5),pdc,"PDC",cPDC,leftAnchor,array.get(ys,5))
    f_draw(6,array.get(enabled,6),pmHigh,"PMH",cPMH,leftAnchor,array.get(ys,6))
    f_draw(7,array.get(enabled,7),pmLow,"PML",cPML,leftAnchor,array.get(ys,7))
    f_draw(8,array.get(enabled,8),todayOpen,"OPEN",cOPEN,leftAnchor,array.get(ys,8))
 
// ============================================================================
f_tfName(string tf) =>
    int seconds = timeframe.in_seconds(tf)
    seconds >= 86400 and seconds % 86400 == 0 ? str.tostring(int(seconds / 86400)) + "D" : seconds >= 3600 and seconds % 3600 == 0 ? str.tostring(int(seconds / 3600)) + "H" : seconds >= 60 and seconds % 60 == 0 ? str.tostring(int(seconds / 60)) + "M" : tf
// TD TARGET LEVELS V3 - local pivots + confirmed higher-timeframe pivots.
// Price structure only. No volume or volume inputs.
// TD prices are calculated internally only for optional target-overlap filtering.
// No TD lines or labels are drawn by this indicator.
// ============================================================================
gTarget = "02 - TD Target Levels"
targetShow = masterTargets
targetLength = input.int(12, "Pivot Confirmation Bars", minval=2, maxval=40, group=gTarget)
targetMinMove = input.float(3.0, "Minimum Pivot Prominence (ATR)", minval=0.2, maxval=10.0, step=0.1, group=gTarget)
targetMaxLevels = input.int(6, "Maximum Displayed Targets", minval=2, maxval=20, group=gTarget)
targetSideCap = input.int(3, "Maximum Targets Per Side", minval=1, maxval=10, group=gTarget)
targetCluster = input.float(1.2, "Nearby Pivot Merge (chart ATR)", minval=0.0, maxval=3.0, step=0.05, group=gTarget)
targetLookback = input.int(1200, "Local Pivot Max Age (bars)", minval=50, maxval=5000, group=gTarget)
targetHideTD = input.bool(true, "Hide Targets Near TD Levels", group=gTarget)
targetTDGapATR = input.float(0.5, "TD Level Overlap Radius (ATR)", minval=0.0, maxval=3.0, step=0.1, group=gTarget)
targetMTF = input.bool(true, "Include Higher Timeframe Targets", group=gTarget)
targetHTF1 = input.timeframe("", "Higher TF 1 (blank = Auto)", group=gTarget)
targetHTF2 = input.timeframe("", "Higher TF 2 (blank = Auto)", group=gTarget)
targetHTFLength = input.int(5, "Higher TF Pivot Confirmation Bars", minval=2, maxval=30, group=gTarget)
targetHTFMinMove = input.float(2.0, "Higher TF Minimum Prominence (ATR)", minval=0.2, maxval=10.0, step=0.1, group=gTarget)
targetMajorBonus = input.float(3.0, "Higher TF Ranking Bonus", minval=0, maxval=20, step=0.5, group=gTarget)
targetShowPrice = input.bool(true, "Show Target Prices", group=gTarget)
targetLabelPosition = input.string("At Line End", "Target Label Position", options=["At Line End", "Right Edge"], group=gTarget)
targetLabelOffset = input.int(2, "Target Label Right Offset (bars)", minval=1, maxval=100, group=gTarget)
targetRightInset = input.int(2, "Right Edge Text Inset (bars)", minval=0, maxval=30, group=gTarget)
targetLineGap = input.int(3, "Right Edge Line-to-Label Gap (bars)", minval=1, maxval=30, group=gTarget)
targetLineWidth = input.int(1, "Local Line Width", minval=1, maxval=4, group=gTarget)
targetLineStyle = input.string("Dashed", "Local Line Style", options=["Solid", "Dashed", "Dotted"], group=gTarget)
targetHighColor = input.color(color.rgb(45, 187, 112), "Local Pivot High Color", group=gTarget)
targetLowColor = input.color(color.rgb(223, 52, 116), "Local Pivot Low Color", group=gTarget)
targetHTFColor = input.color(color.rgb(222, 222, 222), "Higher TF Target Color", group=gTarget)
targetHTFLineStyle = input.string("Dashed", "Higher TF Line Style", options=["Solid", "Dashed", "Dotted"], group=gTarget)
targetHTFWidth = input.int(1, "Higher TF Line Width", minval=1, maxval=4, group=gTarget)
float targetATR = ta.atr(14)
float targetHigh = ta.pivothigh(high, targetLength, targetLength)
float targetLow = ta.pivotlow(low, targetLength, targetLength)
float targetWindowLow = ta.lowest(low, 2 * targetLength + 1)
float targetWindowHigh = ta.highest(high, 2 * targetLength + 1)
// Auto pairs never request a lower timeframe than the chart.
int chartSec = timeframe.in_seconds(timeframe.period)
string auto1 = chartSec < 900 ? "15" : chartSec < 3600 ? "60" : chartSec < 14400 ? "240" : chartSec < 86400 ? "D" : chartSec < 604800 ? "W" : "M"
string auto2 = chartSec < 3600 ? "240" : chartSec < 86400 ? "D" : chartSec < 604800 ? "W" : "M"
string htf1 = targetHTF1 == "" ? auto1 : targetHTF1
string htf2 = targetHTF2 == "" ? auto2 : targetHTF2
bool useHTF1 = targetMTF and timeframe.in_seconds(htf1) > chartSec
bool useHTF2 = targetMTF and timeframe.in_seconds(htf2) > chartSec and htf2 != htf1
// A pivot only appears after the right-hand confirmation candles have CLOSED.
// lookahead_off ensures historical HTF signals do not arrive before confirmation.
f_htfPivots() =>
    float a = ta.atr(14)
    float ph = ta.pivothigh(high, targetHTFLength, targetHTFLength)
    float pl = ta.pivotlow(low, targetHTFLength, targetHTFLength)
    float hiStrength = not na(ph) and a[targetHTFLength] > 0 ? (ph - ta.lowest(low, 2 * targetHTFLength + 1)) / a[targetHTFLength] : na
    float loStrength = not na(pl) and a[targetHTFLength] > 0 ? (ta.highest(high, 2 * targetHTFLength + 1) - pl) / a[targetHTFLength] : na
    [ph, pl, hiStrength, loStrength, time[targetHTFLength], time]
[h1High, h1Low, h1HighScore, h1LowScore, h1Origin, h1Confirm] = request.security(syminfo.tickerid, htf1, f_htfPivots(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
[h2High, h2Low, h2HighScore, h2LowScore, h2Origin, h2Confirm] = request.security(syminfo.tickerid, htf2, f_htfPivots(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
var array<float> targetPrices = array.new<float>()
var array<int> targetTimes = array.new<int>()
var array<int> targetConfirmBars = array.new<int>()
var array<bool> targetIsHigh = array.new<bool>()
var array<float> targetStrength = array.new<float>()
var array<int> targetSource = array.new<int>()  // 0 local, 1 HTF1, 2 HTF2
var array<line> targetLines = array.new<line>()
var array<label> targetLabels = array.new<label>()
f_targetAdd(float price, bool isHigh, float strength, int originTime, int source) =>
    bool merged = false
    // Merge within the same source; cross-source confluence is resolved at display.
    float tolerance = math.max(syminfo.mintick * 3, nz(targetATR, syminfo.mintick) * targetCluster * 0.5)
    if array.size(targetPrices) > 0
        for i = 0 to array.size(targetPrices) - 1
            if array.get(targetSource, i) == source and math.abs(array.get(targetPrices, i) - price) <= tolerance
                merged := true
                if strength > array.get(targetStrength, i)
                    array.set(targetPrices, i, price)
                    array.set(targetTimes, i, originTime)
                    array.set(targetConfirmBars, i, bar_index)
                    array.set(targetIsHigh, i, isHigh)
                    array.set(targetStrength, i, strength)
                break
    if not merged
        array.push(targetPrices, price)
        array.push(targetTimes, originTime)
        array.push(targetConfirmBars, bar_index)
        array.push(targetIsHigh, isHigh)
        array.push(targetStrength, strength)
        array.push(targetSource, source)
var int lastH1Confirm = na
var int lastH2Confirm = na
if barstate.isconfirmed and targetShow
    float pivotATR = targetATR[targetLength]
    if not na(pivotATR) and pivotATR > 0
        if not na(targetHigh)
            float prominence = (targetHigh - targetWindowLow) / pivotATR
            if prominence >= targetMinMove
                f_targetAdd(targetHigh, true, prominence, time[targetLength], 0)
        if not na(targetLow)
            float prominence = (targetWindowHigh - targetLow) / pivotATR
            if prominence >= targetMinMove
                f_targetAdd(targetLow, false, prominence, time[targetLength], 0)
    if useHTF1 and not na(h1Confirm) and (na(lastH1Confirm) or h1Confirm != lastH1Confirm)
        lastH1Confirm := h1Confirm
        if not na(h1High) and nz(h1HighScore) >= targetHTFMinMove
            f_targetAdd(h1High, true, h1HighScore, h1Origin, 1)
        if not na(h1Low) and nz(h1LowScore) >= targetHTFMinMove
            f_targetAdd(h1Low, false, h1LowScore, h1Origin, 1)
    if useHTF2 and not na(h2Confirm) and (na(lastH2Confirm) or h2Confirm != lastH2Confirm)
        lastH2Confirm := h2Confirm
        if not na(h2High) and nz(h2HighScore) >= targetHTFMinMove
            f_targetAdd(h2High, true, h2HighScore, h2Origin, 2)
        if not na(h2Low) and nz(h2LowScore) >= targetHTFMinMove
            f_targetAdd(h2Low, false, h2LowScore, h2Origin, 2)
if barstate.isconfirmed and array.size(targetPrices) > 0
    for i = array.size(targetPrices) - 1 to 0
        if array.get(targetSource, i) == 0 and bar_index - array.get(targetConfirmBars, i) > targetLookback
            array.remove(targetPrices, i)
            array.remove(targetTimes, i)
            array.remove(targetConfirmBars, i)
            array.remove(targetIsHigh, i)
            array.remove(targetStrength, i)
            array.remove(targetSource, i)
    while array.size(targetPrices) > 180
        int weakest = 0
        float weakestScore = 1e20
        for i = 0 to array.size(targetPrices) - 1
            float age = bar_index - array.get(targetConfirmBars, i)
            float score = array.get(targetStrength, i) + (array.get(targetSource, i) > 0 ? targetMajorBonus : 0) - age * 0.002
            if score < weakestScore
                weakestScore := score
                weakest := i
        array.remove(targetPrices, weakest)
        array.remove(targetTimes, weakest)
        array.remove(targetConfirmBars, weakest)
        array.remove(targetIsHigh, weakest)
        array.remove(targetStrength, weakest)
        array.remove(targetSource, weakest)
if barstate.islast
    while array.size(targetLines) > 0
        line.delete(array.pop(targetLines))
    while array.size(targetLabels) > 0
        label.delete(array.pop(targetLabels))
    if targetShow and array.size(targetPrices) > 0
        array<int> selected = array.new<int>()
        int countAbove = 0
        int countBelow = 0
        int poolSize = array.size(targetPrices)
        int attempts = math.min(targetMaxLevels, poolSize)
        float mergeDistance = math.max(syminfo.mintick * 3, nz(targetATR, syminfo.mintick) * targetCluster)
        array<float> tdPrices = array.from(pwh, pwl, pdh, pdl, pdo, pdc, pmHigh, pmLow, todayOpen)
        array<bool> tdEnabled = array.from(showAllTD and showPWH, showAllTD and showPWL, showAllTD and showPDH, showAllTD and showPDL, showPDO and showAllTD, showAllTD and showPDC, showAllTD and showPMH, showAllTD and showPML, showAllTD and showOPEN)
        for slot = 0 to attempts - 1
            int best = -1
            float bestRank = -1e20
            for i = 0 to poolSize - 1
                float p = array.get(targetPrices, i)
                bool above = p >= close
                bool capacity = above ? countAbove < targetSideCap : countBelow < targetSideCap
                bool alreadySelected = array.includes(selected, i)
                bool duplicate = false
                if array.size(selected) > 0
                    for j = 0 to array.size(selected) - 1
                        int prior = array.get(selected, j)
                        if math.abs(p - array.get(targetPrices, prior)) <= mergeDistance
                            duplicate := true
                            break
                bool nearTD = false
                if targetHideTD
                    float tdTolerance = nz(targetATR, syminfo.mintick) * targetTDGapATR
                    for k = 0 to array.size(tdEnabled) - 1
                        if array.get(tdEnabled, k) and not na(array.get(tdPrices, k)) and math.abs(p - array.get(tdPrices, k)) <= tdTolerance
                            nearTD := true
                            break
                if capacity and not alreadySelected and not duplicate and not nearTD
                    float distanceATR = math.abs(p - close) / math.max(nz(targetATR, syminfo.mintick), syminfo.mintick)
                    float age = bar_index - array.get(targetConfirmBars, i)
                    int src = array.get(targetSource, i)
                    float rank = array.get(targetStrength, i) * 0.7 + (src > 0 ? targetMajorBonus + (src == 2 ? 0.5 : 0) : 0) - distanceATR * 1.8 - age * 0.001
                    if rank > bestRank
                        bestRank := rank
                        best := i
            if best >= 0
                array.push(selected, best)
                if array.get(targetPrices, best) >= close
                    countAbove += 1
                else
                    countBelow += 1
        if array.size(selected) > 0
            for j = 0 to array.size(selected) - 1
                int i = array.get(selected, j)
                float p = array.get(targetPrices, i)
                int src = array.get(targetSource, i)
                bool major = src > 0
                color clr = major ? targetHTFColor : array.get(targetIsHigh, i) ? targetHighColor : targetLowColor
                int barMs = math.max(60000, int(nz(timeframe.in_seconds(timeframe.period), 60) * 1000))
                // Match TD Levels: line ends at the latest candle in At Line End mode.
                // Text and bubble labels share left-anchored geometry.
                int xLabel = targetLabelPosition == "Right Edge" ? chart.right_visible_bar_time - targetRightInset * barMs : time_close + targetLabelOffset * barMs
                int endTime = targetLabelPosition == "At Line End" ? time_close : math.max(array.get(targetTimes, i) + 1, xLabel - (targetLineGap + 10) * barMs)
                int startTime = array.get(targetTimes, i)
                line ln = line.new(startTime, p, endTime, p, xloc=xloc.bar_time, color=clr, width=major ? targetHTFWidth : targetLineWidth, style=f_lineStyle(major ? targetHTFLineStyle : targetLineStyle))
                array.push(targetLines, ln)
                if targetShowPrice
                    string srcText = src == 0 ? "LOCAL" : src == 1 ? htf1 : htf2
                    string txt = (major ? f_tfName(srcText) : "PIVOT") + (array.get(targetIsHigh, i) ? " HIGH | " : " LOW | ") + str.tostring(p, format.mintick)
                    label lb = label.new(xLabel, p, txt, xloc=xloc.bar_time, style=label.style_label_left, color=color.new(clr, 100), textcolor=clr, size=size.small, textalign=targetLabelPosition == "Right Edge" ? text.align_right : text.align_left)
                    array.push(targetLabels, lb)

← 返回列表