Pressure Wave Meter

hasanaksoy199264 · study · 368 行 · 点赞 32 · TradingView 原页

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

Pine Script

//@version=6
indicator("Pressure Wave Meter", shorttitle="PWM", overlay=true, max_lines_count=500, max_labels_count=500, max_bars_back=500)
 
// ─────────────────────────────────────
// INPUTS
// ─────────────────────────────────────
 
g1 = "Wave Detection"
 
showBull        = input.bool(true, "Show Buy Pressure (up waves)", group=g1)
showBear        = input.bool(true, "Show Sell Pressure (down waves)", group=g1)
minBars         = input.int(3, "Minimum Wave Bars", minval=2, group=g1, tooltip="Number of bars from the wave start to its furthest closing price. Tolerated pullback bars are not counted; only bars up to the extreme are included.")
tolATR          = input.float(0.75, "Pullback Tolerance (ATR)", minval=0.1, step=0.05, group=g1, tooltip="The wave ends when the largest counter-directional closing price deviation from the extreme exceeds this ATR multiple. Smaller pullbacks are tolerated.")
maxPullbackBars = input.int(2, "Max Bars Without New Extreme", minval=1, group=g1, tooltip="Maximum number of bars allowed without making a new low or high. Exceeding this limit ends the wave.")
atrLen          = input.int(14, "ATR Length", minval=1, group=g1)
 
g2 = "Filters"
 
minEfficiency = input.float(0, "Minimum Efficiency (%)", minval=0, maxval=100, group=g2)
minProgATR    = input.float(0.0, "Minimum Progress (ATR)", minval=0, step=0.25, group=g2)
 
g3 = "Score Weights"
 
wtEff  = input.int(30, "Efficiency", minval=0, group=g3)
wtLoc  = input.int(25, "Close Location", minval=0, group=g3)
wtBody = input.int(15, "Body Dominance", minval=0, group=g3)
wtVol  = input.int(15, "Directional Volume", minval=0, group=g3, tooltip="If volume data is unavailable for the symbol, this component is automatically disabled and its weight is redistributed among the remaining components.")
wtSize = input.int(15, "Size (ATR progress)", minval=0, group=g3)
 
g4 = "Labels"
 
labelMode    = input.string("Live + Compact History", "Label Mode", options=["Live + Compact History", "Live Only", "Off"], group=g4)
histMinScore = input.int(50, "Min Score For History Label", minval=0, maxval=100, group=g4, tooltip="A completed wave's compact historical label is retained only if its score meets or exceeds this threshold.")
 
g5 = "Display"
 
showLines    = input.bool(true, "Show Wave Lines", group=g5)
fadeWeak     = input.bool(true, "Fade Weak Waves (line)", group=g5)
showBarColor = input.bool(true, "Color Bars (pullback bars faint)", group=g5)
lineWidth    = input.int(2, "Line Width", minval=1, maxval=5, group=g5)
bullColor    = input.color(color.lime, "Buy Pressure Color", group=g5)
bearColor    = input.color(color.red, "Sell Pressure Color", group=g5)
 
g6 = "Dashboard"
 
