Structure-Colored EMA [Leonichev]

leonichevandrei · study · 274 行 · 点赞 52 · TradingView 原页

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

Pine Script

//@version=6
indicator("Structure-Colored EMA [Leonichev]", shorttitle = "AL SC-EMA", overlay = true,
     max_bars_back = 5000, max_labels_count = 500, max_boxes_count = 500)
 
// =============================================================================
// Structure-Colored EMA  ·  v1.0.0  ·  Andrei Leonichev
//
// Colors a long EMA by market structure instead of by slope or price crossovers.
//
// 1. Structure: an ATR zigzag. A swing high is the highest high since the last
//    swing low; it is confirmed once price has moved N × ATR away from it.
//    Highs and lows alternate, one swing per bar at most, and a confirmed swing
//    is never moved or removed.
// 2. Each swing gets a zone of fixed height (in ATR) between its wick and the
//    most extreme candle body around it.
// 3. The EMA color is re-evaluated only when a swing is confirmed, using the
//    EMA value at the bar of that swing:
//      green - both the last swing high and swing low zones are above the EMA
//      red   - both zones are below the EMA
//      gray  - both zones touch the EMA
//      transition (high above, low below): the previous color is kept only if
//      the EMA is on the far side of the midpoint between the two zones, i.e.
//      one swing merely pierced the EMA. Otherwise the color turns gray.
//
// No repainting: the swing engine updates only on closed bars. Swing markers
// are drawn on the bar of the extreme at the moment of confirmation, so they
// appear a few bars after that extreme.
// =============================================================================
 
// =============================================================================
// INPUTS: LOGIC
// =============================================================================
grpTrend = "Structure and trend"
emaLength          = input.int(200, "EMA length", minval = 1, group = grpTrend)
atrLength          = input.int(14, "ATR length", minval = 1, group = grpTrend)
swingReversalAtr   = input.float(2.0, "Swing reversal, × ATR", minval = 0.1, step = 0.1, group = grpTrend,
     tooltip = "A swing is confirmed when price moves this many ATRs away from the extreme.")
 
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
// =============================================================================
grpShow = "Visibility"
showEma            = input.bool(true,  "EMA", group = grpShow)
colorEmaByTrend    = input.bool(true,  "Color EMA by structure", group = grpShow)
showSwingMarkers   = input.bool(true,  "Swing markers", group = grpShow)
showSwingText      = input.bool(false, "HH / HL / LH / LL text", group = grpShow)
showSwingZones     = input.bool(true,  "Swing zones", group = grpShow)
showConfirmDots    = input.bool(false, "Dot on the confirmation bar", group = grpShow)
 
// =============================================================================
// INPUTS: STYLE
// =============================================================================
grpEmaStyle = "Style: EMA"
emaPlainColor      = input.color(color.rgb(160, 160, 160), "Color (when not colored by trend)", group = grpEmaStyle)
emaUpColor         = input.color(color.rgb(0, 200, 0), "Up", group = grpEmaStyle, inline = "trend")
emaDownColor       = input.color(color.rgb(220, 0, 0), "Down", group = grpEmaStyle, inline = "trend")
emaNeutralColor    = input.color(color.rgb(160, 160, 160), "Neutral", group = grpEmaStyle, inline = "trend")
emaLineWidth       = input.int(2, "Width", minval = 1, maxval = 4, group = grpEmaStyle)
 
grpSwingStyle = "Style: swings"
swingHighColor     = input.color(color.orange, "High marker", group = grpSwingStyle, inline = "marker")
swingLowColor      = input.color(color.orange, "Low marker", group = grpSwingStyle, inline = "marker")
markerShapeName    = input.string("Triangle", "Shape", options = ["Triangle", "Circle", "Diamond", "Square", "Cross"], group = grpSwingStyle)
markerSizeName     = input.string("Tiny", "Size", options = ["Tiny", "Small", "Normal", "Large"], group = grpSwingStyle)
swingTextColor     = input.color(color.white, "Text color", group = grpSwingStyle)
swingFontName      = input.string("Default", "Text font", options = ["Default", "Monospace"], group = grpSwingStyle)
zoneFillColor      = input.color(color.new(color.orange, 75), "Zone fill", group = grpSwingStyle, inline = "zone")
zoneBorderColor    = input.color(color.new(color.orange, 100), "Border", group = grpSwingStyle, inline = "zone")
confirmDotColor    = input.color(color.yellow, "Confirmation dot", group = grpSwingStyle)
 
// =============================================================================
// HELPERS
// =============================================================================
markerSize = switch markerSizeName
    "Small"  => size.small
    "Normal" => size.normal
    "Large"  => size.large
    => size.tiny
 
swingFont = swingFontName == "Monospace" ? font.family_monospace : font.family_default
 
markerStyle(bool isHigh) =>
    switch markerShapeName
        "Circle"  => label.style_circle
        "Diamond" => label.style_diamond
        "Square"  => label.style_square
        "Cross"   => label.style_xcross
        => isHigh ? label.style_triangledown : label.style_triangleup
 
// 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]
 
drawSwing(bool isHigh, int swingBar, float price, float zoneTop, float zoneBottom, string structureText) =>
    if showSwingMarkers
        label.new(swingBar, price, showSwingText ? structureText : "", xloc = xloc.bar_index,
             yloc = isHigh ? yloc.abovebar : yloc.belowbar, color = isHigh ? swingHighColor : swingLowColor,
             style = showSwingText ? (isHigh ? label.style_label_down : label.style_label_up) : markerStyle(isHigh),
             textcolor = swingTextColor, size = markerSize, text_font_family = swingFont)
    if showSwingZones
        box.new(swingBar - 1, zoneTop, swingBar + 1, zoneBottom, border_color = zoneBorderColor,
             border_width = 1, bgcolor = zoneFillColor)
 
