Donchian Breakout & Retest Signals [bitpunk]

bitpunk_labs · study · 268 行 · 点赞 151 · TradingView 原页

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

Pine Script

// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Bitpunk
//@version=6
indicator("Donchian Breakout & Retest Signals [bitpunk]", shorttitle="bitpunk.donchian", overlay=true)
// Independent public breakout and retest definitions. See research/design.md.
 
int length = input.int(20, "Channel Length", minval=5, maxval=200, tooltip="Highest high / lowest low of these preceding candles, excluding the breakout candle. The broken edge is then frozen.", display=display.none)
int validityBars = input.int(10, "Retest Window", minval=1, maxval=60, tooltip="Following candles available to find a held retest. Confirmation has its own window. Same-side breakouts do not renew a live watch; an opposite breakout replaces it.", display=display.none)
int confirmationBars = input.int(5, "Confirmation Window", minval=1, maxval=30, tooltip="Following candles after the first held retest available to close beyond its frozen high/low. A test on the final Retest Window candle still receives this full window.", display=display.none)
float pocket = input.float(0.25, "Retest Pocket (TR)", minval=0, maxval=1, step=0.05, tooltip="Half-width around the frozen edge in its prior 20-bar mean TR. A later wick must intersect this pocket and its close must hold the adverse boundary. The first held retest with a reachable confirmation gate is frozen. Unreachable tests do not renew the original window. Zero requires exact edge contact.", display=display.none)
float maxExtension = input.float(0.0, "Max Retest Extension (TR)", minval=0, maxval=3, step=0.1, tooltip="Optional R confirmation-close distance beyond the frozen edge in its frozen TR scale. Zero disables the cap. An oversized confirmation consumes the retest watch. Breakout B events are never capped.", display=display.none)
bool bodyRetestGate = input.bool(true, "Body Retest Gate", group="Signals", tooltip="Provisional R timing; earlier confirmation can be weaker, and market efficacy is unproven. Turn off to restore Original. Review by 2027-01-01. R timing: Use the held retest candle body extreme as the frozen confirmation gate. A later close must still clear the original edge. Raw B events, clocks, edge-loss cancellation and wick-feasibility checks are unchanged. Earlier confirmation can admit weaker events.", display=display.none)
bool structureSignals = input.bool(true, "Structure Signal Reset", group="Signals", tooltip="One breakout and one retest per direction until a completed close returns to the rolling channel midpoint. Can miss useful continuation entries. Turn off for the previous event stream. Recreate saved alerts after changing this setting.", display=display.none)
string signalType = input.string("Both", "Signal Type", options=["Both", "Breakout", "Retest"], tooltip="Select markers and alerts; both raw event engines keep running. B = first close in a consecutive same-side channel-breakout run. R = later retest confirmation. If both coincide, Both shows R once.", display=display.none)
bool enableSignals = input.bool(true, "Enable Signals", group="Signals", tooltip="Enable entry markers and signal alerts. Disabling keeps structure, setup state and context readings active. Recreate existing alerts after changing this setting.", display=display.none)
bool showStructure = input.bool(true, "Structure", group="Display", tooltip="Show the rolling channel and frozen retest area/gate. Display switches never change events or alerts.", display=display.none)
string panelChoice = input.string("bottom", "Status Panel", options=["none", "bottom", "top", "bottom-left", "top-left"], group="Display", display=display.none)
string panelSize = input.string("small", "Panel Size", options=["small", "medium", "large"], group="Display", display=display.none)
string structureEffects = input.string("Enhanced", "Structure Effects", options=["Normal", "Enhanced"], group="Display", tooltip="Enhanced uses quiet native glass with a transparent center. Exact boundaries and the signal definition are unchanged.", display=display.none)
string signalEffects = input.string("Enhanced", "Signal Effects", options=["Normal", "Enhanced"], group="Display", tooltip="White ▲/▼ with LB/SB (breakout) or LR/SR (retest) on theme backgrounds. Enhanced adds a close pin and soft glow. The letter identifies timing, not a signal grade.", display=display.none)
color bullColor = input.color(color.rgb(0, 194, 255), "Bull", inline="theme", group="Theme Colors", display=display.none)
color bearColor = input.color(color.rgb(255, 56, 100), "Bear", inline="theme", group="Theme Colors", display=display.none)
 
// Pure visual helpers from the public Compression Break product; no private dependency.
// Public presentation helpers: opaque primary ink and readable white glyphs.
f_v_linear(float channel) =>
    float unit = channel / 255.0
    unit <= 0.04045 ? unit / 12.92 : math.pow((unit + 0.055) / 1.055, 2.4)
