Previous Day Range Fib Lite (PDR Fib Lite)

joshuayip · study · 371 行 · 点赞 14 · TradingView 原页

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

Pine Script

//@version=6
indicator("PDR Fib Lite", shorttitle = "PDR Fib", overlay=true, max_lines_count=500, max_labels_count=500)
 
// ═══════════════════════════════════════════════════════════════════
// VERSION HEADER
// ═══════════════════════════════════════════════════════════════════
// PDR Fib Lite
// v1.0 - Initial version: Previous Day/Session Range Fibonacci levels only,
//        plain thin lines + small ratio labels (no boxes, no shading, no tables).
//        - Single session anchor (timezone + hour/minute).
//        - Optional Inverse Levels: mirrors each ratio r to -r.
//        - Optional 50%/CE sub-lines between every pair of adjacent levels.
//        - Independent color/width/style controls per category.
// v1.1 - Added multi-day history for manual backtesting: draws the last N
//        completed sessions, each projected forward through the NEXT session
//        (i.e. day D's range spans from when it was frozen through the next
//        anchor), except the most recent day which extends to the current bar
//        like before. Added optional fade (increasing transparency per day
//        back) so older days are visually distinguishable from the live one.
// v1.2 - Label text color is now independent from line color per category
//        (Main/Inverse/CE), defaulting to white for maximum legibility against
//        a dark chart regardless of line hue. Bumped default line colors to
//        more saturated variants and default widths from 1 to 2 (bolder/less
//        washed out). Added Line Length Mode: "Full Session Width" (previous
//        behavior) or "Fixed Length" - caps every line to a set number of bars
//        from its left edge, giving short stub-style lines instead of spanning
//        the whole session.
// v1.3 - Added mirroring beyond the origin (100%), same mechanism as the existing
//        beyond-extreme mirror: level r -> (2-r). Renamed "Show Inverse Levels" to
//        two separate toggles, "Mirror Beyond Extreme (0%)" and "Mirror Beyond
//        Origin (100%)", covering both sides. Fixed a related bug where levels
//        beyond 100% weren't being styled as mirrored (only negative values were).
//      - Added Level Mode: "Fibonacci" (unchanged 7-level ladder) or "Standard
//        Deviation" (0/0.5/1 core - NOT statistical stdev, ICT-style range
//        multiples). Combining SD mode with both mirror toggles produces a clean
//        -1/-0.5/0/0.5/1/1.5/2 ladder using the same generic mirror mechanism.
// v1.4 - Fixed runtime error RE10026 ("Bar index value... too far from the
//        current bar index"): on a 1-minute chart, ~10,000 bars is only about a
//        week, and the multi-day history was storing bar_index for each day's
//        anchor - once enough bars had accumulated, the oldest stored anchors
//        exceeded Pine's max distance for xloc.bar_index lines/labels and the
//        whole script stopped. Switched every line and label to xloc.bar_time
//        (coordinates in actual time, not bar count), which has no such limit.
//        "N bars" extension settings (Extend Right, Fixed Line Length) now
//        convert bars to a time offset using the chart's own timeframe duration.
// v1.5 - Added "Show Points Between Levels" - labels the point distance between
//        each pair of adjacent rendered lines. Built from the combined, sorted
//        set of levels + CE midpoints actually being drawn, so this naturally
//        becomes level-to-CE-to-next-level when CE is on, or level-to-level
//        directly when it's off - no separate logic needed for each case.
// v1.6 - Publish-ready cleanup. Fixed wasted drawing objects: a Pine for loop whose
//        end is below its start counts down instead of skipping, so with CE off the
//        script allocated 2 unused CE lines and labels per day, and the point labels
//        were allocated even with that toggle off. Both are now only allocated when
//        used, which raises how many days fit under the 500 line/label cap. Indicator
//        title no longer carries a version number; tooltip wording updated.
// v1.7 - Fixed session boundaries on daylight-saving change days. The old detector
//        subtracted a fixed number of hours from each bar's time and read the
//        calendar date, which lands an hour off when a clock change falls inside
//        that window: on the spring-forward Sunday it started a false second
//        session an hour after the real one (19:00 New York with the default
//        anchor), and with some anchor times it started a session an hour early on
//        the fall-back day. It now reads the local wall-clock time directly. Checked
//        against simulated bars: identical to the old logic on ordinary days, and
//        no false boundary on the March change. No inputs added, removed or moved.
// v1.8 - When the 500 label (or line) cap is exceeded, the OLDEST day now loses objects first. Before,
//        the newest day was created first, so it was the first to lose its lowest ratio labels (seen
//        at 7 days with mirrors, CE and point labels all on: 511 labels against a cap of 500). Only
//        the order the days are stored in changed; nothing is drawn differently when under the cap.
// v1.9 - Added an optional vertical line at the anchor time (the start of each session, e.g. 18:00),
//        for every day being drawn. Thin and dotted by default, with its own color, width and style.
//        Off by default. The new inputs are declared last, so saved settings are not moved.
// ═══════════════════════════════════════════════════════════════════
 
