ATK/DEF Quant Mecha WarShield Command

ATTDEFS · study · 633 行 · 点赞 172 · 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 at https://mozilla.org/MPL/2.0/
//@version=6
indicator("ATK/DEF Quant Mecha WarShield Command ", shorttitle="ATK/DEF Mecha WarShield  ", overlay=true, max_labels_count=500, max_lines_count=500, max_boxes_count=500)
 
// ═══════════════════════════ UDT 定义 ═══════════════════════════
type AtrLevels
    line  upperLine
    line  lowerLine
    line  defenseUpperLine
    line  defenseLowerLine
    label upperLabel
    label lowerLabel
    label defenseUpperLabel
    label defenseLowerLabel
    label livePingLabel
    label breakoutAlertLabel
 
type StructureState
    float        chainPrice
    int          chainBar
    string       chainType
    float        refHigh
    float        refLow
    label        curLabel
    array<label> historyLabels
    string       lastHighType
    string       lastLowType
    string       sequenceState
    float        lastLHPrice
    float        lastHLPrice
 
type BoxItem
    box   bx
    label lbl
    float top
    float bot
    bool  isBull
 
// ═══════════════════════════ Inputs: Structure ═══════════════════════════
showStructure = input.bool(true, "Show HH/LH/HL/LL Labels", group="Structure")
swingLen      = input.int(3, "Swing Lookback", minval=1, group="Structure")
deduplicate   = input.bool(true, "Remove Duplicates", group="Structure")
bullColor     = input.color(color.new(color.teal, 0), "Bullish Color", group="Structure")
bearColor     = input.color(color.new(color.red, 0), "Bearish Color", group="Structure")
sizeStruct    = input.string("small", "Structure Label Size", options=["tiny", "small", "normal", "large"], group="Structure")
 
// ── Order Block (OB) ──
gOB       = "Order Block (OB)"
showOB    = input.bool(true, "Show OB Boxes", group=gOB)
obBullC   = input.color(color.new(color.teal, 80), "Bullish OB Bg", group=gOB)
obBearC   = input.color(color.new(color.red, 80),  "Bearish OB Bg", group=gOB)
obTxtBull = input.color(color.new(color.teal, 0),  "Bullish OB Text", group=gOB)
obTxtBear = input.color(color.new(color.red, 0),   "Bearish OB Text", group=gOB)
maxOB     = input.int(5, "Max OB Count", minval=1, group=gOB)
sizeOB    = input.string("tiny", "OB Text Size", options=["tiny", "small", "normal", "large"], group=gOB)
 
// ── FVG ──
gFVG      = "Fair Value Gap (FVG)"
showFVG   = input.bool(true, "Show Unmitigated FVG", group=gFVG)
fvgC      = input.color(color.new(color.gray, 85), "FVG Color", group=gFVG)
fvgTxtC   = input.color(color.new(color.gray, 0),  "FVG Text Color", group=gFVG)
maxFVG    = input.int(5, "Max FVG Count", minval=1, group=gFVG)
sizeFVG   = input.string("tiny", "FVG Text Size", options=["tiny", "small", "normal", "large"], group=gFVG)
 
// ── Quant Dashboard ──
gDash     = "Quant Dashboard"
showDash  = input.bool(true, "Show Dashboard", group=gDash)
dashPos   = input.string("top_right", "Table Position", options=["top_right", "bottom_right", "top_left", "bottom_left"], group=gDash)
sizeDash  = input.string("small", "Dashboard Text Size", options=["tiny", "small", "normal", "large"], group=gDash)
 
// ═══════════════════════════ Inputs: Validation ═══════════════════════════
showHV        = input.bool(true, "Show HV Bu/Be", group="Volatility")
hvLen         = input.int(10, "HV Length", minval=2, group="Volatility")
stochKLen     = input.int(14, "Stoch K Length", minval=1, group="Volatility")
stochDLen     = input.int(3, "Stoch D Length", minval=1, group="Volatility")
showSequence  = input.bool(true, "Show Sequence", group="Volatility")
 