f_v_luminance(color value) =>
    0.2126 * f_v_linear(color.r(value)) + 0.7152 * f_v_linear(color.g(value)) + 0.0722 * f_v_linear(color.b(value))
f_v_contrast(color first, color second) =>
    float a = f_v_luminance(first)
    float b = f_v_luminance(second)
    (math.max(a, b) + 0.05) / (math.min(a, b) + 0.05)
f_v_ink(color source) =>
    color result = color.rgb(color.r(source), color.g(source), color.b(source))
    bool lightBackground = f_v_luminance(chart.bg_color) > 0.179
    for step = 0 to 15
        if f_v_contrast(result, chart.bg_color) < 3.2
            result := lightBackground ? color.rgb(math.floor(color.r(result) * 0.8), math.floor(color.g(result) * 0.8), math.floor(color.b(result) * 0.8)) : color.rgb(math.ceil(color.r(result) + (255 - color.r(result)) * 0.2), math.ceil(color.g(result) + (255 - color.g(result)) * 0.2), math.ceil(color.b(result) + (255 - color.b(result)) * 0.2))
    result
f_v_label(color source) =>
    color result = color.rgb(color.r(source), color.g(source), color.b(source))
    for step = 0 to 15
        if f_v_luminance(result) > 0.175
            result := color.rgb(math.floor(color.r(result) * 0.9), math.floor(color.g(result) * 0.9), math.floor(color.b(result) * 0.9))
    result
var color f_vBullInk = f_v_ink(bullColor)
var color f_vBearInk = f_v_ink(bearColor)
var color f_vBullLabel = f_v_label(bullColor)
var color f_vBearLabel = f_v_label(bearColor)
f_panel_position(string choice) =>
    switch choice
        "top" => position.top_right
        "top-left" => position.top_left
        "bottom-left" => position.bottom_left
        => position.bottom_right
f_dim(color source, float strength) =>
    color.from_gradient(strength, 0, 1, chart.bg_color, source)
f_ink(color source) =>
    float luminance = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color)
    luminance > 128 ? color.from_gradient(0.35, 0, 1, source, chart.fg_color) : source
f_signal(color source) =>
    float luminance = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color)
    luminance > 128 ? color.from_gradient(0.50, 0, 1, source, chart.fg_color) : color.from_gradient(0.78, 0, 1, chart.bg_color, source)
f_tf() =>
    float seconds = timeframe.isticks ? na : timeframe.in_seconds()
    seconds < 60 ? str.tostring(seconds) + "s" : seconds < 3600 ? str.tostring(seconds / 60) + "m" : seconds < 86400 ? str.tostring(seconds / 3600) + "h" : timeframe.period == "D" ? "1D" : timeframe.period == "W" ? "1W" : timeframe.period == "M" ? "1M" : timeframe.period
// Dimensionless comparisons avoid Pine's absolute nine-decimal comparison
// floor on small quotes. This adds no price tolerance or user parameter.
f_distance(float price, float referencePrice, float scale) =>
    (price - referencePrice) / scale
var color neutralColor = chart.fg_color
var color bullInk = f_v_ink(bullColor)
var color bearInk = f_v_ink(bearColor)
var color bullSignal = f_signal(bullColor)
var color bearSignal = f_signal(bearColor)
 
