AutoSRZones

PyneSys · library · 468 行 · 点赞 7 · TradingView 原页

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

Pine Script

//@version=6
// ============================================================================
//              [] ##          PyneSys
//           [] [] ## ##
//        [] [] [] ## ## ##
//     [] [] [] [] ## ## ## ##
//  [] [] [] [] [] ## ## ## ## ##
//              || ||
// ============================================================================
// AutoSRZones
// © 2026 PyneSys LLC. Licensed under MPL-2.0: https://mozilla.org/MPL/2.0/
// ============================================================================
 
// @description Automatic support and resistance levels with their own history.
// A zigzag with an ATR-based reversal threshold finds the turning points, and every turning point is
// stored as it is, never merged. A turning point is significant when it stands out: its prominence is
// how far price had to move away from it, on both sides, before reaching a more extreme turning point
// of the same kind. Small reversals inside a larger move have a small prominence and never become a
// level on their own. Levels start from significant peaks only; nearby peaks of any size count with
// them, and the level sits at the price of the strongest real peak of the group, not at an average.
// Weights fade with a half-life. The best levels are drawn as plots, so every bar keeps the levels
// that were valid on it and the whole history stays visible.
// Nothing here looks at future bars: a peak is stored only after price has turned away from it, and
// its prominence grows only as later prices confirm it.
library("AutoSRZones", overlay = true)
 
 
// @type A confirmed zigzag turning point.
// @field id A unique, increasing identifier.
// @field price The extreme price of the turning point.
// @field bar The bar index of the extreme.
// @field isHigh True for a top, false for a bottom.
// @field atr The ATR when the turning point was confirmed. Prominence is measured in it.
// @field volume The average volume at the extreme.
// @field prominence How far price moved away on both sides before a more extreme peak of the same
// kind, in ATR: the smaller of the two sides. 0 until a later peak confirms the right side.
export type Peak
    int id
    float price
    int bar
    bool isHigh
    float atr
    float volume
    float prominence
 
// @type A support/resistance level formed by one or more stored peaks.
// @field id The id of the peak that gives the level its price. The same id always means the same
// price; when a stronger peak takes over the group, the level gets that peak's id.
// @field price The price of the strongest peak in the group, a real turning point.
// @field score The faded weights of the group, added up. Compare scores with each other only.
// @field touches How many stored peaks form the level.
// @field firstBar The bar of the oldest peak in the group.
// @field lastBar The bar of the newest peak in the group.
// @field strength The faded prominence of the group, added up, in ATR, as of bar `scoredAt`.
// @field scoredAt The bar on which `score` and `strength` were measured.
export type Level
    int id
    float price
    float score
    int touches
    int firstBar
    int lastBar
    float strength
    int scoredAt
 
 
// @function Zigzag turning points with a reversal threshold. A top is confirmed when the close falls
// at least `threshold` below the highest high since the last bottom, a bottom the other way round.
// @param threshold The reversal needed to confirm a turning point, in price.
// @param volMa The volume average to remember at each extreme, used only for volume weighting.
// @returns [price, bar, isHigh, leg, volume] The turning point confirmed on this bar, or na values.
// `leg` is the size of the move that ended at the turning point.
export zigzag(float threshold, float volMa) =>
    var int dir = 0
    var float extHigh = na
    var int extHighBar = na
    var float extHighVol = na
    var float extLow = na
    var int extLowBar = na
    var float extLowVol = na
    var float legStart = na
 
    float peakPrice = na
    int peakBar = na
    bool peakIsHigh = false
    float leg = na
    float peakVol = na
 
    if na(extHigh) or high > extHigh
        extHigh := high
        extHighBar := bar_index
        extHighVol := volMa
    if na(extLow) or low < extLow
        extLow := low
        extLowBar := bar_index
        extLowVol := volMa
 
    if dir == 0
        // Before the first turn: wait for the first move of the threshold size.
        if extHigh - close >= threshold
            dir := -1
            legStart := extHigh
            extLow := low
            extLowBar := bar_index
            extLowVol := volMa
        else if close - extLow >= threshold
            dir := 1
            legStart := extLow
            extHigh := high
            extHighBar := bar_index
            extHighVol := volMa
    else if dir == 1 and extHigh - close >= threshold
        // The up leg is over: its highest high is a top.
        peakPrice := extHigh
        peakBar := extHighBar
        peakIsHigh := true
        leg := extHigh - legStart
        peakVol := extHighVol
        dir := -1
        legStart := extHigh
        extLow := low
        extLowBar := bar_index
        extLowVol := volMa
    else if dir == -1 and close - extLow >= threshold
        // The down leg is over: its lowest low is a bottom.
        peakPrice := extLow
        peakBar := extLowBar
        peakIsHigh := false
        leg := legStart - extLow
        peakVol := extLowVol
        dir := 1
        legStart := extLow
        extHigh := high
        extHighBar := bar_index
        extHighVol := volMa
    [peakPrice, peakBar, peakIsHigh, leg, peakVol]
 
 