// =============================================================================
// CORE SERIES (computed on every bar so their history stays consistent)
// =============================================================================
emaValue = ta.ema(close, emaLength)
atrValue = ta.atr(atrLength)
 
// =============================================================================
// 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 legExtremeEma   = na
var float pullbackExtreme = na
var int   pullbackBar     = na
 
var float swingHigh       = na
var float swingHighEma    = na
var float swingHighTop    = na
var float swingHighBottom = na
 
var float swingLow        = na
var float swingLowEma     = na
var float swingLowTop     = na
var float swingLowBottom  = na
 
newSwingHigh = false
newSwingLow  = false
 
// 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, legExtremeEma := emaValue
            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, legExtremeEma := emaValue
            pullbackExtreme := na, pullbackBar := na
        else if na(pullbackExtreme) or high > pullbackExtreme
            pullbackExtreme := high, pullbackBar := bar_index
 
    // Confirmation
    if searchDir == -1 and not na(pullbackExtreme) and pullbackExtreme <= legExtreme - swingReversalAtr * legExtremeAtr
        [zoneTop, zoneBottom] = swingZone(true, legExtreme, bodyExtreme(true, legExtremeBar), legExtremeAtr)
        structureText = na(swingHigh) ? "H" : legExtreme > swingHigh ? "HH" : "LH"
        swingHigh := legExtreme, swingHighEma := legExtremeEma, swingHighTop := zoneTop, swingHighBottom := zoneBottom
        drawSwing(true, legExtremeBar, swingHigh, zoneTop, zoneBottom, structureText)
        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], legExtremeEma := emaValue[pullbackOffset]
        [nextPrice, nextBar] = extremeAfter(true, legExtremeBar)
        pullbackExtreme := nextPrice, pullbackBar := nextBar
    else if searchDir == 1 and not na(pullbackExtreme) and pullbackExtreme >= legExtreme + swingReversalAtr * legExtremeAtr
        [zoneTop, zoneBottom] = swingZone(false, legExtreme, bodyExtreme(false, legExtremeBar), legExtremeAtr)
        structureText = na(swingLow) ? "L" : legExtreme > swingLow ? "HL" : "LL"
        swingLow := legExtreme, swingLowEma := legExtremeEma, swingLowTop := zoneTop, swingLowBottom := zoneBottom
        drawSwing(false, legExtremeBar, swingLow, zoneTop, zoneBottom, structureText)
        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], legExtremeEma := emaValue[pullbackOffset]
        [nextPrice, nextBar] = extremeAfter(false, legExtremeBar)
        pullbackExtreme := nextPrice, pullbackBar := nextBar
 
// =============================================================================
// TREND STATE (EMA color): re-evaluated only when a swing is confirmed
// =============================================================================
var int trend = 0     // 1 up, -1 down, 0 neutral
 
if (newSwingHigh or newSwingLow) and not na(swingHigh) and not na(swingLow)
    refEma       = newSwingHigh ? swingHighEma : swingLowEma   // EMA at the bar of the newest swing
    highZoneAbove = swingHighTop >= refEma                     // high zone touches the EMA or is above it
    highZoneBelow = swingHighBottom <= refEma                  // high zone touches the EMA or is below it
    lowZoneAbove  = swingLowTop >= refEma
    lowZoneBelow  = swingLowBottom <= refEma
    bothAbove     = highZoneAbove and lowZoneAbove
    bothBelow     = highZoneBelow and lowZoneBelow
    if bothAbove and not bothBelow
        trend := 1
    else if bothBelow and not bothAbove
        trend := -1
    else if bothAbove and bothBelow
        trend := 0                                             // both zones sit on the EMA
    else
        // Transition: high above the EMA, low below it - midpoint rule
        zonesOverlap = swingLowTop >= swingHighBottom
        gapBottom    = zonesOverlap ? swingLow : swingLowTop
        gapTop       = zonesOverlap ? swingHigh : swingHighBottom
        midpoint     = (gapBottom + gapTop) / 2
        if trend == -1 and refEma > midpoint
            trend := -1                                        // the high only pierced the EMA
        else if trend == 1 and refEma < midpoint
            trend := 1                                         // the low only pierced the EMA
        else
            trend := 0
 
trendChanged = trend != trend[1]
 
// =============================================================================
// PLOTS AND ALERTS
// =============================================================================
emaColor = colorEmaByTrend ? (trend == 1 ? emaUpColor : trend == -1 ? emaDownColor : emaNeutralColor) : emaPlainColor
plot(showEma ? emaValue : na, "EMA", emaColor, emaLineWidth)
 
plotshape(showConfirmDots and newSwingHigh, "Swing high confirmed", shape.circle, location.abovebar, confirmDotColor, size = size.tiny)
plotshape(showConfirmDots and newSwingLow, "Swing low confirmed", shape.circle, location.belowbar, confirmDotColor, size = size.tiny)
 
// Trend state for other scripts and alerts (Data Window only)
plot(trend, "Trend (1 / -1 / 0)", display = display.data_window)
 
alertcondition(trendChanged and trend == 1, "Trend turned up", "Structure-Colored EMA: trend turned UP on {{ticker}} {{interval}}")
alertcondition(trendChanged and trend == -1, "Trend turned down", "Structure-Colored EMA: trend turned DOWN on {{ticker}} {{interval}}")
alertcondition(trendChanged and trend == 0, "Trend turned neutral", "Structure-Colored EMA: trend turned NEUTRAL on {{ticker}} {{interval}}")
alertcondition(newSwingHigh or newSwingLow, "Swing confirmed", "Structure-Colored EMA: new swing confirmed on {{ticker}} {{interval}}")

← 返回列表