// ─── HELPERS ───
calcFibPrice(hi, lo, bullish, r) =>
    sz = hi - lo
    bullish ? hi - r * sz : lo + r * sz
 
toLineStyle(s) =>
    st = line.style_dotted
    if s == "Solid"
        st := line.style_solid
    else if s == "Dashed"
        st := line.style_dashed
    else if s == "Dotted"
        st := line.style_dotted
    st
 
toLabelSize(s) =>
    sz = size.small
    if s == "Tiny"
        sz := size.tiny
    else if s == "Small"
        sz := size.small
    else if s == "Normal"
        sz := size.normal
    sz
 
// Detects the first bar at or after the anchor time (hour:minute) on the wall clock
// of the given timezone, so a session starts at the anchor rather than at midnight.
// Works from the local clock reading instead of subtracting a fixed number of hours,
// which keeps it correct on daylight-saving change days.
// The key is the local calendar date, moved forward one day once the clock reaches
// the anchor time. It changes exactly when the anchor is crossed and not at midnight.
// The date is turned into a day number with a UTC timestamp so month ends count up.
isNewAnchor(h, m, tz) =>
    anchorMin = h * 60 + m
    localMin  = hour(time, tz) * 60 + minute(time, tz)
    localDay  = timestamp("UTC", year(time, tz), month(time, tz), dayofmonth(time, tz), 0, 0)
    key       = localDay + (localMin >= anchorMin ? 86400000 : 0)
    var int prevKey = na
    isNew = na(prevKey) or key != prevKey
    if isNew
        prevKey := key
    isNew
 
// ═══════════════════════════════════════════════════════════════════
// INPUTS
// ═══════════════════════════════════════════════════════════════════
enablePDR      = input.bool(true, "Enable PDR Fib", group = "PDR")
pdrTimezone    = input.string("America/New_York", "Session Timezone", group = "PDR", tooltip = "IANA timezone string, e.g. America/New_York (auto-adjusts EST/EDT), Etc/GMT-8, Etc/GMT+5.")
pdrAnchorHour  = input.int(18, "Anchor Hour (0-23)", minval = 0, maxval = 23, group = "PDR", tooltip = "Session boundary used to compute each day's high/low. 18 = 6:00 PM rollover.")
pdrAnchorMin   = input.int(0, "Anchor Minute", minval = 0, maxval = 59, group = "PDR")
maxDays        = input.int(5, "Number of Days to Draw", minval = 1, maxval = 20, group = "PDR", tooltip = "How many previous completed sessions to draw. Each day's range is projected forward through the NEXT session (fixed in its own historical time slot), except the most recent day which extends live to the current bar. TradingView caps a script at 500 lines and 500 labels, so high day counts combined with mirror levels, CE sub-lines and point labels can reach that cap - if lines or labels start disappearing, reduce this or switch an option off.")
expandLines    = input.bool(true, "Expand Most Recent Day Beyond Current Bar", group = "PDR")
extendBars     = input.int(10, "Extend Right (bars, if expand ON)", minval = 0, group = "PDR")
fadeOlderDays  = input.bool(true, "Fade Older Days (increasing transparency)", group = "PDR", tooltip = "Makes each day further back progressively more transparent, so the live/most-recent day stands out.")
fadeStepPct    = input.int(8, "Fade Step per Day Back (%)", minval = 0, maxval = 20, group = "PDR")
 
