OS RSI Auction Map, RSI-Derived Support, Resistance & Role Flips

JesseV365 · study · 868 行 · 点赞 50 · TradingView 原页

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

Pine Script

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0
// © JesseV365
 
//@version=6
 
indicator("OS RSI Auction Map — RSI-Derived Support, Resistance & Role Flips", shorttitle="OS RSI Auction Map", overlay=true,
     max_bars_back=1000, max_lines_count=30, max_boxes_count=30, max_labels_count=30)
 
//=============================================================================
// INPUTS
//=============================================================================
 
string GROUP_ENGINE = "01 — RSI Auction Engine"
int rsiLen          = input.int(14, "RSI Length", minval=2, group=GROUP_ENGINE)
int rsiOB           = input.int(70, "Overbought", minval=51, maxval=99, inline="rsi", group=GROUP_ENGINE)
int rsiOS           = input.int(30, "Oversold", minval=1, maxval=49, inline="rsi", group=GROUP_ENGINE)
int reactionHigh    = input.int(60, "Reaction High", minval=51, maxval=80, inline="reaction", group=GROUP_ENGINE)
int reactionLow     = input.int(40, "Reaction Low", minval=20, maxval=49, inline="reaction", group=GROUP_ENGINE)
int atrLen          = input.int(14, "ATR Length", minval=2, group=GROUP_ENGINE)
float zoneAtr       = input.float(0.10, "Zone Half-Width (ATR)", minval=0.0, step=0.01, group=GROUP_ENGINE)
float mergeAtr      = input.float(0.20, "Merge Distance (ATR)", minval=0.0, step=0.05, group=GROUP_ENGINE)
float actionableAtr = input.float(3.0, "Dashboard Relevance (ATR)", minval=0.5, step=0.5,
     tooltip="Levels farther away remain stored but do not occupy the live chart or dashboard.", group=GROUP_ENGINE)
float secondarySepAtr = input.float(0.35, "Secondary Display Separation (ATR)", minval=0.0, step=0.05,
     tooltip="Suppresses S2/R2 when it is too close to S1/R1 to add useful structure.", group=GROUP_ENGINE)
int breakCloses     = input.int(2, "Closes to Confirm Break", minval=1, maxval=5, group=GROUP_ENGINE)
int distinctTestBars = input.int(3, "Bars Between Distinct Tests", minval=1, maxval=20,
     tooltip="Prevents several candles inside the same zone from being counted as separate tests.", group=GROUP_ENGINE)
float defenseAtr    = input.float(0.15, "Minimum Defense Travel (ATR)", minval=0.0, step=0.05,
     tooltip="Minimum close-away distance required before a test strengthens a level.", group=GROUP_ENGINE)
int majorLife       = input.int(180, "Major Level Life (bars)", minval=20, maxval=1000, group=GROUP_ENGINE)
int reactionLife    = input.int(60, "Reaction Level Life (bars)", minval=10, maxval=500, group=GROUP_ENGINE)
int maxStored       = input.int(20, "Maximum Stored Levels", minval=4, maxval=50, group=GROUP_ENGINE)
 
string GROUP_VIEW = "02 — Display"
bool showZones     = input.bool(true, "Show Active Zones", group=GROUP_VIEW)
bool showSecondary = input.bool(true, "Show Previous / Secondary Levels", group=GROUP_VIEW)
bool showFlip      = input.bool(true, "Show Latest Role Flip", group=GROUP_VIEW)
bool showDashboard = input.bool(true, "Show Dashboard", group=GROUP_VIEW)
int extendBars     = input.int(14, "Right Extension", minval=3, maxval=50, group=GROUP_VIEW)
string dashLoc     = input.string("Bottom Right", "Dashboard Location",
     options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group=GROUP_VIEW)
string dashSize    = input.string("Small", "Dashboard Size",
     options=["Tiny", "Small", "Normal", "Large"], group=GROUP_VIEW)
 
color SUPPORT = input.color(color.rgb(0, 255, 120), "Support", inline="colors", group=GROUP_VIEW)
color RESIST  = input.color(color.rgb(255, 45, 210), "Resistance", inline="colors", group=GROUP_VIEW)
color FLIP    = input.color(color.rgb(255, 180, 35), "Role Flip", inline="colors", group=GROUP_VIEW)
color NEUTRAL = color.rgb(175, 180, 192)
 
//=============================================================================
// HELPERS
//=============================================================================
 
f_position(string value) =>
    switch value
        "Top Left" => position.top_left
        "Top Center" => position.top_center
        "Top Right" => position.top_right
        "Middle Left" => position.middle_left
        "Middle Center" => position.middle_center
        "Middle Right" => position.middle_right
        "Bottom Left" => position.bottom_left
        "Bottom Center" => position.bottom_center
        => position.bottom_right
 
f_size(string value) =>
    switch value
        "Tiny" => size.tiny
        "Normal" => size.normal
        "Large" => size.large
        => size.small
 
f_signed(float value, string pattern) =>
    na(value) ? "n/a" : (value > 0 ? "+" : "") + str.tostring(value, pattern)
 
f_state_text(int state) =>
    switch state
        1 => "TESTED"
        2 => "DEFENDED"
        4 => "FLIPPED"
        5 => "ACCEPTED"
        6 => "RECLAIMED"
        => "ACTIVE"
 
f_quality_text(int state, int tests, int defenses) =>
    int unanswered = math.max(tests - defenses, 0)
    state == 5 ? "ACCEPTED" :
     unanswered >= 2 ? "WEAKENING" :
     state == 4 ? "FLIPPED" :
     defenses >= 3 ? "DEFENDED x" + str.tostring(defenses) :
     defenses > 0 ? "DEFENDED x" + str.tostring(defenses) :
     tests > 0 ? "TESTED" : "FRESH"
 
f_level_score(int levelKind, int state, int tests, int defenses, float distanceAtr) =>
    int unanswered = math.max(tests - defenses, 0)
    float stateBonus = state == 4 ? 35.0 : state == 2 ? 15.0 : 0.0
    levelKind * 100.0 + defenses * 25.0 + stateBonus - unanswered * 18.0 - distanceAtr
 
f_distance_text(float level, float current, float currentAtr) =>
    na(level) or currentAtr <= 0 ? "n/a" : str.tostring(math.abs(level - current) / currentAtr, "0.00") + " ATR " + (level >= current ? "ABOVE" : "BELOW")
 
