Advanced Chandelier Exit with S/R [Alpha Extract]

AlphaExtract · study · 220 行 · 点赞 1,121 · TradingView 原页

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

Pine Script

//@version=6
indicator('Advanced Chandelier Exit with S/R [Alpha Extract]', overlay=true, max_bars_back=2000)
 
// ═══════════════════════════════════════════════════════════════════
// INPUT GROUPS & SETTINGS
// ═══════════════════════════════════════════════════════════════════
 
var string calcGroup = 'Calculation Settings'
length = input.int(title='ATR Period', defval=22, minval=1, maxval=200, group=calcGroup, tooltip='Period for ATR calculation')
mult = input.float(title='ATR Multiplier', step=0.1, defval=3.0, minval=0.1, maxval=10.0, group=calcGroup, tooltip='Multiplier for ATR-based stops')
useClose = input.bool(title='Use Close Price for Extremums', defval=true, group=calcGroup, tooltip='Use close prices instead of high/low for calculations')
sensitivity = input.float(title='Sensitivity Factor', defval=1.0, minval=0.5, maxval=3.0, step=0.1, group=calcGroup, tooltip='Adjust sensitivity of direction changes')
enableVolatilityFilter = input.bool(title='Volatility-Based Filtering', defval=false, group=calcGroup)
 