// ═══════════════════════════ Inputs: Live Ping ═══════════════════════════
showLivePing  = input.bool(true, "Show Live Ping", group="Live Ping")
sizeLivePing  = input.string("small", "Ping Size", options=["tiny", "small", "normal", "large"], group="Live Ping")
pingMomLen    = input.int(10, "Momentum Length", minval=1, group="Live Ping")
pingBbLen     = input.int(20, "Squeeze BB Length", minval=2, group="Live Ping")
pingBbMult    = input.float(2.0, "Squeeze BB Mult", minval=0.5, step=0.1, group="Live Ping")
pingAtrLen    = input.int(14, "Squeeze ATR Length", minval=1, group="Live Ping")
pingThreshold = input.float(1.0, "Ping Threshold", minval=0.1, step=0.1, group="Live Ping")
 
// ═══════════════════════════ Inputs: Alerts ═══════════════════════════
showBreakAlert = input.bool(true, "Show Breakout Alerts", group="Alerts")
sizeAlert      = input.string("small", "Alert Size", options=["tiny", "small", "normal", "large"], group="Alerts")
 
// ═══════════════════════════ Inputs: ATR Levels ═══════════════════════════
show_atr_levels   = input.bool(true,  "Show ATR Levels", group="ATR Levels")
show_atr_lines    = input.bool(true,  "Show ATR Lines", group="ATR Levels")
show_atr_labels   = input.bool(true,  "Show ATR Labels", group="ATR Levels")
sizeAtr           = input.string("tiny", "ATR Size", options=["tiny", "small", "normal", "large"], group="ATR Levels")
atrLength         = input.int(14, "ATR Length", minval=1, group="ATR Levels")
atrMultiplier     = input.float(1.0, "ATR Mult", minval=0.1, step=0.1, group="ATR Levels")
atrLineLen        = input.int(3, "Line Extend Bars", minval=1, group="ATR Levels")
atrUpperColor     = input.color(color.new(color.red, 50), "ATR Upper Color", group="ATR Levels")
atrLowerColor     = input.color(color.new(color.green, 50), "ATR Lower Color", group="ATR Levels")
atrUpperLabelBg   = input.color(color.rgb(200, 0, 0, 80), "ATR Upper Bg", group="ATR Levels")
atrLowerLabelBg   = input.color(color.rgb(0, 150, 0, 80), "ATR Lower Bg", group="ATR Levels")
atrLabelTextColor = input.color(color.white, "ATR Text Color", group="ATR Levels")
 
// ═══════════════════════════ Inputs: Defense ═══════════════════════════
showDefense        = input.bool(true, "Show Defense Levels", group="Defense")
showDefenseLine    = input.bool(true, "Show Defense Lines", group="Defense")
showDefenseText    = input.bool(true, "Show Defense Labels", group="Defense")
defenseMult        = input.float(1.0, "Defense Mult", minval=0.1, step=0.1, group="Defense")
defenseLineColorUp = input.color(color.new(color.red, 70), "Defense Upper Color", group="Defense")
defenseLineColorDn = input.color(color.new(color.green, 70), "Defense Lower Color", group="Defense")
defenseLabelBgUp   = input.color(color.rgb(120, 0, 0, 80), "Defense Upper Bg", group="Defense")
defenseLabelBgDn   = input.color(color.rgb(0, 90, 0, 80), "Defense Lower Bg", group="Defense")
 
f_size(string s) =>
    string result = s
    switch result
        "tiny" => size.tiny
        "small" => size.small
        "normal" => size.normal
        => size.large
 
f_classify(string typ, float price, float ref) =>
    string result = na
    if na(ref)
        result := typ == "H" ? "H" : "L"
    else if typ == "H"
        result := price > ref ? "HH" : "LH"
    else
        result := price < ref ? "LL" : "HL"
    result
 
f_color(string cls) =>
    color result = color.gray
    if cls == "HH" or cls == "HL"
        result := bullColor
    else if cls == "LH" or cls == "LL"
        result := bearColor
    result
 
// ═══════════════════════════ Quant Dashboard Calculations ═══════════════════════════
[stVal, stDir] = ta.supertrend(3.0, 10)
stDevPct = math.abs(close - stVal) / stVal * 100
 
bbBasis = ta.sma(close, 20)
bbDev   = ta.stdev(close, 20)
bbWidth = (bbBasis + 2*bbDev) - (bbBasis - 2*bbDev)
kcBasis = ta.ema(close, 20)
kcAtr   = ta.atr(20)
kcWidth = (kcBasis + 1.5*kcAtr) - (kcBasis - 1.5*kcAtr)
squeezePct = (bbWidth / math.max(kcWidth, 0.001)) * 100
 