// The prominence of peak `i` in ATR. On each side, walk away from the peak until a more extreme peak
// of the same kind appears, and note how far price got from the peak on the way (the most extreme
// opposite turning point). The prominence is the smaller of the two sides. The right side must be
// known: the newest peak has none yet, so it scores 0 until the next turning point arrives. On the
// left, the start of the stored history stands in for an unknown past.
_prominence(array<Peak> peaks, int i) =>
    Peak k = peaks.get(i)
    float sgn = k.isHigh ? 1.0 : -1.0
    float result = na
    bool rightKnown = false
    for step in array.from(-1, 1)
        int j = i + step
        float extreme = na
        while j >= 0 and j < peaks.size()
            Peak q = peaks.get(j)
            if q.isHigh == k.isHigh
                if sgn * (q.price - k.price) > 0
                    break
            else
                extreme := na(extreme) ? q.price : k.isHigh ? math.min(extreme, q.price) : math.max(extreme, q.price)
            j += step
        if not na(extreme)
            float drop = sgn * (k.price - extreme)
            result := na(result) ? drop : math.min(result, drop)
            if step == 1
                rightKnown := true
    rightKnown ? nz(result) / k.atr : 0.0
 
 
// The weight of a peak on the current bar: prominence, volume or 1, faded by its age.
_faded(Peak p, float decay, string weighting) =>
    float base = weighting == "Volume" ? p.volume : weighting == "Equal" ? 1.0 : p.prominence
    base * math.pow(decay, bar_index - p.bar)
 
 
// The level's strength on the current bar: its faded prominence fades further with every bar.
_strengthNow(Level l, float decay) =>
    l.strength * math.pow(decay, bar_index - l.scoredAt)
 
 
// Groups the stored peaks into levels. The strongest significant peak not yet in a group starts a
// new group and collects every free peak, of any size, within `radius` of its own price: smaller
// reactions at a strong level count for it, but never start a level themselves. The group never
// drifts: its level stays at the starting peak's price, and peaks join by their distance from that
// price only. Two levels therefore always stand more than `radius` apart. A level whose faded
// prominence has dropped below half of `minProminence` is gone: nothing has renewed it for too long.
_cluster(array<Peak> peaks, float radius, float decay, float minProminence, string weighting) =>
    array<float> weights = array.new<float>()
    array<float> fadedProminence = array.new<float>()
    for p in peaks
        weights.push(_faded(p, decay, weighting))
        fadedProminence.push(_faded(p, decay, "Prominence"))
    array<int> ranking = weights.sort_indices(order.descending)
    array<bool> used = array.new<bool>(peaks.size(), false)
    array<Level> result = array.new<Level>()
    for i in ranking
        Peak anchor = peaks.get(i)
        if not used.get(i) and anchor.prominence >= minProminence
            used.set(i, true)
            Level lvl = Level.new(anchor.id, anchor.price, weights.get(i), 1, anchor.bar, anchor.bar, fadedProminence.get(i), bar_index)
            for [j, p] in peaks
                if not used.get(j) and math.abs(p.price - anchor.price) <= radius
                    used.set(j, true)
                    lvl.score += weights.get(j)
                    lvl.touches += 1
                    lvl.firstBar := math.min(lvl.firstBar, p.bar)
                    lvl.lastBar := math.max(lvl.lastBar, p.bar)
                    lvl.strength += fadedProminence.get(j)
            if lvl.strength >= minProminence / 2
                result.push(lvl)
    result
 
 
