Chandelier Exit Flip Zones [AGPro Series]

AGProLabs · study · 305 行 · 点赞 127 · TradingView 原页

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

Pine Script

// -------------------------------------------------
// Chandelier Exit Flip Zones [AGPro Series]
//
// Author  : AGProLabs | AGPro Series
// Version : 1.0
//
// Chandelier Exit Flip Zones is a premium ATR trailing stop and exit-state
// engine for traders who want cleaner trend continuation reads, Chandelier
// trail flips, ATR distance context, and structured exit pressure labels
// without turning the chart into a noisy generic signal map.
// -------------------------------------------------
 
//@version=6
indicator("Chandelier Exit Flip Zones [AGPro Series]",
     shorttitle = "AG Pro CEZ",
     overlay = true,
     max_labels_count = 300,
     max_boxes_count = 120,
     max_lines_count = 50)
 
// -------------------------------------------------
// AGPro Color Palette
// -------------------------------------------------
// Brand
headerBg      = color.rgb(37, 99, 235)      // #2563EB
headerText    = color.rgb(245, 247, 250)    // #F5F7FA
// Panel
panelBg       = color.rgb(15, 23, 42)       // #0F172A
panelBorder   = color.rgb(51, 65, 85)       // #334155
panelLabelCol = color.rgb(148, 163, 184)    // #94A3B8
panelValueCol = color.rgb(226, 232, 240)    // #E2E8F0
// States
bullColor     = color.rgb(34, 197, 166)     // #22C5A6
bearColor     = color.rgb(244, 114, 182)    // #F472B6
neutralColor  = color.rgb(245, 189, 92)     // #F5BD5C
accentColor   = color.rgb(129, 140, 248)    // #818CF8
 
// -------------------------------------------------
// Inputs
// -------------------------------------------------
groupEngine = "Chandelier Engine"
atrLength = input.int(22, "ATR Length", minval = 2, group = groupEngine,
     tooltip = "Defines the volatility window used to calculate the Chandelier trailing stop distance.")
structureLength = input.int(22, "Structure Lookback", minval = 2, group = groupEngine,
     tooltip = "Defines the highest high and lowest low window used as the Chandelier anchor.")
atrMultiple = input.float(3.0, "ATR Multiple", minval = 0.5, maxval = 10.0, step = 0.1, group = groupEngine,
     tooltip = "Controls how far the active Chandelier trail is placed from the recent structure extreme.")
confirmOnClose = input.bool(true, "Confirm Flips On Bar Close", group = groupEngine,
     tooltip = "When enabled, flip labels and zones are confirmed only after the bar closes.")
 
groupQuality = "Flip Quality"
fastEmaLength = input.int(21, "Fast Trend EMA", minval = 2, group = groupQuality,
     tooltip = "Fast trend filter used to score whether a Chandelier flip agrees with short-term direction.")
slowEmaLength = input.int(55, "Slow Trend EMA", minval = 3, group = groupQuality,
     tooltip = "Slow trend filter used to classify continuation quality after a Chandelier flip.")
useVolumeScore = input.bool(true, "Use Volume In Quality Score", group = groupQuality,
     tooltip = "Includes relative volume participation in the flip-quality score when volume data is available.")
volumeLength = input.int(20, "Volume Baseline Length", minval = 2, group = groupQuality,
     tooltip = "Defines the volume average used by the optional participation component of the flip score.")
primeScore = input.int(72, "Prime Flip Threshold", minval = 40, maxval = 95, group = groupQuality,
     tooltip = "Minimum score required for a flip to be classified as a prime-quality Chandelier transition.")
minimumFlipLabelScore = input.int(45, "Minimum Flip Label Score", minval = 0, maxval = 100, group = groupQuality,
     tooltip = "Hides very low-quality flip labels by default so the chart stays clean during choppy conditions.")
 
groupState = "Continuation And Exit State"
continuationAtrDistance = input.float(1.15, "Continuation Distance", minval = 0.2, maxval = 5.0, step = 0.05, group = groupState,
     tooltip = "Minimum ATR distance from the active trail required to classify the trend as a continuation state.")
