ATK/DEF Power Swing -HP Minor Swing Point

ATTDEFS · study · 453 行 · 点赞 35 · 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 Power Swing -HP Minor Swing Point", shorttitle="HP Minor Swing Point", overlay=true, max_labels_count=500, max_lines_count=500, max_boxes_count=500)
 
// ═══════════════════════════ UDT Definition ═══════════════════════════
type Structure
    label lbl           
    line  ln            
    label hpLbl         
    float price         
    int   barIdx        
    bool  isHigh        
    bool  isBroken      
 
type FvgObj
    box   b
    label lb
    int   stage
    float top
    float bot
    int   bar
    bool  isBull
    float bullVol  
    float bearVol  
 
// ═══════════════════════════ Inputs ═══════════════════════════
swingLen   = input.int(3, "Minor Swing Length", minval=1)
maxKeep    = input.int(50, "FIFO Max Capacity", minval=10, step=10)
 
showMicro  = input.bool(true, "1. Show Minor Swing Structure")
showHP     = input.bool(true, "2. Show HP (Hedge Power & Volume)")
showStruct = input.bool(true, "3. Show BOS / CHoCH (Standalone)")
showLine   = input.bool(true, "4. Show Breakout Horizontal Line")
 
showFVG    = input.bool(true, "5. Show FVG Zones")
fvgMinSize = input.float(0.0, "FVG Min Size", step=0.1)
fvgBoxWidth= input.int(40, "FVG Extend Bars", minval=15)
fvgBullColor = input.color(color.new(color.teal, 80), "FVG Bullish (BU) Background")
fvgBearColor = input.color(color.new(color.red, 80),  "FVG Bearish (BE) Background")
liqThreshold = input.float(1.2, "Dominance Threshold (x)", minval=1.0, step=0.1)
 
highColor  = input.color(color.new(color.orange, 0), "High Color")
lowColor   = input.color(color.new(color.purple, 0), "Low Color")
strongColor= input.color(color.green, "Real Accumulation/Strong Break")
weakColor  = input.color(color.rgb(255, 102, 0), "Fake Hedge/Distribution")
midColor   = input.color(color.yellow, "Medium Power")
hpBgColor  = input.color(color.new(color.black, 80), "HP Text Background")
hpOffset   = input.int(35, "Text Offset from Structure (Ticks)", minval=10)
bullColor  = input.color(color.aqua, "Bullish Breakout Color")
bearColor  = input.color(color.red,  "Bearish Breakout Color")
 
lineStyle  = input.string("Dashed", "Line Style", options=["Solid", "Dashed", "Dotted"])
lineWidth  = input.int(1, "Line Width", minval=1, maxval=4)
bullOffset = input.int(10, "Bullish Text Offset Up (Ticks)", minval=0)
bearOffset = input.int(10, "Bearish Text Offset Down (Ticks)", minval=0)
 
// ═══════════════════════════ HP Settings ═══════════════════════════
hpMode        = input.string("Hedge Power", "HP Semantic Mode", options=["Hedge Power", "Hidden Power", "Hybrid Power"], group="HP Settings")
showScore     = input.bool(true, "Show HP Strength Score (0-100)", group="HP Settings")
showGrade     = input.bool(true, "Color by Strength Grade", group="HP Settings")
strongThresh  = input.int(70, "Strong Threshold (>=)", minval=50, maxval=100, group="HP Settings")
midThresh     = input.int(40, "Mid Threshold (>=)", minval=10, maxval=90, group="HP Settings")
 
// ═══════════════════════════ Liquidity Settings ═══════════════════════════
showLiq     = input.bool(true,  "Show Minor Liquidity Volatility", group="Liquidity Settings")
liqMode     = input.string("Value", "Liquidity Calculation Mode", options=["Volume", "Value", "Volatility"], group="Liquidity Settings")
liqLookback = input.int(10, "Liquidity Lookback Bars (N)", minval=1, maxval=50, group="Liquidity Settings")
liqRankLen  = input.int(20, "Liquidity Rank Sample Size (M)", minval=5, maxval=100, group="Liquidity Settings")
 