// @function Finds turning points, stores them and forms the levels. Call it once on every bar,
// outside any condition.
// @param minSwingAtr The reversal that confirms a turning point, as an ATR multiple. Every confirmed
// turning point is stored; this only sets the finest detail the zigzag sees.
// @param minProminenceAtr The prominence a peak needs to start a level, as an ATR multiple. The main
// filter: raise it for fewer, more significant levels.
// @param groupAtr Peaks within this distance of a stronger peak, as an ATR multiple, count as the same level,
// so no two levels stand closer than this.
// @param toleranceAtr The tolerance band of a level on each side, as an ATR multiple: how close price
// must come to count as a test of the level. At most half of `groupAtr`, the bands of two levels never overlap.
// @param halfLife Bars after which a peak's weight and prominence are halved. It sets how long a level
// lives: a level disappears once its faded prominence drops below half of `minProminenceAtr`, unless
// new peaks at the level renew it.
// @param maxPeaks The most peaks stored. When full, the oldest goes.
// @param weighting "Prominence": how much the peak stands out, in ATR. "Volume": the average volume
// at the peak. "Equal": every peak counts the same.
// @param atrLen The ATR length. A long ATR keeps a sudden burst of volatility from shrinking the
// prominence of the very peaks that burst created.
// @returns [levels, tolerance] The current levels, strongest first, and the tolerance band (half-width) in price.
export levels(simple float minSwingAtr = 4.0, simple float minProminenceAtr = 10.0, simple float groupAtr = 2.0, simple float toleranceAtr = 1.0, simple int halfLife = 1000, simple int maxPeaks = 300, simple string weighting = "Prominence", simple int atrLen = 200) =>
    var array<Peak> peaks = array.new<Peak>()
    var array<Level> lvls = array.new<Level>()
    var int nextId = 0
    float atr = ta.atr(atrLen)
    float volMa = ta.sma(volume, 5)
    float decay = math.pow(0.5, 1.0 / halfLife)
    float groupDist = groupAtr * atr
    float tolerance = toleranceAtr * atr
    [peakPrice, peakBar, peakIsHigh, leg, peakVol] = zigzag(minSwingAtr * atr, volMa)
    if not na(peakPrice)
        nextId += 1
        peaks.push(Peak.new(nextId, peakPrice, peakBar, peakIsHigh, atr, nz(peakVol, 1.0), 0.0))
        if peaks.size() > maxPeaks
            peaks.shift()
        // A new turning point can change the prominence of the earlier ones, so all are measured again.
        for [i, p] in peaks
            p.prominence := _prominence(peaks, i)
        // Fading is the same factor for every peak, so the order of the levels only changes when a
        // peak arrives: the levels are formed again only then.
        lvls := _cluster(peaks, groupDist, decay, minProminenceAtr, weighting)
    // Levels keep fading between two peaks: drop the ones that faded out on this bar.
    int k = 0
    while k < lvls.size()
        if _strengthNow(lvls.get(k), decay) < minProminenceAtr / 2
            lvls.remove(k)
        else
            k += 1
    [lvls, tolerance]
 
 
// @function The price of the nearest level below the close.
// @param lvls The levels returned by `levels()`.
// @param minTouches The fewest peaks a level needs.
// @returns The level price, or na.
export supportBelow(array<Level> lvls, int minTouches = 1) =>
    float best = na
    for l in lvls
        if l.touches >= minTouches and l.price < close and (na(best) or l.price > best)
            best := l.price
    best
 
 