exitWatchAtrDistance = input.float(0.45, "Exit Watch Distance", minval = 0.05, maxval = 2.0, step = 0.05, group = groupState,
     tooltip = "ATR distance from the active trail where the script starts marking exit-pressure conditions.")
exitCooldownBars = input.int(20, "Exit Label Cooldown", minval = 1, maxval = 100, group = groupState,
     tooltip = "Minimum number of bars between exit-pressure labels to keep chart annotation density controlled.")
 
groupZones = "Flip Zones"
showFlipZones = input.bool(true, "Show Flip Zones", group = groupZones,
     tooltip = "Draws a rectangular zone around the trail break area when a qualified Chandelier flip appears.")
zoneForwardBars = input.int(48, "Zone Forward Length", minval = 5, maxval = 300, group = groupZones,
     tooltip = "Controls how far each flip zone extends to the right after the original trail transition.")
zoneAtrPadding = input.float(0.12, "Zone ATR Padding", minval = 0.0, maxval = 1.0, step = 0.01, group = groupZones,
     tooltip = "Adds ATR-based padding to each flip zone so the box remains visible on low-range transition bars.")
minimumZoneScore = input.int(50, "Minimum Zone Score", minval = 0, maxval = 100, group = groupZones,
     tooltip = "Creates flip zones only when the transition score is strong enough to deserve chart space.")
maxVisibleZones = input.int(8, "Maximum Visible Zones", minval = 1, maxval = 50, group = groupZones,
     tooltip = "Caps the number of active flip-zone boxes to keep the script fast and visually restrained.")
 
groupVisual = "Visuals"
showTrail = input.bool(true, "Show Chandelier Trail", group = groupVisual,
     tooltip = "Displays the active Chandelier trailing stop as a directional line on the chart.")
showFlipLabels = input.bool(true, "Show Flip Labels", group = groupVisual,
     tooltip = "Displays compact labels when the Chandelier trail changes side.")
showExitLabels = input.bool(false, "Show Exit Labels", group = groupVisual,
     tooltip = "Displays optional exit-pressure labels when price compresses back into the active trail.")
flipCooldownBars = input.int(6, "Flip Label Cooldown", minval = 1, maxval = 100, group = groupVisual,
     tooltip = "Minimum number of bars between flip labels so clusters do not overwhelm the chart.")
maxVisibleLabels = input.int(18, "Maximum Visible Labels", minval = 5, maxval = 150, group = groupVisual,
     tooltip = "Caps the number of labels retained on the chart to protect performance and presentation quality.")
labelOffsetAtr = input.float(0.35, "Label Offset In ATR", minval = 0.05, maxval = 2.0, step = 0.05, group = groupVisual,
     tooltip = "Places labels away from candle bodies using an ATR-based offset so they remain readable.")
labelSizeInput = input.string("Normal", "Label Font Size", options = ["Tiny", "Small", "Normal", "Large"], group = groupVisual,
     tooltip = "Controls the size of chart labels. Normal is the default publication setting.")
 
groupPanel = "Panel"
showPanel = input.bool(true, "Show Panel", group = groupPanel,
     tooltip = "Shows or hides the AGPro status panel.")
panelLocationInput = input.string("Top Right", "Panel Location", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = groupPanel,
     tooltip = "Controls where the status panel is placed on the chart.")
panelThemeInput = input.string("Dark", "Panel Theme", options = ["Dark", "Light", "Auto"], group = groupPanel,
     tooltip = "Selects the panel color theme. Auto adapts the panel to the chart background brightness.")
panelSizeInput = input.string("Normal", "Panel Font Size", options = ["Tiny", "Small", "Normal", "Large"], group = groupPanel,
     tooltip = "Controls the text size of the panel. Normal is the default publication setting.")
 
// -------------------------------------------------
// Helper Functions
// -------------------------------------------------
f_size(string sizeName) =>
    switch sizeName
        "Tiny" => size.tiny
        "Small" => size.small
        "Large" => size.large
        => size.normal
 