f_lineStyle(string s) =>
    string result = s
    switch result
        "Solid"  => line.style_solid
        "Dashed" => line.style_dashed
        => line.style_dotted
 
// ═══════════════════════════ 4-Stage State Machine Text ═══════════════════════════
bullFvgTxt(int st) =>
    switch st
        1 => "FVG ↑ CLIMB"
        2 => "FVG ↑ INSIDE"
        3 => "FVG ↑ LEAVE"
        =>   "FVG ↑ STOP"
 
bearFvgTxt(int st) =>
    switch st
        1 => "FVG ↓ DROP"
        2 => "FVG ↓ INSIDE"
        3 => "FVG ↓ LEAVE"
        =>   "FVG ↓ STOP"
 
liqText(float bullVol, float bearVol) =>
    float total = bullVol + bearVol
    if total <= 0
        " [L: —]"
    else
        float bullPct = bullVol / total * 100
        float bearPct = bearVol / total * 100
        string state = "Balanced"
        if bullVol > bearVol * liqThreshold
            state := "Bull Dominance"
        else if bearVol > bullVol * liqThreshold
            state := "Bear Dominance"
        " [L: " + state + " | Bull " + str.tostring(bullPct, "#") + "% | Bear " + str.tostring(bearPct, "#") + "%]"
 
// ═══════════════════════════ HP Text Generator ═══════════════════════════
hpLabelText(bool isReal, bool isBull, int score) =>
    string arrow = isBull ? "↑" : "↓"
    string stateWord = ""
    if hpMode == "Hedge Power"
        stateWord := isBull ? (isReal ? "RS (Real Accumulation)" : "SP (Fake Distribution)")
                             : (isReal ? "SP (Real Distribution)" : "RS (Fake Accumulation)")
    else if hpMode == "Hidden Power"
        stateWord := isBull ? (isReal ? "Hidden Accumulation" : "Hidden Distribution")
                             : (isReal ? "Hidden Distribution" : "Hidden Accumulation")
    else
        stateWord := isBull ? (isReal ? "Hybrid Bull" : "Hybrid Bear")
                             : (isReal ? "Hybrid Bear" : "Hybrid Bull")
    string scoreTxt = showScore ? " | HP: " + str.tostring(score) + "/100" : ""
    "HP " + arrow + " " + stateWord + scoreTxt
 
// ═══════════════════════════ HP Score Color ═══════════════════════════
hpScoreColor(int score, bool isReal) =>
    if not showGrade
        isReal ? strongColor : weakColor
    else
        if score >= strongThresh
            strongColor
        else if score >= midThresh
            midColor
        else
            weakColor
 
// ═══════════════════════════ Liquidity Calculation ═══════════════════════════
var array<float> liqHistory = array.new<float>()
 
calcLiquidity(int pivotBar) =>
    float liq = 0.0
    if not na(pivotBar)
        int barsSincePivot = bar_index - pivotBar
        int minOffset = math.max(0, barsSincePivot)          
        int maxOffset = math.max(0, barsSincePivot + liqLookback) 
 
        for offset = minOffset to maxOffset
            float v  = volume[offset]
            float hi = high[offset]
            float lo = low[offset]
 
            if liqMode == "Volume"
                liq += v
            else if liqMode == "Value"
                liq += v * (hi + lo) / 2
            else
                liq += v * (hi - lo)
    liq
 
fmtNum(float x) =>
    float ax = math.abs(x)
    string s = ""
    if ax >= 1e9
        s := str.tostring(x / 1e9, "#.##") + "B"
    else if ax >= 1e6
        s := str.tostring(x / 1e6, "#.##") + "M"
    else if ax >= 1e3
        s := str.tostring(x / 1e3, "#.##") + "K"
    else
        s := str.tostring(x, "#.##")
    s
 