// Current candles cannot expand the channel they are breaking.
float priorUpper = ta.highest(high, length)[1]
float priorLower = ta.lowest(low, length)[1]
float priorScale = ta.sma(ta.tr(true), 20)[1]
bool supported = chart.is_standard and not timeframe.isticks and not na(time_close)
bool pricesReady = not na(high) and not na(low) and not na(close) and high >= low and close >= low and close <= high
bool trueRangeReady = pricesReady and not na(close[1])
bool channelReady = math.sum(pricesReady ? 1.0 : 0.0, length)[1] == length
bool scaleReady = math.sum(trueRangeReady ? 1.0 : 0.0, 20)[1] == 20
bool dataReady = supported and pricesReady and channelReady and scaleReady and not na(priorScale) and math.sign(priorScale) == 1 and math.sign(priorUpper - priorLower) == 1
var int previousOutsideSide = 0
var int pendingSide = 0
var int setupSide = 0
var int startedAt = na
var int touchedAt = na
var float frozenEdge = na
var float frozenScale = na
var float frozenGate = na
var string status = "Warming up"
bool longBreakout = false
bool shortBreakout = false
bool longRetest = false
bool shortRetest = false
bool newSetup = false
bool heldRetest = false
if barstate.isconfirmed
    if not dataReady
        pendingSide := 0
        previousOutsideSide := 0
        status := supported ? "Warming up" : "Standard time chart required"
    else
        int breakoutSide = f_distance(close, priorUpper, priorScale) > 0 ? 1 : f_distance(close, priorLower, priorScale) < 0 ? -1 : 0
        // B events are independent of the retest watch. Equality rearms the run.
        int freshBreakSide = breakoutSide != 0 and breakoutSide != previousOutsideSide ? breakoutSide : 0
        previousOutsideSide := breakoutSide
        longBreakout := freshBreakSide == 1
        shortBreakout := freshBreakSide == -1
        // Opposite replacement has priority. Resolve stale watches BEFORE admission.
        if pendingSide != 0
            bool expired = na(touchedAt) ? bar_index - startedAt > validityBars : bar_index - touchedAt > confirmationBars
            if freshBreakSide == -pendingSide
                pendingSide := 0
                status := "Opposite breakout · replace watch"
            else if expired
                pendingSide := 0
                status := na(touchedAt) ? "Retest window expired" : "Confirmation window expired"
            else if pendingSide * f_distance(close, frozenEdge, frozenScale) < -pocket
                pendingSide := 0
                status := "Broken edge lost"
            else if not na(touchedAt) and bar_index > touchedAt and pendingSide * f_distance(close, frozenGate, frozenScale) > 0 and pendingSide * f_distance(close, frozenEdge, frozenScale) > 0
                bool withinCap = maxExtension == 0 or pendingSide * f_distance(close, frozenEdge, frozenScale) <= maxExtension
                longRetest := pendingSide == 1 and withinCap
                shortRetest := pendingSide == -1 and withinCap
                pendingSide := 0
                status := withinCap ? (longRetest ? "Long R · retest confirmed" : "Short R · retest confirmed") : "Retest extended · watch consumed"
            else if na(touchedAt) and bar_index > startedAt and f_distance(low, frozenEdge, frozenScale) <= pocket and f_distance(high, frozenEdge, frozenScale) >= -pocket
                float contactExtreme = pendingSide > 0 ? high : low
                float candidateGate = bodyRetestGate ? (pendingSide > 0 ? math.max(open, close) : math.min(open, close)) : contactExtreme
                // Skip only this infeasible contact; retain the edge and retest clock.
                bool gateDataReady = not bodyRetestGate or (not na(open) and open >= low and open <= high)
                if not gateDataReady
                    status := "Retest body unavailable"
                else if maxExtension > 0 and pendingSide * f_distance(contactExtreme, frozenEdge, frozenScale) >= maxExtension
                    status := "Retest too wide · await cleaner test"
                else
                    touchedAt := bar_index
                    frozenGate := candidateGate
                    heldRetest := true
                    status := pendingSide > 0 ? "Long retest held · wait for break" : "Short retest held · wait for break"
        if pendingSide == 0 and freshBreakSide != 0 and not (longRetest or shortRetest)
            pendingSide := freshBreakSide
            setupSide := freshBreakSide
            startedAt := bar_index
            frozenEdge := freshBreakSide > 0 ? priorUpper : priorLower
            frozenScale := priorScale
            touchedAt := na
            frozenGate := na
            newSetup := true
            status := freshBreakSide > 0 ? "Long B · wait for retest" : "Short B · wait for retest"
        else if pendingSide != 0 and freshBreakSide != 0 and not newSetup and not (longRetest or shortRetest)
            // A same-side B event is visible, but never renews the older R watch.
            if not heldRetest
                status := na(touchedAt) ? "New B · original retest watch" : "New B · original confirmation watch"
        else if pendingSide == 0 and status == "Warming up"
            status := "Await channel breakout"
 
// Independent event locks: B never consumes R, and selection never changes locks.
var int lastBreakSignalSide = 0
var int lastRetestSignalSide = 0
bool acceptedLongBreakout = false
bool acceptedShortBreakout = false
bool acceptedLongRetest = false
bool acceptedShortRetest = false
if barstate.isconfirmed
    if not dataReady
        lastBreakSignalSide := 0
        lastRetestSignalSide := 0
    else
        float channelMidpoint = priorLower + (priorUpper - priorLower) * 0.5
        if lastBreakSignalSide != 0 and lastBreakSignalSide * f_distance(close, channelMidpoint, priorScale) <= 0
            lastBreakSignalSide := 0
        if lastRetestSignalSide != 0 and lastRetestSignalSide * f_distance(close, channelMidpoint, priorScale) <= 0
            lastRetestSignalSide := 0
        acceptedLongBreakout := longBreakout and (not structureSignals or lastBreakSignalSide != 1)
        acceptedShortBreakout := shortBreakout and (not structureSignals or lastBreakSignalSide != -1)
        acceptedLongRetest := longRetest and (not structureSignals or lastRetestSignalSide != 1)
        acceptedShortRetest := shortRetest and (not structureSignals or lastRetestSignalSide != -1)
        if acceptedLongBreakout or acceptedShortBreakout
            lastBreakSignalSide := acceptedLongBreakout ? 1 : -1
        if acceptedLongRetest or acceptedShortRetest
            lastRetestSignalSide := acceptedLongRetest ? 1 : -1
 