// @function The price of the nearest level above the close.
// @param lvls The levels returned by `levels()`.
// @param minTouches The fewest peaks a level needs.
// @returns The level price, or na.
export resistanceAbove(array<Level> lvls, int minTouches = 1) =>
    float best = na
    for l in lvls
        if l.touches >= minTouches and l.price > close and (na(best) or l.price < best)
            best := l.price
    best
 
 
// @function True when this bar reached down into the band of a level and closed above the level:
// price came back to support and held.
// @param lvls The levels returned by `levels()`.
// @param tolerance The tolerance returned by `levels()`.
// @param minTouches The fewest peaks a level needs.
// @returns True on a support test.
export atSupport(array<Level> lvls, float tolerance, int minTouches = 1) =>
    bool hit = false
    for l in lvls
        if l.touches >= minTouches and low <= l.price + tolerance and close > l.price
            hit := true
    hit
 
 
// @function True when this bar reached up into the band of a level and closed below the level:
// price came back to resistance and was rejected.
// @param lvls The levels returned by `levels()`.
// @param tolerance The tolerance returned by `levels()`.
// @param minTouches The fewest peaks a level needs.
// @returns True on a resistance test.
export atResistance(array<Level> lvls, float tolerance, int minTouches = 1) =>
    bool hit = false
    for l in lvls
        if l.touches >= minTouches and high >= l.price - tolerance and close < l.price
            hit := true
    hit
 
 
// @function The levels nearest to the close, each kept in the same output slot while it is shown. When
// there are more levels than slots, the nearest ones win, but a shown level gives up its slot only to
// a level at least `margin` closer to the close, so two levels at almost the same distance do not keep
// swapping. One plot per slot then draws a steady line with its full history.
// @param lvls The levels returned by `levels()`.
// @param slots The number of output slots. Use a constant: the slots keep their state between bars.
// @param margin How much closer, in price, a level must be to replace a shown one.
// @param minTouches The fewest peaks a level needs.
// @returns [prices, strengths, ids] One entry per slot, na when empty. Strength is the score relative
// to the strongest level, from 0 to 1.
export nearest(array<Level> lvls, simple int slots = 5, float margin = 0.0, int minTouches = 1) =>
    var array<int> slotIds = array.new<int>(slots, na)
 
    float top = 0.0
    array<Level> qualified = array.new<Level>()
    array<int> qualifiedIds = array.new<int>()
    array<float> distances = array.new<float>()
    for l in lvls
        top := math.max(top, l.score)
        if l.touches >= minTouches
            qualified.push(l)
            qualifiedIds.push(l.id)
            distances.push(math.abs(l.price - close))
 
    // A slot whose level is gone (faded out, merged away) is freed.
    int s = 0
    while s < slots
        if not qualifiedIds.includes(slotIds.get(s))
            slotIds.set(s, na)
        s += 1
    // The nearest levels claim a slot, closest first: a free one, or the slot of the farthest shown
    // level when the newcomer is closer by at least `margin`.
    int taken = 0
    for i in distances.sort_indices()
        if taken >= slots
            break
        int id = qualifiedIds.get(i)
        if slotIds.includes(id)
            taken += 1
        else
            int target = -1
            float farthest = na
            int f = 0
            while f < slots
                int occupant = slotIds.get(f)
                if na(occupant)
                    target := f
                    break
                float d = distances.get(qualifiedIds.indexof(occupant))
                if na(farthest) or d > farthest
                    farthest := d
                    target := f
                f += 1
            if target >= 0 and (na(slotIds.get(target)) or farthest - distances.get(i) >= margin)
                slotIds.set(target, id)
                taken += 1
 
    array<float> prices = array.new<float>(slots, na)
    array<float> strengths = array.new<float>(slots, na)
    for l in qualified
        int slot = slotIds.indexof(l.id)
        if slot >= 0
            prices.set(slot, l.price)
            strengths.set(slot, top > 0 ? l.score / top : 1.0)
    [prices, strengths, slotIds.copy()]
 
 