f_position(string locationName) =>
    switch locationName
        "Top Left" => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left" => position.bottom_left
        => position.top_right
 
f_clamp(float value, float minValue, float maxValue) =>
    math.max(minValue, math.min(maxValue, value))
 
f_quality_text(float score, float primeLevel) =>
    na(score) ? "Waiting" : score >= primeLevel ? "Prime" : score >= 55.0 ? "Qualified" : "Developing"
 
f_quality_short(float score, float primeLevel) =>
    na(score) ? "Wait" : score >= primeLevel ? "Prime" : score >= 55.0 ? "Qual" : "Build"
 
f_quality_color(float score, float primeLevel) =>
    na(score) ? neutralColor : score >= primeLevel ? bullColor : score >= 55.0 ? accentColor : neutralColor
 
// -------------------------------------------------
// Chandelier Engine
// -------------------------------------------------
atrValue = ta.atr(atrLength)
highestAnchor = ta.highest(high, structureLength)
lowestAnchor = ta.lowest(low, structureLength)
rawLongStop = highestAnchor - atrValue * atrMultiple
rawShortStop = lowestAnchor + atrValue * atrMultiple
 
var float longStop = na
var float shortStop = na
priorLongStop = nz(longStop[1], rawLongStop)
priorShortStop = nz(shortStop[1], rawShortStop)
 
longStop := close[1] > priorLongStop ? math.max(rawLongStop, priorLongStop) : rawLongStop
shortStop := close[1] < priorShortStop ? math.min(rawShortStop, priorShortStop) : rawShortStop
 
var int trailSide = 1
previousSide = nz(trailSide[1], 1)
trailSide := close > priorShortStop ? 1 : close < priorLongStop ? -1 : previousSide
 
activeTrail = trailSide == 1 ? longStop : shortStop
flipUpRaw = trailSide == 1 and previousSide == -1
flipDownRaw = trailSide == -1 and previousSide == 1
confirmedSignal = not confirmOnClose or barstate.isconfirmed
flipUp = flipUpRaw and confirmedSignal
flipDown = flipDownRaw and confirmedSignal
flipEvent = flipUp or flipDown
 
emaFast = ta.ema(close, fastEmaLength)
emaSlow = ta.ema(close, slowEmaLength)
trendAlignedLong = emaFast > emaSlow and close > emaSlow
trendAlignedShort = emaFast < emaSlow and close < emaSlow
 
rangeSpan = math.max(high - low, syminfo.mintick)
closeLocation = (close - low) / rangeSpan
trueRange = ta.tr(true)
volumeAverage = ta.sma(volume, volumeLength)
hasVolume = not na(volume) and not na(volumeAverage) and volumeAverage > 0.0
 
breachStrength = flipUp ? (close - priorShortStop) / atrValue : flipDown ? (priorLongStop - close) / atrValue : 0.0
breachScore = f_clamp(breachStrength / 1.20, 0.0, 1.0) * 35.0
trendScore = (flipUp and trendAlignedLong) or (flipDown and trendAlignedShort) ? 20.0 : 0.0
expansionScore = f_clamp((trueRange / atrValue - 0.80) / 0.80, 0.0, 1.0) * 20.0
float closeScore = 0.0
if flipUp
    closeScore := closeLocation >= 0.65 ? 15.0 : closeLocation >= 0.50 ? 8.0 : 0.0
else if flipDown
    closeScore := closeLocation <= 0.35 ? 15.0 : closeLocation <= 0.50 ? 8.0 : 0.0
volumeRatio = hasVolume ? volume / volumeAverage : 1.0
volumeScore = useVolumeScore ? (hasVolume ? f_clamp((volumeRatio - 0.85) / 0.55, 0.0, 1.0) * 10.0 : 5.0) : 10.0
currentFlipScore = math.round(breachScore + trendScore + expansionScore + closeScore + volumeScore)
 
var float lastFlipScore = na
 
if flipEvent
    lastFlipScore := currentFlipScore
 