getLiqGrade(float curLiq) =>
    string grade = "—"
    if array.size(liqHistory) >= 5
        int cnt = array.size(liqHistory)
        int below = 0
        for i = 0 to cnt - 1
            if array.get(liqHistory, i) < curLiq
                below += 1
        float pct = below / cnt * 100
        if pct >= 70
            grade := "High"
        else if pct >= 30
            grade := "Mid"
        else
            grade := "Low"
    grade
 
pushLiq(float v) =>
    array.push(liqHistory, v)
    while array.size(liqHistory) > liqRankLen
        array.shift(liqHistory)
 
// ═══════════════════════════ Global State & Arrays ═══════════════════════════
var array<Structure> structures = array.new<Structure>()
var int currentLeg = 0 
var int lastBrokenLeg = 0 
 
var array<FvgObj> fvgs = array.new<FvgObj>()
 
smaVol20 = ta.sma(volume, 20)
 
// ═══════════════════════════ Minor Swing Detection ═══════════════════════════
minorHighPt = ta.pivothigh(high, swingLen, swingLen)
minorLowPt  = ta.pivotlow(low,  swingLen, swingLen)
 
// ═══════════════════════════ Market Data (incl. maxBody) ═══════════════════════════
getMarketData(int from_bi, int to_bi) =>
    float totalVol = 0.0
    float totalSma = 0.0
    float deltaVal = 0.0
    float maxBody  = 0.0
    int count = 0
    if not na(from_bi) and not na(to_bi) and to_bi >= from_bi
        int len = math.min(to_bi - from_bi + 1, 30) 
        for i = 0 to len - 1
            totalVol += volume[i]
            totalSma += smaVol20[i]
            float bodySize = math.abs(close[i] - open[i])
            maxBody := math.max(maxBody, bodySize)
            if close[i] > open[i]
                deltaVal += bodySize * volume[i]
            else
                deltaVal -= bodySize * volume[i]
            count += 1
    [totalVol, totalSma, deltaVal, maxBody]
 
// ═══════════════════════════ Structure Generation ═══════════════════════════
if not na(minorHighPt)
    if currentLeg != 1
        currentLeg := 1
        label newLbl = na
        if showMicro
            string liqTxt = ""
            if showLiq
                float lq = calcLiquidity(bar_index - swingLen)
                string grd = getLiqGrade(lq)
                liqTxt := " | Liq: " + fmtNum(lq) + " (" + grd + ")"
                pushLiq(lq)
            newLbl := label.new(bar_index - swingLen, minorHighPt, "Minor High (Liquidity)" + liqTxt, 
                 style=label.style_label_down, size=size.tiny,
                 color=color.new(highColor, 100), textcolor=highColor, xloc=xloc.bar_index)
        st = Structure.new(newLbl, na, na, minorHighPt, bar_index - swingLen, true, false)
        array.push(structures, st)
        
        if showHP and array.size(structures) > 1
            prevLowSt = array.get(structures, array.size(structures) - 2)
            if not prevLowSt.isHigh
                [v, s, d, mb] = getMarketData(prevLowSt.barIdx, bar_index - swingLen)
                if v > 0
                    bool isReal = d > 0
                    float denom = v * mb
                    int score = denom > 0 ? math.round(math.abs(d) / denom * 100) : 0
                    string hdgTxt = hpLabelText(isReal, true, score)
                    color col = hpScoreColor(score, isReal)
                    st.hpLbl := label.new(prevLowSt.barIdx, prevLowSt.price - syminfo.mintick * hpOffset, hdgTxt, 
                              style=label.style_none, size=size.tiny, 
                              color=hpBgColor, textcolor=col, xloc=xloc.bar_index)
    else
        st = array.get(structures, array.size(structures) - 1)
        if st.isHigh and not st.isBroken
            st.price := minorHighPt
            st.barIdx := bar_index - swingLen
            if showMicro and not na(st.lbl)
                label.set_y(st.lbl, minorHighPt)
                label.set_x(st.lbl, bar_index - swingLen)
 