cmfLen = 20
mfMultiplier = ((close - low) - (high - close)) / math.max(high - low, 0.001)
mfVolume = mfMultiplier * volume
cmf = math.sum(mfVolume, cmfLen) / math.max(math.sum(volume, cmfLen), 0.001)
cmfPct = cmf * 100
 
k_stoch = ta.stoch(close, high, low, 9)
d_stoch = ta.sma(k_stoch, 3)
j_stoch = 3 * k_stoch - 2 * d_stoch
var int obCount = 0
if j_stoch > 80 or j_stoch < 20
    obCount += 1
kdjOscPct = (obCount / 20.0) * 100
if bar_index % 20 == 0
    obCount := 0 
 
rsi = ta.rsi(close, 14)
rsiSwingHigh = ta.pivothigh(rsi, 5, 5)
rsiSwingLow  = ta.pivotlow(rsi, 5, 5)
priceHigh    = ta.pivothigh(high, 5, 5)
priceLow     = ta.pivotlow(low, 5, 5)
var float rsiDivPct = 0.0
if not na(rsiSwingHigh) and not na(priceHigh)
    rsiDivPct := (rsiSwingHigh - 70) / 70 * 100
if not na(rsiSwingLow) and not na(priceLow)
    rsiDivPct := (rsiSwingLow - 30) / 30 * 100
rsiDivPctAbs = math.abs(rsiDivPct)
 
// Mecha Colors
color mechaBg    = color.rgb(10, 15, 20, 10) 
color mechaText  = color.rgb(0, 255, 200)    
color mechaRed   = color.rgb(255, 50, 50)    
color mechaYellow= color.rgb(255, 220, 0)    
color mechaGray  = color.rgb(150, 150, 150)  
 
string decision = "[ STANDBY ]"
color decColor = mechaGray
if squeezePct < 80 and stDevPct < 1.0 and kdjOscPct > 50
    decision := "[ SQUEEZE : SCALPING ]"
    decColor := mechaYellow
else if squeezePct > 120 and stDevPct > 2.0 and stDir == 1
    decision := "[ EXPANSION : LONG ]"
    decColor := mechaText
else if squeezePct > 120 and stDevPct > 2.0 and stDir == -1
    decision := "[ EXPANSION : SHORT ]"
    decColor := mechaRed
else if cmfPct > 15 and stDir == 1 and rsiDivPctAbs < 10
    decision := "[ INFLOW : BULL BIAS ]"
    decColor := mechaText
else if cmfPct < -15 and stDir == -1 and rsiDivPctAbs < 10
    decision := "[ OUTFLOW : BEAR BIAS ]"
    decColor := mechaRed
 
// Dashboard Table
var posTable = dashPos == "top_right" ? position.top_right : dashPos == "bottom_right" ? position.bottom_right : dashPos == "top_left" ? position.top_left : position.bottom_left
var table dash = table.new(posTable, 2, 7, bgcolor=mechaBg, border_width=1, border_color=mechaText)
 
if showDash and barstate.islast
    table.cell(dash, 0, 0, "S Y S T E M", text_color=mechaText, text_size=f_size(sizeDash))
    table.cell(dash, 1, 0, "O N L I N E", text_color=mechaText, text_size=f_size(sizeDash))
    table.cell(dash, 0, 1, "ST Dev %", text_color=mechaGray, text_size=f_size(sizeDash))
    table.cell(dash, 1, 1, str.tostring(stDevPct, "#.##") + " %", text_color=stDevPct > 2 ? mechaRed : mechaText, text_size=f_size(sizeDash))
    table.cell(dash, 0, 2, "Squeeze %", text_color=mechaGray, text_size=f_size(sizeDash))
    table.cell(dash, 1, 2, str.tostring(squeezePct, "#.#") + " %", text_color=squeezePct < 80 ? mechaYellow : mechaText, text_size=f_size(sizeDash))
    table.cell(dash, 0, 3, "CMF Flow %", text_color=mechaGray, text_size=f_size(sizeDash))
    table.cell(dash, 1, 3, str.tostring(cmfPct, "#.#") + " %", text_color=cmfPct > 0 ? mechaText : mechaRed, text_size=f_size(sizeDash))
    table.cell(dash, 0, 4, "KDJ Osc %", text_color=mechaGray, text_size=f_size(sizeDash))
    table.cell(dash, 1, 4, str.tostring(kdjOscPct, "#") + " %", text_color=mechaText, text_size=f_size(sizeDash))
    table.cell(dash, 0, 5, "RSI Div %", text_color=mechaGray, text_size=f_size(sizeDash))
    table.cell(dash, 1, 5, str.tostring(rsiDivPctAbs, "#.#") + " %", text_color=rsiDivPctAbs > 15 ? mechaRed : mechaText, text_size=f_size(sizeDash))
    table.cell(dash, 0, 6, "DECISION >", text_color=mechaGray, text_size=f_size(sizeDash))
    table.cell(dash, 1, 6, decision, text_color=decColor, text_size=f_size(sizeDash))
 
