ATK/DEF Power Swing -EP Major Swing Point

ATTDEFS · study · 424 行 · 点赞 6 · 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 -EP Major Swing Point", shorttitle="EP Major Swing Point ", overlay=true, max_labels_count=500, max_lines_count=500, max_boxes_count=500)
 
// ═══════════════════════════ Inputs ═══════════════════════════
swingLen   = input.int(25, "Major Swing Length", minval=5, tooltip="大周期摆动点,建议 15-50")
maxKeep    = input.int(20, "FIFO Max Capacity", minval=5)
 
// ★ 独立 FVG (顺势) 设置
showFVG     = input.bool(false, "Show HTF FVG (Continuation)", group="HTF FVG Settings")
fvgColorBull= input.color(color.new(color.teal, 80), "FVG Bull Bg", group="HTF FVG Settings")
fvgColorBear= input.color(color.new(color.red, 80),  "FVG Bear Bg", group="HTF FVG Settings")
 
// ★ 独立 IFVG (反转) 设置
showIFVG    = input.bool(true, "Show HTF IFVG (Inversion)", group="HTF IFVG Settings")
ifvgBullBg  = input.color(color.new(color.gray, 75), "IFVG Bull Bg", group="HTF IFVG Settings")
ifvgBearBg  = input.color(color.new(color.gray, 75), "IFVG Bear Bg", group="HTF IFVG Settings")
showPull    = input.bool(true, "Show Vortex Pull Strength (%)", group="HTF IFVG Settings")
 
// 共同周期设置
htfTf       = input.timeframe("D", "HTF Timeframe", group="HTF Global Settings")
fvgMinSize  = input.float(0.0, "Min Gap Size", step=0.1, group="HTF Global Settings")
 
// 各个模块独立开关
showMajor  = input.bool(true, "1. Show Major Swing Labels", group="Modules")
showOB     = input.bool(true, "2. Show OB (Order Block Box)", group="Modules")
showStruct = input.bool(true, "3. Show BOS / CHoCH (Standalone)", group="Modules")
showLine   = input.bool(true, "4. Show Breakout Horizontal Line", group="Modules")
showLiq    = input.bool(true, "5. Show Major Liquidity Volatility", group="Modules")
 
// 去重设置
dedupATR    = input.float(0.5, "Dedup Price Threshold (ATR)", step=0.1, group="Deduplication")
dedupBars   = input.int(3, "Dedup Time Threshold (Bars)", minval=1, group="Deduplication")
 
// 颜色设置
highColor  = input.color(color.new(color.red, 0), "High Color", group="Colors")
lowColor   = input.color(color.new(color.teal, 0), "Low Color", group="Colors")
bullColor  = input.color(color.aqua, "Bullish Breakout Color", group="Colors")
bearColor  = input.color(color.new(color.red, 0), "Bearish Breakout Color", group="Colors")
 
// OB 颜色(灰色框,白色字)
obBullBg   = input.color(color.new(color.gray, 60), "Bullish OB Box Background", group="Colors")
obBearBg   = input.color(color.new(color.gray, 60), "Bearish OB Box Background", group="Colors")
obTextColor= input.color(color.white, "OB Text Color", group="Colors")
 
// ═══════════════════════════ 流动性计算 ═══════════════════════════
liqMode     = input.string("Value", "Liquidity Mode", options=["Volume", "Value", "Volatility"], group="Liquidity Settings")
liqLookback = input.int(10, "Liq Lookback Bars", minval=1, group="Liquidity Settings")
liqRankLen  = input.int(20, "Liq Rank Sample Size", minval=5, group="Liquidity Settings")
 
// ═══════════════════════════ 数据结构 ═══════════════════════════
type Structure
    label lbl           
    line  ln            
    label obLbl         
    box   obBox         
    float price         
    int   barIdx        
    int   breakBar      
    bool  isHigh        
    bool  isBroken      
 