labelSizeInput = input.string("Small", "Label Text Size", options = ["Tiny", "Small", "Normal"], group = "PDR")
 
levelMode = input.string("Fibonacci", "Level Mode", options = ["Fibonacci", "Standard Deviation"], group = "Levels", tooltip = "Fibonacci: classic 0 / 0.236 / 0.382 / 0.5 / 0.618 / 0.786 / 1 retracement ratios - best for reading where price has retraced WITHIN the range.\nStandard Deviation: ICT-style range multiples (0 / 0.5 / 1 core) - NOT statistical standard deviation, just the range distance projected outward. Best for reading continuation/reversal targets BEYOND the range. Combine with the mirror toggles below to get the full -1/-0.5/0/0.5/1/1.5/2 ladder.")
showMirrorBelow = input.bool(false, "Mirror Beyond Extreme (0%)", group = "Levels", tooltip = "For every core level r (except 0 itself), also plots -r - reflecting the ladder across the 0% (extreme) line. E.g. 0.236 -> -0.236, and 1 -> -1.")
showMirrorAbove = input.bool(false, "Mirror Beyond Origin (100%)", group = "Levels", tooltip = "For every core level r (except 1 itself), also plots (2-r) - reflecting the ladder across the 100% (origin) line. E.g. 0.382 -> 1.618, and 0 -> 2.")
showCE      = input.bool(false, "Show 50%/CE Sub-lines Between Levels", group = "Levels", tooltip = "Adds a midpoint line between every pair of currently-visible adjacent levels (core + mirrored, if enabled).")
showGapPts  = input.bool(false, "Show Points Between Levels", group = "Levels", tooltip = "Labels the point distance between each pair of adjacent rendered lines. If CE is ON, this naturally becomes level-to-CE and CE-to-next-level (since CE lines sit between their parent levels); if CE is OFF, it's level-to-level directly.")
gapLabelColor = input.color(#9E9E9E, "Points Label Color", group = "Levels")
 
lineLengthMode = input.string("Full Session Width", "Line Length Mode", options = ["Full Session Width", "Fixed Length"], group = "PDR", tooltip = "Full Session Width: each day's line spans from when it was frozen through the next anchor (or to the current bar for the most recent day). Fixed Length: every line is capped to a set number of bars from its left edge, giving short stub-style lines instead.")
lineLengthBars = input.int(20, "Fixed Line Length (bars, if mode is Fixed Length)", minval = 1, group = "PDR")
 
mainColor      = input.color(#00B0FF, "Core Ladder Line Color", group = "Style - Core Ladder")
mainLabelColor = input.color(#FFFFFF, "Core Ladder Label Color", group = "Style - Core Ladder", tooltip = "Independent from the line color, so labels can stay bold/legible regardless of line color choice.")
mainWidthInput = input.int(2, "Core Ladder Width", minval = 1, maxval = 4, group = "Style - Core Ladder")
mainStyleInput = input.string("Dotted", "Core Ladder Style", options = ["Solid", "Dashed", "Dotted"], group = "Style - Core Ladder")
 
invColor      = input.color(#FF1493, "Mirrored Level Line Color", group = "Style - Mirrored Levels", tooltip = "Applies to BOTH mirror directions (beyond extreme and beyond origin).")
invLabelColor = input.color(#FFFFFF, "Mirrored Level Label Color", group = "Style - Mirrored Levels")
invWidthInput = input.int(2, "Mirrored Level Width", minval = 1, maxval = 4, group = "Style - Mirrored Levels")
invStyleInput = input.string("Dashed", "Mirrored Level Style", options = ["Solid", "Dashed", "Dotted"], group = "Style - Mirrored Levels")
 
ceColor      = input.color(#FFC107, "CE/50% Sub-line Line Color", group = "Style - CE Sub-lines")
ceLabelColor = input.color(#FFFFFF, "CE/50% Sub-line Label Color", group = "Style - CE Sub-lines")
ceWidthInput = input.int(2, "CE/50% Sub-line Width", minval = 1, maxval = 4, group = "Style - CE Sub-lines")
ceStyleInput = input.string("Dotted", "CE/50% Sub-line Style", options = ["Solid", "Dashed", "Dotted"], group = "Style - CE Sub-lines")
 
// ─── ANCHOR TIME LINE (new inputs are declared last, so saved settings are not moved) ───
showAnchorLine       = input.bool(false, "Show Anchor Time Vertical Line", group = "Anchor Line", tooltip = "Draws a thin vertical line at the start of each session (the anchor time, e.g. 18:00) for every day being drawn, so you do not need another indicator to mark it. Off by default.")
anchorLineColor      = input.color(color.new(color.gray, 25), "Anchor Line Color", group = "Anchor Line")
anchorLineWidthInput = input.int(1, "Anchor Line Width", minval = 1, maxval = 4, group = "Anchor Line")
anchorLineStyleInput = input.string("Dotted", "Anchor Line Style", options = ["Solid", "Dashed", "Dotted"], group = "Anchor Line")
 
// ═══════════════════════════════════════════════════════════════════
// SESSION TRACKING - keeps the last `maxDays` completed sessions
// ═══════════════════════════════════════════════════════════════════
newSession = isNewAnchor(pdrAnchorHour, pdrAnchorMin, pdrTimezone)
barMs = timeframe.in_seconds() * 1000   // one bar's duration in ms, for converting "N bars" to a time offset
 
var float curSessHigh    = na
var int   curSessHighBar = na
var float curSessLow     = na
var int   curSessLowBar  = na
 
// Index 0 = most recently completed session, index 1 = the one before that, etc.
// anchorTimeHist stores TIME (ms), not bar_index - see v1.4 note above.
var float[] sessHighHist   = array.new<float>()
var float[] sessLowHist    = array.new<float>()
var bool[]  sessBullHist   = array.new<bool>()
var int[]   anchorTimeHist = array.new<int>()
 
if newSession
    if not na(curSessHigh)
        array.unshift(sessHighHist, curSessHigh)
        array.unshift(sessLowHist, curSessLow)
        array.unshift(sessBullHist, curSessHighBar > curSessLowBar)
        array.unshift(anchorTimeHist, time)
        if array.size(sessHighHist) > maxDays
            array.pop(sessHighHist)
            array.pop(sessLowHist)
            array.pop(sessBullHist)
            array.pop(anchorTimeHist)
    curSessHigh    := high
    curSessHighBar := bar_index
    curSessLow     := low
    curSessLowBar  := bar_index
else
    if high > curSessHigh
        curSessHigh    := high
        curSessHighBar := bar_index
    if low < curSessLow
        curSessLow    := low
        curSessLowBar := bar_index
 
// ═══════════════════════════════════════════════════════════════════
// LEVEL LIST CONSTRUCTION (built once - toggle inputs are constant for the run)
// ═══════════════════════════════════════════════════════════════════
var float[] fibLevels    = array.from(0.0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0)
var float[] sdLevels     = array.from(0.0, 0.5, 1.0)
var float[] baseLevels   = levelMode == "Standard Deviation" ? sdLevels : fibLevels
var float[] activeLevels = array.new<float>()
var float[] ceLevels     = array.new<float>()
 
if barstate.isfirst
    for i = 0 to array.size(baseLevels) - 1
        r = array.get(baseLevels, i)
        array.push(activeLevels, r)
        if showMirrorBelow and r != 0.0
            array.push(activeLevels, -r)
        if showMirrorAbove and r != 1.0
            array.push(activeLevels, 2 - r)
    array.sort(activeLevels, order.ascending)
    if showCE
        for i = 0 to array.size(activeLevels) - 2
            a = array.get(activeLevels, i)
            b = array.get(activeLevels, i + 1)
            array.push(ceLevels, (a + b) / 2)
 
var int levelsPerDay   = 0
var int ceLevelsPerDay = 0
if barstate.isfirst
    levelsPerDay   := array.size(activeLevels)
    ceLevelsPerDay := array.size(ceLevels)
 
// Combined, sorted list of every line actually being drawn (levels + CE midpoints,
// if CE is on) - used to compute the point gap between each pair of adjacent lines.
var float[] allPoints = array.new<float>()
if barstate.isfirst
    for i = 0 to array.size(activeLevels) - 1
        array.push(allPoints, array.get(activeLevels, i))
    if showCE
        for i = 0 to array.size(ceLevels) - 1
            array.push(allPoints, array.get(ceLevels, i))
    array.sort(allPoints, order.ascending)
 
// Gap labels are only allocated when the toggle is on - otherwise they would eat into
// the 500-label cap for nothing.
var int gapsPerDay = 0
if barstate.isfirst
    gapsPerDay := showGapPts ? math.max(array.size(allPoints) - 1, 0) : 0
 
// ─── PREALLOCATE DRAWING OBJECTS (maxDays copies of the full level set) ───
// xloc=xloc.bar_time on every line/label here - fixed at creation, must be set now.
// Creation order matters: when a script goes over 500 lines or labels, TradingView deletes the
// OLDEST-CREATED ones first. Slot 0 is created first, and day d uses slot (maxDays - 1 - d), so the
// oldest day sits in the first slot and is the first to lose objects; the newest day is created last.
var line[]  mainLines  = array.new<line>()
var label[] mainLabels = array.new<label>()
var line[]  ceLines    = array.new<line>()
var label[] ceLabels   = array.new<label>()
var label[] gapLabels  = array.new<label>()
 
if barstate.isfirst
    labelSz       = toLabelSize(labelSizeInput)
    mainLineStyle = toLineStyle(mainStyleInput)
    invLineStyle  = toLineStyle(invStyleInput)
    ceLineStyle   = toLineStyle(ceStyleInput)
    for d = 0 to maxDays - 1
        for i = 0 to levelsPerDay - 1
            r      = array.get(activeLevels, i)
            isInv  = r < 0 or r > 1
            col    = isInv ? invColor : mainColor
            lblCol = isInv ? invLabelColor : mainLabelColor
            wid    = isInv ? invWidthInput : mainWidthInput
            sty    = isInv ? invLineStyle : mainLineStyle
            array.push(mainLines, line.new(na, na, na, na, xloc = xloc.bar_time, color = col, width = wid, style = sty))
            array.push(mainLabels, label.new(na, na, "", xloc = xloc.bar_time, style = label.style_label_right, size = labelSz, textcolor = lblCol, color = color.new(color.black, 100)))
        // A Pine for loop whose end is below its start counts DOWN instead of skipping,
        // so a count of 0 (CE or point labels off) must be guarded or it runs twice.
        if ceLevelsPerDay > 0
            for j = 0 to ceLevelsPerDay - 1
                array.push(ceLines, line.new(na, na, na, na, xloc = xloc.bar_time, color = ceColor, width = ceWidthInput, style = ceLineStyle))
                array.push(ceLabels, label.new(na, na, "", xloc = xloc.bar_time, style = label.style_label_right, size = labelSz, textcolor = ceLabelColor, color = color.new(color.black, 100)))
        if gapsPerDay > 0
            for k = 0 to gapsPerDay - 1
                array.push(gapLabels, label.new(na, na, "", xloc = xloc.bar_time, style = label.style_label_right, size = labelSz, textcolor = gapLabelColor, color = color.new(color.black, 100)))
 
// Anchor time vertical lines: one per day drawn, created after everything else and only when switched on.
// extend.both makes it run the full height of the chart; the two points only need different prices.
var line[] anchorLines = array.new<line>()
if barstate.isfirst and showAnchorLine
    for d = 0 to maxDays - 1
        array.push(anchorLines, line.new(na, na, na, na, xloc = xloc.bar_time, extend = extend.both, color = anchorLineColor, width = anchorLineWidthInput, style = toLineStyle(anchorLineStyleInput)))
 
// ═══════════════════════════════════════════════════════════════════
// DRAWING - one full ladder per stored day
// ═══════════════════════════════════════════════════════════════════
numStored = array.size(sessHighHist)
 
for d = 0 to maxDays - 1
    dayValid = enablePDR and d < numStored
    fadePct  = fadeOlderDays ? math.min(80, d * fadeStepPct) : 0
    if dayValid
        hi     = array.get(sessHighHist, d)
        lo     = array.get(sessLowHist, d)
        bull   = array.get(sessBullHist, d)
        dStart   = array.get(anchorTimeHist, d)
        dEndFull = d == 0 ? (expandLines ? time + extendBars * barMs : time) : array.get(anchorTimeHist, d - 1)
        dEnd     = lineLengthMode == "Fixed Length" ? math.min(dStart + lineLengthBars * barMs, dEndFull) : dEndFull
        if showAnchorLine
            // dStart is the anchor bar. The previous session's high and low keep the two points near price.
            anchorLn = array.get(anchorLines, d)
            line.set_xy1(anchorLn, dStart, lo)
            line.set_xy2(anchorLn, dStart, hi + syminfo.mintick)
        for i = 0 to levelsPerDay - 1
            r       = array.get(activeLevels, i)
            isInv   = r < 0 or r > 1
            baseCol = isInv ? invColor : mainColor
            lblCol  = isInv ? invLabelColor : mainLabelColor
            y      = calcFibPrice(hi, lo, bull, r)
            objIdx = (maxDays - 1 - d) * levelsPerDay + i
            ln     = array.get(mainLines, objIdx)
            lb     = array.get(mainLabels, objIdx)
            line.set_xy1(ln, dStart, y)
            line.set_xy2(ln, dEnd, y)
            line.set_color(ln, color.new(baseCol, fadePct))
            label.set_xy(lb, dStart, y)
            label.set_text(lb, str.tostring(r, "#.###"))
            label.set_textcolor(lb, color.new(lblCol, fadePct))
        if showCE
            for j = 0 to ceLevelsPerDay - 1
                r        = array.get(ceLevels, j)
                y        = calcFibPrice(hi, lo, bull, r)
                objIdxCE = (maxDays - 1 - d) * ceLevelsPerDay + j
                ln       = array.get(ceLines, objIdxCE)
                lb       = array.get(ceLabels, objIdxCE)
                line.set_xy1(ln, dStart, y)
                line.set_xy2(ln, dEnd, y)
                line.set_color(ln, color.new(ceColor, fadePct))
                label.set_xy(lb, dStart, y)
                label.set_text(lb, "CE")
                label.set_textcolor(lb, color.new(ceLabelColor, fadePct))
        if showGapPts
            for k = 0 to gapsPerDay - 1
                rLo = array.get(allPoints, k)
                rHi = array.get(allPoints, k + 1)
                yLo = calcFibPrice(hi, lo, bull, rLo)
                yHi = calcFibPrice(hi, lo, bull, rHi)
                gapPts = math.abs(yHi - yLo)
                midY   = (yLo + yHi) / 2
                objIdxGap = (maxDays - 1 - d) * gapsPerDay + k
                glb = array.get(gapLabels, objIdxGap)
                label.set_xy(glb, dStart, midY)
                label.set_text(glb, str.tostring(gapPts, "#.##") + " pts")
                label.set_textcolor(glb, color.new(gapLabelColor, fadePct))
    else
        if showAnchorLine
            line.set_xy1(array.get(anchorLines, d), na, na)
        for i = 0 to levelsPerDay - 1
            objIdx = (maxDays - 1 - d) * levelsPerDay + i
            line.set_xy1(array.get(mainLines, objIdx), na, na)
            label.set_xy(array.get(mainLabels, objIdx), na, na)
        if ceLevelsPerDay > 0
            for j = 0 to ceLevelsPerDay - 1
                objIdxCE = (maxDays - 1 - d) * ceLevelsPerDay + j
                line.set_xy1(array.get(ceLines, objIdxCE), na, na)
                label.set_xy(array.get(ceLabels, objIdxCE), na, na)
        if gapsPerDay > 0
            for k = 0 to gapsPerDay - 1
                objIdxGap = (maxDays - 1 - d) * gapsPerDay + k
                label.set_xy(array.get(gapLabels, objIdxGap), na, na)

← 返回列表