// ═══════════════════════════ OB & FVG Core Logic ═══════════════════════════
var array<BoxItem> obs  = array.new<BoxItem>()
var array<BoxItem> fvgs = array.new<BoxItem>()
 
float atrVal = ta.atr(14)
float stochK = ta.stoch(close, high, low, stochKLen)
 
if showOB or showFVG
    if showOB and array.size(obs) > 0
        i = array.size(obs) - 1
        while i >= 0
            o = array.get(obs, i)
            bool mitigated = false
            if o.isBull and close < o.bot
                mitigated := true
            else if not o.isBull and close > o.top
                mitigated := true
            if mitigated
                box.delete(o.bx)
                if not na(o.lbl)
                    label.delete(o.lbl)
                array.remove(obs, i)
            else
                box.set_right(o.bx, bar_index + 5)
                if not na(o.lbl)
                    label.set_x(o.lbl, bar_index + 2)
            i -= 1
            
    if showFVG and array.size(fvgs) > 0
        i = array.size(fvgs) - 1
        while i >= 0
            f = array.get(fvgs, i)
            bool mitigated = false
            if f.isBull and low < f.bot
                mitigated := true
            else if not f.isBull and high > f.top
                mitigated := true
            if mitigated
                box.delete(f.bx)
                if not na(f.lbl)
                    label.delete(f.lbl)
                array.remove(fvgs, i)
            else
                box.set_right(f.bx, bar_index + 5)
                if not na(f.lbl)
                    label.set_x(f.lbl, bar_index + 2)
            i -= 1
 
if showFVG
    if high[2] < low[0] // Bullish FVG
        float upMomentum = math.abs(close - open)
        float dnMomentum = high - low - upMomentum
        bool isLiqStrong = (upMomentum / math.max(dnMomentum, 0.001)) >= 1.2
        string behavior = (high - low) > atrVal * 1.5 ? "Explosive" : ((high - low) < atrVal * 0.6 ? "Contraction" : "Shift")
        string intent = "Wait"
        if stochK < 30 and behavior == "Contraction"
            intent := "Accumulation"
        else if stochK > 70 and behavior == "Explosive"
            intent := "Distribution"
        string signal = ""
        if isLiqStrong and intent != "Distribution"
            signal := " ⭐Entry"
        else if intent == "Distribution"
            signal := " ⚠️Trap"
        string liqTxt = isLiqStrong ? " (High Liq)" : ""
        string txt = "BU ↑ FVG | " + behavior + " | " + intent + liqTxt + signal
 
        bx = box.new(bar_index-2, low[0], bar_index+5, high[2], border_color=na, bgcolor=fvgC)
        lbl = label.new(bar_index+2, (low[0]+high[2])/2, txt, style=label.style_none, textcolor=fvgTxtC, size=f_size(sizeFVG))
        array.push(fvgs, BoxItem.new(bx, lbl, low[0], high[2], true))
        while array.size(fvgs) > maxFVG
            old = array.shift(fvgs)
            box.delete(old.bx)
            if not na(old.lbl)
                label.delete(old.lbl)
            
    if low[2] > high[0] // Bearish FVG
        float dnMomentum = math.abs(close - open)
        float upMomentum = high - low - dnMomentum
        bool isLiqStrong = (dnMomentum / math.max(upMomentum, 0.001)) >= 1.2
        string behavior = (high - low) > atrVal * 1.5 ? "Explosive" : ((high - low) < atrVal * 0.6 ? "Contraction" : "Shift")
        string intent = "Wait"
        if stochK > 70 and behavior == "Contraction"
            intent := "Accumulation"
        else if stochK < 30 and behavior == "Explosive"
            intent := "Distribution"
        string signal = ""
        if isLiqStrong and intent != "Distribution"
            signal := " ⭐Entry"
        else if intent == "Distribution"
            signal := " ⚠️Trap"
        string liqTxt = isLiqStrong ? " (High Liq)" : ""
        string txt = "BE ↓ FVG | " + behavior + " | " + intent + liqTxt + signal
 
        bx = box.new(bar_index-2, low[2], bar_index+5, high[0], border_color=na, bgcolor=fvgC)
        lbl = label.new(bar_index+2, (low[2]+high[0])/2, txt, style=label.style_none, textcolor=fvgTxtC, size=f_size(sizeFVG))
        array.push(fvgs, BoxItem.new(bx, lbl, low[2], high[0], false))
        while array.size(fvgs) > maxFVG
            old = array.shift(fvgs)
            box.delete(old.bx)
            if not na(old.lbl)
                label.delete(old.lbl)
 