var array<Structure> structures = array.new<Structure>()
var int currentLeg = 0 
var int lastBrokenLeg = 0 
 
// ═══════════════════════════ 函数区 ═══════════════════════════
f_lineStyle() =>
    line.style_dashed
 
calcDays(int bars) =>
    float days = 0.0
    if timeframe.isseconds
        days := bars * timeframe.multiplier / 86400
    else if timeframe.isminutes
        days := bars * timeframe.multiplier / 1440
    else if timeframe.isdaily
        days := bars
    else if timeframe.isweekly
        days := bars * 7
    else if timeframe.ismonthly
        days := bars * 30
    else
        days := bars
    days
 
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)
 
getPivotOB(int from_bi, int to_bi, bool isHighPivot) =>
    float obHigh = na
    float obLow = na
    int obBar = na
    float obVol = 0.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, 100) 
        for i = 0 to len - 1
            bool isOpposite = isHighPivot ? (close[i] < open[i]) : (close[i] > open[i])
            if isOpposite
                obHigh := math.max(open[i], close[i])
                obLow  := math.min(open[i], close[i])
                obBar  := bar_index - i
                obVol  := volume[i]
                break 
    [obHigh, obLow, obBar, obVol]
 
// ═══════════════════════════ 核心逻辑 ═══════════════════════════
majorHighPt = ta.pivothigh(high, swingLen, swingLen)
majorLowPt  = ta.pivotlow(low, swingLen, swingLen)
 
atr14 = ta.atr(14)
float offsetDist = atr14 * 0.6
 
// --- 高点生成 ---
if not na(majorHighPt)
    if currentLeg != 1
        bool tooClose = false
        if array.size(structures) > 0
            lastSt = array.get(structures, array.size(structures) - 1)
            if bar_index - swingLen - lastSt.barIdx < dedupBars
                tooClose := true
            if lastSt.isHigh and math.abs(majorHighPt - lastSt.price) < atr14 * dedupATR
                tooClose := true
 
        if not tooClose
            currentLeg := 1
            label newLbl = na
            if showMajor
                string liqTxt = ""
                if showLiq
                    float lq = calcLiquidity(bar_index - swingLen)
                    string grd = getLiqGrade(lq)
                    liqTxt := " | Liq: " + fmtNum(lq) + " (" + grd + ")"
                    pushLiq(lq)
                
                string daysTxt = ""
                if array.size(structures) > 0
                    prevSt = array.get(structures, array.size(structures) - 1)
                    int legBars = (bar_index - swingLen) - prevSt.barIdx
                    float legDays = calcDays(legBars)
                    daysTxt := " | " + str.tostring(legDays, "#.#") + "D"
 
                newLbl := label.new(bar_index - swingLen, majorHighPt + offsetDist, "Major High" + liqTxt + daysTxt, 
                     style=label.style_none, size=size.small,
                     color=color.new(highColor, 100), textcolor=highColor, xloc=xloc.bar_index)
            
            st = Structure.new(newLbl, na, na, na, majorHighPt, bar_index - swingLen, 0, true, false)
            array.push(structures, st)
            
            // 绘制 Supply OB
            if showOB and array.size(structures) > 1
                prevLowSt = array.get(structures, array.size(structures) - 2)
                if not prevLowSt.isHigh
                    [obH, obL, obBar, obVol] = getPivotOB(prevLowSt.barIdx, bar_index - swingLen, true)
                    if not na(obH) and obVol > 0
                        string obTxt = "OB ↓ SUPPLY | Vol: " + fmtNum(obVol)
                        box obBox = box.new(obBar, obH, bar_index + 30, obL, border_color=na, border_width=0, bgcolor=obBearBg)
                        float boxMidPrice = (box.get_top(obBox) + box.get_bottom(obBox)) / 2
                        label obLbl = label.new(obBar + 15, boxMidPrice, obTxt, style=label.style_none, size=size.small, color=color.new(color.black, 100), textcolor=obTextColor, xloc=xloc.bar_index)
                        label.set_textalign(obLbl, text.align_center) 
                        st.obLbl := obLbl
                        st.obBox := obBox
    else
        st = array.get(structures, array.size(structures) - 1)
        if st.isHigh and not st.isBroken
            st.price := majorHighPt
            st.barIdx := bar_index - swingLen
            if showMajor and not na(st.lbl)
                label.set_y(st.lbl, majorHighPt + offsetDist)
                label.set_x(st.lbl, bar_index - swingLen)
 