if not na(minorLowPt)
    if currentLeg != -1
        currentLeg := -1
        label newLbl = na
        if showMicro
            string liqTxt = ""
            if showLiq
                float lq = calcLiquidity(bar_index - swingLen)
                string grd = getLiqGrade(lq)
                liqTxt := " | Liq: " + fmtNum(lq) + " (" + grd + ")"
                pushLiq(lq)
            newLbl := label.new(bar_index - swingLen, minorLowPt, "Minor Low (Liquidity)" + liqTxt, 
                 style=label.style_label_up, size=size.tiny,
                 color=color.new(lowColor, 100), textcolor=lowColor, xloc=xloc.bar_index)
        st = Structure.new(newLbl, na, na, minorLowPt, bar_index - swingLen, false, false)
        array.push(structures, st)
        
        if showHP and array.size(structures) > 1
            prevHighSt = array.get(structures, array.size(structures) - 2)
            if prevHighSt.isHigh
                [v, s, d, mb] = getMarketData(prevHighSt.barIdx, bar_index - swingLen)
                if v > 0
                    bool isReal = d < 0
                    float denom = v * mb
                    int score = denom > 0 ? math.round(math.abs(d) / denom * 100) : 0
                    string hdgTxt = hpLabelText(isReal, false, score)
                    color col = hpScoreColor(score, isReal)
                    st.hpLbl := label.new(prevHighSt.barIdx, prevHighSt.price + syminfo.mintick * hpOffset, hdgTxt, 
                              style=label.style_none, size=size.tiny, 
                              color=hpBgColor, textcolor=col, xloc=xloc.bar_index)
    else
        st = array.get(structures, array.size(structures) - 1)
        if not st.isHigh and not st.isBroken
            st.price := minorLowPt
            st.barIdx := bar_index - swingLen
            if showMicro and not na(st.lbl)
                label.set_y(st.lbl, minorLowPt)
                label.set_x(st.lbl, bar_index - swingLen)
 
// ═══════════════════════════ BOS / CHoCH Breakout Logic ═══════════════════════════
if array.size(structures) > 0
    int lastIdx = array.size(structures) - 1
    st = array.get(structures, lastIdx)
    
    if not st.isBroken
        // Upward Breakout
        if st.isHigh and close > st.price and close[1] <= st.price
            st.isBroken := true
            isChoch = lastBrokenLeg == -1 
            txt     = isChoch ? "CHoCH ↑ Swept" : "BOS ↑ Swept" 
            col     = bullColor
            
            if showLine
                st.ln := line.new(st.barIdx, st.price, bar_index, st.price, color = color.new(col, 0), width = lineWidth, style = f_lineStyle(lineStyle), xloc = xloc.bar_index)
                
            if showStruct
                label.new(bar_index, st.price + syminfo.mintick * bullOffset, txt, 
                          style=label.style_none, size=size.tiny, 
                          color=color.new(col, 100), textcolor=col, xloc=xloc.bar_index)
                          
            lastBrokenLeg := 1 
            
        // Downward Breakout
        if not st.isHigh and close < st.price and close[1] >= st.price
            st.isBroken := true
            isChoch = lastBrokenLeg == 1
            txt     = isChoch ? "CHoCH ↓ Swept" : "BOS ↓ Swept"
            col     = bearColor
            
            if showLine
                st.ln := line.new(st.barIdx, st.price, bar_index, st.price, color = color.new(col, 0), width = lineWidth, style = f_lineStyle(lineStyle), xloc = xloc.bar_index)
                
            if showStruct
                label.new(bar_index, low - syminfo.mintick * bearOffset, txt, 
                          style=label.style_none, size=size.tiny, 
                          color=color.new(col, 100), textcolor=col, xloc=xloc.bar_index)
                          
            lastBrokenLeg := -1 
 
// ═══════════════════════════ FVG 4-Stage Logic ═══════════════════════════
float curBullVol = close > open ? volume : 0.0
float curBearVol = close < open ? volume : 0.0
 