if showOB
    if close > open and close[1] < open[1] and close > high[1] // Bullish OB
        string status = "Dense (High)" 
        bx = box.new(bar_index-1, high[1], bar_index+5, low[1], border_color=na, bgcolor=obBullC)
        string txt = "BU ↑ OB | " + status
        lbl = label.new(bar_index+2, (high[1]+low[1])/2, txt, style=label.style_none, textcolor=obTxtBull, size=f_size(sizeOB))
        array.push(obs, BoxItem.new(bx, lbl, high[1], low[1], true))
        while array.size(obs) > maxOB
            old = array.shift(obs)
            box.delete(old.bx)
            if not na(old.lbl)
                label.delete(old.lbl)
                
    if close < open and close[1] > open[1] and close < low[1] // Bearish OB
        string status = "Dense (High)"
        bx = box.new(bar_index-1, high[1], bar_index+5, low[1], border_color=na, bgcolor=obBearC)
        string txt = "BE ↓ OB | " + status
        lbl = label.new(bar_index+2, (high[1]+low[1])/2, txt, style=label.style_none, textcolor=obTxtBear, size=f_size(sizeOB))
        array.push(obs, BoxItem.new(bx, lbl, high[1], low[1], false))
        while array.size(obs) > maxOB
            old = array.shift(obs)
            box.delete(old.bx)
            if not na(old.lbl)
                label.delete(old.lbl)
 
// 🌟 更新:动态追踪 OB 状态并增加入场信号
if showOB and array.size(obs) > 0
    i = array.size(obs) - 1
    while i >= 0
        o = array.get(obs, i)
        if not na(o.lbl)
            bool isTesting = (high >= o.bot and low <= o.top)
            if isTesting
                string newStatus = ""
                string entrySignal = ""
                if o.isBull
                    if close > open 
                        newStatus := "Recovery (High)"
                        // 资金未大幅流出,且收阳线,亮起多头入场信号
                        if cmfPct > -5 
                            entrySignal := " ⭐ LONG ENTRY"
                    else 
                        newStatus := "Consumed (Mid)"
                else
                    if close < open
                        newStatus := "Recovery (High)"
                        // 资金未大幅流入,且收阴线,亮起空头入场信号
                        if cmfPct < 5
                            entrySignal := " ⭐ SHORT ENTRY"
                    else
                        newStatus := "Consumed (Mid)"
                
                string baseTxt = o.isBull ? "BU ↑ OB | " : "BE ↓ OB | "
                label.set_text(o.lbl, baseTxt + newStatus + entrySignal)
        i -= 1
 
// ═══════════════════════════ HV + Stoch Validation ═══════════════════════════
ret = math.log(close / close[1])
sqUp = ret > 0 ? math.pow(ret, 2) : 0.0
sqDn = ret < 0 ? math.pow(ret, 2) : 0.0
sumUp = math.sum(sqUp, hvLen)
sumDn = math.sum(sqDn, hvLen)
totalVar = sumUp + sumDn
baseBuPct = totalVar > 0 ? (sumUp / totalVar) * 100 : 50.0
baseBePct = totalVar > 0 ? (sumDn / totalVar) * 100 : 50.0
stochK_ = ta.stoch(close, high, low, stochKLen)
stochWeight = 1.0 + ((stochK_ - 50) / 100)
validatedBu = baseBuPct * stochWeight
validatedBe = baseBePct * (2 - stochWeight)
totalValidated = validatedBu + validatedBe
finalBuPct = totalValidated > 0 ? (validatedBu / totalValidated) * 100 : 50.0
finalBePct = totalValidated > 0 ? (validatedBe / totalValidated) * 100 : 50.0
finalBuAtSwing = finalBuPct[swingLen]
finalBeAtSwing = finalBePct[swingLen]
hvSuffix = showHV ? "\nVal Bu: " + str.tostring(finalBuAtSwing, "#.#") + "% / Be: " + str.tostring(finalBeAtSwing, "#.#") + "%" : ""
 