// --- 低点生成 ---
if not na(majorLowPt)
    if currentLeg != -1
        bool tooClose = false
        if array.size(structures) > 0
            lastSt = array.get(structures, array.size(structures) - 1)
            if bar_index - swingLen - lastSt.barIdx < dedupBars
                tooClose := true
            if not lastSt.isHigh and math.abs(majorLowPt - lastSt.price) < atr14 * dedupATR
                tooClose := true
 
        if not tooClose
            currentLeg := -1
            label newLbl = na
            if showMajor
                string liqTxt = ""
                if showLiq
                    float lq = calcLiquidity(bar_index - swingLen)
                    string grd = getLiqGrade(lq)
                    liqTxt := " | Liq: " + fmtNum(lq) + " (" + grd + ")"
                    pushLiq(lq)
                
                string daysTxt = ""
                if array.size(structures) > 0
                    prevSt = array.get(structures, array.size(structures) - 1)
                    int legBars = (bar_index - swingLen) - prevSt.barIdx
                    float legDays = calcDays(legBars)
                    daysTxt := " | " + str.tostring(legDays, "#.#") + "D"
 
                newLbl := label.new(bar_index - swingLen, majorLowPt - offsetDist, "Major Low" + liqTxt + daysTxt, 
                     style=label.style_none, size=size.small,
                     color=color.new(lowColor, 100), textcolor=lowColor, xloc=xloc.bar_index)
            
            st = Structure.new(newLbl, na, na, na, majorLowPt, bar_index - swingLen, 0, false, false)
            array.push(structures, st)
            
            // 绘制 Demand OB
            if showOB and array.size(structures) > 1
                prevHighSt = array.get(structures, array.size(structures) - 2)
                if prevHighSt.isHigh
                    [obH, obL, obBar, obVol] = getPivotOB(prevHighSt.barIdx, bar_index - swingLen, false)
                    if not na(obH) and obVol > 0
                        string obTxt = "OB ↑ DEMAND | Vol: " + fmtNum(obVol)
                        box obBox = box.new(obBar, obH, bar_index + 30, obL, border_color=na, border_width=0, bgcolor=obBullBg)
                        float boxMidPrice = (box.get_top(obBox) + box.get_bottom(obBox)) / 2
                        label obLbl = label.new(obBar + 15, boxMidPrice, obTxt, style=label.style_none, size=size.small, color=color.new(color.black, 100), textcolor=obTextColor, xloc=xloc.bar_index)
                        label.set_textalign(obLbl, text.align_center)
                        st.obLbl := obLbl
                        st.obBox := obBox
    else
        st = array.get(structures, array.size(structures) - 1)
        if not st.isHigh and not st.isBroken
            st.price := majorLowPt
            st.barIdx := bar_index - swingLen
            if showMajor and not na(st.lbl)
                label.set_y(st.lbl, majorLowPt - offsetDist)
                label.set_x(st.lbl, bar_index - swingLen)
 