// Select outputs AFTER both event engines; R wins a same-side B/R coincidence.
bool includeBreakout = signalType != "Retest"
bool includeRetest = signalType != "Breakout"
bool longRetestSignal = includeRetest and acceptedLongRetest
bool shortRetestSignal = includeRetest and acceptedShortRetest
bool longBreakoutSignal = includeBreakout and acceptedLongBreakout and not longRetestSignal
bool shortBreakoutSignal = includeBreakout and acceptedShortBreakout and not shortRetestSignal
bool longSignal = longBreakoutSignal or longRetestSignal
bool shortSignal = shortBreakoutSignal or shortRetestSignal
 
// Native glass around the active frozen edge; quiet lines show the whole channel.
plot(showStructure and dataReady ? priorUpper : na, "Donchian Upper", color.new(bullInk, 72), 1, plot.style_linebr, display=display.pane)
plot(showStructure and dataReady ? priorLower : na, "Donchian Lower", color.new(bearInk, 72), 1, plot.style_linebr, display=display.pane)
bool setupVisible = pendingSide != 0 or longRetest or shortRetest
float reference = showStructure and setupVisible and not newSetup ? frozenEdge : na
color accent = setupSide > 0 ? bullInk : bearInk
bool retestReady = not na(touchedAt)
bool enhancedStructure = structureEffects == "Enhanced"
float entryLimit = setupVisible and maxExtension > 0 ? frozenEdge + setupSide * maxExtension * frozenScale : na
plot(enhancedStructure ? reference : na, "Broken Edge Glow", color.new(accent, retestReady ? 86 : 94), 6, plot.style_linebr, display=display.pane, editable=false)
centerPlot = plot(reference, "Frozen Broken Edge", color.new(accent, retestReady ? 0 : 22), 2, plot.style_linebr, display=display.pane)
upperPlot = plot(reference + pocket * frozenScale, "Retest Pocket Upper", color.new(accent, retestReady ? 38 : 62), 1, plot.style_linebr, display=display.pane)
lowerPlot = plot(reference - pocket * frozenScale, "Retest Pocket Lower", color.new(accent, retestReady ? 38 : 62), 1, plot.style_linebr, display=display.pane)
color glass = color.new(accent, enhancedStructure ? (retestReady ? 92 : 97) : 98)
fill(upperPlot, centerPlot, reference + pocket * frozenScale, reference, glass, color.new(accent, 100), title="Upper Glass", fillgaps=false)
fill(centerPlot, lowerPlot, reference, reference - pocket * frozenScale, color.new(accent, 100), glass, title="Lower Glass", fillgaps=false)
plot(showStructure and setupVisible and not newSetup ? frozenGate : na, "Retest Confirmation Gate", color.new(accent, 30), 1, plot.style_linebr, display=display.pane, linestyle=plot.linestyle_dotted)
plot(showStructure and not newSetup ? entryLimit : na, "Retest Extension Limit", color.new(accent, 65), 1, plot.style_linebr, display=display.pane, linestyle=plot.linestyle_dashed)
plotshape(showStructure and enhancedStructure and heldRetest ? frozenEdge : na, "Held Retest", shape.circle, location.absolute, color.new(accent, 10), size=size.tiny, display=display.pane)
plot(setupVisible ? frozenEdge : na, "Exact Broken Edge", display=display.data_window)
plot(setupVisible ? frozenGate : na, "Exact Price Gate", display=display.data_window)
plot(pendingSide, "Pending Side", display=display.data_window)
plot(pendingSide != 0 ? (na(touchedAt) ? 1 : 2) : 0, "Setup Phase", display=display.data_window)
int completedIndex = barstate.isconfirmed ? bar_index : bar_index - 1
int remainingCloses = pendingSide != 0 ? (na(touchedAt) ? validityBars - (completedIndex - startedAt) : confirmationBars - (completedIndex - touchedAt)) : na
plot(remainingCloses, "Eligible Future Closes", display=display.data_window)
plot(entryLimit, "Exact Retest Limit", display=display.data_window)
plot(longBreakout ? 1 : shortBreakout ? -1 : 0, "Raw Breakout Side", display=display.data_window)
plot(longRetest ? 1 : shortRetest ? -1 : 0, "Raw Retest Side", display=display.data_window)
string detail = pendingSide != 0 ? "Edge " + str.tostring(frozenEdge, format.mintick) + " · " + (na(touchedAt) ? "retest " : "confirm ") + str.tostring(remainingCloses) + " closes" : str.tostring(length) + "-bar channel · B breakout / R retest"
 