// ═══════════════════════════ Live Ping ═══════════════════════════
pingMomentum = math.abs((close - close[pingMomLen]) / close[pingMomLen] * 100)
pingBbBasis  = ta.sma(close, pingBbLen)
pingBbDev    = ta.stdev(close, pingBbLen)
pingBbWidth  = (pingBbBasis + pingBbMult * pingBbDev) - (pingBbBasis - pingBbMult * pingBbDev)
pingAtr      = ta.atr(pingAtrLen)
pingSqueeze  = pingBbWidth / math.max(pingAtr, 0.001)
pingPressure = pingMomentum * (1 / math.max(pingSqueeze, 0.01))
livePingTrigger = pingPressure >= pingThreshold
 
// ═══════════════════════════ Structure State ═══════════════════════════
var StructureState st = StructureState.new()
st.historyLabels := na(st.historyLabels) ? array.new<label>() : st.historyLabels
 
f_pushLabel(label lbl) =>
    array.push(st.historyLabels, lbl)
    if array.size(st.historyLabels) > 50
        label.delete(array.shift(st.historyLabels))
 
f_getSequence(string hType, string lType) =>
    if na(hType) or na(lType)
        "Building"
    else if hType == "HH" and lType == "HL"
        "Bullish ↑ (Up)"
    else if hType == "LH" and lType == "LL"
        "Bearish ↓ (Down)"
    else if hType == "HH" and lType == "LL"
        "Expansion (Broadening)" 
    else if hType == "LH" and lType == "HL"
        "Contraction (Triangle)" 
    else
        "Complex"
 
swingHighPt = ta.pivothigh(high, swingLen, swingLen)
swingLowPt  = ta.pivotlow(low, swingLen, swingLen)
 
if not na(swingHighPt)
    float pPrice = swingHighPt
    int   pBar   = bar_index - swingLen
    if na(st.chainType)
        st.chainType  := "H"
        st.chainPrice := pPrice
        st.chainBar   := pBar
        st.lastHighType := "H"
        st.lastLHPrice := pPrice
        string cls = f_classify("H", pPrice, st.refHigh)
        color  col = f_color(cls)
        if showStructure
            st.sequenceState := f_getSequence(st.lastHighType, st.lastLowType)
            string seqSuffix = showSequence ? "\nSeq: " + st.sequenceState : ""
            st.curLabel := label.new(pBar, pPrice, cls + hvSuffix + seqSuffix, style=label.style_label_down, size=f_size(sizeStruct),
                 color=color.new(col, 15), textcolor=color.white)
            f_pushLabel(st.curLabel)
    else if st.chainType == "H"
        if pPrice > st.chainPrice or not deduplicate
            if deduplicate and not na(st.curLabel)
                label.delete(st.curLabel)
                int idx = array.indexof(st.historyLabels, st.curLabel)
                if idx >= 0
                    array.remove(st.historyLabels, idx)
            st.chainPrice := pPrice
            st.chainBar   := pBar
            string cls = f_classify("H", pPrice, st.refHigh)
            st.lastHighType := cls 
            st.lastLHPrice := pPrice 
            color  col = f_color(cls)
            if showStructure
                st.sequenceState := f_getSequence(st.lastHighType, st.lastLowType)
                string seqSuffix = showSequence ? "\nSeq: " + st.sequenceState : ""
                st.curLabel := label.new(pBar, pPrice, cls + hvSuffix + seqSuffix, style=label.style_label_down, size=f_size(sizeStruct),
                     color=color.new(col, 15), textcolor=color.white)
                f_pushLabel(st.curLabel)
    else
        st.refLow := st.chainPrice
        string cls = f_classify("H", pPrice, st.refHigh)
        st.lastHighType := cls
        st.lastLHPrice := pPrice
        color  col = f_color(cls)
        if showStructure
            st.sequenceState := f_getSequence(st.lastHighType, st.lastLowType)
            string seqSuffix = showSequence ? "\nSeq: " + st.sequenceState : ""
            st.curLabel := label.new(pBar, pPrice, cls + hvSuffix + seqSuffix, style=label.style_label_down, size=f_size(sizeStruct),
                 color=color.new(col, 15), textcolor=color.white)
            f_pushLabel(st.curLabel)
        st.chainType  := "H"
        st.chainPrice := pPrice
        st.chainBar   := pBar
 