// ═══════════════════════════ BOS / CHoCH 判定与时间计算 ═══════════════════════════
if array.size(structures) > 0
    int lastIdx = array.size(structures) - 1
    st = array.get(structures, lastIdx)
    
    if not st.isBroken
        // 向上突破
        if st.isHigh and close > st.price and close[1] <= st.price
            st.isBroken := true
            st.breakBar := bar_index 
            isChoch = lastBrokenLeg == -1 
            
            float formationDays = 0.0
            if array.size(structures) > 1
                prevSt = array.get(structures, array.size(structures) - 2)
                formationDays := calcDays(st.barIdx - prevSt.barIdx)
                
            float holdingDays = calcDays(bar_index - st.breakBar)
            
            txt = (isChoch ? "CHoCH ↑ Swept" : "BOS ↑ Swept") + " | F: " + str.tostring(formationDays, "#.#") + "D | H: " + str.tostring(holdingDays, "#.#") + "D"
            col = bullColor
            
            if showLine
                st.ln := line.new(st.barIdx, st.price, bar_index, st.price, color=color.new(col, 0), width=2, style=f_lineStyle(), xloc=xloc.bar_index)
            if showStruct
                label.new(bar_index, st.price + offsetDist, txt, style=label.style_none, size=size.small, color=color.new(col, 100), textcolor=col, xloc=xloc.bar_index)
            lastBrokenLeg := 1 
            
        // 向下突破
        if not st.isHigh and close < st.price and close[1] >= st.price
            st.isBroken := true
            st.breakBar := bar_index 
            isChoch = lastBrokenLeg == 1
            
            float formationDays = 0.0
            if array.size(structures) > 1
                prevSt = array.get(structures, array.size(structures) - 2)
                formationDays := calcDays(st.barIdx - prevSt.barIdx)
                
            float holdingDays = calcDays(bar_index - st.breakBar)
            
            txt = (isChoch ? "CHoCH ↓ Swept" : "BOS ↓ Swept") + " | F: " + str.tostring(formationDays, "#.#") + "D | H: " + str.tostring(holdingDays, "#.#") + "D"
            col = bearColor
            
            if showLine
                st.ln := line.new(st.barIdx, st.price, bar_index, st.price, color=color.new(col, 0), width=2, style=f_lineStyle(), xloc=xloc.bar_index)
            if showStruct
                label.new(bar_index, low - offsetDist, txt, style=label.style_none, size=size.small, color=color.new(col, 100), textcolor=col, xloc=xloc.bar_index)
            lastBrokenLeg := -1 
 
// ═══════════════════════════ HTF FVG & IFVG 独立处理 ═══════════════════════════
string tfStr = htfTf == "D" ? "1D" : htfTf == "W" ? "1W" : htfTf == "60" ? "1H" : htfTf == "240" ? "4H" : htfTf
 
[htfOpen, htfHigh, htfLow, htfClose, htfVol] = request.security(syminfo.tickerid, htfTf, [open, high, low, close, volume], lookahead=barmerge.lookahead_off)
 