//=============================================================================
// RSI EXCURSIONS -> PRICE AUCTION LEVELS
//=============================================================================
 
float rsi = ta.rsi(close, rsiLen)
float atr = ta.atr(atrLen)
float halfWidth = math.max(atr * zoneAtr, syminfo.mintick * 2.0)
float mergeDistance = atr * mergeAtr
 
var bool inOversold = false
var bool inOverbought = false
var float excursionLow = na
var float excursionHigh = na
var bool inReactionLow = false
var bool inReactionHigh = false
var float reactionExcursionLow = na
var float reactionExcursionHigh = na
 
if rsi <= rsiOS
    if not inOversold
        inOversold := true
        excursionLow := low
    else
        excursionLow := math.min(excursionLow, low)
 
if rsi >= rsiOB
    if not inOverbought
        inOverbought := true
        excursionHigh := high
    else
        excursionHigh := math.max(excursionHigh, high)
 
if rsi <= reactionLow
    if not inReactionLow
        inReactionLow := true
        reactionExcursionLow := low
    else
        reactionExcursionLow := math.min(reactionExcursionLow, low)
 
if rsi >= reactionHigh
    if not inReactionHigh
        inReactionHigh := true
        reactionExcursionHigh := high
    else
        reactionExcursionHigh := math.max(reactionExcursionHigh, high)
 
bool supportCreated = inOversold and ta.crossover(rsi, rsiOS)
bool resistanceCreated = inOverbought and ta.crossunder(rsi, rsiOB)
float newSupport = supportCreated ? excursionLow : na
float newResistance = resistanceCreated ? excursionHigh : na
bool reactionSupportCreated = inReactionLow and ta.crossover(rsi, reactionLow)
bool reactionResistanceCreated = inReactionHigh and ta.crossunder(rsi, reactionHigh)
float newReactionSupport = reactionSupportCreated ? reactionExcursionLow : na
float newReactionResistance = reactionResistanceCreated ? reactionExcursionHigh : na
 
if supportCreated
    inOversold := false
    excursionLow := na
 
if resistanceCreated
    inOverbought := false
    excursionHigh := na
 
if reactionSupportCreated
    inReactionLow := false
    reactionExcursionLow := na
 
if reactionResistanceCreated
    inReactionHigh := false
    reactionExcursionHigh := na
 
// role: +1 support, -1 resistance. class: 2 major (30/70), 1 reaction (40/60).
// state: 0 active, 1 testing this bar, 2 defended this bar, 4 flipped,
//        5 breached/awaiting retest, 6 failed flip this bar.
var array<float> levelPrice = array.new_float()
var array<int> levelRole = array.new_int()
var array<int> levelClass = array.new_int()
var array<int> levelState = array.new_int()
var array<int> levelBorn = array.new_int()
var array<int> levelBreakCount = array.new_int()
var array<int> levelBreachBar = array.new_int()
var array<int> levelTests = array.new_int()
var array<int> levelDefenses = array.new_int()
var array<int> levelLastTestBar = array.new_int()
var array<int> levelLastDefenseBar = array.new_int()
 
if supportCreated and not na(newSupport)
    int mergeIndex = -1
    if array.size(levelPrice) > 0
        for i = 0 to array.size(levelPrice) - 1
            if array.get(levelRole, i) == 1 and math.abs(array.get(levelPrice, i) - newSupport) <= mergeDistance
                mergeIndex := i
                break
    if mergeIndex >= 0
        if array.get(levelClass, mergeIndex) == 2
            array.set(levelPrice, mergeIndex, array.get(levelPrice, mergeIndex))
        else
            array.set(levelPrice, mergeIndex, newSupport)
        array.set(levelClass, mergeIndex, 2)
        array.set(levelState, mergeIndex, 0)
        array.set(levelBorn, mergeIndex, bar_index)
        array.set(levelBreakCount, mergeIndex, 0)
        array.set(levelBreachBar, mergeIndex, na)
    else
        array.push(levelPrice, newSupport)
        array.push(levelRole, 1)
        array.push(levelClass, 2)
        array.push(levelState, 0)
        array.push(levelBorn, bar_index)
        array.push(levelBreakCount, 0)
        array.push(levelBreachBar, na)
        array.push(levelTests, 0)
        array.push(levelDefenses, 0)
        array.push(levelLastTestBar, na)
        array.push(levelLastDefenseBar, na)
 
if resistanceCreated and not na(newResistance)
    int mergeIndex = -1
    if array.size(levelPrice) > 0
        for i = 0 to array.size(levelPrice) - 1
            if array.get(levelRole, i) == -1 and math.abs(array.get(levelPrice, i) - newResistance) <= mergeDistance
                mergeIndex := i
                break
    if mergeIndex >= 0
        if array.get(levelClass, mergeIndex) == 2
            array.set(levelPrice, mergeIndex, array.get(levelPrice, mergeIndex))
        else
            array.set(levelPrice, mergeIndex, newResistance)
        array.set(levelClass, mergeIndex, 2)
        array.set(levelState, mergeIndex, 0)
        array.set(levelBorn, mergeIndex, bar_index)
        array.set(levelBreakCount, mergeIndex, 0)
        array.set(levelBreachBar, mergeIndex, na)
    else
        array.push(levelPrice, newResistance)
        array.push(levelRole, -1)
        array.push(levelClass, 2)
        array.push(levelState, 0)
        array.push(levelBorn, bar_index)
        array.push(levelBreakCount, 0)
        array.push(levelBreachBar, na)
        array.push(levelTests, 0)
        array.push(levelDefenses, 0)
        array.push(levelLastTestBar, na)
        array.push(levelLastDefenseBar, na)
 