if not na(swingLowPt)
    float pPrice = swingLowPt
    int   pBar   = bar_index - swingLen
    if na(st.chainType)
        st.chainType  := "L"
        st.chainPrice := pPrice
        st.chainBar   := pBar
        st.lastLowType := "L"
        st.lastHLPrice := pPrice
        string cls = f_classify("L", pPrice, st.refLow)
        color  col = f_color(cls)
        if showStructure
            st.sequenceState := f_getSequence(st.lastHighType, st.lastLowType)
            string seqSuffix = showSequence ? "\nSeq: " + st.sequenceState : ""
            st.curLabel := label.new(pBar, pPrice, cls + hvSuffix + seqSuffix, style=label.style_label_up, size=f_size(sizeStruct),
                 color=color.new(col, 15), textcolor=color.white)
            f_pushLabel(st.curLabel)
    else if st.chainType == "L"
        if pPrice < st.chainPrice or not deduplicate
            if deduplicate and not na(st.curLabel)
                label.delete(st.curLabel)
                int idx = array.indexof(st.historyLabels, st.curLabel)
                if idx >= 0
                    array.remove(st.historyLabels, idx)
            st.chainPrice := pPrice
            st.chainBar   := pBar
            string cls = f_classify("L", pPrice, st.refLow)
            st.lastLowType := cls
            st.lastHLPrice := pPrice
            color  col = f_color(cls)
            if showStructure
                st.sequenceState := f_getSequence(st.lastHighType, st.lastLowType)
                string seqSuffix = showSequence ? "\nSeq: " + st.sequenceState : ""
                st.curLabel := label.new(pBar, pPrice, cls + hvSuffix + seqSuffix, style=label.style_label_up, size=f_size(sizeStruct),
                     color=color.new(col, 15), textcolor=color.white)
                f_pushLabel(st.curLabel)
    else
        st.refHigh := st.chainPrice
        string cls = f_classify("L", pPrice, st.refLow)
        st.lastLowType := cls
        st.lastHLPrice := pPrice
        color  col = f_color(cls)
        if showStructure
            st.sequenceState := f_getSequence(st.lastHighType, st.lastLowType)
            string seqSuffix = showSequence ? "\nSeq: " + st.sequenceState : ""
            st.curLabel := label.new(pBar, pPrice, cls + hvSuffix + seqSuffix, style=label.style_label_up, size=f_size(sizeStruct),
                 color=color.new(col, 15), textcolor=color.white)
            f_pushLabel(st.curLabel)
        st.chainType  := "L"
        st.chainPrice := pPrice
        st.chainBar   := pBar
 
// ═══════════════════════════ ATR & Defense ═══════════════════════════
atrValue    = ta.atr(atrLength)
atrPct      = atrValue / close * 100
atr_upper = close * (1 + (atrPct * atrMultiplier) / 100)
atr_lower = close * (1 - (atrPct * atrMultiplier) / 100)
defenseUpper = atr_upper * (1 + (atrPct * defenseMult) / 100)
defenseLower = atr_lower * (1 - (atrPct * defenseMult) / 100)
 
upperText = "🔴 ATR Upper\n" + str.tostring(atr_upper, "#.##") + " (" + str.tostring(atrPct * atrMultiplier, "#.##") + "%)"
lowerText = "🟢 ATR Lower\n" + str.tostring(atr_lower, "#.##") + " (" + str.tostring(atrPct * atrMultiplier, "#.##") + "%)"
defUpText = "🛡 Defense Upper\n" + str.tostring(defenseUpper, "#.##") + " (" + str.tostring(atrPct * defenseMult, "#.##") + "%)"
defDnText = "🛡 Defense Lower\n" + str.tostring(defenseLower, "#.##") + " (" + str.tostring(atrPct * defenseMult, "#.##") + "%)"
 
var AtrLevels atrLevels = AtrLevels.new()
 