if barstate.isconfirmed
    float gapTopBull = htfLow[1]
    float gapBotBull = htfHigh[3]
    float gapTopBear = htfLow[3]
    float gapBotBear = htfHigh[1]
    
    // ★ 提前计算好大周期的多空比例字符串,避免作用域报错
    float bVol = htfClose > htfOpen ? htfVol : 0.0
    float sVol = htfClose < htfOpen ? htfVol : 0.0
    float totalV = bVol + sVol
    string bPctStr = totalV > 0 ? str.tostring(math.round(bVol / totalV * 100)) + "%" : "0%"
    string sPctStr = totalV > 0 ? str.tostring(math.round(sVol / totalV * 100)) + "%" : "0%"
    string ratioTxt = " | Bull " + bPctStr + " | Bear " + sPctStr
 
    // --- 1. 独立的 FVG (顺势) ---
    if showFVG
        // 多头 FVG
        if htfHigh[2] < htfLow[0] and (gapTopBull - gapBotBull) >= fvgMinSize
            int leftX = bar_index
            box b = box.new(leftX - 2, gapTopBull, leftX + 20, gapBotBull, border_color=na, border_width=0, bgcolor=fvgColorBull)
            float midY = (gapTopBull + gapBotBull) / 2
            label l = label.new(leftX + 9, midY, tfStr + " FVG ↑ (Support)" + ratioTxt, style=label.style_none, size=size.small, color=color.new(color.black, 100), textcolor=color.white, xloc=xloc.bar_index)
            label.set_textalign(l, text.align_center)
            
        // 空头 FVG
        if htfLow[2] > htfHigh[0] and (gapTopBear - gapBotBear) >= fvgMinSize
            int leftX = bar_index
            box b = box.new(leftX - 2, gapTopBear, leftX + 20, gapBotBear, border_color=na, border_width=0, bgcolor=fvgColorBear)
            float midY = (gapTopBear + gapBotBear) / 2
            label l = label.new(leftX + 9, midY, tfStr + " FVG ↓ (Resistance)" + ratioTxt, style=label.style_none, size=size.small, color=color.new(color.black, 100), textcolor=color.white, xloc=xloc.bar_index)
            label.set_textalign(l, text.align_center)
 
    // --- 2. 独立的 IFVG (反转) ---
    if showIFVG
        // 空头反转
        if htfHigh[2] < htfLow[0] and (gapTopBull - gapBotBull) >= fvgMinSize
            if htfClose > gapTopBull
                int leftX = bar_index
                box b = box.new(leftX - 2, gapTopBull, leftX + 20, gapBotBull, border_color=na, border_width=0, bgcolor=ifvgBearBg)
                float midY = (gapTopBull + gapBotBull) / 2
                
                float gapSize = gapTopBull - gapBotBull
                float sizeFactor = math.min(100, (gapSize / ta.atr(14)) * 100) 
                float bodySize = math.abs(htfClose - htfOpen)
                float volRatio = htfVol / ta.sma(htfVol, 20)
                float momentumFactor = math.min(100, (bodySize / gapSize) * 50 + (volRatio * 20))
                float pullScore = math.round(sizeFactor * 0.5 + momentumFactor * 0.5)
                
                string ifvgTxt = tfStr + " IFVG ↓ (Resistance)"
                if showPull
                    ifvgTxt := ifvgTxt + " | Pull: " + str.tostring(pullScore) + "%"
                    
                label l = label.new(leftX + 9, midY, ifvgTxt, style=label.style_none, size=size.small, color=color.new(color.black, 100), textcolor=color.white, xloc=xloc.bar_index)
                label.set_textalign(l, text.align_center)
 
        // 多头反转
        if htfLow[2] > htfHigh[0] and (gapTopBear - gapBotBear) >= fvgMinSize
            if htfClose < gapBotBear
                int leftX = bar_index
                box b = box.new(leftX - 2, gapTopBear, leftX + 20, gapBotBear, border_color=na, border_width=0, bgcolor=ifvgBullBg)
                float midY = (gapTopBear + gapBotBear) / 2
                
                float gapSize = gapTopBear - gapBotBear
                float sizeFactor = math.min(100, (gapSize / ta.atr(14)) * 100)
                float bodySize = math.abs(htfClose - htfOpen)
                float volRatio = htfVol / ta.sma(htfVol, 20)
                float momentumFactor = math.min(100, (bodySize / gapSize) * 50 + (volRatio * 20))
                float pullScore = math.round(sizeFactor * 0.5 + momentumFactor * 0.5)
                
                string ifvgTxt = tfStr + " IFVG ↑ (Support)"
                if showPull
                    ifvgTxt := ifvgTxt + " | Pull: " + str.tostring(pullScore) + "%"
                    
                label l = label.new(leftX + 9, midY, ifvgTxt, style=label.style_none, size=size.small, color=color.new(color.black, 100), textcolor=color.white, xloc=xloc.bar_index)
                label.set_textalign(l, text.align_center)
 
// ═══════════════════════════ 清理队列 ═══════════════════════════
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.obLbl)
        label.delete(st.obLbl)
    if not na(st.obBox)   
        box.delete(st.obBox)

← 返回列表