if reactionSupportCreated and not na(newReactionSupport)
    int mergeIndex = -1
    if array.size(levelPrice) > 0
        for i = 0 to array.size(levelPrice) - 1
            if array.get(levelRole, i) == 1 and math.abs(array.get(levelPrice, i) - newReactionSupport) <= mergeDistance
                mergeIndex := i
                break
    if mergeIndex >= 0
        if array.get(levelClass, mergeIndex) == 1
            array.set(levelPrice, mergeIndex, math.avg(array.get(levelPrice, mergeIndex), newReactionSupport))
            array.set(levelBorn, mergeIndex, bar_index)
        array.set(levelBreakCount, mergeIndex, 0)
        array.set(levelBreachBar, mergeIndex, na)
    else
        array.push(levelPrice, newReactionSupport)
        array.push(levelRole, 1)
        array.push(levelClass, 1)
        array.push(levelState, 0)
        array.push(levelBorn, bar_index)
        array.push(levelBreakCount, 0)
        array.push(levelBreachBar, na)
        array.push(levelTests, 0)
        array.push(levelDefenses, 0)
        array.push(levelLastTestBar, na)
        array.push(levelLastDefenseBar, na)
 
if reactionResistanceCreated and not na(newReactionResistance)
    int mergeIndex = -1
    if array.size(levelPrice) > 0
        for i = 0 to array.size(levelPrice) - 1
            if array.get(levelRole, i) == -1 and math.abs(array.get(levelPrice, i) - newReactionResistance) <= mergeDistance
                mergeIndex := i
                break
    if mergeIndex >= 0
        if array.get(levelClass, mergeIndex) == 1
            array.set(levelPrice, mergeIndex, math.avg(array.get(levelPrice, mergeIndex), newReactionResistance))
            array.set(levelBorn, mergeIndex, bar_index)
        array.set(levelBreakCount, mergeIndex, 0)
        array.set(levelBreachBar, mergeIndex, na)
    else
        array.push(levelPrice, newReactionResistance)
        array.push(levelRole, -1)
        array.push(levelClass, 1)
        array.push(levelState, 0)
        array.push(levelBorn, bar_index)
        array.push(levelBreakCount, 0)
        array.push(levelBreachBar, na)
        array.push(levelTests, 0)
        array.push(levelDefenses, 0)
        array.push(levelLastTestBar, na)
        array.push(levelLastDefenseBar, na)
 
while array.size(levelPrice) > maxStored
    array.shift(levelPrice)
    array.shift(levelRole)
    array.shift(levelClass)
    array.shift(levelState)
    array.shift(levelBorn)
    array.shift(levelBreakCount)
    array.shift(levelBreachBar)
    array.shift(levelTests)
    array.shift(levelDefenses)
    array.shift(levelLastTestBar)
    array.shift(levelLastDefenseBar)
 
//=============================================================================
// LEVEL LIFECYCLE
//=============================================================================
 
var float latestFlipPrice = na
var int latestFlipRole = 0
var int latestFlipBar = na
var int latestFlipClass = 1
 
bool supportTested = false
bool resistanceTested = false
bool supportDefended = false
bool resistanceDefended = false
bool supportBreached = false
bool resistanceBreached = false
bool supportRetesting = false
bool resistanceRetesting = false
bool supportFlipped = false
bool resistanceFlipped = false
bool failedFlip = false
 
if array.size(levelPrice) > 0
    for i = 0 to array.size(levelPrice) - 1
        float p = array.get(levelPrice, i)
        int role = array.get(levelRole, i)
        int state = array.get(levelState, i)
        int levelKind = array.get(levelClass, i)
        int born = array.get(levelBorn, i)
        int breaks = array.get(levelBreakCount, i)
        int breachBar = array.get(levelBreachBar, i)
        int tests = array.get(levelTests, i)
        int defenses = array.get(levelDefenses, i)
        int lastTestBar = array.get(levelLastTestBar, i)
        int lastDefenseBar = array.get(levelLastDefenseBar, i)
        bool oldEnough = bar_index > born
        bool overlaps = low <= p + halfWidth and high >= p - halfWidth
 
        // TESTED, DEFENDED and FAILED FLIP are live event states.
        if state == 1 or state == 2 or state == 6
            array.set(levelState, i, 0)
            state := 0
 
        bool distinctTest = state != 5 and oldEnough and overlaps and (na(lastTestBar) or bar_index - lastTestBar >= distinctTestBars)
        if distinctTest
            tests += 1
            lastTestBar := bar_index
            array.set(levelTests, i, tests)
            array.set(levelLastTestBar, i, lastTestBar)
            if state != 4
                array.set(levelState, i, 1)
            if role == 1
                supportTested := true
            else
                resistanceTested := true
 
        bool recentTest = not na(lastTestBar) and bar_index - lastTestBar <= distinctTestBars
        float defenseTravel = atr > 0 ? math.abs(close - p) / atr : 0.0
        bool supportDefense = role == 1 and recentTest and close > p + halfWidth and close > open and defenseTravel >= defenseAtr
        bool resistanceDefense = role == -1 and recentTest and close < p - halfWidth and close < open and defenseTravel >= defenseAtr
        bool distinctDefense = (supportDefense or resistanceDefense) and (na(lastDefenseBar) or bar_index - lastDefenseBar >= distinctTestBars)
        if state != 5 and distinctDefense
            defenses += 1
            lastDefenseBar := bar_index
            array.set(levelDefenses, i, defenses)
            array.set(levelLastDefenseBar, i, lastDefenseBar)
            if state != 4
                array.set(levelState, i, 2)
            if supportDefense
                supportDefended := true
            else
                resistanceDefended := true
 
        if state != 5
            bool beyond = role == 1 ? close < p - halfWidth : close > p + halfWidth
            breaks := beyond ? breaks + 1 : 0
            array.set(levelBreakCount, i, breaks)
 
            if breaks >= breakCloses
                array.set(levelState, i, 5)
                array.set(levelBreachBar, i, bar_index)
                array.set(levelBreakCount, i, 0)
                if role == 1
                    supportBreached := true
                else
                    resistanceBreached := true
        else if not na(breachBar) and bar_index > breachBar
            bool reclaimed = role == 1 ? close > p + halfWidth : close < p - halfWidth
            bool retesting = overlaps
            bool oppositeReject = role == 1 ? (high >= p - halfWidth and close < p - halfWidth) : (low <= p + halfWidth and close > p + halfWidth)
 
            if reclaimed
                array.set(levelState, i, 6)
                array.set(levelBreachBar, i, na)
                array.set(levelBorn, i, bar_index)
                failedFlip := true
            else if retesting
                if role == 1
                    supportRetesting := true
                else
                    resistanceRetesting := true
                if oppositeReject
                    int newRole = -role
                    array.set(levelRole, i, newRole)
                    array.set(levelState, i, 4)
                    array.set(levelBreachBar, i, na)
                    array.set(levelBorn, i, bar_index)
                    array.set(levelTests, i, 1)
                    array.set(levelDefenses, i, 1)
                    array.set(levelLastTestBar, i, bar_index)
                    array.set(levelLastDefenseBar, i, bar_index)
                    latestFlipRole := newRole
                    latestFlipPrice := p
                    latestFlipBar := bar_index
                    latestFlipClass := levelKind
                    if role == 1
                        supportFlipped := true
                    else
                        resistanceFlipped := true
 
