[blackcat] L2 Better Donchian Trend Ranges

blackcat1402 · study · 212 行 · 点赞 165 · TradingView 原页

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

Pine Script

//@version=6
indicator(title = '[blackcat] L2 Better Donchian Trend Ranges', shorttitle = 'Better Donchian Trend', overlay = true, max_labels_count = 500)
 
// ═══════════════ Input groups (const strings) ═══════════════
var string GRP_ENG  = '1) Engine'
var string GRP_SIG  = '2) Signal Governance'
var string GRP_RISK = '3) Risk (ATR TP/SL)'
var string GRP_VIS  = '4) Visuals'
 
// ═══════════════ Inputs: Engine (V1 defaults unchanged) ═══════════════
length   = input.int(50, 'Donchian Length', minval = 1, group = GRP_ENG)
mult     = input.float(3, 'Range Multiplier', minval = 1, group = GRP_ENG)
hystMult = input.float(0.35, 'Step Hysteresis (x ATR)', minval = 0, step = 0.05, group = GRP_ENG)
robustP  = input.int(5, 'Robust Extremes % (0 = classic)', minval = 0, maxval = 45, group = GRP_ENG)
useAtrW  = input.bool(false, 'Band Width Engine: ATR (Keltner hybrid)', group = GRP_ENG)
atrWBoost = input.float(1.5, 'ATR Width Boost', minval = 0.5, step = 0.1, group = GRP_ENG, tooltip = 'Multiplier for the ATR band-width engine. 1.5 reproduces the V1 hardcoded value.')
colorUp   = input.color(#00ffbb, 'Up Color', group = GRP_VIS, inline = 'colors')
colorDown = input.color(#ff1100, 'Down Color', group = GRP_VIS, inline = 'colors')
 
// Robust Donchian extremes: percentile filter replaces single-bar spike extremes
uMax = ta.highest(high, length)
uPct = ta.percentile_nearest_rank(high, length, 100 - robustP)
lMax = ta.lowest(low, length)
lPct = ta.percentile_nearest_rank(low, length, robustP)
u = robustP == 0 ? uMax : uPct
l = robustP == 0 ? lMax : lPct
basis = math.avg(u, l)
 
// Hysteresis deadband stepping replaces float-equality freeze (tunable responsiveness vs noise)
vol = ta.atr(14)
hyst = hystMult * nz(vol)
var float fbasis = na
fbasis := na(fbasis) ? basis : math.abs(basis - fbasis) > hyst ? basis : fbasis
 
// Band width: stdev (default) or drift-free ATR hybrid; refreshes only on step (channel property kept)
devStd = ta.stdev(close, length, false) * mult
devAtr = vol * mult * atrWBoost
dev = useAtrW ? devAtr : devStd
var float rangge = na
rangge := na(rangge) ? dev : fbasis != fbasis[1] ? dev : rangge
 
upper = fbasis + rangge
lower = fbasis - rangge
 
fu = fbasis + vol
fl = fbasis - vol
uu = upper + vol
ul = upper - vol
lu = lower + vol
ll = lower - vol
 
// ═══════════════ Raw edge triggers (V1 semantics preserved) ═══════════════
xBull = ta.crossover(close, fbasis)
xBear = ta.crossunder(close, fbasis)
xUl = ta.crossunder(close, ul)
xUu = ta.crossunder(close, uu)
xLu = ta.crossover(close, lu)
xLl = ta.crossover(close, ll)
 
strongLongTpRaw  = xUu
weakLongTpRaw    = xUl and not xUu
strongShortTpRaw = xLl
weakShortTpRaw   = xLu and not xLl
 
// ═══════════════ Inputs: Signal Governance ═══════════════
useExclusivity = input.bool(true, 'Same-bar Entry/Exit Exclusivity', group = GRP_SIG)
cooldownBars   = input.int(3, 'Cooldown Bars', minval = 0, group = GRP_SIG)
useTrendExit   = input.bool(false, 'Exit on Opposite Trend Shift', group = GRP_SIG, tooltip = 'Off (default): position flips directly on opposite trend shift. On: opposite shift closes the position first; reversal entry is then subject to cooldown.')
 
// Exit predicates: band TP triggers while holding, optionally opposite trend shift
longExitCond  = xUl or xUu or (useTrendExit and xBear)
shortExitCond = xLu or xLl or (useTrendExit and xBull)
 
// ═══════════════ State machine (entries = trend shifts, exits = band TP) ═══════════════
var int posState      = 0     // +1 long / 0 flat / -1 short
var int lastSignalBar = na
 
cooldownOK = na(lastSignalBar) or bar_index - lastSignalBar > cooldownBars
 
rawLongEntry  = xBull and posState <= 0 and cooldownOK
rawShortEntry = xBear and posState >= 0 and cooldownOK
rawLongExit   = longExitCond  and posState == 1
rawShortExit  = shortExitCond and posState == -1
 
longExit   = useExclusivity ? rawLongExit  and not rawLongEntry and not rawShortEntry : rawLongExit
shortExit  = useExclusivity ? rawShortExit and not rawLongEntry and not rawShortEntry : rawShortExit
longEntry  = useExclusivity ? rawLongEntry  and not longExit and not shortExit : rawLongEntry
shortEntry = useExclusivity ? rawShortEntry and not longExit and not shortExit : rawShortEntry
 
// Exit strength (evaluated before state mutation)
longExitStrong  = longExit  and xUu
shortExitStrong = shortExit and xLl
 
// State migration + entry price tracking (at most one change per bar)
var float entryPrice = na
if longEntry
    posState := 1
    lastSignalBar := bar_index
    entryPrice := close
else if shortEntry
    posState := -1
    lastSignalBar := bar_index
    entryPrice := close
else if longExit or shortExit
    posState := 0
    lastSignalBar := bar_index
    entryPrice := na
 
plot(posState, 'Position State', display = display.data_window)
 
// ═══════════════ Risk: ATR TP/SL reference levels ═══════════════
atrLen  = input.int(14, 'ATR Length', minval = 1, group = GRP_RISK)
slMult  = input.float(2.0, 'Stop Loss (xATR)', minval = 0.5, step = 0.25, group = GRP_RISK)
tpMult  = input.float(3.0, 'Take Profit (xATR)', minval = 0.5, step = 0.25, group = GRP_RISK)
useTPSL = input.bool(true, 'Show TP/SL Levels', group = GRP_RISK)
 
atrRisk = ta.atr(atrLen)
float slPrice = useTPSL and not na(entryPrice) and posState != 0 ? entryPrice - posState * slMult * atrRisk : na
float tpPrice = useTPSL and not na(entryPrice) and posState != 0 ? entryPrice + posState * tpMult * atrRisk : na
plot(slPrice, 'Stop Loss', color = color.new(color.red, 0), style = plot.style_linebr)
plot(tpPrice, 'Take Profit', color = color.new(color.teal, 0), style = plot.style_linebr)
 
// ═══════════════ Channel plots & fills (V1 unchanged) ═══════════════
midu = plot(fu, 'Basis', color = color.blue, display = display.none)
mmm = plot(fbasis, 'Basis', color = color.new(close > fbasis ? colorUp : colorDown, 3), display = display.all)
midl = plot(fl, 'Basis', color = color.blue, display = display.none)
 
upu = plot(uu, 'upper', color = color.blue, display = display.none)
uuu = plot(upper, 'upper', color = color.blue, display = display.none)
upl = plot(ul, 'upper', color = color.blue, display = display.none)
 
lpu = plot(lu, 'lower', color = color.blue, display = display.none)
lll = plot(lower, 'lower', color = color.blue, display = display.none)
lpl = plot(ll, 'lower', color = color.blue, display = display.none)
 
plot(math.avg(fu, ul), 'Upper Inter Range', color.new(chart.fg_color, 80), 1, plot.style_circles)
plot(math.avg(fl, lu), 'Lower Inter Range', color.new(chart.fg_color, 80), 1, plot.style_circles)
 
fill(upu, uuu, color.new(colorDown, close > fbasis ? 65 : 90), 'Upper Cloud')
fill(upl, uuu, color.new(colorDown, 90), 'Upper Cloud')
fill(midu, midl, color.new(chart.fg_color, 90), 'Basis Cloud')
fill(lpl, lll, color.new(colorUp, close < fbasis ? 65 : 90), 'lower Cloud')
fill(lpu, lll, color.new(colorUp, 90), 'lower Cloud')
 
// ═══════════════ Visuals: color semantics ═══════════════
color C_LONG  = color.new(color.green, 0)
color C_SHORT = color.new(color.red, 0)
color C_EXIT  = color.new(color.orange, 0)
 
// ═══════════════ Visuals: classic raw TP marks (V1 plotchars, opt-in) ═══════════════
showTpChars = input.bool(false, 'Show Raw TP Marks (classic)', group = GRP_VIS)
plotchar(showTpChars and strongLongTpRaw, 'Strong Long TP', 'X', location.abovebar, colorDown, size = size.tiny)
plotchar(showTpChars and strongShortTpRaw, 'Strong Short TP', 'X', location.belowbar, colorUp, size = size.tiny)
plotchar(showTpChars and weakLongTpRaw, 'Weak Long TP', '◆', location.abovebar, colorDown, size = size.tiny)
plotchar(showTpChars and weakShortTpRaw, 'Weak Short TP', '◆', location.belowbar, colorUp, size = size.tiny)
 
// ═══════════════ Visuals: signal labels (state-machine governed) ═══════════════
showLabels = input.bool(true, 'Show Signal Labels', group = GRP_VIS)
if showLabels and longEntry
    label.new(bar_index, low, 'LE', style = label.style_label_up, color = C_LONG, textcolor = color.white, size = size.small)
if showLabels and shortEntry
    label.new(bar_index, high, 'SE', style = label.style_label_down, color = C_SHORT, textcolor = color.white, size = size.small)
if showLabels and longExit
    label.new(bar_index, high, longExitStrong ? 'XL+' : 'XL', style = label.style_xcross, color = C_EXIT, textcolor = color.white, size = size.tiny)
if showLabels and shortExit
    label.new(bar_index, low, shortExitStrong ? 'XS+' : 'XS', style = label.style_xcross, color = C_EXIT, textcolor = color.white, size = size.tiny)
 
// ═══════════════ Visuals: state background & bar colors ═══════════════
showBg      = input.bool(true, 'Show Position Background', group = GRP_VIS)
showBarColor = input.bool(true, 'Color Bars by Trend', group = GRP_VIS)
bgcolor(showBg and posState == 1 ? color.new(colorUp, 92) : showBg and posState == -1 ? color.new(colorDown, 92) : na, title = 'Position Background')
barcolor(showBarColor ? (close > fbasis ? colorUp : colorDown) : na, title = 'Trend Bar Color')
 
// ═══════════════ Visuals: dashboard ═══════════════
showDash = input.bool(true, 'Show Dashboard', group = GRP_VIS)
var table dash = table.new(position.top_right, 2, 5, bgcolor = color.new(color.black, 60), border_width = 1)
cdRemain = na(lastSignalBar) ? 0 : math.max(0, cooldownBars - (bar_index - lastSignalBar))
if showDash and barstate.islast
    table.cell(dash, 0, 0, 'Position', text_color = color.white, text_size = size.tiny)
    table.cell(dash, 1, 0, posState == 1 ? 'LONG' : posState == -1 ? 'SHORT' : 'FLAT', text_color = posState == 1 ? colorUp : posState == -1 ? colorDown : color.white, text_size = size.tiny)
    table.cell(dash, 0, 1, 'Trend', text_color = color.white, text_size = size.tiny)
    table.cell(dash, 1, 1, close > fbasis ? 'UP' : 'DOWN', text_color = color.white, text_size = size.tiny)
    table.cell(dash, 0, 2, 'ATR(14)', text_color = color.white, text_size = size.tiny)
    table.cell(dash, 1, 2, str.tostring(vol, format.mintick), text_color = color.white, text_size = size.tiny)
    table.cell(dash, 0, 3, 'TP / SL', text_color = color.white, text_size = size.tiny)
    table.cell(dash, 1, 3, na(tpPrice) or na(slPrice) ? '-' : str.tostring(tpPrice, format.mintick) + ' / ' + str.tostring(slPrice, format.mintick), text_color = color.white, text_size = size.tiny)
    table.cell(dash, 0, 4, 'Cooldown', text_color = color.white, text_size = size.tiny)
    table.cell(dash, 1, 4, str.tostring(cdRemain), text_color = color.white, text_size = size.tiny)
 
// ═══════════════ Alerts ═══════════════
// V1 raw trigger alerts (preserved for compatibility)
alertcondition(xBull, 'Bullish Trend Shift', 'Bullish trend shift: close crossed above stepped basis')
alertcondition(xBear, 'Bearish Trend Shift', 'Bearish trend shift: close crossed below stepped basis')
alertcondition(xUl, 'Weak Long TP', 'Price crossed under upper inner band (weak long TP zone)')
alertcondition(xLu, 'Weak Short TP', 'Price crossed over lower inner band (weak short TP zone)')
alertcondition(xUu, 'Strong Long TP', 'Price crossed under upper outer band (strong long TP zone)')
alertcondition(xLl, 'Strong Short TP', 'Price crossed over lower outer band (strong short TP zone)')
 
// V2 state-machine governed alerts
alertcondition(longEntry, 'Long Entry', 'Long entry: bullish trend shift accepted by state machine')
alertcondition(shortEntry, 'Short Entry', 'Short entry: bearish trend shift accepted by state machine')
alertcondition(longExit, 'Long Exit', 'Long exit: band TP triggered')
alertcondition(shortExit, 'Short Exit', 'Short exit: band TP triggered')
 
if longEntry
    alert('Better Donchian: LONG entry @ ' + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
if shortEntry
    alert('Better Donchian: SHORT entry @ ' + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
if longExit
    alert('Better Donchian: LONG exit (TP ' + (longExitStrong ? 'strong' : 'weak') + ') @ ' + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
if shortExit
    alert('Better Donchian: SHORT exit (TP ' + (shortExitStrong ? 'strong' : 'weak') + ') @ ' + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)

← 返回列表