f_clear(AtrLevels lv) =>
    line.delete(lv.upperLine)
    line.delete(lv.lowerLine)
    line.delete(lv.defenseUpperLine)
    line.delete(lv.defenseLowerLine)
    label.delete(lv.upperLabel)
    label.delete(lv.lowerLabel)
    label.delete(lv.defenseUpperLabel)
    label.delete(lv.defenseLowerLabel)
    label.delete(lv.livePingLabel)
    label.delete(lv.breakoutAlertLabel)
    lv.upperLine  := na
    lv.lowerLine  := na
    lv.defenseUpperLine := na
    lv.defenseLowerLine := na
    lv.upperLabel := na
    lv.lowerLabel := na
    lv.defenseUpperLabel := na
    lv.defenseLowerLabel := na
    lv.livePingLabel := na
    lv.breakoutAlertLabel := na
    lv
 
if not barstate.islast
    atrLevels := f_clear(atrLevels)
 
if barstate.islast
    if show_atr_levels
        if show_atr_lines
            atrLevels.upperLine := line.new(x1=bar_index - atrLineLen, y1=atr_upper, x2=bar_index, y2=atr_upper,
                     color=atrUpperColor, width=1, style=line.style_dashed)
            atrLevels.lowerLine := line.new(x1=bar_index - atrLineLen, y1=atr_lower, x2=bar_index, y2=atr_lower,
                     color=atrLowerColor, width=1, style=line.style_dashed)
        if show_atr_labels
            atrLevels.upperLabel := label.new(x=bar_index + 1, y=atr_upper,
                      text=upperText, color=atrUpperLabelBg, textcolor=atrLabelTextColor,
                      style=label.style_label_left, size=f_size(sizeAtr))
            atrLevels.lowerLabel := label.new(x=bar_index + 1, y=atr_lower,
                      text=lowerText, color=atrLowerLabelBg, textcolor=atrLabelTextColor,
                      style=label.style_label_left, size=f_size(sizeAtr))
        if showDefense
            if showDefenseLine
                atrLevels.defenseUpperLine := line.new(x1=bar_index - atrLineLen, y1=defenseUpper, x2=bar_index, y2=defenseUpper,
                         color=defenseLineColorUp, width=1, style=line.style_dashed)
                atrLevels.defenseLowerLine := line.new(x1=bar_index - atrLineLen, y1=defenseLower, x2=bar_index, y2=defenseLower,
                         color=defenseLineColorDn, width=1, style=line.style_dashed)
            if showDefenseText
                atrLevels.defenseUpperLabel := label.new(x=bar_index + 1, y=defenseUpper,
                          text=defUpText, color=defenseLabelBgUp, textcolor=atrLabelTextColor,
                          style=label.style_label_left, size=f_size(sizeAtr))
                atrLevels.defenseLowerLabel := label.new(x=bar_index + 1, y=defenseLower,
                          text=defDnText, color=defenseLabelBgDn, textcolor=atrLabelTextColor,
                          style=label.style_label_left, size=f_size(sizeAtr))
    if showLivePing
        float pingY = high + (atrValue * 0.5) 
        string liveTxt = "⏱️ live ping: " + str.tostring(pingPressure, "#.##") + " (m/s)"
        color pingColor = livePingTrigger ? color.new(color.yellow, 0) : color.new(color.gray, 30)
        color pingTextColor = livePingTrigger ? color.black : color.white
        if livePingTrigger
            liveTxt := "⚡ Explosive\n" + liveTxt
        atrLevels.livePingLabel := label.new(x=bar_index, y=pingY, text=liveTxt,
                  color=pingColor, textcolor=pingTextColor, style=label.style_label_down, size=f_size(sizeLivePing))
    if showBreakAlert
        float alertY = high + (atrValue * 1.2)
        if not na(st.lastLHPrice) and close > st.lastLHPrice
            string breakTxt = "🚨 Breakout: Above LH ↑\nBullish Attack"
            atrLevels.breakoutAlertLabel := label.new(x=bar_index, y=alertY, text=breakTxt,
                      color=color.new(color.yellow, 0), textcolor=color.black,
                      style=label.style_label_down, size=f_size(sizeAlert))
        else if not na(st.lastHLPrice) and close < st.lastHLPrice
            string breakTxt = "🚨 Breakout: Below HL ↓\nBearish Attack"
            atrLevels.breakoutAlertLabel := label.new(x=bar_index, y=alertY, text=breakTxt,
                      color=color.new(color.red, 0), textcolor=color.white,
                      style=label.style_label_down, size=f_size(sizeAlert))

← 返回列表