// Collapse nearby records into one auction zone even when their original roles
// differ. Confirmed flips outrank pending breaches, major zones outrank reaction
// zones, and the newest otherwise-equivalent record wins.
if array.size(levelPrice) > 1
    int i = array.size(levelPrice) - 1
    while i > 0
        int duplicateIndex = -1
        for j = 0 to i - 1
            if math.abs(array.get(levelPrice, i) - array.get(levelPrice, j)) <= mergeDistance
                duplicateIndex := j
                break
        if duplicateIndex >= 0
            int stateI = array.get(levelState, i)
            int stateJ = array.get(levelState, duplicateIndex)
            int priorityI = stateI == 4 ? 3 : stateI == 5 ? 2 : 1
            int priorityJ = stateJ == 4 ? 3 : stateJ == 5 ? 2 : 1
            int classI = array.get(levelClass, i)
            int classJ = array.get(levelClass, duplicateIndex)
            int mergedTests = math.max(array.get(levelTests, i), array.get(levelTests, duplicateIndex))
            int mergedDefenses = math.max(array.get(levelDefenses, i), array.get(levelDefenses, duplicateIndex))
            int mergedLastTest = math.max(nz(array.get(levelLastTestBar, i), 0), nz(array.get(levelLastTestBar, duplicateIndex), 0))
            int mergedLastDefense = math.max(nz(array.get(levelLastDefenseBar, i), 0), nz(array.get(levelLastDefenseBar, duplicateIndex), 0))
            bool iWins = priorityI > priorityJ or (priorityI == priorityJ and classI > classJ) or
                 (priorityI == priorityJ and classI == classJ and array.get(levelBorn, i) > array.get(levelBorn, duplicateIndex))
            if iWins
                array.set(levelPrice, duplicateIndex, array.get(levelPrice, i))
                array.set(levelRole, duplicateIndex, array.get(levelRole, i))
                array.set(levelClass, duplicateIndex, array.get(levelClass, i))
                array.set(levelState, duplicateIndex, array.get(levelState, i))
                array.set(levelBorn, duplicateIndex, array.get(levelBorn, i))
                array.set(levelBreakCount, duplicateIndex, array.get(levelBreakCount, i))
                array.set(levelBreachBar, duplicateIndex, array.get(levelBreachBar, i))
            array.set(levelTests, duplicateIndex, mergedTests)
            array.set(levelDefenses, duplicateIndex, mergedDefenses)
            array.set(levelLastTestBar, duplicateIndex, mergedLastTest == 0 ? na : mergedLastTest)
            array.set(levelLastDefenseBar, duplicateIndex, mergedLastDefense == 0 ? na : mergedLastDefense)
            array.remove(levelPrice, i)
            array.remove(levelRole, i)
            array.remove(levelClass, i)
            array.remove(levelState, i)
            array.remove(levelBorn, i)
            array.remove(levelBreakCount, i)
            array.remove(levelBreachBar, i)
            array.remove(levelTests, i)
            array.remove(levelDefenses, i)
            array.remove(levelLastTestBar, i)
            array.remove(levelLastDefenseBar, i)
        i -= 1
 
// Expire stale levels from the back so array indices remain valid.
if array.size(levelPrice) > 0
    int i = array.size(levelPrice) - 1
    while i >= 0
        int qualityLifeMultiplier = array.get(levelDefenses, i) >= 2 ? 2 : 1
        int life = (array.get(levelClass, i) == 2 ? majorLife : reactionLife) * qualityLifeMultiplier
        if bar_index - array.get(levelBorn, i) > life
            array.remove(levelPrice, i)
            array.remove(levelRole, i)
            array.remove(levelClass, i)
            array.remove(levelState, i)
            array.remove(levelBorn, i)
            array.remove(levelBreakCount, i)
            array.remove(levelBreachBar, i)
            array.remove(levelTests, i)
            array.remove(levelDefenses, i)
            array.remove(levelLastTestBar, i)
            array.remove(levelLastDefenseBar, i)
        i -= 1
 
if not na(latestFlipBar) and bar_index - latestFlipBar > (latestFlipClass == 2 ? majorLife : reactionLife)
    latestFlipPrice := na
    latestFlipRole := 0
    latestFlipBar := na
    latestFlipClass := 1
 
//=============================================================================
// SELECT PRIMARY + PREVIOUS/STRUCTURAL SUPPORT / RESISTANCE
//=============================================================================
 
int nearestSupportIndex = -1
int nearestResistanceIndex = -1
int secondarySupportIndex = -1
int secondaryResistanceIndex = -1
int nearestBreachIndex = -1
float nearestSupportDistance = 1e10
float nearestResistanceDistance = 1e10
float secondarySupportScore = -1e10
float secondaryResistanceScore = -1e10
float nearestBreachDistance = 1e10
float actionableDistance = atr * actionableAtr
 
if array.size(levelPrice) > 0
    for i = 0 to array.size(levelPrice) - 1
        float p = array.get(levelPrice, i)
        int role = array.get(levelRole, i)
        int state = array.get(levelState, i)
        float distance = math.abs(close - p)
        if state == 5 and distance <= actionableDistance and distance < nearestBreachDistance
            nearestBreachDistance := distance
            nearestBreachIndex := i
        if state != 5 and role == 1 and p <= close + halfWidth and distance <= actionableDistance and distance < nearestSupportDistance
            nearestSupportDistance := distance
            nearestSupportIndex := i
        if state != 5 and role == -1 and p >= close - halfWidth and distance <= actionableDistance and distance < nearestResistanceDistance
            nearestResistanceDistance := distance
            nearestResistanceIndex := i
 