showTable   = input.bool(true, "Show Dashboard", group=g6)
tablePosStr = input.string("Top Right", "Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=g6)
 
tblPos = switch tablePosStr
    "Top Right"    => position.top_right
    "Top Left"     => position.top_left
    "Bottom Right" => position.bottom_right
    => position.bottom_left
 
// ─────────────────────────────────────
// HELPERS
// ─────────────────────────────────────
 
f_clamp(float x) =>
    math.min(math.max(x, 0.0), 100.0)
 
// Calculate metrics from bars within the wave
// (excluding the starting bar and including the extreme bar)
//
// eff  : net progress / total true range
// loc  : range-weighted closing position within candles
//        (closer to the low for selling, closer to the high for buying)
// body : directional candle body / total range
// vol  : volume share of directionally closing bars (na if unavailable)
 
f_waveStats(int dirSign, int sBar, int eBar, float prog) =>
    float sumRng = 0.0
    float sumTR = 0.0
    float sumLoc = 0.0
    float sumBody = 0.0
    float sumVol = 0.0
    float sumDirVol = 0.0
 
    if eBar > sBar
        for b = sBar + 1 to eBar
            int o = bar_index - b
            float rng = high[o] - low[o]
            float pc = close[o + 1]
 
            sumTR += math.max(rng, math.max(math.abs(high[o] - pc), math.abs(low[o] - pc)))
            sumRng += rng
 
            float v = nz(volume[o])
            sumVol += v
 
            if dirSign < 0
                sumLoc += high[o] - close[o]
                sumBody += open[o] - close[o]
                sumDirVol += close[o] < pc ? v : 0.0
            else
                sumLoc += close[o] - low[o]
                sumBody += close[o] - open[o]
                sumDirVol += close[o] > pc ? v : 0.0
 
    float eff = sumTR > 0 ? f_clamp(prog / sumTR * 100) : 0.0
    float loc = sumRng > 0 ? f_clamp(sumLoc / sumRng * 100) : 0.0
    float body = sumRng > 0 ? f_clamp(sumBody / sumRng * 100) : 0.0
    float vol = sumVol > 0 ? sumDirVol / sumVol * 100 : na
 
    [eff, loc, body, vol]
 
// Speed ratio: average progress per bar in the second half
// divided by average progress per bar in the first half
 
f_accel(int dirSign, int sBar, int eBar, float sPrice, float ePrice) =>
    float ratio = na
    int n = eBar - sBar
 
    if n >= 4
        int mid = sBar + math.floor(n / 2.0)
        float midPrice = close[bar_index - mid]
 
        float p1 = dirSign < 0 ? sPrice - midPrice : midPrice - sPrice
        float p2 = dirSign < 0 ? midPrice - ePrice : ePrice - midPrice
 
        float s1 = p1 / (mid - sBar)
        float s2 = p2 / (eBar - mid)
 
        ratio := s1 > 0 ? s2 / s1 : na
 
    ratio
 
f_score(float eff, float loc, float body, float vol, float progATR) =>
    float sizePart = f_clamp(math.max(progATR, 0.0) / 3.0 * 100)
    float wsum = wtEff + wtLoc + wtBody + wtSize + (na(vol) ? 0.0 : wtVol)
    float s = wtEff * eff + wtLoc * loc + wtBody * body + wtSize * sizePart + (na(vol) ? 0.0 : wtVol * vol)
 
    wsum > 0 ? s / wsum : 0.0
 
f_grade(float score) =>
    score >= 75 ? "A" : score >= 60 ? "B" : score >= 45 ? "C" : "D"
 
f_fade(float score) =>
    math.round(70 - score * 0.7)
 
f_accelText(float r) =>
    na(r) ? "—" : (r >= 1.25 ? "Accelerating" : r <= 0.6 ? "Fading" : "Steady") + " (x" + str.tostring(r, "0.0") + ")"
 
f_liveText(int d, int bars, float progATR, float eff, float loc, float body, float vol, float score, int pbBars, float pbATR) =>
    string t = (d < 0 ? "▼ SELL PRESSURE · " : "▲ BUY PRESSURE · ") + f_grade(score) + " " + str.tostring(score, "0")
    t += "\n" + str.tostring(bars) + " bars · " + str.tostring(progATR, "0.0") + " ATR"
    t += "\nEff " + str.tostring(eff, "0") + "% · Loc " + str.tostring(loc, "0") + "% · Body " + str.tostring(body, "0") + "%"
 
    if not na(vol)
        t += "\n" + (d < 0 ? "Sell" : "Buy") + " Vol " + str.tostring(vol, "0") + "%"
 
    if pbBars > 0
        t += "\nPullback: " + str.tostring(pbBars) + "b · " + str.tostring(pbATR, "0.0") + " ATR"
 
    t
 
f_compactText(int d, int bars, float eff, float progATR, float score) =>
    (d < 0 ? "▼ " : "▲ ") + str.tostring(bars) + "b · " + str.tostring(eff, "0") + "% · " + str.tostring(progATR, "0.0") + " ATR · " + f_grade(score)
 
f_row(table t, int r, string k, string v, color vc) =>
    table.cell(t, 0, r, k, text_color=color.new(color.white, 35), text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#131722, 8))
    table.cell(t, 1, r, v, text_color=vc, text_halign=text.align_right, text_size=size.small, bgcolor=color.new(#131722, 8))
 
// ─────────────────────────────────────
// STATE
// dir: 0 = no wave, -1 = bearish wave, +1 = bullish wave
// ─────────────────────────────────────
 
float atrVal = nz(ta.atr(atrLen), ta.tr(true))
 
var int dir = 0
var int startBar = 0
var float startPrice = na
var int extBar = 0
var float extPrice = na
var float bncPrice = na
var int bncBar = 0
var int curPbBars = 0
var float curPbATR = 0.0
 
var int wBars = 0
var float wProg = 0.0
var float wProgATR = 0.0
var float wEff = 0.0
var float wLoc = 0.0
var float wBody = 0.0
var float wVol = na
var float wAcc = na
var float wScore = 0.0
 
var bool live = false
var line waveLine = na
var label waveLabel = na
 
bool newExtreme = false
bool qualified = false
 
// ─────────────────────────────────────
// WAVE STATE MACHINE
// ─────────────────────────────────────
 
if dir == 0
    if close < close[1]
        dir := -1
        startBar := bar_index - 1
        startPrice := close[1]
        extBar := bar_index
        extPrice := close
        bncPrice := na
        bncBar := bar_index
        curPbBars := 0
        curPbATR := 0.0
        newExtreme := true
 
    else if close > close[1]
        dir := 1
        startBar := bar_index - 1
        startPrice := close[1]
        extBar := bar_index
        extPrice := close
        bncPrice := na
        bncBar := bar_index
        curPbBars := 0
        curPbATR := 0.0
        newExtreme := true
 
else
    bool isNewExt = dir < 0 ? close < extPrice : close > extPrice
 
    if isNewExt
        extBar := bar_index
        extPrice := close
        bncPrice := na
        bncBar := bar_index
        curPbBars := 0
        curPbATR := 0.0
        newExtreme := true
 
    else
        // Track the best closing price in the counter-direction
        if na(bncPrice) or (dir < 0 ? close > bncPrice : close < bncPrice)
            bncPrice := close
            bncBar := bar_index
 
        float bounce = dir < 0 ? bncPrice - extPrice : extPrice - bncPrice
 
        curPbBars := bar_index - extBar
        curPbATR := atrVal > 0 ? bounce / atrVal : 0.0
 
        bool reversal = bounce > tolATR * atrVal
        bool stalled = curPbBars > maxPullbackBars
        bool tooLong = bar_index - startBar >= 450
 
        if reversal or stalled or tooLong
            // Finalize the drawings of the completed wave
            // (statistics still belong to the previous wave)
 
            if live and not na(waveLabel)
                if labelMode == "Live + Compact History" and wScore >= histMinScore
                    label.set_text(waveLabel, f_compactText(dir, wBars, wEff, wProgATR, wScore))
                    label.set_size(waveLabel, size.tiny)
                else
                    label.delete(waveLabel)
 
            waveLine := na
            waveLabel := na
            live := false
 
            if reversal and not tooLong
                // The opposite wave starts from the previous wave's extreme
                startBar := extBar
                startPrice := extPrice
                extBar := bncBar
                extPrice := bncPrice
                dir := -dir
                bncPrice := na
                bncBar := bar_index
                curPbBars := bar_index - extBar
                curPbATR := 0.0
                newExtreme := true
 
            else
                dir := 0
 
// ─────────────────────────────────────
// METRICS (recalculated only when a new extreme forms)
// ─────────────────────────────────────
 
if newExtreme and dir != 0
    wBars := extBar - startBar
    wProg := dir < 0 ? startPrice - extPrice : extPrice - startPrice
    wProgATR := atrVal > 0 ? wProg / atrVal : 0.0
 
    [sEff, sLoc, sBody, sVol] = f_waveStats(dir, startBar, extBar, wProg)
 
    wEff := sEff
    wLoc := sLoc
    wBody := sBody
    wVol := sVol
 
    wAcc := f_accel(dir, startBar, extBar, startPrice, extPrice)
    wScore := f_score(wEff, wLoc, wBody, wVol, wProgATR)
 
    // Filters are evaluated once when the wave qualifies.
    // Once qualified, the wave remains active until it ends.
    if not live and wBars >= minBars and wEff >= minEfficiency and wProgATR >= minProgATR and (dir < 0 ? showBear : showBull)
        live := true
        qualified := true
 
// ─────────────────────────────────────
// DRAWING
// ─────────────────────────────────────
 
color waveCol = dir < 0 ? bearColor : dir > 0 ? bullColor : color.gray
 
if live and dir != 0
    color lineCol = fadeWeak ? color.new(waveCol, f_fade(wScore)) : waveCol
 
    if showLines
        if na(waveLine)
            waveLine := line.new(startBar, startPrice, extBar, extPrice, color=lineCol, width=lineWidth)
        else if newExtreme
            line.set_xy2(waveLine, extBar, extPrice)
            line.set_color(waveLine, lineCol)
 
    if labelMode != "Off"
        string txt = f_liveText(dir, wBars, wProgATR, wEff, wLoc, wBody, wVol, wScore, curPbBars, curPbATR)
        float ly = dir < 0 ? low[bar_index - extBar] : high[bar_index - extBar]
 
        if na(waveLabel)
            waveLabel := label.new(extBar, ly, txt, style=dir < 0 ? label.style_label_up : label.style_label_down, color=waveCol, textcolor=dir < 0 ? color.white : color.black, size=size.small)
        else
            label.set_xy(waveLabel, extBar, ly)
            label.set_text(waveLabel, txt)
 
// ─────────────────────────────────────
// DASHBOARD (last bar only)
// ─────────────────────────────────────
 
var table dash = showTable ? table.new(tblPos, 2, 12, border_width=1, border_color=color.new(color.gray, 75), frame_width=1, frame_color=color.new(color.gray, 60)) : na
 
if barstate.islast and showTable
    bool has = dir != 0
    string dirTxt = dir < 0 ? "▼ SELL PRESSURE" : dir > 0 ? "▲ BUY PRESSURE" : "—"
    string statusTxt = not has ? "No wave" : live ? (curPbBars > 0 ? "Qualified · pullback" : "Qualified") : "Building"
    string volLabel = dir > 0 ? "Buy Volume" : "Sell Volume"
 
    f_row(dash, 0, "PRESSURE WAVE", dirTxt, waveCol)
    f_row(dash, 1, "Status", statusTxt, live ? waveCol : color.white)
    f_row(dash, 2, "Score", has ? str.tostring(wScore, "0") + " (" + f_grade(wScore) + ")" : "—", waveCol)
    f_row(dash, 3, "Bars", has ? str.tostring(wBars) : "—", color.white)
    f_row(dash, 4, "Progress", has ? str.tostring(wProg, format.mintick) : "—", color.white)
    f_row(dash, 5, "Progress (ATR)", has ? str.tostring(wProgATR, "0.0") : "—", color.white)
    f_row(dash, 6, "Efficiency", has ? str.tostring(wEff, "0") + "%" : "—", color.white)
    f_row(dash, 7, "Close Location", has ? str.tostring(wLoc, "0") + "%" : "—", color.white)
    f_row(dash, 8, "Body Dominance", has ? str.tostring(wBody, "0") + "%" : "—", color.white)
    f_row(dash, 9, volLabel, has and not na(wVol) ? str.tostring(wVol, "0") + "%" : "n/a", color.white)
    f_row(dash, 10, "Momentum", has ? f_accelText(wAcc) : "—", color.white)
    f_row(dash, 11, "Pullback", has and curPbBars > 0 ? str.tostring(curPbBars) + "b · " + str.tostring(curPbATR, "0.0") + " ATR" : "—", color.white)
 
// ─────────────────────────────────────
// BAR COLOR & ALERTS
// ─────────────────────────────────────
 
barcolor((showBarColor and live) ? (newExtreme ? waveCol : color.new(waveCol, 70)) : na)
 
alertcondition(qualified and dir < 0, "Sell Pressure Wave", "Sell pressure wave qualified")
alertcondition(qualified and dir > 0, "Buy Pressure Wave", "Buy pressure wave qualified")

← 返回列表