//
// Demo: the levels around the price, with their history
//
 
minSwingAtrIn = input.float(4.0, "Minimum reversal (ATR)", minval = 0.5, step = 0.5, group = "Peaks", tooltip = "The finest turning point the zigzag sees: price must turn this far from it.")
minProminenceAtrIn = input.float(10.0, "Minimum prominence (ATR)", minval = 0, step = 1, group = "Peaks", tooltip = "How far price must move away from a peak on both sides before a more extreme one, for the peak to start a level. The main filter: raise it for fewer, more significant levels.")
atrLenIn = input.int(200, "ATR length", minval = 1, group = "Peaks")
weightingIn = input.string("Prominence", "Peak weight", options = ["Prominence", "Volume", "Equal"], group = "Peaks")
groupAtrIn = input.float(2.0, "Same level within (ATR)", minval = 0.1, step = 0.1, group = "Levels", tooltip = "Peaks this close to a stronger peak count as the same level, so no two levels stand closer.")
toleranceAtrIn = input.float(1.0, "Tolerance band (ATR)", minval = 0.05, step = 0.05, group = "Levels", tooltip = "How close price must come to a level, on each side, to count as a test of it. At most half of 'Same level within', the bands never overlap.")
halfLifeIn = input.int(1000, "Half-life (bars)", minval = 1, group = "Levels", tooltip = "A peak's weight and prominence halve after this many bars. A level disappears once its faded prominence drops below half of the minimum prominence, unless new peaks at the level renew it.")
maxPeaksIn = input.int(300, "Stored peaks", minval = 10, maxval = 1000, group = "Levels", tooltip = "The oldest peak goes when the store is full.")
minTouchesIn = input.int(1, "Minimum peaks per level", minval = 1, group = "Levels")
levelCountIn = input.int(5, "S/R count", minval = 1, maxval = 20, group = "Display", tooltip = "How many levels to show: the ones nearest to the price.")
showBandIn = input.bool(true, "Tolerance band around the nearest level", group = "Display")
 
[srLevels, srTolerance] = levels(minSwingAtrIn, minProminenceAtrIn, groupAtrIn, toleranceAtrIn, halfLifeIn, maxPeaksIn, weightingIn, atrLenIn)
// The levels nearest to the price, each in its own steady plot.
[slotPrices, slotStrengths, slotIds] = nearest(srLevels, levelCountIn, 2 * srTolerance, minTouchesIn)
 
// The price in slot `k`, or na when the slot is empty or took a different level on this bar.
// The one-bar break keeps a vertical connector from joining two different levels.
_slotPrice(array<float> prices, array<int> ids, int k) =>
    int id = k < ids.size() ? ids.get(k) : na
    float p = k < prices.size() ? prices.get(k) : na
    id == id[1] ? p : na
 
// Green below the close (support), red above it (resistance), decided bar by bar.
// Stronger levels are more opaque.
_slotColor(array<float> strengths, float price, int k) =>
    float st = k < strengths.size() ? strengths.get(k) : na
    color base = price < close ? color.green : color.red
    color.new(base, 80 - 80 * nz(st))
 
float sr0 = _slotPrice(slotPrices, slotIds, 0)
float sr1 = _slotPrice(slotPrices, slotIds, 1)
float sr2 = _slotPrice(slotPrices, slotIds, 2)
float sr3 = _slotPrice(slotPrices, slotIds, 3)
float sr4 = _slotPrice(slotPrices, slotIds, 4)
float sr5 = _slotPrice(slotPrices, slotIds, 5)
float sr6 = _slotPrice(slotPrices, slotIds, 6)
float sr7 = _slotPrice(slotPrices, slotIds, 7)
float sr8 = _slotPrice(slotPrices, slotIds, 8)
float sr9 = _slotPrice(slotPrices, slotIds, 9)
float sr10 = _slotPrice(slotPrices, slotIds, 10)
float sr11 = _slotPrice(slotPrices, slotIds, 11)
float sr12 = _slotPrice(slotPrices, slotIds, 12)
float sr13 = _slotPrice(slotPrices, slotIds, 13)
float sr14 = _slotPrice(slotPrices, slotIds, 14)
float sr15 = _slotPrice(slotPrices, slotIds, 15)
float sr16 = _slotPrice(slotPrices, slotIds, 16)
float sr17 = _slotPrice(slotPrices, slotIds, 17)
float sr18 = _slotPrice(slotPrices, slotIds, 18)
float sr19 = _slotPrice(slotPrices, slotIds, 19)
 