trailDistanceAtr = atrValue > 0.0 ? math.abs(close - activeTrail) / atrValue : na
trailDistancePct = close != 0.0 ? math.abs(close - activeTrail) / math.abs(close) * 100.0 : na
exitWatch = trailDistanceAtr <= exitWatchAtrDistance
continuationState = trailDistanceAtr >= continuationAtrDistance and (trailSide == 1 ? trendAlignedLong : trendAlignedShort)
 
string stateText = ""
if trailSide == 1
    stateText := exitWatch ? "Long Exit Watch" : continuationState ? "Long Continuation" : "Long Control"
else
    stateText := exitWatch ? "Short Exit Watch" : continuationState ? "Short Continuation" : "Short Control"
stateColor = exitWatch ? neutralColor : continuationState ? (trailSide == 1 ? bullColor : bearColor) : accentColor
sideText = trailSide == 1 ? "Long Trail" : "Short Trail"
sideColor = trailSide == 1 ? bullColor : bearColor
qualityText = na(lastFlipScore) ? "Waiting" : str.tostring(lastFlipScore, "#") + "/100 - " + f_quality_text(lastFlipScore, primeScore)
 
// -------------------------------------------------
// Visual Layer
// -------------------------------------------------
trailColor = trailSide == 1 ? bullColor : bearColor
plot(showTrail ? activeTrail : na, "Active Chandelier Trail", color = trailColor, linewidth = 2, style = plot.style_linebr)
plot(showTrail ? emaFast : na, "Fast Trend EMA", color = color.new(accentColor, 78), linewidth = 1)
 
var array<label> chartLabels = array.new<label>()
var array<box> flipZones = array.new<box>()
labelSize = f_size(labelSizeInput)
labelOffset = atrValue * labelOffsetAtr
var int lastFlipLabelBar = na
flipLabelAllowed = currentFlipScore >= minimumFlipLabelScore and (na(lastFlipLabelBar) or bar_index - lastFlipLabelBar >= flipCooldownBars)
 
if showFlipZones and flipEvent and currentFlipScore >= minimumZoneScore
    zoneBase = flipUp ? priorShortStop : priorLongStop
    zonePadding = atrValue * zoneAtrPadding
    zoneTop = math.max(close, zoneBase) + zonePadding
    zoneBottom = math.min(close, zoneBase) - zonePadding
    zoneColor = flipUp ? bullColor : bearColor
    newZone = box.new(left = bar_index, top = zoneTop, right = bar_index + zoneForwardBars, bottom = zoneBottom,
         bgcolor = color.new(zoneColor, 92), border_color = color.new(zoneColor, 55), border_width = 1)
    array.push(flipZones, newZone)
    while array.size(flipZones) > maxVisibleZones
        oldZone = array.shift(flipZones)
        box.delete(oldZone)
 
if showFlipLabels and flipEvent and flipLabelAllowed
    flipLabelText = (flipUp ? "Bull" : "Bear") + "\nQ" + str.tostring(currentFlipScore, "#") + " " + f_quality_short(currentFlipScore, primeScore)
    flipLabelY = flipUp ? low - labelOffset : high + labelOffset
    flipLabelStyle = flipUp ? label.style_label_up : label.style_label_down
    flipLabelColor = currentFlipScore >= primeScore ? (flipUp ? bullColor : bearColor) : color.new(accentColor, 8)
    newFlipLabel = label.new(bar_index, flipLabelY, flipLabelText, style = flipLabelStyle, color = flipLabelColor,
         textcolor = headerText, size = labelSize)
    array.push(chartLabels, newFlipLabel)
    lastFlipLabelBar := bar_index
    while array.size(chartLabels) > maxVisibleLabels
        oldLabel = array.shift(chartLabels)
        label.delete(oldLabel)
 
var int lastExitLabelBar = na
exitWatchStarted = exitWatch and nz(trailDistanceAtr[1], exitWatchAtrDistance + 1.0) > exitWatchAtrDistance
exitTrigger = showExitLabels and exitWatchStarted and not flipEvent and confirmedSignal and (na(lastExitLabelBar) or bar_index - lastExitLabelBar >= exitCooldownBars)
 
