本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("ATR Swing Structure [Leonichev]", shorttitle = "AL ASS", overlay = true,
max_bars_back = 5000, max_labels_count = 500, max_boxes_count = 500, max_lines_count = 500)
// =============================================================================
// ATR Swing Structure · v1.0.0 · Andrei Leonichev
//
// Marks market structure with an ATR zigzag and shows where it breaks.
//
// 1. Swings: a swing high is the highest high since the last swing low. It is
// confirmed once price moves N × ATR below it (by close or by wick, as
// selected). Highs and lows alternate and a confirmed swing never moves.
// The ATR used for the threshold is the one at the bar of the extreme, so
// a volatility spike after the swing does not change its confirmation.
// 2. Labels: each swing is tagged HH / LH or HL / LL against the previous swing
// of the same type.
// 3. Zones: each swing gets a fixed-height zone (in ATR) from the wick toward
// the most extreme candle body around it.
// 4. Structure breaks (BOS): a close beyond the last confirmed swing high or
// low. Each swing level can be broken once.
//
// No repainting: everything updates on closed bars only. Swing markers are
// placed on the bar of the extreme at the moment of confirmation, so they
// appear after that bar.
// =============================================================================
// =============================================================================
// INPUTS: LOGIC
// =============================================================================
grpEngine = "Swing engine"
atrLength = input.int(14, "ATR length", minval = 1, group = grpEngine)
swingReversalAtr = input.float(2.0, "Swing reversal, × ATR", minval = 0.1, step = 0.1, group = grpEngine,
tooltip = "A swing is confirmed when price moves this many ATRs away from the extreme.")
confirmMode = input.string("Close", "Confirm reversal by", options = ["Close", "Wick"], group = grpEngine,
tooltip = "Close: the bar must close beyond the threshold (fewer false swings).\nWick: the high/low is enough (faster).")
grpZone = "Swing zones"
zoneHeightAtr = input.float(0.25, "Zone height, × ATR", minval = 0.01, step = 0.05, group = grpZone)
zoneWindowBars = input.int(2, "Body search window, bars each side", minval = 0, maxval = 10, group = grpZone,
tooltip = "Bars on each side of the swing bar that are searched for the most extreme candle body.")
// =============================================================================
// INPUTS: VISIBILITY AND STYLE
// =============================================================================
grpShow = "Visibility"
showZigzag = input.bool(true, "Zigzag lines", group = grpShow)
showSwingLabels = input.bool(true, "HH / HL / LH / LL labels", group = grpShow)
showSwingZones = input.bool(true, "Swing zones", group = grpShow)
showLevels = input.bool(true, "Active swing levels", group = grpShow,
tooltip = "Lines from the last unbroken swing high and low to the current bar.")
showBreaks = input.bool(true, "Structure breaks (BOS)", group = grpShow)
grpStyle = "Style"
upColor = input.color(color.rgb(67, 160, 71), "Bullish", group = grpStyle, inline = "col")
downColor = input.color(color.rgb(229, 57, 53), "Bearish", group = grpStyle, inline = "col")
zigzagColor = input.color(color.new(color.gray, 30), "Zigzag", group = grpStyle, inline = "zz")
zigzagWidth = input.int(1, "Width", minval = 1, maxval = 4, group = grpStyle, inline = "zz")
zoneTransparency = input.int(75, "Zone transparency", minval = 0, maxval = 100, group = grpStyle)
labelSizeName = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = grpStyle)
// =============================================================================
// HELPERS
// =============================================================================
labelSize = switch labelSizeName
"Tiny" => size.tiny
"Normal" => size.normal
=> size.small
// Highest high (or lowest low) on bars fromBar+1 .. current bar. Ties go to the earlier bar.
extremeAfter(bool findHigh, int fromBar) =>
float extremePrice = na
int extremeBar = na
if fromBar < bar_index
for barNo = fromBar + 1 to bar_index
offset = bar_index - barNo
value = findHigh ? high[offset] : low[offset]
if na(extremePrice) or (findHigh ? value > extremePrice : value < extremePrice)
extremePrice := value
extremeBar := barNo
[extremePrice, extremeBar]
// Most extreme candle body within ±zoneWindowBars of the swing bar (closed bars only).
bodyExtreme(bool isHigh, int swingBar) =>
float extreme = na
firstBar = math.max(swingBar - zoneWindowBars, 0)
lastBar = math.min(swingBar + zoneWindowBars, bar_index)
for barNo = firstBar to lastBar
offset = bar_index - barNo
value = isHigh ? math.max(open[offset], close[offset]) : math.min(open[offset], close[offset])
extreme := na(extreme) ? value : isHigh ? math.max(extreme, value) : math.min(extreme, value)
extreme
// Swing zone from the wick toward the body, always zoneHeightAtr × ATR tall:
// a narrow wick-to-body range is widened evenly, a wide one is cut from the wick.
swingZone(bool isHigh, float wick, float body, float atrAtSwing) =>
targetHeight = zoneHeightAtr * atrAtSwing
top = isHigh ? wick : body
bottom = isHigh ? body : wick
height = top - bottom
if height < targetHeight
pad = (targetHeight - height) / 2
top += pad
bottom -= pad
else if height > targetHeight
if isHigh
bottom := wick - targetHeight
else
top := wick + targetHeight
[top, bottom]
// =============================================================================
// CORE SERIES
// =============================================================================
atrValue = ta.atr(atrLength)
useClose = confirmMode == "Close"
// =============================================================================
// SWING ENGINE: ATR ZIGZAG
// searchDir = -1: last confirmed swing is a low, looking for a high; 1: the reverse.
// leg* - running extreme of the current leg (swing candidate).
// pullback* - opposite extreme after leg*, the candidate for the next swing.
// The bar that set a new leg extreme cannot be the pullback bar.
// =============================================================================
var int searchDir = -1
var float legExtreme = na
var int legExtremeBar = na
var float legExtremeAtr = na
var float pullbackExtreme = na
var int pullbackBar = na
var float lastHigh = na
var int lastHighBar = na
var bool lastHighBroken = true
var float lastLow = na
var int lastLowBar = na
var bool lastLowBroken = true
var int prevSwingBar = na // for the zigzag line
var float prevSwingPrice = na
newSwingHigh = false
newSwingLow = false
confirmSwing(bool isHigh) =>
[zoneTop, zoneBottom] = swingZone(isHigh, legExtreme, bodyExtreme(isHigh, legExtremeBar), legExtremeAtr)
previous = isHigh ? lastHigh : lastLow
tag = na(previous) ? (isHigh ? "H" : "L") : isHigh ? (legExtreme > previous ? "HH" : "LH") : (legExtreme > previous ? "HL" : "LL")
bullishTag = tag == "HH" or tag == "HL"
tagColor = tag == "H" or tag == "L" ? color.gray : bullishTag ? upColor : downColor
if showSwingLabels
label.new(legExtremeBar, legExtreme, tag, xloc = xloc.bar_index,
yloc = isHigh ? yloc.abovebar : yloc.belowbar, color = color.new(tagColor, 100),
style = isHigh ? label.style_label_down : label.style_label_up, textcolor = tagColor, size = labelSize)
if showSwingZones
box.new(legExtremeBar - 1, zoneTop, legExtremeBar + 1, zoneBottom, border_color = color.new(tagColor, 100),
bgcolor = color.new(tagColor, zoneTransparency))
if showZigzag and not na(prevSwingBar)
line.new(prevSwingBar, prevSwingPrice, legExtremeBar, legExtreme, color = zigzagColor, width = zigzagWidth)
// Only closed bars move the engine, so a live bar can never confirm and then "unconfirm" a swing.
if barstate.isconfirmed and not na(atrValue)
// Track the leg extreme and the pullback after it
if searchDir == -1
if na(legExtreme) or high > legExtreme
legExtreme := high, legExtremeBar := bar_index, legExtremeAtr := atrValue
pullbackExtreme := na, pullbackBar := na
else if na(pullbackExtreme) or low < pullbackExtreme
pullbackExtreme := low, pullbackBar := bar_index
else
if na(legExtreme) or low < legExtreme
legExtreme := low, legExtremeBar := bar_index, legExtremeAtr := atrValue
pullbackExtreme := na, pullbackBar := na
else if na(pullbackExtreme) or high > pullbackExtreme
pullbackExtreme := high, pullbackBar := bar_index
// Confirmation. pullbackExtreme is na on a bar that set a new leg extreme, so a swing
// is never confirmed on its own bar.
threshold = swingReversalAtr * legExtremeAtr
if searchDir == -1 and not na(pullbackExtreme) and (useClose ? close : pullbackExtreme) <= legExtreme - threshold
confirmSwing(true)
lastHigh := legExtreme, lastHighBar := legExtremeBar, lastHighBroken := false
prevSwingBar := legExtremeBar, prevSwingPrice := legExtreme
newSwingHigh := true
// The next leg looks for a low, starting from the lowest low after this high
pullbackOffset = bar_index - pullbackBar
searchDir := 1
legExtreme := pullbackExtreme, legExtremeBar := pullbackBar, legExtremeAtr := atrValue[pullbackOffset]
[nextPrice, nextBar] = extremeAfter(true, legExtremeBar)
pullbackExtreme := nextPrice, pullbackBar := nextBar
else if searchDir == 1 and not na(pullbackExtreme) and (useClose ? close : pullbackExtreme) >= legExtreme + threshold
confirmSwing(false)
lastLow := legExtreme, lastLowBar := legExtremeBar, lastLowBroken := false
prevSwingBar := legExtremeBar, prevSwingPrice := legExtreme
newSwingLow := true
// The next leg looks for a high, starting from the highest high after this low
pullbackOffset = bar_index - pullbackBar
searchDir := -1
legExtreme := pullbackExtreme, legExtremeBar := pullbackBar, legExtremeAtr := atrValue[pullbackOffset]
[nextPrice, nextBar] = extremeAfter(false, legExtremeBar)
pullbackExtreme := nextPrice, pullbackBar := nextBar
// =============================================================================
// STRUCTURE BREAKS: first close beyond the last confirmed swing level
// =============================================================================
bullishBreak = barstate.isconfirmed and not lastHighBroken and close > lastHigh
bearishBreak = barstate.isconfirmed and not lastLowBroken and close < lastLow
if bullishBreak
lastHighBroken := true
if showBreaks
line.new(lastHighBar, lastHigh, bar_index, lastHigh, color = upColor, style = line.style_dashed)
label.new(math.round((lastHighBar + bar_index) / 2), lastHigh, "BOS", color = color.new(upColor, 100),
style = label.style_label_down, textcolor = upColor, size = size.tiny)
if bearishBreak
lastLowBroken := true
if showBreaks
line.new(lastLowBar, lastLow, bar_index, lastLow, color = downColor, style = line.style_dashed)
label.new(math.round((lastLowBar + bar_index) / 2), lastLow, "BOS", color = color.new(downColor, 100),
style = label.style_label_up, textcolor = downColor, size = size.tiny)
// =============================================================================
// ACTIVE LEVELS: one line per side, from the last unbroken swing to the current bar
// =============================================================================
var line highLevel = line.new(na, na, na, na, color = color.new(downColor, 40), style = line.style_dotted)
var line lowLevel = line.new(na, na, na, na, color = color.new(upColor, 40), style = line.style_dotted)
if showLevels and barstate.islast
if not lastHighBroken
line.set_xy1(highLevel, lastHighBar, lastHigh)
line.set_xy2(highLevel, bar_index, lastHigh)
else
line.set_xy1(highLevel, na, na)
line.set_xy2(highLevel, na, na)
if not lastLowBroken
line.set_xy1(lowLevel, lastLowBar, lastLow)
line.set_xy2(lowLevel, bar_index, lastLow)
else
line.set_xy1(lowLevel, na, na)
line.set_xy2(lowLevel, na, na)
// =============================================================================
// DATA WINDOW AND ALERTS
// =============================================================================
plot(lastHigh, "Last swing high", display = display.data_window)
plot(lastLow, "Last swing low", display = display.data_window)
alertcondition(newSwingHigh, "Swing high confirmed", "ATR Swing Structure: swing high confirmed on {{ticker}} {{interval}}")
alertcondition(newSwingLow, "Swing low confirmed", "ATR Swing Structure: swing low confirmed on {{ticker}} {{interval}}")
alertcondition(bullishBreak, "Bullish structure break", "ATR Swing Structure: close above the last swing high on {{ticker}} {{interval}}")
alertcondition(bearishBreak, "Bearish structure break", "ATR Swing Structure: close below the last swing low on {{ticker}} {{interval}}")