PFK Key Levels

PropFirmKid · study · 577 行 · 点赞 14 · TradingView 原页

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

Pine Script

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © propfirmkid
 
//@version=6
indicator("PFK Key Levels", shorttitle="PFK KL", overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
 
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                              INPUTS                                        ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
 
// Public build identifier shown in the dashboard footer.
PFK_VERSION = "v1.0.0"
 
GROUP_DAILY   = "⬤ Daily Levels"
GROUP_WEEKLY  = "⬤ Weekly / Monthly Levels"
GROUP_SESSION = "⬤ Session Levels"
GROUP_PSYCH   = "⬤ Psychological Levels"
GROUP_CUSTOM  = "⬤ Custom Levels"
GROUP_OVERLAY = "⬤ Overlays"
GROUP_PANEL   = "⬤ Dashboard"
GROUP_STYLE   = "⬤ Colors"
 
// --- Daily Levels ---
showDailyOpen      = input.bool(true,  "Daily Open", group=GROUP_DAILY, tooltip="Where the current trading day opened. Uses the symbol's own daily session, so futures and FX roll at their usual daily open.")
showPrevDailyClose = input.bool(false, "Previous Day Close", group=GROUP_DAILY)
showPrevDayHigh    = input.bool(true,  "Previous Day High", group=GROUP_DAILY)
showPrevDayLow     = input.bool(true,  "Previous Day Low", group=GROUP_DAILY, tooltip="Yesterday's extremes. They are fixed for the whole day once it opens.")
showCurrentDayHL   = input.bool(false, "Current Day High / Low", group=GROUP_DAILY, tooltip="Today's running high and low. These move with price until the day closes.")
 
// --- Weekly / Monthly Levels ---
showWeeklyOpen     = input.bool(false, "Weekly Open", group=GROUP_WEEKLY, tooltip="Week and month levels often sit far from price. Turning many on can zoom the price scale out.")
showPrevWeekHigh   = input.bool(false, "Previous Week High", group=GROUP_WEEKLY)
showPrevWeekLow    = input.bool(false, "Previous Week Low", group=GROUP_WEEKLY)
showPrevWeekClose  = input.bool(false, "Previous Week Close", group=GROUP_WEEKLY)
showMonthlyOpen    = input.bool(false, "Monthly Open", group=GROUP_WEEKLY)
showPrevMonthHigh  = input.bool(false, "Previous Month High", group=GROUP_WEEKLY)
showPrevMonthLow   = input.bool(false, "Previous Month Low", group=GROUP_WEEKLY)
showPrevMonthClose = input.bool(false, "Previous Month Close", group=GROUP_WEEKLY)
 
// --- Session Levels ---
keySession          = input.session("0930-1600", "Key Session", group=GROUP_SESSION, tooltip="The session the session levels and opening range are built from. The default is the New York cash session. Needs an intraday chart.")
sessionTimezone     = input.string("America/New_York", "Session Timezone", options=["Exchange", "America/New_York", "America/Chicago", "Europe/London", "Europe/Berlin", "Asia/Tokyo", "Asia/Hong_Kong", "Asia/Singapore", "Australia/Sydney", "UTC"], group=GROUP_SESSION, tooltip="The time zone the Key Session is read in. Exchange uses the symbol's own time zone. Daylight saving is handled for you.")
showPrevSessOpen    = input.bool(true,  "Previous Session Open", group=GROUP_SESSION, tooltip="Levels from the most recently completed Key Session. During today's session they show yesterday's values, and after the close they switch to today's. On charts with no bars after the close, such as stocks with extended hours off, they switch at the next session open.")
showPrevSessClose   = input.bool(false, "Previous Session Close", group=GROUP_SESSION)
showPrevSessHL      = input.bool(false, "Previous Session High / Low", group=GROUP_SESSION)
showOpeningRange    = input.bool(false, "Current Opening Range High / Low", group=GROUP_SESSION, tooltip="High and low of the first minutes of the current Key Session. They move while the range forms, then hold until the first bar after the session. If a chart bar is longer than the range, the first bar sets it.")
openingRangeMinutes = input.int(30, "Opening Range Minutes", minval=1, maxval=240, group=GROUP_SESSION)
 
// --- Psychological Levels ---
showPsychMajor       = input.bool(true, "Major Round Numbers", group=GROUP_PSYCH, tooltip="Big round numbers, such as 4000 on gold. A major level appears once price is near it, so far-off levels do not squeeze the chart.")
showPsychMinor       = input.bool(true, "Minor Round Numbers", group=GROUP_PSYCH, tooltip="Steps between the major round numbers, nearest to price. A step that lands on a major number is shown as major.")
psychStepMode        = input.string("Auto", "Step Mode", options=["Auto", "Manual"], group=GROUP_PSYCH, tooltip="Auto picks a step from the symbol's price, e.g. 100.00 on XAUUSD. Manual uses the steps below.")
psychManualMajorStep = input.float(0.0, "Manual Major Step", minval=0.0, group=GROUP_PSYCH, tooltip="Manual mode only. Set to 0 to fall back to auto.")
psychManualMinorStep = input.float(0.0, "Manual Minor Step", minval=0.0, group=GROUP_PSYCH, tooltip="Manual mode only. Set to 0 to use one quarter of the Manual Major Step, or the auto minor step when that is also 0.")
psychMinorCount      = input.int(2, "Minor Count Each Side", minval=0, maxval=2, group=GROUP_PSYCH)
psychMajorNearPct    = input.float(35.0, "Show Major Within (% Step)", minval=1.0, maxval=50.0, step=1.0, group=GROUP_PSYCH, tooltip="How close price must be before a major level appears on its own, as a share of one major step. Majors that fall inside the minor levels shown always appear, so this matters most with minor levels off.")
 
// --- Custom Levels ---
custom1On    = input.bool(false, "1", inline="c1", group=GROUP_CUSTOM)
custom1Price = input.price(0.0, "Level", inline="c1", group=GROUP_CUSTOM)
custom1Name  = input.string("Custom 1", "Label", inline="c1", group=GROUP_CUSTOM, tooltip="Your own prices, such as a level from your trading plan. Tick the box to show it.")
custom2On    = input.bool(false, "2", inline="c2", group=GROUP_CUSTOM)
custom2Price = input.price(0.0, "Level", inline="c2", group=GROUP_CUSTOM)
custom2Name  = input.string("Custom 2", "Label", inline="c2", group=GROUP_CUSTOM)
custom3On    = input.bool(false, "3", inline="c3", group=GROUP_CUSTOM)
custom3Price = input.price(0.0, "Level", inline="c3", group=GROUP_CUSTOM)
custom3Name  = input.string("Custom 3", "Label", inline="c3", group=GROUP_CUSTOM)
custom4On    = input.bool(false, "4", inline="c4", group=GROUP_CUSTOM)
custom4Price = input.price(0.0, "Level", inline="c4", group=GROUP_CUSTOM)
custom4Name  = input.string("Custom 4", "Label", inline="c4", group=GROUP_CUSTOM)
custom5On    = input.bool(false, "5", inline="c5", group=GROUP_CUSTOM)
custom5Price = input.price(0.0, "Level", inline="c5", group=GROUP_CUSTOM)
custom5Name  = input.string("Custom 5", "Label", inline="c5", group=GROUP_CUSTOM)
custom6On    = input.bool(false, "6", inline="c6", group=GROUP_CUSTOM)
custom6Price = input.price(0.0, "Level", inline="c6", group=GROUP_CUSTOM)
custom6Name  = input.string("Custom 6", "Label", inline="c6", group=GROUP_CUSTOM)
custom7On    = input.bool(false, "7", inline="c7", group=GROUP_CUSTOM)
custom7Price = input.price(0.0, "Level", inline="c7", group=GROUP_CUSTOM)
custom7Name  = input.string("Custom 7", "Label", inline="c7", group=GROUP_CUSTOM)
custom8On    = input.bool(false, "8", inline="c8", group=GROUP_CUSTOM)
custom8Price = input.price(0.0, "Level", inline="c8", group=GROUP_CUSTOM)
custom8Name  = input.string("Custom 8", "Label", inline="c8", group=GROUP_CUSTOM)
 
// --- Overlays ---
visualMode          = input.string("Magnet Map", "Mode", options=["Magnet Map", "Clean Lines", "Labels Only"], group=GROUP_OVERLAY, tooltip="Magnet Map: lines plus a soft zone around each level. Clean Lines: lines only. Labels Only: just the labels on the right.")
historyBars         = input.int(220, "Line History Bars", minval=25, maxval=500, group=GROUP_OVERLAY, tooltip="How far back each line is drawn. Lines show the current value of each level, not where it sat in the past.")
projectionBars      = input.int(35, "Right Projection Bars", minval=5, maxval=250, group=GROUP_OVERLAY, tooltip="How far past the last bar the lines reach. Labels sit at the right end.")
showLevelValues     = input.bool(true, "Show Price In Labels", group=GROUP_OVERLAY)
showDistance        = input.bool(true, "Show Distance In Labels", group=GROUP_OVERLAY)
mergeNearbyLabels   = input.bool(true, "Merge Nearby Labels", group=GROUP_OVERLAY, tooltip="Levels that sit close together share one label, such as 'Daily Open + Major Psych | x2', and draw a thicker line.")
 
// --- Dashboard ---
showDashboard       = input.bool(true, "Show Dashboard", group=GROUP_PANEL, tooltip="Lists the two nearest levels above and below price, with their distance.")
dashboardPosition   = input.string("Bottom Right", "Panel Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=GROUP_PANEL)
dashboardSize       = input.string("Normal", "Panel Size", options=["Tiny", "Small", "Normal", "Large"], group=GROUP_PANEL)
 
// --- Colors & Styles ---
dailyColor          = input.color(#00B8D9, "Daily", group=GROUP_STYLE)
weeklyColor         = input.color(#7C4DFF, "Weekly / Monthly", group=GROUP_STYLE)
sessionColor        = input.color(#FFAB00, "Session", group=GROUP_STYLE)
psychColor          = input.color(#00C853, "Psychological", group=GROUP_STYLE)
psychMinorColor     = input.color(#64DD17, "Psychological Minor", group=GROUP_STYLE)
customColor         = input.color(#FF4081, "Custom", group=GROUP_STYLE)
nearestColor        = input.color(#FFD740, "Nearest Level Highlight", group=GROUP_STYLE)
nearestTextColor    = input.color(#1A1A2E, "Nearest Label Text", group=GROUP_STYLE)
labelTextColor      = input.color(#FFFFFF, "Label Text", group=GROUP_STYLE, tooltip="Label text on dark charts. Light charts switch to dark text automatically.")
lineStyleInput      = input.string("Solid", "Line Style", options=["Solid", "Dashed", "Dotted"], group=GROUP_STYLE)
lineWidth           = input.int(2, "Line Width", minval=1, maxval=4, group=GROUP_STYLE)
labelSizeInput      = input.string("Small", "Label Size", options=["Tiny", "Small", "Normal"], group=GROUP_STYLE)
zoneAtrPct          = input.float(4.0, "Aura Zone Width (% ATR)", minval=0.0, maxval=50.0, step=0.25, group=GROUP_STYLE, tooltip="The zone reaches this far above and below each level, as a % of ATR(14). The shading shows in Magnet Map only, but the same width sets when price counts as near a level and how close levels must be to merge.")
zoneMinTicks        = input.int(6, "Minimum Aura Width (ticks)", minval=1, maxval=200, group=GROUP_STYLE, tooltip="The smallest zone size, in ticks on each side of the level.")
 
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                               DATA                                         ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
 
// Current-period opens avoid lookahead: on historical bars the higher-timeframe request only returns
// confirmed periods, so while the latest period is still open on a historical bar (e.g. the market is
// closed mid-week), the open of that period's first chart bar is used instead. If the chart's history
// starts after the period began, weekly and monthly opens fall back to the period's first daily open.
f_periodStartOpen(simple string tf) =>
    var float periodOpen = na
    if timeframe.change(tf)
        periodOpen := open
    periodOpen
 
f_currentPeriodOpen(simple string tf) =>
    [htfOpen, htfTime] = request.security(syminfo.tickerid, tf, [open, time])
    dailyStartOpen = request.security(syminfo.tickerid, "D", f_periodStartOpen(tf))
    newPeriod = timeframe.change(tf)
    var float firstBarOpen = na
    if newPeriod and bar_index > 0
        firstBarOpen := open
    htfTime == time(tf) ? htfOpen : not na(firstBarOpen) ? firstBarOpen : tf != "D" ? dailyStartOpen : na
 
dailyOpen      = f_currentPeriodOpen("D")
prevDailyClose = request.security(syminfo.tickerid, "D", close[1], lookahead=barmerge.lookahead_on)
prevDayHigh    = request.security(syminfo.tickerid, "D", high[1], lookahead=barmerge.lookahead_on)
prevDayLow     = request.security(syminfo.tickerid, "D", low[1], lookahead=barmerge.lookahead_on)
 
weeklyOpen     = f_currentPeriodOpen("W")
prevWeekHigh   = request.security(syminfo.tickerid, "W", high[1], lookahead=barmerge.lookahead_on)
prevWeekLow    = request.security(syminfo.tickerid, "W", low[1], lookahead=barmerge.lookahead_on)
prevWeekClose  = request.security(syminfo.tickerid, "W", close[1], lookahead=barmerge.lookahead_on)
monthlyOpen    = f_currentPeriodOpen("M")
prevMonthHigh  = request.security(syminfo.tickerid, "M", high[1], lookahead=barmerge.lookahead_on)
prevMonthLow   = request.security(syminfo.tickerid, "M", low[1], lookahead=barmerge.lookahead_on)
prevMonthClose = request.security(syminfo.tickerid, "M", close[1], lookahead=barmerge.lookahead_on)
 
sessionTz       = sessionTimezone == "Exchange" ? syminfo.timezone : sessionTimezone
sessionStartMin = int(nz(str.tonumber(str.substring(keySession, 0, 2))) * 60 + nz(str.tonumber(str.substring(keySession, 2, 4))))
inSession  = not na(time(timeframe.period, keySession, sessionTz))
hasPrevBar = not na(time[1])
// Minutes since the latest session start on the session clock, so sessions that run past midnight stay whole.
sessionClock = (hour(time, sessionTz) * 60 + minute(time, sessionTz) - sessionStartMin + 1440) % 1440
sessionRestarted = hasPrevBar and (sessionClock < sessionClock[1] or time - time[1] >= 86400000)
newSession = inSession and (not (inSession[1] == true) or sessionRestarted)
endSession = not inSession and (inSession[1] == true)
 
newCalendarDay = ta.change(time("D")) != 0
var float currentDayHigh = na
var float currentDayLow = na
 
if newCalendarDay or na(currentDayHigh)
    currentDayHigh := high
    currentDayLow := low
else
    currentDayHigh := math.max(currentDayHigh, high)
    currentDayLow := math.min(currentDayLow, low)
 
var float currentSessionOpen = na
var float currentSessionHigh = na
var float currentSessionLow  = na
var float currentSessionClose = na
var float previousSessionOpen = na
var float previousSessionHigh = na
var float previousSessionLow  = na
var float previousSessionClose = na
var int   currentSessionStartTime = na
var float openingRangeHigh = na
var float openingRangeLow  = na
 
if newSession
    if not na(currentSessionOpen)
        previousSessionOpen := currentSessionOpen
        previousSessionHigh := currentSessionHigh
        previousSessionLow := currentSessionLow
        previousSessionClose := currentSessionClose
 
    currentSessionOpen := open
    currentSessionHigh := high
    currentSessionLow := low
    currentSessionClose := close
    currentSessionStartTime := time
    openingRangeHigh := high
    openingRangeLow := low
 
if inSession
    currentSessionHigh := na(currentSessionHigh) ? high : math.max(currentSessionHigh, high)
    currentSessionLow := na(currentSessionLow) ? low : math.min(currentSessionLow, low)
    currentSessionClose := close
 
    openingRangeActive = not na(currentSessionStartTime) and time < currentSessionStartTime + openingRangeMinutes * 60 * 1000
    if openingRangeActive
        openingRangeHigh := na(openingRangeHigh) ? high : math.max(openingRangeHigh, high)
        openingRangeLow := na(openingRangeLow) ? low : math.min(openingRangeLow, low)
 
if endSession
    previousSessionOpen := currentSessionOpen
    previousSessionHigh := currentSessionHigh
    previousSessionLow := currentSessionLow
    previousSessionClose := currentSessionClose
    currentSessionOpen := na
    currentSessionHigh := na
    currentSessionLow := na
    currentSessionClose := na
    currentSessionStartTime := na
    openingRangeHigh := na
    openingRangeLow := na
 
atr = ta.atr(14)
isDark = color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color) < 380
 
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                             HELPERS                                        ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
 
var float[] levelValues = array.new_float()
var string[] levelNames = array.new_string()
var color[] levelColors = array.new_color()
var int[] levelWeights = array.new_int()
 
var line[] drawLines = array.new_line()
var label[] drawLabels = array.new_label()
var box[] drawBoxes = array.new_box()
 
// Major step is about 2% of price snapped to 1, 2 or 5; a 5 step splits into fifths, others into quarters.
f_autoPsychStep() =>
    tick = syminfo.mintick
    raw = math.max(math.abs(close) * 0.02, tick * 20.0)
    exponent = math.floor(math.log(raw) / math.log(10.0))
    base = math.pow(10.0, exponent)
    normalized = raw / base
    step = normalized <= 1.0 ? base : normalized <= 2.0 ? 2.0 * base : normalized <= 5.0 ? 5.0 * base : 10.0 * base
    minor = normalized > 2.0 and normalized <= 5.0 ? step / 5.0 : step / 4.0
    [math.max(step, tick), math.max(minor, tick)]
 
f_roundToTick(float value) =>
    math.round(value / syminfo.mintick) * syminfo.mintick
 
f_lineStyle(string styleName) =>
    switch styleName
        "Dashed" => line.style_dashed
        "Dotted" => line.style_dotted
        => line.style_solid
 
f_labelSize(string sizeName) =>
    switch sizeName
        "Tiny" => size.tiny
        "Normal" => size.normal
        => size.small
 
f_panelSize(string sizeName) =>
    switch sizeName
        "Tiny" => size.tiny
        "Small" => size.small
        "Large" => size.large
        => size.normal
 
f_tablePosition(string posName) =>
    switch posName
        "Top Left" => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left" => position.bottom_left
        => position.top_right
 
f_addLevel(bool enabled, float value, string name, color levelColor, int weight) =>
    if enabled and not na(value)
        array.push(levelValues, f_roundToTick(value))
        array.push(levelNames, name)
        array.push(levelColors, levelColor)
        array.push(levelWeights, weight)
 
f_clearObjects() =>
    lineCount = array.size(drawLines)
    if lineCount > 0
        for i = 0 to lineCount - 1
            line.delete(array.get(drawLines, i))
    array.clear(drawLines)
 
    labelCount = array.size(drawLabels)
    if labelCount > 0
        for i = 0 to labelCount - 1
            label.delete(array.get(drawLabels, i))
    array.clear(drawLabels)
 
    boxCount = array.size(drawBoxes)
    if boxCount > 0
        for i = 0 to boxCount - 1
            box.delete(array.get(drawBoxes, i))
    array.clear(drawBoxes)
 
f_confluenceCount(float value, float tolerance) =>
    count = 0
    total = array.size(levelValues)
    if total > 0
        for i = 0 to total - 1
            if math.abs(array.get(levelValues, i) - value) <= tolerance
                count += 1
    count
 
f_isFirstInCluster(int idx, float tolerance) =>
    result = true
    if mergeNearbyLabels and idx > 0
        value = array.get(levelValues, idx)
        for i = 0 to idx - 1
            if math.abs(array.get(levelValues, i) - value) <= tolerance
                result := false
    result
 
f_clusterLabel(int idx, float tolerance) =>
    value = array.get(levelValues, idx)
    clusterText = ""
    count = 0
    total = array.size(levelValues)
    if total > 0
        for i = 0 to total - 1
            if math.abs(array.get(levelValues, i) - value) <= tolerance
                count += 1
                if count <= 3
                    clusterText := clusterText == "" ? array.get(levelNames, i) : clusterText + " + " + array.get(levelNames, i)
                else if count == 4
                    clusterText := clusterText + " + more"
    [clusterText, count]
 
f_distanceText(float value) =>
    str.tostring(math.abs(close - value), format.mintick) + " pts"
 
f_findNearestIndex() =>
    int nearest = na
    float bestDistance = na
    total = array.size(levelValues)
    if total > 0
        for i = 0 to total - 1
            value = array.get(levelValues, i)
            distance = math.abs(close - value)
            if na(bestDistance) or distance < bestDistance
                bestDistance := distance
                nearest := i
    nearest
 
f_findNearestSideRank(bool above, int rank, float tolerance) =>
    string resultName = "None"
    float resultValue = na
    float resultDistance = na
    float minimumDistance = na
    bool foundRank = false
    total = array.size(levelValues)
    if total > 0
        for selected = 0 to rank
            int bestIdx = na
            float bestDistance = na
            for i = 0 to total - 1
                value = array.get(levelValues, i)
                validSide = above ? value > close : value <= close
                distance = math.abs(close - value)
                farEnough = na(minimumDistance) or distance > minimumDistance + tolerance
                if validSide and farEnough and (na(bestDistance) or distance < bestDistance)
                    bestIdx := i
                    bestDistance := distance
            if not na(bestIdx)
                minimumDistance := bestDistance
                if selected == rank
                    [clusterName, clusterCount] = f_clusterLabel(bestIdx, tolerance)
                    resultName := clusterName
                    resultValue := array.get(levelValues, bestIdx)
                    resultDistance := bestDistance
                    foundRank := true
    if not foundRank
        resultName := "None"
        resultValue := na
        resultDistance := na
    [resultName, resultValue, resultDistance]
 
f_drawLevel(int idx, int nearestIdx, float zoneHalfWidth, float clusterTolerance) =>
    value = array.get(levelValues, idx)
    levelColor = array.get(levelColors, idx)
    isNearest = idx == nearestIdx
    confluence = f_confluenceCount(value, clusterTolerance)
    [clusterName, clusterCount] = f_clusterLabel(idx, clusterTolerance)
 
    leftX = math.max(bar_index - historyBars, 0)
    rightX = bar_index + projectionBars
    activeColor = isNearest ? nearestColor : levelColor
    priceNear = math.abs(close - value) <= zoneHalfWidth
    levelWeight = array.get(levelWeights, idx)
    importantLevel = levelWeight >= 4
    lineAlpha = visualMode == "Labels Only" ? 100 : (priceNear or isNearest ? 0 : 20)
    zoneAlpha = priceNear or isNearest ? 82 : 91
    confluenceWidth = math.min(lineWidth + (importantLevel ? 1 : 0) + math.max(confluence - 1, 0), 5)
 
    if visualMode == "Magnet Map" and zoneHalfWidth > 0.0
        zone = box.new(leftX, value + zoneHalfWidth, rightX, value - zoneHalfWidth, xloc=xloc.bar_index, bgcolor=color.new(activeColor, zoneAlpha), border_color=color.new(activeColor, 100))
        array.push(drawBoxes, zone)
 
    if visualMode != "Labels Only"
        levelLine = line.new(leftX, value, rightX, value, xloc=xloc.bar_index, extend=extend.none, color=color.new(activeColor, lineAlpha), style=f_lineStyle(lineStyleInput), width=confluenceWidth)
        array.push(drawLines, levelLine)
 
    if f_isFirstInCluster(idx, clusterTolerance)
        // A merged label carries the highlight when any level it names is the nearest one.
        labelNearest = mergeNearbyLabels and not na(nearestIdx) ? math.abs(array.get(levelValues, nearestIdx) - value) <= clusterTolerance : isNearest
        labelText = mergeNearbyLabels ? clusterName : array.get(levelNames, idx)
        if showLevelValues
            labelText := labelText + " " + str.tostring(value, format.mintick)
        if showDistance
            labelText := labelText + " | " + f_distanceText(value)
        if clusterCount > 1
            labelText := labelText + " | x" + str.tostring(clusterCount)
        if labelNearest
            labelText := "NEAREST | " + labelText
 
        labelAlpha = labelNearest ? 8 : priceNear ? 14 : 30
        labelFg = labelNearest ? nearestTextColor : isDark ? labelTextColor : color.new(#1A1A2E, 0)
        labelBg = labelNearest ? nearestColor : levelColor
        sideLabel = label.new(rightX, value, labelText, xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_left, color=color.new(labelBg, labelAlpha), textcolor=labelFg, size=f_labelSize(labelSizeInput))
        array.push(drawLabels, sideLabel)
 
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                         BUILD LEVEL MAP                                    ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
 
array.clear(levelValues)
array.clear(levelNames)
array.clear(levelColors)
array.clear(levelWeights)
 
f_addLevel(showDailyOpen, dailyOpen, "Daily Open", dailyColor, 5)
f_addLevel(showPrevDailyClose, prevDailyClose, "Previous Day Close", dailyColor, 5)
f_addLevel(showPrevDayHigh, prevDayHigh, "Previous Day High", dailyColor, 4)
f_addLevel(showPrevDayLow, prevDayLow, "Previous Day Low", dailyColor, 4)
f_addLevel(showCurrentDayHL, currentDayHigh, "Daily High", dailyColor, 3)
f_addLevel(showCurrentDayHL, currentDayLow, "Daily Low", dailyColor, 3)
 
f_addLevel(showWeeklyOpen, weeklyOpen, "Weekly Open", weeklyColor, 4)
f_addLevel(showPrevWeekHigh, prevWeekHigh, "Previous Week High", weeklyColor, 3)
f_addLevel(showPrevWeekLow, prevWeekLow, "Previous Week Low", weeklyColor, 3)
f_addLevel(showPrevWeekClose, prevWeekClose, "Previous Week Close", weeklyColor, 3)
f_addLevel(showMonthlyOpen, monthlyOpen, "Monthly Open", weeklyColor, 3)
f_addLevel(showPrevMonthHigh, prevMonthHigh, "Previous Month High", weeklyColor, 2)
f_addLevel(showPrevMonthLow, prevMonthLow, "Previous Month Low", weeklyColor, 2)
f_addLevel(showPrevMonthClose, prevMonthClose, "Previous Month Close", weeklyColor, 2)
 
f_addLevel(showPrevSessOpen, previousSessionOpen, "Previous Session Open", sessionColor, 4)
f_addLevel(showPrevSessClose, previousSessionClose, "Previous Session Close", sessionColor, 3)
f_addLevel(showPrevSessHL, previousSessionHigh, "Previous Session High", sessionColor, 3)
f_addLevel(showPrevSessHL, previousSessionLow, "Previous Session Low", sessionColor, 3)
f_addLevel(showOpeningRange, openingRangeHigh, "OR High", sessionColor, 4)
f_addLevel(showOpeningRange, openingRangeLow, "OR Low", sessionColor, 4)
 
[psychAutoMajorStep, psychAutoMinorStep] = f_autoPsychStep()
psychManualMajor = psychStepMode == "Manual" and psychManualMajorStep > 0.0
psychMajorStep = psychManualMajor ? psychManualMajorStep : psychAutoMajorStep
psychMinorStep = psychStepMode == "Manual" and psychManualMinorStep > 0.0 ? psychManualMinorStep : psychManualMajor ? psychMajorStep * 0.25 : psychAutoMinorStep
// The tiny offset stops float noise (e.g. 0.29 / 0.01 = 28.999...) from dropping the grid a step.
psychMajorBase = math.floor(close / psychMajorStep + 1e-9) * psychMajorStep
psychMinorBase = math.floor(close / psychMinorStep + 1e-9) * psychMinorStep
psychMinorCeiling = psychMinorBase + psychMinorStep
psychMajorNear = psychMajorStep * psychMajorNearPct * 0.01
 
var float[] psychValues = array.new_float()
array.clear(psychValues)
 
// Each round number is added once; a minor step that lands on a major number is shown as major.
f_addPsych(float level) =>
    value = f_roundToTick(level)
    isNew = true
    total = array.size(psychValues)
    if total > 0
        for i = 0 to total - 1
            if math.abs(array.get(psychValues, i) - value) <= syminfo.mintick * 0.5
                isNew := false
    if isNew
        array.push(psychValues, value)
        nearestMajor = math.round(value / psychMajorStep) * psychMajorStep
        isMajor = math.abs(value - nearestMajor) <= syminfo.mintick * 0.5
        if isMajor and showPsychMajor
            f_addLevel(true, value, "Major Psych", psychColor, 3)
        else
            f_addLevel(showPsychMinor, value, "Minor Psych", psychMinorColor, 1)
 
if showPsychMajor
    for i = 0 to 1
        majorLevel = psychMajorBase + i * psychMajorStep
        if math.abs(close - majorLevel) <= psychMajorNear
            f_addPsych(majorLevel)
 
if showPsychMinor and psychMinorCount > 0
    for i = 0 to psychMinorCount - 1
        f_addPsych(psychMinorBase - i * psychMinorStep)
        f_addPsych(psychMinorCeiling + i * psychMinorStep)
 
f_addLevel(custom1On, custom1Price, custom1Name, customColor, 5)
f_addLevel(custom2On, custom2Price, custom2Name, customColor, 5)
f_addLevel(custom3On, custom3Price, custom3Name, customColor, 5)
f_addLevel(custom4On, custom4Price, custom4Name, customColor, 5)
f_addLevel(custom5On, custom5Price, custom5Name, customColor, 5)
f_addLevel(custom6On, custom6Price, custom6Name, customColor, 5)
f_addLevel(custom7On, custom7Price, custom7Name, customColor, 5)
f_addLevel(custom8On, custom8Price, custom8Name, customColor, 5)
 
atrForZone = nz(atr, syminfo.mintick * zoneMinTicks)
zoneHalfWidth = math.max(atrForZone * zoneAtrPct * 0.01, syminfo.mintick * zoneMinTicks)
clusterTolerance = mergeNearbyLabels ? math.max(zoneHalfWidth * 0.35, syminfo.mintick * 2.0) : syminfo.mintick * 0.5
 
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                             DRAWING                                        ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
 
if barstate.islast
    nearestIdx = f_findNearestIndex()
    f_clearObjects()
    totalLevels = array.size(levelValues)
    if totalLevels > 0
        for i = 0 to totalLevels - 1
            f_drawLevel(i, nearestIdx, zoneHalfWidth, clusterTolerance)
 
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                            DASHBOARD                                       ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
 
panelTextSize = f_panelSize(dashboardSize)
P_ROW_A = isDark ? color.new(#0D0D1F, 15) : color.new(#F0F0F8, 15)
P_ROW_B = isDark ? color.new(#12122A, 15) : color.new(#E8E8F2, 15)
P_LABEL = isDark ? color.new(#8888AA, 0) : color.new(#555577, 0)
P_TEXT = isDark ? color.new(color.white, 15) : color.new(#1A1A2E, 5)
P_TITLE = isDark ? color.new(color.white, 0) : color.new(#1A1A2E, 0)
P_BUY = isDark ? #00E676 : #2E7D32
P_SELL = isDark ? #FF8A80 : #C62828
P_MUTED = isDark ? #B0BEC5 : #546E7A
 
pSection(table t, int r, string title, color accent) =>
    sectionBg = isDark ? color.new(accent, 88) : color.new(accent, 86)
    table.cell(t, 0, r, title, bgcolor=sectionBg, text_color=accent, text_size=panelTextSize, text_halign=text.align_center, text_formatting=text.format_bold)
    table.merge_cells(t, 0, r, 2, r)
 
pLevelRow(table t, int r, color bg, color accent, string levelName, string distanceText, float levelValue, bool hasValue) =>
    rowAccent = hasValue ? accent : P_MUTED
    rowName = hasValue ? levelName : "None"
    rowDistance = hasValue ? distanceText + " @ " + str.tostring(levelValue, format.mintick) : "-"
    table.cell(t, 0, r, " | ", bgcolor=bg, text_color=rowAccent, text_size=panelTextSize, text_halign=text.align_center)
    table.cell(t, 1, r, " " + rowName, bgcolor=bg, text_color=hasValue ? P_TEXT : P_LABEL, text_size=panelTextSize, text_halign=text.align_left)
    table.cell(t, 2, r, rowDistance + "  ", bgcolor=bg, text_color=rowAccent, text_size=panelTextSize, text_halign=text.align_right)
 
var table dashboard = table.new(f_tablePosition(dashboardPosition), 3, 8, bgcolor=na, border_width=0, frame_width=0, frame_color=na)
 
if barstate.islast
    table.clear(dashboard, 0, 0, 2, 7)
    if showDashboard
        [aboveName1, aboveValue1, aboveDistance1] = f_findNearestSideRank(true, 0, clusterTolerance)
        [aboveName2, aboveValue2, aboveDistance2] = f_findNearestSideRank(true, 1, clusterTolerance)
        [belowName1, belowValue1, belowDistance1] = f_findNearestSideRank(false, 0, clusterTolerance)
        [belowName2, belowValue2, belowDistance2] = f_findNearestSideRank(false, 1, clusterTolerance)
 
        headerBg = isDark ? color.new(nearestColor, 86) : color.new(nearestColor, 78)
 
        table.cell(dashboard, 0, 0, "PFK Key Levels", bgcolor=headerBg, text_color=P_TITLE, text_size=panelTextSize, text_halign=text.align_center, text_formatting=text.format_bold)
        table.merge_cells(dashboard, 0, 0, 2, 0)
 
        pSection(dashboard, 1, "Resistance Above", P_SELL)
        pLevelRow(dashboard, 2, P_ROW_A, P_SELL, aboveName1, f_distanceText(aboveValue1), aboveValue1, not na(aboveValue1))
        pLevelRow(dashboard, 3, P_ROW_B, P_SELL, aboveName2, f_distanceText(aboveValue2), aboveValue2, not na(aboveValue2))
        pSection(dashboard, 4, "Support Below", P_BUY)
        pLevelRow(dashboard, 5, P_ROW_A, P_BUY, belowName1, f_distanceText(belowValue1), belowValue1, not na(belowValue1))
        pLevelRow(dashboard, 6, P_ROW_B, P_BUY, belowName2, f_distanceText(belowValue2), belowValue2, not na(belowValue2))
        table.cell(dashboard, 0, 7, PFK_VERSION + "  ", bgcolor=P_ROW_A, text_color=P_LABEL, text_size=size.tiny, text_halign=text.align_right)
        table.merge_cells(dashboard, 0, 7, 2, 7)

← 返回列表