if array.size(levelPrice) > 0
    for i = 0 to array.size(levelPrice) - 1
        float p = array.get(levelPrice, i)
        int role = array.get(levelRole, i)
        int state = array.get(levelState, i)
        float distance = math.abs(close - p)
        float distanceAtr = atr > 0 ? distance / atr : distance
        float score = f_level_score(array.get(levelClass, i), state, array.get(levelTests, i), array.get(levelDefenses, i), distanceAtr)
        if state != 5 and distance <= actionableDistance
            if role == 1 and p <= close + halfWidth and i != nearestSupportIndex and score > secondarySupportScore
                secondarySupportScore := score
                secondarySupportIndex := i
            if role == -1 and p >= close - halfWidth and i != nearestResistanceIndex and score > secondaryResistanceScore
                secondaryResistanceScore := score
                secondaryResistanceIndex := i
 
// A secondary level must contribute genuinely different structure. It remains
// stored internally even when it is temporarily suppressed from the chart.
float secondaryMinDistance = atr * secondarySepAtr
if nearestSupportIndex >= 0 and secondarySupportIndex >= 0 and
     math.abs(array.get(levelPrice, secondarySupportIndex) - array.get(levelPrice, nearestSupportIndex)) < secondaryMinDistance
    secondarySupportIndex := -1
if nearestResistanceIndex >= 0 and secondaryResistanceIndex >= 0 and
     math.abs(array.get(levelPrice, secondaryResistanceIndex) - array.get(levelPrice, nearestResistanceIndex)) < secondaryMinDistance
    secondaryResistanceIndex := -1
 
float supportPrice = nearestSupportIndex >= 0 ? array.get(levelPrice, nearestSupportIndex) : na
float resistancePrice = nearestResistanceIndex >= 0 ? array.get(levelPrice, nearestResistanceIndex) : na
float support2Price = secondarySupportIndex >= 0 ? array.get(levelPrice, secondarySupportIndex) : na
float resistance2Price = secondaryResistanceIndex >= 0 ? array.get(levelPrice, secondaryResistanceIndex) : na
int supportState = nearestSupportIndex >= 0 ? array.get(levelState, nearestSupportIndex) : 0
int resistanceState = nearestResistanceIndex >= 0 ? array.get(levelState, nearestResistanceIndex) : 0
int support2State = secondarySupportIndex >= 0 ? array.get(levelState, secondarySupportIndex) : 0
int resistance2State = secondaryResistanceIndex >= 0 ? array.get(levelState, secondaryResistanceIndex) : 0
int supportClass = nearestSupportIndex >= 0 ? array.get(levelClass, nearestSupportIndex) : 1
int resistanceClass = nearestResistanceIndex >= 0 ? array.get(levelClass, nearestResistanceIndex) : 1
int support2Class = secondarySupportIndex >= 0 ? array.get(levelClass, secondarySupportIndex) : 1
int resistance2Class = secondaryResistanceIndex >= 0 ? array.get(levelClass, secondaryResistanceIndex) : 1
int supportBorn = nearestSupportIndex >= 0 ? array.get(levelBorn, nearestSupportIndex) : bar_index
int resistanceBorn = nearestResistanceIndex >= 0 ? array.get(levelBorn, nearestResistanceIndex) : bar_index
int support2Born = secondarySupportIndex >= 0 ? array.get(levelBorn, secondarySupportIndex) : bar_index
int resistance2Born = secondaryResistanceIndex >= 0 ? array.get(levelBorn, secondaryResistanceIndex) : bar_index
int supportTests = nearestSupportIndex >= 0 ? array.get(levelTests, nearestSupportIndex) : 0
int resistanceTests = nearestResistanceIndex >= 0 ? array.get(levelTests, nearestResistanceIndex) : 0
int support2Tests = secondarySupportIndex >= 0 ? array.get(levelTests, secondarySupportIndex) : 0
int resistance2Tests = secondaryResistanceIndex >= 0 ? array.get(levelTests, secondaryResistanceIndex) : 0
int supportDefenses = nearestSupportIndex >= 0 ? array.get(levelDefenses, nearestSupportIndex) : 0
int resistanceDefenses = nearestResistanceIndex >= 0 ? array.get(levelDefenses, nearestResistanceIndex) : 0
int support2Defenses = secondarySupportIndex >= 0 ? array.get(levelDefenses, secondarySupportIndex) : 0
int resistance2Defenses = secondaryResistanceIndex >= 0 ? array.get(levelDefenses, secondaryResistanceIndex) : 0
 
string supportDistanceText = f_distance_text(supportPrice, close, atr)
string resistanceDistanceText = f_distance_text(resistancePrice, close, atr)
string support2DistanceText = f_distance_text(support2Price, close, atr)
string resistance2DistanceText = f_distance_text(resistance2Price, close, atr)
string supportQualityText = supportState == 4 ? "R→S FLIP" : f_quality_text(supportState, supportTests, supportDefenses)
string resistanceQualityText = resistanceState == 4 ? "S→R FLIP" : f_quality_text(resistanceState, resistanceTests, resistanceDefenses)
string support2QualityText = support2State == 4 ? "R→S FLIP" : f_quality_text(support2State, support2Tests, support2Defenses)
string resistance2QualityText = resistance2State == 4 ? "S→R FLIP" : f_quality_text(resistance2State, resistance2Tests, resistance2Defenses)
float breachPrice = nearestBreachIndex >= 0 ? array.get(levelPrice, nearestBreachIndex) : na
int breachRole = nearestBreachIndex >= 0 ? array.get(levelRole, nearestBreachIndex) : 0
int breachBorn = nearestBreachIndex >= 0 ? array.get(levelBreachBar, nearestBreachIndex) : bar_index
 
//=============================================================================
// FOUR AUCTION LEVELS + TRANSITION DISPLAY
//=============================================================================
 
var line supportLine = na
var line support2Line = na
var line resistanceLine = na
var line resistance2Line = na
var line flipLine = na
var box supportBox = na
var box support2Box = na
var box resistanceBox = na
var box resistance2Box = na
var box flipBox = na
var label supportLabel = na
var label support2Label = na
var label resistanceLabel = na
var label resistance2Label = na
var label flipLabel = na
bool flipRelevant = not na(latestFlipPrice) and math.abs(close - latestFlipPrice) <= actionableDistance
// Confirmation is a short-lived event headline. The flipped S/R level remains
// active after the headline expires and continues to participate in structure.
bool recentFlip = flipRelevant and not na(latestFlipBar) and bar_index - latestFlipBar <= 8
 