// Fixed sizes keep plotshape parameters const; cosmetic effects never grade events.
bool enhancedSignal = signalEffects == "Enhanced"
color entryAccent = longSignal ? bullColor : bearColor
color entryInk = longSignal ? bullSignal : bearSignal
plotshape(enableSignals and (enhancedSignal and (longSignal or shortSignal)) ? close : na, "Entry Glow", shape.circle, location.absolute, color.new(entryAccent, 80), size=size.large, display=display.pane)
plotshape(enableSignals and (enhancedSignal and (longSignal or shortSignal)) ? close : na, "Entry Close Pin", shape.circle, location.absolute, longSignal ? f_vBullInk : f_vBearInk, size=size.tiny, display=display.pane)
plotshape(enableSignals and (longBreakoutSignal), "Long Breakout B", shape.labelup, location.belowbar, f_vBullLabel, text="▲ LB", textcolor=color.white, size=size.tiny, display=display.pane)
plotshape(enableSignals and (shortBreakoutSignal), "Short Breakout B", shape.labeldown, location.abovebar, f_vBearLabel, text="▼ SB", textcolor=color.white, size=size.tiny, display=display.pane)
plotshape(enableSignals and (longRetestSignal), "Long Retest R", shape.labelup, location.belowbar, f_vBullLabel, text="▲ LR", textcolor=color.white, size=size.tiny, display=display.pane)
plotshape(enableSignals and (shortRetestSignal), "Short Retest R", shape.labeldown, location.abovebar, f_vBearLabel, text="▼ SR", textcolor=color.white, size=size.tiny, display=display.pane)
plot(enableSignals and (longSignal) ? close : na, "Long Entry Close", display=display.data_window)
plot(enableSignals and (shortSignal) ? close : na, "Short Entry Close", display=display.data_window)
 
// Select a directional condition OR Any alert() function call to avoid duplicates.
alertcondition(enableSignals and (longSignal), "Long Channel Signal", "{{interval}} ▲ LONG CHANNEL @{{close}}")
alertcondition(enableSignals and (shortSignal), "Short Channel Signal", "{{interval}} ▼ SHORT CHANNEL @{{close}}")
if enableSignals and barstate.isrealtime and barstate.isconfirmed and (longSignal or shortSignal)
    string eventName = longRetestSignal or shortRetestSignal ? " RETEST" : " BREAKOUT"
    alert(f_tf() + (longSignal ? " ▲ LONG" : " ▼ SHORT") + eventName + " @" + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
// The card reports a completed setup, never a probability or an open position.
var table panel = na
if barstate.islast
    if panelChoice == "none"
        if not na(panel)
            table.delete(panel)
            panel := na
    else
        if na(panel)
            panel := table.new(position.bottom_right, 1, 3, bgcolor=f_dim(chart.fg_color, 0.025), frame_color=f_dim(chart.fg_color, 0.12), frame_width=1, border_width=0)
        table.set_position(panel, f_panel_position(panelChoice))
        string panelTextSize = panelSize == "small" ? size.tiny : panelSize == "large" ? size.normal : size.small
        string panelHeadingSize = panelSize == "small" ? size.small : panelSize == "large" ? size.large : size.normal
        color panelAccent = pendingSide > 0 or longSignal ? bullColor : pendingSide < 0 or shortSignal ? bearColor : neutralColor
        string eventStatus = longRetestSignal ? "Long R · retest confirmed" : shortRetestSignal ? "Short R · retest confirmed" : longBreakoutSignal ? "Long B · channel breakout" : shortBreakoutSignal ? "Short B · channel breakout" : status
        table.cell(panel, 0, 0, "  DONCHIAN CHANNEL · " + f_tf() + "  ", bgcolor=f_dim(panelAccent, 0.06), text_color=f_ink(panelAccent), text_size=panelHeadingSize, text_halign=text.align_left)
        table.cell(panel, 0, 1, "  " + eventStatus + "  ", text_color=f_dim(chart.fg_color, 0.86), text_size=panelTextSize, text_halign=text.align_left)
        table.cell(panel, 0, 2, "  " + detail + "  ", text_color=f_dim(chart.fg_color, 0.60), text_size=panelTextSize, text_halign=text.align_left)

← 返回列表