if exitTrigger
    exitLabelText = "Exit Watch\nTrail"
    exitLabelY = trailSide == 1 ? low - labelOffset : high + labelOffset
    exitLabelStyle = trailSide == 1 ? label.style_label_up : label.style_label_down
    exitLabelColor = color.new(neutralColor, 0)
    newExitLabel = label.new(bar_index, exitLabelY, exitLabelText, style = exitLabelStyle, color = exitLabelColor,
         textcolor = color.rgb(15, 23, 42), size = labelSize)
    array.push(chartLabels, newExitLabel)
    lastExitLabelBar := bar_index
    while array.size(chartLabels) > maxVisibleLabels
        oldLabel = array.shift(chartLabels)
        label.delete(oldLabel)
 
// -------------------------------------------------
// Panel
// -------------------------------------------------
bgBrightness = color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color)
useLightPanel = panelThemeInput == "Light" or (panelThemeInput == "Auto" and bgBrightness > 390)
panelBgActive = useLightPanel ? color.rgb(248, 250, 252) : panelBg
panelBorderActive = useLightPanel ? color.rgb(203, 213, 225) : panelBorder
panelLabelActive = useLightPanel ? color.rgb(71, 85, 105) : panelLabelCol
panelValueActive = useLightPanel ? color.rgb(15, 23, 42) : panelValueCol
panelSize = f_size(panelSizeInput)
 
var table dash = table.new(f_position(panelLocationInput), 2, 6, border_width = 1, border_color = panelBorderActive)
 
if barstate.islast
    table.clear(dash, 0, 0, 1, 5)
    if showPanel
        table.merge_cells(dash, 0, 0, 1, 0)
        table.cell(dash, 0, 0, "AG Pro Chandelier Exit Flip Zones", bgcolor = headerBg, text_color = headerText, text_size = panelSize)
        table.cell(dash, 0, 1, "Trail Side", bgcolor = panelBgActive, text_color = panelLabelActive, text_size = panelSize)
        table.cell(dash, 1, 1, sideText, bgcolor = panelBgActive, text_color = sideColor, text_size = panelSize)
        table.cell(dash, 0, 2, "ATR Multiple", bgcolor = panelBgActive, text_color = panelLabelActive, text_size = panelSize)
        table.cell(dash, 1, 2, str.tostring(atrMultiple, "#.##") + "x", bgcolor = panelBgActive, text_color = panelValueActive, text_size = panelSize)
        table.cell(dash, 0, 3, "Distance", bgcolor = panelBgActive, text_color = panelLabelActive, text_size = panelSize)
        table.cell(dash, 1, 3, str.tostring(trailDistanceAtr, "#.##") + " ATR / " + str.tostring(trailDistancePct, "#.##") + "%", bgcolor = panelBgActive, text_color = panelValueActive, text_size = panelSize)
        table.cell(dash, 0, 4, "Flip Quality", bgcolor = panelBgActive, text_color = panelLabelActive, text_size = panelSize)
        table.cell(dash, 1, 4, qualityText, bgcolor = panelBgActive, text_color = f_quality_color(lastFlipScore, primeScore), text_size = panelSize)
        table.cell(dash, 0, 5, "State", bgcolor = panelBgActive, text_color = panelLabelActive, text_size = panelSize)
        table.cell(dash, 1, 5, stateText, bgcolor = panelBgActive, text_color = stateColor, text_size = panelSize)
 
// -------------------------------------------------
// Alerts
// -------------------------------------------------
alertcondition(flipUp, "Bullish Chandelier Flip", "Chandelier Exit Flip Zones: bullish trail flip confirmed.")
alertcondition(flipDown, "Bearish Chandelier Flip", "Chandelier Exit Flip Zones: bearish trail flip confirmed.")
alertcondition(flipEvent and currentFlipScore >= primeScore, "Prime Chandelier Flip", "Chandelier Exit Flip Zones: prime-quality trail flip confirmed.")
alertcondition(exitTrigger, "Chandelier Exit Watch", "Chandelier Exit Flip Zones: price compressed into the active Chandelier trail.")

← 返回列表