if barstate.islast
    if showZones and not na(supportPrice)
        string supportKindText = supportClass == 2 ? "MAJOR" : "REACTION"
        bool supportWeakening = supportTests - supportDefenses >= 2
        int supportWidth = supportWeakening ? 1 : supportDefenses >= 3 or supportClass == 2 ? 3 : supportDefenses > 0 ? 2 : 1
        color supportDisplayColor = supportWeakening ? color.new(SUPPORT, 55) : SUPPORT
        if na(supportLine)
            supportLine := line.new(supportBorn, supportPrice, bar_index + extendBars, supportPrice, color=supportDisplayColor, width=supportWidth)
            supportBox := box.new(supportBorn, supportPrice + halfWidth, bar_index + extendBars, supportPrice - halfWidth,
                 border_color=color.new(supportDisplayColor, 45), bgcolor=color.new(supportDisplayColor, 90))
            supportLabel := label.new(bar_index + extendBars, supportPrice, "", style=label.style_label_left,
                 color=color.new(supportDisplayColor, 82), textcolor=supportDisplayColor, size=size.small)
        line.set_xy1(supportLine, supportBorn, supportPrice)
        line.set_xy2(supportLine, bar_index + extendBars, supportPrice)
        line.set_width(supportLine, supportWidth)
        line.set_color(supportLine, supportDisplayColor)
        box.set_lefttop(supportBox, supportBorn, supportPrice + halfWidth)
        box.set_rightbottom(supportBox, bar_index + extendBars, supportPrice - halfWidth)
        box.set_border_color(supportBox, color.new(supportDisplayColor, 45))
        box.set_bgcolor(supportBox, color.new(supportDisplayColor, 90))
        label.set_xy(supportLabel, bar_index + extendBars, supportPrice)
        label.set_textcolor(supportLabel, supportDisplayColor)
        label.set_text(supportLabel, "S1 " + supportKindText + " · " + supportQualityText + " · " + supportDistanceText)
    else
        line.delete(supportLine)
        box.delete(supportBox)
        label.delete(supportLabel)
        supportLine := na
        supportBox := na
        supportLabel := na
 
    if showZones and showSecondary and not na(support2Price)
        string support2KindText = support2Class == 2 ? "MAJOR" : "REACTION"
        bool support2Weakening = support2Tests - support2Defenses >= 2
        int support2Width = support2Weakening ? 1 : support2Defenses >= 3 or support2Class == 2 ? 2 : 1
        color support2DisplayColor = color.new(SUPPORT, support2Weakening ? 72 : 28)
        if na(support2Line)
            support2Line := line.new(support2Born, support2Price, bar_index + extendBars, support2Price,
                 color=support2DisplayColor, width=support2Width)
            support2Box := box.new(support2Born, support2Price + halfWidth, bar_index + extendBars, support2Price - halfWidth,
                 border_color=color.new(support2DisplayColor, 55), bgcolor=color.new(support2DisplayColor, 94))
            support2Label := label.new(bar_index + extendBars, support2Price, "", style=label.style_label_left,
                 color=color.new(support2DisplayColor, 86), textcolor=support2DisplayColor, size=size.small)
        line.set_xy1(support2Line, support2Born, support2Price)
        line.set_xy2(support2Line, bar_index + extendBars, support2Price)
        line.set_width(support2Line, support2Width)
        line.set_color(support2Line, support2DisplayColor)
        box.set_lefttop(support2Box, support2Born, support2Price + halfWidth)
        box.set_rightbottom(support2Box, bar_index + extendBars, support2Price - halfWidth)
        box.set_border_color(support2Box, color.new(support2DisplayColor, 55))
        box.set_bgcolor(support2Box, color.new(support2DisplayColor, 94))
        label.set_xy(support2Label, bar_index + extendBars, support2Price)
        label.set_textcolor(support2Label, support2DisplayColor)
        label.set_text(support2Label, "S2 " + support2KindText + " · " + support2QualityText + " · " + support2DistanceText)
    else
        line.delete(support2Line)
        box.delete(support2Box)
        label.delete(support2Label)
        support2Line := na
        support2Box := na
        support2Label := na
 
    if showZones and not na(resistancePrice)
        string resistanceKindText = resistanceClass == 2 ? "MAJOR" : "REACTION"
        bool resistanceWeakening = resistanceTests - resistanceDefenses >= 2
        int resistanceWidth = resistanceWeakening ? 1 : resistanceDefenses >= 3 or resistanceClass == 2 ? 3 : resistanceDefenses > 0 ? 2 : 1
        color resistanceDisplayColor = resistanceWeakening ? color.new(RESIST, 55) : RESIST
        if na(resistanceLine)
            resistanceLine := line.new(resistanceBorn, resistancePrice, bar_index + extendBars, resistancePrice, color=resistanceDisplayColor, width=resistanceWidth)
            resistanceBox := box.new(resistanceBorn, resistancePrice + halfWidth, bar_index + extendBars, resistancePrice - halfWidth,
                 border_color=color.new(resistanceDisplayColor, 45), bgcolor=color.new(resistanceDisplayColor, 90))
            resistanceLabel := label.new(bar_index + extendBars, resistancePrice, "", style=label.style_label_left,
                 color=color.new(resistanceDisplayColor, 82), textcolor=resistanceDisplayColor, size=size.small)
        line.set_xy1(resistanceLine, resistanceBorn, resistancePrice)
        line.set_xy2(resistanceLine, bar_index + extendBars, resistancePrice)
        line.set_width(resistanceLine, resistanceWidth)
        line.set_color(resistanceLine, resistanceDisplayColor)
        box.set_lefttop(resistanceBox, resistanceBorn, resistancePrice + halfWidth)
        box.set_rightbottom(resistanceBox, bar_index + extendBars, resistancePrice - halfWidth)
        box.set_border_color(resistanceBox, color.new(resistanceDisplayColor, 45))
        box.set_bgcolor(resistanceBox, color.new(resistanceDisplayColor, 90))
        label.set_xy(resistanceLabel, bar_index + extendBars, resistancePrice)
        label.set_textcolor(resistanceLabel, resistanceDisplayColor)
        label.set_text(resistanceLabel, "R1 " + resistanceKindText + " · " + resistanceQualityText + " · " + resistanceDistanceText)
    else
        line.delete(resistanceLine)
        box.delete(resistanceBox)
        label.delete(resistanceLabel)
        resistanceLine := na
        resistanceBox := na
        resistanceLabel := na
 
    if showZones and showSecondary and not na(resistance2Price)
        string resistance2KindText = resistance2Class == 2 ? "MAJOR" : "REACTION"
        bool resistance2Weakening = resistance2Tests - resistance2Defenses >= 2
        int resistance2Width = resistance2Weakening ? 1 : resistance2Defenses >= 3 or resistance2Class == 2 ? 2 : 1
        color resistance2DisplayColor = color.new(RESIST, resistance2Weakening ? 72 : 28)
        if na(resistance2Line)
            resistance2Line := line.new(resistance2Born, resistance2Price, bar_index + extendBars, resistance2Price,
                 color=resistance2DisplayColor, width=resistance2Width)
            resistance2Box := box.new(resistance2Born, resistance2Price + halfWidth, bar_index + extendBars, resistance2Price - halfWidth,
                 border_color=color.new(resistance2DisplayColor, 55), bgcolor=color.new(resistance2DisplayColor, 94))
            resistance2Label := label.new(bar_index + extendBars, resistance2Price, "", style=label.style_label_left,
                 color=color.new(resistance2DisplayColor, 86), textcolor=resistance2DisplayColor, size=size.small)
        line.set_xy1(resistance2Line, resistance2Born, resistance2Price)
        line.set_xy2(resistance2Line, bar_index + extendBars, resistance2Price)
        line.set_width(resistance2Line, resistance2Width)
        line.set_color(resistance2Line, resistance2DisplayColor)
        box.set_lefttop(resistance2Box, resistance2Born, resistance2Price + halfWidth)
        box.set_rightbottom(resistance2Box, bar_index + extendBars, resistance2Price - halfWidth)
        box.set_border_color(resistance2Box, color.new(resistance2DisplayColor, 55))
        box.set_bgcolor(resistance2Box, color.new(resistance2DisplayColor, 94))
        label.set_xy(resistance2Label, bar_index + extendBars, resistance2Price)
        label.set_textcolor(resistance2Label, resistance2DisplayColor)
        label.set_text(resistance2Label, "R2 " + resistance2KindText + " · " + resistance2QualityText + " · " + resistance2DistanceText)
    else
        line.delete(resistance2Line)
        box.delete(resistance2Box)
        label.delete(resistance2Label)
        resistance2Line := na
        resistance2Box := na
        resistance2Label := na
 
    bool flipAlreadyActive = not na(latestFlipPrice) and ((not na(supportPrice) and math.abs(supportPrice - latestFlipPrice) <= syminfo.mintick) or
         (not na(support2Price) and math.abs(support2Price - latestFlipPrice) <= syminfo.mintick) or
         (not na(resistancePrice) and math.abs(resistancePrice - latestFlipPrice) <= syminfo.mintick) or
         (not na(resistance2Price) and math.abs(resistance2Price - latestFlipPrice) <= syminfo.mintick))
    bool showBreachLine = not na(breachPrice)
    bool showRetestLine = showBreachLine and (supportRetesting or resistanceRetesting)
    bool showConfirmedFlipLine = recentFlip and not flipAlreadyActive and not showBreachLine
    bool showPendingBreachLine = showBreachLine and not showRetestLine and not supportFlipped and not resistanceFlipped and not failedFlip
    if showFlip and (showRetestLine or showConfirmedFlipLine or showPendingBreachLine)
        bool useBreach = showRetestLine or showPendingBreachLine
        float transitionPrice = useBreach ? breachPrice : latestFlipPrice
        int transitionBar = useBreach ? breachBorn : latestFlipBar
        string flipText = showRetestLine ?
             (breachRole == 1 ? "ACCEPTED BELOW · RETESTING" : "ACCEPTED ABOVE · RETESTING") :
             showPendingBreachLine ?
             (breachRole == 1 ? "ACCEPTED BELOW · WATCHING RETEST" : "ACCEPTED ABOVE · WATCHING RETEST") :
             (latestFlipRole == 1 ? "SUPPORT FLIP · R→S CONFIRMED" : "RESISTANCE FLIP · S→R CONFIRMED")
        if na(flipLine)
            flipLine := line.new(transitionBar, transitionPrice, bar_index + extendBars, transitionPrice,
                 color=FLIP, width=2, style=line.style_dashed)
            flipBox := box.new(transitionBar, transitionPrice + halfWidth, bar_index + extendBars, transitionPrice - halfWidth,
                 border_color=color.new(FLIP, 35), bgcolor=color.new(FLIP, 91))
            flipLabel := label.new(bar_index + extendBars, transitionPrice, "", style=label.style_label_left,
                 color=color.new(FLIP, 82), textcolor=FLIP, size=size.small)
        line.set_xy1(flipLine, transitionBar, transitionPrice)
        line.set_xy2(flipLine, bar_index + extendBars, transitionPrice)
        box.set_lefttop(flipBox, transitionBar, transitionPrice + halfWidth)
        box.set_rightbottom(flipBox, bar_index + extendBars, transitionPrice - halfWidth)
        label.set_xy(flipLabel, bar_index + extendBars, transitionPrice)
        label.set_text(flipLabel, flipText)
    else
        line.delete(flipLine)
        box.delete(flipBox)
        label.delete(flipLabel)
        flipLine := na
        flipBox := na
        flipLabel := na
 