if showFVG and low > high[2]
    float gapTop = low
    float gapBot = high[2]
    if gapTop - gapBot >= fvgMinSize
        int leftX  = bar_index - 2
        int rightX = bar_index + fvgBoxWidth
        box b = box.new(leftX, gapTop, rightX, gapBot, border_color=na, border_width=0, bgcolor=fvgBullColor, xloc=xloc.bar_index)
        int midX = leftX + math.round(fvgBoxWidth/2)
        float midY = (gapTop + gapBot)/2
        
        lbl = label.new(midX, midY, bullFvgTxt(1) + liqText(curBullVol, curBearVol), style=label.style_none, textcolor=color.new(color.teal, 0), size=size.tiny, xloc=xloc.bar_index)
        label.set_textalign(lbl, text.align_center)
        
        obj = FvgObj.new(b, lbl, 1, gapTop, gapBot, bar_index, true, curBullVol, curBearVol)
        array.push(fvgs, obj)
 
if showFVG and high < low[2]
    float gapTop = low[2]
    float gapBot = high
    if gapTop - gapBot >= fvgMinSize
        int leftX  = bar_index - 2
        int rightX = bar_index + fvgBoxWidth
        box b = box.new(leftX, gapTop, rightX, gapBot, border_color=na, border_width=0, bgcolor=fvgBearColor, xloc=xloc.bar_index)
        int midX = leftX + math.round(fvgBoxWidth/2)
        float midY = (gapTop + gapBot)/2
        
        lbl = label.new(midX, midY, bearFvgTxt(1) + liqText(curBullVol, curBearVol), style=label.style_none, textcolor=color.new(color.red, 0), size=size.tiny, xloc=xloc.bar_index)
        label.set_textalign(lbl, text.align_center)
        
        obj = FvgObj.new(b, lbl, 1, gapTop, gapBot, bar_index, false, curBullVol, curBearVol)
        array.push(fvgs, obj)
 
// 4-Stage Flow & Cumulative Volume
if showFVG and array.size(fvgs) > 0
    int i = 0
    while i < array.size(fvgs)
        FvgObj f = array.get(fvgs, i)
        if bar_index > f.bar
            f.bullVol += curBullVol
            f.bearVol += curBearVol
            
            int newStage = f.stage
            if f.isBull
                if f.stage == 1
                    if low <= f.top
                        newStage := 2
                else if f.stage == 2
                    if close > f.top
                        newStage := 3
                    else if close < f.bot
                        newStage := 4
                else if f.stage == 3 or f.stage == 4
                    if high >= f.bot and low <= f.top
                        newStage := 2
            else
                if f.stage == 1
                    if high >= f.bot
                        newStage := 2
                else if f.stage == 2
                    if close < f.bot
                        newStage := 3
                    else if close > f.top
                        newStage := 4
                else if f.stage == 3 or f.stage == 4
                    if high >= f.bot and low <= f.top
                        newStage := 2
            
            if newStage != f.stage or f.bullVol > 0 or f.bearVol > 0
                f.stage := newStage
                string baseTxt = f.isBull ? bullFvgTxt(f.stage) : bearFvgTxt(f.stage)
                label.set_text(f.lb, baseTxt + liqText(f.bullVol, f.bearVol))
        i += 1
 
// FVG Cleanup
if showFVG and array.size(fvgs) > 0
    int i = 0
    while i < array.size(fvgs)
        FvgObj f = array.get(fvgs, i)
        bool expired = false
        if f.isBull and close < f.bot
            expired := true
        else if not f.isBull and close > f.top
            expired := true
            
        if expired
            box.delete(f.b)
            label.delete(f.lb)
            array.remove(fvgs, i)
        else
            i += 1
 
// ═══════════════════════════ FIFO Queue Cleanup ═══════════════════════════
while array.size(structures) > maxKeep
    st = array.shift(structures) 
    if not na(st.lbl)
        label.delete(st.lbl)
    if not na(st.ln)
        line.delete(st.ln)
    if not na(st.hpLbl)
        label.delete(st.hpLbl)
 
while array.size(fvgs) > maxKeep
    f = array.shift(fvgs)
    box.delete(f.b)
    label.delete(f.lb)

← 返回列表