var string visualGroup = 'Visual Settings'
showZones = input.bool(title='Show Support/Resistance Zones', defval=true, group=visualGroup)
highlightState = input.bool(title='Highlight Trend State', defval=true, group=visualGroup)
dynamicColors = input.bool(title='Dynamic Color Intensity', defval=true, group=visualGroup, tooltip='Colors intensify with trend strength')
resistanceColor = input.color(title='Resistance Color', defval=#F33644)
supportColor = input.color(title='Support Color', defval=#099881)
 
var string srGroup = 'Support/Resistance Zones'
srLookback = input.int(200, "S/R Lookback Period", minval=50, group=srGroup)
srThreshold = input.float(0.2, "Price Threshold %", minval=0.1, step=0.1, group=srGroup)
maxSRLevels = input.int(10, "Maximum S/R Levels", minval=1, group=srGroup)
showFixedLines = input.bool(title='Show Fixed Timeframe Lines', defval=true, tooltip='Show thin connecting lines from higher timeframe S/R levels')
 
 
// ═══════════════════════════════════════════════════════════════════
// CORE CALCULATIONS
// ═══════════════════════════════════════════════════════════════════
 
// Enhanced ATR with volatility filtering
baseATR = ta.atr(length)
volatilityFilter = enableVolatilityFilter ? ta.sma(baseATR, length) / baseATR : 1.0
atr = mult * baseATR * sensitivity * volatilityFilter
 
// Trend strength calculation
priceChange = math.abs(close - close[1])
avgPriceChange = ta.sma(priceChange, length)
trendStrength = math.min(priceChange / avgPriceChange * 100, 200)
 
// Enhanced stop calculations with adaptive features
longStop = (useClose ? ta.highest(close, length) : ta.highest(length)) - atr
longStopPrev = nz(longStop[1], longStop)
longStop := close[1] > longStopPrev ? math.max(longStop, longStopPrev) : longStop
 
shortStop = (useClose ? ta.lowest(close, length) : ta.lowest(length)) + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := close[1] < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop
 
// Enhanced direction logic with strength consideration
var int dir = 1
strongBull = close > shortStopPrev and trendStrength > 100
strongBear = close < longStopPrev and trendStrength > 100
regularBull = close > shortStopPrev
regularBear = close < longStopPrev
dir := strongBull ? 1 : strongBear ? -1 : regularBull ? 1 : regularBear ? -1 : dir
 
// ═══════════════════════════════════════════════════════════════════
// DYNAMIC COLORS & STYLING
// ═══════════════════════════════════════════════════════════════════
 
// Base colors with dynamic intensity
intensityFactor = dynamicColors ? math.max(trendStrength / 200, 0.3) : 1.0
longBaseColor = #00ffd5
shortBaseColor = #F33644
neutralColor = color.rgb(255, 193, 7)
 
// Dynamic color calculation
longColor = dynamicColors ? color.new(longBaseColor, math.max(100 - (intensityFactor * 100), 0)) : longBaseColor
shortColor = dynamicColors ? color.new(shortBaseColor, math.max(100 - (intensityFactor * 100), 0)) : shortBaseColor
 
longFillColor = color.new(longBaseColor, 80)
shortFillColor = color.new(shortBaseColor, 80)
neutralFillColor = color.new(neutralColor, 80)
 
// S/R Colors
srResistanceColor = resistanceColor
srSupportColor = supportColor
 
// ═══════════════════════════════════════════════════════════════════
// PLOTTING & VISUALIZATION
// ═══════════════════════════════════════════════════════════════════
 
// Enhanced stop line plots with dynamic styling
longStopPlot = plot(longStop, title='Long Stop', 
     style=plot.style_line, linewidth=3, color=dir == 1 ? longColor : na)
 
shortStopPlot = plot(shortStop, title='Short Stop', 
     style=plot.style_line, linewidth=3, color=dir == -1 ? shortColor : na)
 
// Signal detection with enhanced logic
buySignal = dir == 1 and dir[1] == -1
sellSignal = dir == -1 and dir[1] == 1
 
// ═══════════════════════════════════════════════════════════════════
// SUPPORT & RESISTANCE DETECTION 
// ═══════════════════════════════════════════════════════════════════
 
// Initialize S/R break variables
var bool srResistanceBreak = false
var bool srSupportBreak = false
 
// Pivot detection
ph = ta.pivothigh(high, 15, 15)
pl = ta.pivotlow(low, 15, 15)
 
// Store levels 
var float[] resistanceLevels = array.new_float(0)
var float[] supportLevels = array.new_float(0)
var int[] resistanceStrength = array.new_int(0)
var int[] supportStrength = array.new_int(0)
 
// Function to check if price level is unique
isUniqueLevel(level, levels) =>
    if array.size(levels) == 0
        true
    else
        isUnique = true
        for i = 0 to array.size(levels) - 1
            if math.abs(array.get(levels, i) - level) / level * 100 < srThreshold
                isUnique := false
                break
        isUnique
 
// Enhanced Support/Resistance zones 
if showZones
    if not na(ph)
        if isUniqueLevel(ph, resistanceLevels)
            array.unshift(resistanceLevels, ph)
            array.unshift(resistanceStrength, 0)
            while array.size(resistanceLevels) > maxSRLevels
                array.pop(resistanceLevels)
                array.pop(resistanceStrength)
 
    if not na(pl)
        if isUniqueLevel(pl, supportLevels)
            array.unshift(supportLevels, pl)
            array.unshift(supportStrength, 0)
            while array.size(supportLevels) > maxSRLevels
                array.pop(supportLevels)
                array.pop(supportStrength)
 
    if array.size(resistanceLevels) > 0
        for i = array.size(resistanceLevels) - 1 to 0
            if i < array.size(resistanceLevels)
                level = array.get(resistanceLevels, i)
                if high > level
                    array.set(resistanceStrength, i, array.get(resistanceStrength, i) + 1)
                if array.get(resistanceStrength, i) > srLookback
                    array.remove(resistanceLevels, i)
                    array.remove(resistanceStrength, i)
 
    if array.size(supportLevels) > 0
        for i = array.size(supportLevels) - 1 to 0
            if i < array.size(supportLevels)
                level = array.get(supportLevels, i)
                if low < level
                    array.set(supportStrength, i, array.get(supportStrength, i) + 1)
                if array.get(supportStrength, i) > srLookback
                    array.remove(supportLevels, i)
                    array.remove(supportStrength, i)
 
// Get current levels for plotting 
var float plotRes = na
var float plotSup = na
 
// Update plot levels only when we have valid levels 
plotRes := array.size(resistanceLevels) > 0 ? array.get(resistanceLevels, 0) : plotRes
plotSup := array.size(supportLevels) > 0 ? array.get(supportLevels, 0) : plotSup
 
// Timeframe logic for fixed lines 
tfSec = timeframe.in_seconds(timeframe.period)
higherTF = tfSec <= 60 ? "5" : tfSec <= 300 ? "15" :  tfSec <= 900 ? "60" :  tfSec <= 3600 ? "240" :     tfSec <= 14400 ? "D" : "D"
fixedRes = request.security(syminfo.tickerid, higherTF, plotRes, lookahead=barmerge.lookahead_on) 
fixedSup = request.security(syminfo.tickerid, higherTF, plotSup, lookahead=barmerge.lookahead_on)
 
// Plot resistance & support 
resPlot = plot(showZones ? fixnan(plotRes) : na, color=ta.change(plotRes) != 0 ? na : srResistanceColor, linewidth=2, offset=-16, title="S/R Resistance")
supPlot = plot(showZones ? fixnan(plotSup) : na, color=ta.change(plotSup) != 0 ? na : srSupportColor, linewidth=2, offset=-16, title="S/R Support")
 
// Add the thin connecting lines with toggle option 
plot(showZones and showFixedLines ? fixnan(fixedRes) : na, color=srResistanceColor, linewidth=1, title="Fixed Resistance", style=plot.style_stepline, offset=0)
plot(showZones and showFixedLines ? fixnan(fixedSup) : na, color=srSupportColor, linewidth=1, title="Fixed Support", style=plot.style_stepline, offset=0)
 
// Break detection logic
if showZones
    srResistanceBreak := ta.crossover(close, plotRes)
    srSupportBreak := ta.crossunder(close, plotSup)
else
    srResistanceBreak := false
    srSupportBreak := false
 
// ═══════════════════════════════════════════════════════════════════
// BACKGROUND & FILL EFFECTS
// ═══════════════════════════════════════════════════════════════════
 
// Enhanced background coloring with gradient effect
midPricePlot = plot(ohlc4, title='Mid Price', style=plot.style_circles, display=display.none)
 
// Dynamic fill colors based on trend strength
fillTransparency = dynamicColors ? math.max(95 - (trendStrength / 10), 80) : 90
longStateFillColor = highlightState and dir == 1 ? 
     color.new(longBaseColor, fillTransparency) : na
shortStateFillColor = highlightState and dir == -1 ? 
     color.new(shortBaseColor, fillTransparency) : na
 
fill(midPricePlot, longStopPlot, title='Long State Fill', color=longStateFillColor)
fill(midPricePlot, shortStopPlot, title='Short State Fill', color=shortStateFillColor)
 
// ═══════════════════════════════════════════════════════════════════
// SIGNAL ALERTS & SHAPES
// ═══════════════════════════════════════════════════════════════════
 
// Alert conditions
alertcondition(buySignal, title="ACE Buy Signal", message="Advanced Chandelier Exit: Buy Signal")
alertcondition(sellSignal, title="ACE Sell Signal", message="Advanced Chandelier Exit: Sell Signal")
alertcondition(srResistanceBreak and showZones, title="Break Up", message="Support/Resistance: Resistance Break Up")
alertcondition(srSupportBreak and showZones, title="Break Down", message="Support/Resistance: Support Break Down")

← 返回列表