//=============================================================================
// COMPACT DASHBOARD
//=============================================================================
 
string transitionText = supportRetesting ? "ACCEPTED BELOW · RETESTING" :
     resistanceRetesting ? "ACCEPTED ABOVE · RETESTING" :
     supportBreached ? "ACCEPTED BELOW" :
     resistanceBreached ? "ACCEPTED ABOVE" :
     failedFlip ? "FAILED ACCEPTANCE · RECLAIMED" :
     supportFlipped ? "RESISTANCE FLIP CONFIRMED" :
     resistanceFlipped ? "SUPPORT FLIP CONFIRMED" :
     not na(breachPrice) ? (breachRole == 1 ? "ACCEPTED BELOW · WATCHING RETEST" : "ACCEPTED ABOVE · WATCHING RETEST") :
     recentFlip ? (latestFlipRole == 1 ? "SUPPORT FLIP CONFIRMED" : "RESISTANCE FLIP CONFIRMED") : "NONE"
 
string eventText = transitionText != "NONE" ? transitionText :
     supportDefended ? "SUPPORT DEFENDED" : resistanceDefended ? "RESIST DEFENDED" :
     supportCreated ? "NEW MAJOR SUPPORT" : resistanceCreated ? "NEW MAJOR RESIST" :
     reactionSupportCreated ? "NEW REACTION SUPPORT" : reactionResistanceCreated ? "NEW REACTION RESIST" :
     supportTested ? "TESTING SUPPORT" : resistanceTested ? "TESTING RESISTANCE" : "MONITORING"
 