plot(sr0, "S/R 0", _slotColor(slotStrengths, sr0, 0), 3, plot.style_linebr)
plot(sr1, "S/R 1", _slotColor(slotStrengths, sr1, 1), 3, plot.style_linebr)
plot(sr2, "S/R 2", _slotColor(slotStrengths, sr2, 2), 3, plot.style_linebr)
plot(sr3, "S/R 3", _slotColor(slotStrengths, sr3, 3), 3, plot.style_linebr)
plot(sr4, "S/R 4", _slotColor(slotStrengths, sr4, 4), 3, plot.style_linebr)
plot(sr5, "S/R 5", _slotColor(slotStrengths, sr5, 5), 3, plot.style_linebr)
plot(sr6, "S/R 6", _slotColor(slotStrengths, sr6, 6), 3, plot.style_linebr)
plot(sr7, "S/R 7", _slotColor(slotStrengths, sr7, 7), 3, plot.style_linebr)
plot(sr8, "S/R 8", _slotColor(slotStrengths, sr8, 8), 3, plot.style_linebr)
plot(sr9, "S/R 9", _slotColor(slotStrengths, sr9, 9), 3, plot.style_linebr)
plot(sr10, "S/R 10", _slotColor(slotStrengths, sr10, 10), 3, plot.style_linebr)
plot(sr11, "S/R 11", _slotColor(slotStrengths, sr11, 11), 3, plot.style_linebr)
plot(sr12, "S/R 12", _slotColor(slotStrengths, sr12, 12), 3, plot.style_linebr)
plot(sr13, "S/R 13", _slotColor(slotStrengths, sr13, 13), 3, plot.style_linebr)
plot(sr14, "S/R 14", _slotColor(slotStrengths, sr14, 14), 3, plot.style_linebr)
plot(sr15, "S/R 15", _slotColor(slotStrengths, sr15, 15), 3, plot.style_linebr)
plot(sr16, "S/R 16", _slotColor(slotStrengths, sr16, 16), 3, plot.style_linebr)
plot(sr17, "S/R 17", _slotColor(slotStrengths, sr17, 17), 3, plot.style_linebr)
plot(sr18, "S/R 18", _slotColor(slotStrengths, sr18, 18), 3, plot.style_linebr)
plot(sr19, "S/R 19", _slotColor(slotStrengths, sr19, 19), 3, plot.style_linebr)
 
// The tolerance band of the shown level nearest to the close.
int nearestSlot = -1
for [i, p] in slotPrices
    if not na(p) and (nearestSlot < 0 or math.abs(p - close) < math.abs(slotPrices.get(nearestSlot) - close))
        nearestSlot := i
int nearestId = nearestSlot >= 0 ? slotIds.get(nearestSlot) : na
float nearestLevel = na
if showBandIn and nearestSlot >= 0 and nearestId == nearestId[1]
    nearestLevel := slotPrices.get(nearestSlot)
bandUpper = plot(nearestLevel + srTolerance, "Band upper", color.new(color.gray, 100), style = plot.style_linebr)
bandLower = plot(nearestLevel - srTolerance, "Band lower", color.new(color.gray, 100), style = plot.style_linebr)
fill(bandUpper, bandLower, nearestLevel < close ? color.new(color.green, 88) : color.new(color.red, 88), "Tolerance band")

← 返回列表