color transitionColor = supportRetesting or supportBreached or supportFlipped ? RESIST :
     resistanceRetesting or resistanceBreached or resistanceFlipped ? SUPPORT :
     failedFlip ? FLIP :
     not na(breachPrice) ? (breachRole == 1 ? RESIST : SUPPORT) :
     recentFlip ? (latestFlipRole == 1 ? SUPPORT : RESIST) : NEUTRAL
 
color eventColor = transitionText != "NONE" ? transitionColor :
     supportFlipped or supportBreached or resistanceDefended or resistanceCreated or reactionResistanceCreated ? RESIST :
     resistanceFlipped or resistanceBreached or supportDefended or supportCreated or reactionSupportCreated ? SUPPORT :
     supportRetesting or resistanceRetesting or failedFlip ? FLIP : NEUTRAL
 
string supportDashText = na(supportPrice) ? "NONE" : "S1 " + supportQualityText + " · " + supportDistanceText +
     (showSecondary and not na(support2Price) ? "\nS2 " + support2QualityText + " · " + support2DistanceText : "")
string resistanceDashText = na(resistancePrice) ? "NONE" : "R1 " + resistanceQualityText + " · " + resistanceDistanceText +
     (showSecondary and not na(resistance2Price) ? "\nR2 " + resistance2QualityText + " · " + resistance2DistanceText : "")
var table dashboard = table.new(f_position(dashLoc), 2, 4,
     frame_color=color.rgb(70, 75, 85), frame_width=1, border_color=color.rgb(55, 60, 70))
 
if barstate.islast
    if showDashboard
        table.cell(dashboard, 0, 0, "RSI AUCTION", bgcolor=color.rgb(35, 39, 48), text_color=NEUTRAL, text_size=f_size(dashSize))
        table.cell(dashboard, 1, 0, str.tostring(rsi, "0.0") + " · " + eventText,
             bgcolor=color.rgb(35, 39, 48), text_color=eventColor, text_size=f_size(dashSize))
        table.cell(dashboard, 0, 1, "SUPPORT", bgcolor=color.rgb(23, 27, 34), text_color=NEUTRAL, text_size=f_size(dashSize))
        table.cell(dashboard, 1, 1, supportDashText,
             bgcolor=color.rgb(23, 27, 34), text_color=na(supportPrice) ? NEUTRAL : SUPPORT, text_size=f_size(dashSize))
        table.cell(dashboard, 0, 2, "RESIST", bgcolor=color.rgb(23, 27, 34), text_color=NEUTRAL, text_size=f_size(dashSize))
        table.cell(dashboard, 1, 2, resistanceDashText,
             bgcolor=color.rgb(23, 27, 34), text_color=na(resistancePrice) ? NEUTRAL : RESIST, text_size=f_size(dashSize))
        table.cell(dashboard, 0, 3, "TRANSITION", bgcolor=color.rgb(23, 27, 34), text_color=NEUTRAL, text_size=f_size(dashSize))
        table.cell(dashboard, 1, 3, transitionText,
             bgcolor=color.rgb(23, 27, 34), text_color=transitionColor, text_size=f_size(dashSize))
    else
        table.clear(dashboard, 0, 0, 1, 3)
 
//=============================================================================
// ALERTS
//=============================================================================
 
alertcondition(supportCreated, "RSI Auction — New Support", "RSI exited oversold and created a new auction support zone")
alertcondition(resistanceCreated, "RSI Auction — New Resistance", "RSI exited overbought and created a new auction resistance zone")
alertcondition(reactionSupportCreated, "RSI Auction — New Reaction Support", "RSI crossed back above its reaction-low threshold and created an internal support zone")
alertcondition(reactionResistanceCreated, "RSI Auction — New Reaction Resistance", "RSI crossed back below its reaction-high threshold and created an internal resistance zone")
alertcondition(supportTested, "RSI Auction — Support Test", "Price is testing the nearest RSI auction support zone")
alertcondition(resistanceTested, "RSI Auction — Resistance Test", "Price is testing the nearest RSI auction resistance zone")
alertcondition(supportDefended, "RSI Auction — Support Defended", "RSI auction support was defended")
alertcondition(resistanceDefended, "RSI Auction — Resistance Defended", "RSI auction resistance was defended")
alertcondition(supportBreached, "RSI Auction — Accepted Below Support", "Price accepted below RSI auction support; watching for a retest from underneath")
alertcondition(resistanceBreached, "RSI Auction — Accepted Above Resistance", "Price accepted above RSI auction resistance; watching for a retest from above")
alertcondition(supportRetesting or resistanceRetesting, "RSI Auction — Accepted Level Retest", "Price is retesting an accepted RSI auction level from the opposite side")
alertcondition(supportFlipped, "RSI Auction — Support Flipped to Resistance", "Broken support rejected its retest and confirmed as resistance")
alertcondition(resistanceFlipped, "RSI Auction — Resistance Flipped to Support", "Broken resistance rejected its retest and confirmed as support")
alertcondition(failedFlip, "RSI Auction — Failed Role Flip", "Price reclaimed a breached level before its role flip confirmed")
 
// Data Window diagnostics.
plot(rsi, "RSI", color=na, display=display.data_window)
plot(supportPrice, "Nearest Support", color=na, display=display.data_window)
plot(support2Price, "Previous / Structural Support", color=na, display=display.data_window)
plot(resistancePrice, "Nearest Resistance", color=na, display=display.data_window)
plot(resistance2Price, "Previous / Structural Resistance", color=na, display=display.data_window)
plot(latestFlipPrice, "Latest Role Flip", color=na, display=display.data_window)

← 返回列表