Smart Volume with Pocket Pivots

KapilVP · study · 332 行 · 点赞 19 · TradingView 原页

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

Pine Script

//@version=6
// Smart Volume with Pocket Pivots.
 
indicator("Smart Volume with Pocket Pivots", shorttitle = "Smart Volume", format = format.volume, max_labels_count = 500)
 
// ───────────────────────── Inputs ─────────────────────────
const string G_USER = "User Inputs"
int    ppLen    = input.int(10, "Pocket Pivot Lookback", options = [5, 10, 20], group = G_USER, tooltip = "A pocket pivot is an up-bar volume greater than every down-bar volume of the previous N bars.")
int    maLen    = input.int(50, "Volume Average Lookback", minval = 1, group = G_USER, tooltip = "Length of the volume moving average. Bars above it are coloured, bars below it are noise.")
int    rvLen    = input.int(20, "Relative Volume Lookback", minval = 1, group = G_USER, tooltip = "Number of bars used for the average volume in the relative volume (RVol) calculation.")
int    udLen    = input.int(20, "Up Down Volume Lookback", minval = 1, group = G_USER, tooltip = "Number of bars over which up-bar volume is divided by down-bar volume.")
int    bsLen    = input.int(50, "Bull Snort Volume Average Lookback", minval = 1, group = G_USER, tooltip = "A Bull Snort needs 3 times this average volume, a close in the top 35% of the bar and above the previous close.")
string toLenIn  = input.string("50 period", "Turnover Calculation Method", options = ["10 period", "20 period", "50 period"], group = G_USER, tooltip = "Number of bars used for the average turnover.")
string toMethod = input.string("SMA", "Turnover Calculation Type", options = ["SMA", "VWAP"], group = G_USER, tooltip = "SMA: average volume × average close. VWAP: average volume × volume-weighted average price.")
 
const string G_DISP = "Display Options"
bool   darkMode      = input.bool(false, "Dark Mode", group = G_DISP)
bool   usePrevClose  = input.bool(false, "Color based on previous close", group = G_DISP)
bool   showDry       = input.bool(true, "Display Dry Volumes lesser than 1/", group = G_DISP, inline = "dry")
int    lowFrac       = input.int(5, "", options = [2, 3, 4, 5, 6, 8, 10], group = G_DISP, inline = "dry", tooltip = "Dry volume: volume at or below this fraction of the volume average. 5 = one fifth.")
bool   showPower     = input.bool(false, "Display Power Volumes greater than", group = G_DISP, inline = "pow")
int    powerVol      = input.int(500000, "", options = [100000, 250000, 500000, 1000000, 2000000, 5000000], group = G_DISP, inline = "pow", tooltip = "Power volume: volume beyond this number on a bar where price moves at least 5%. Shown as a background highlight.")
bool   showPowerDown = input.bool(false, "Show Power Volumes for Down Days?", group = G_DISP, tooltip = "Also highlight power volumes where price falls at least 5%.")
bool   showProj      = input.bool(false, "Display Projected Volume Bar?", group = G_DISP, tooltip = "Projects the live bar's final volume from the volume per second so far.")
bool   showBS        = input.bool(false, "Display Bull Snort?", group = G_DISP, tooltip = "Marks Bull Snort bars with a dot at the bottom of the pane and a background colour.")
 
const string G_TBL = "Table Customisation"
string tblSizeIn  = input.string("small", "Table", options = ["tiny", "small", "normal", "large"], group = G_TBL, inline = "tbl")
string tblVertIn  = input.string("top", "↕", options = ["top", "middle", "bottom"], group = G_TBL, inline = "tbl")
string tblHorzIn  = input.string("right", "↔", options = ["left", "center", "right"], group = G_TBL, inline = "tbl")
bool   tblHoriz   = input.bool(true, "Horizontal Table?", group = G_TBL)
bool   tblNoCol   = input.bool(false, "Do not display colors in table?", group = G_TBL)
float  toThresh   = input.float(5, "Turnover Background Color Threshold", minval = 0, group = G_TBL, tooltip = "In the selected units (Crores or Millions). At or above: green cell. Below: red cell.")
float  rvThresh   = input.float(100, "RVol Background Color Threshold", minval = 0, group = G_TBL, tooltip = "Relative volume in percent. At or above: green cell. Below: red cell.")
float  mlThresh   = input.float(0.5, "1mL Background Color Threshold", minval = 0, step = 0.1, group = G_TBL, tooltip = "In the selected units (Crores or Millions). At or above: green cell. Below: red cell.")
 
const string G_TOG = "Table Toggles"
bool   showTo    = input.bool(true, "Display Average ₹ Volume?", group = G_TOG, tooltip = "Average volume multiplied by the average price. It should be many times your position size.")
string toUnit    = input.string("Crores", "Display Average ₹/$ Volume Units as", options = ["Crores", "Millions"], group = G_TOG)
bool   showMl    = input.bool(true, "Display 1-minute Liquidity?", group = G_TOG, tooltip = "1mL: closing price × average volume on the 1-minute timeframe.")
bool   showUd    = input.bool(false, "Display Up Down volume Ratio?", group = G_TOG, tooltip = "Sum of up-bar volume divided by sum of down-bar volume. Above 1 is bullish.")
bool   showRv    = input.bool(false, "Display RVol?", group = G_TOG, tooltip = "Current volume as a percentage of the average volume. 200% = twice the average.")
bool   showPRv   = input.bool(false, "Display Projected RVol in the table?", group = G_TOG, tooltip = "Projected volume for the live bar divided by the average volume, as a multiplier.")
bool   rvAsTV    = input.bool(false, "Display Rvol as TradingView RVol?", group = G_TOG, tooltip = "Shows 1.5 in place of 150%.")
bool   rvAsBuzz  = input.bool(false, "Display Rvol as Volume Buzz Rvol?", group = G_TOG, tooltip = "Percentage by which the volume is above or below its average.")
 
const string G_COL = "Color Customisation"
color noiseLight   = input.color(#2A2E39, "Light mode default Color", group = G_COL)
color noiseDark    = input.color(#787B86, "Dark mode default Color", group = G_COL)
color smaCol       = input.color(#9E4A4A, "Background Color for MA value in price scale", group = G_COL)
color ppvCol       = input.color(#2196F3, "Pocket Pivot Volume Color", group = G_COL, inline = "c1")
color dryCol       = input.color(#FF9800, "Dry Volume Color", group = G_COL, inline = "c1")
color upCol        = input.color(#4CAF50, "High Up Volume Color", group = G_COL, inline = "c2")
color downCol      = input.color(#FF5252, "High Down Volume Color", group = G_COL, inline = "c2")
color powerUpCol   = input.color(#C8E6C9, "Power Volume Up Color", group = G_COL, inline = "c3")
color powerDownCol = input.color(#FFCCBC, "Power Volume Down Color", group = G_COL, inline = "c3")
color ipoCol       = input.color(#2196F3, "IPO Volume Bar Color", group = G_COL)
color hveCol       = input.color(#2196F3, "HVE Volume Bar Color", group = G_COL)
color hvyCol       = input.color(#2196F3, "HVY Volume Bar Color", group = G_COL)
color hvqCol       = input.color(#2196F3, "HVQ Volume Bar Color", group = G_COL)
 
const string G_HV = "Highest Volume"
bool   showHV      = input.bool(true, "Show Highest Volumes?", group = G_HV, tooltip = "HVE: highest volume ever. HVY: highest volume in over a year. HVQ: highest volume in a quarter. Daily timeframe and above.")
bool   onlyLastHVE = input.bool(false, "Show Only Latest HVE?", group = G_HV)
bool   onlyLastHVY = input.bool(true, "Show Only Latest HVY?", group = G_HV)
bool   onlyLastHVQ = input.bool(false, "Show Only Latest HVQ?", group = G_HV)
bool   showDataAll = input.bool(true, "Show Data on All HV?", group = G_HV)
bool   showHvPct   = input.bool(false, "Show Highest Volume %?", group = G_HV, tooltip = "Adds the volume as a percentage of its average, e.g. HVE 1285%.")
bool   showHvVol   = input.bool(true, "Show Highest Volume value?", group = G_HV, tooltip = "Adds the formatted volume, e.g. HVE 9.52M.")
bool   hvUpOnly    = input.bool(true, "Color Highest Volumes Only on Up Days?", group = G_HV, tooltip = "On a down day the HVE / HVY / HVQ / IPO bar keeps its normal colour.")
 
const string G_LV = "Lowest Volume"
bool   showLV      = input.bool(true, "Show Lowest Volumes?", group = G_LV, tooltip = "Q: lowest volume in a quarter. Y: lowest volume in a year. These bars take the dry volume colour.")
bool   onlyLastLVY = input.bool(false, "Show Only Latest LVY?", group = G_LV)
bool   onlyLastLVQ = input.bool(false, "Show Only Latest LVQ?", group = G_LV)
 
const string G_PB = "Paint Price Bars Options"
bool   paintBars  = input.bool(false, "Paint Price Bars?", group = G_PB, tooltip = "Colours the price bars to match the volume bar colours.")
bool   keepOthers = input.bool(true, "Preserve default colors on other bars?", group = G_PB, tooltip = "Off: every bar that is not painted below takes the noise colour.")
 
const string G_PC = "Choose which price bars to paint"
bool   paintPPV   = input.bool(true, "Paint Pocket Pivot volumes", group = G_PC, tooltip = "Paint price bars that have a pocket pivot volume.")
bool   paintHVE   = input.bool(true, "Paint HVE volumes", group = G_PC, tooltip = "Paint price bars with the highest volume ever (and the IPO bar).")
bool   paintHVY   = input.bool(true, "Paint HVY volumes", group = G_PC, tooltip = "Paint price bars with the highest volume in over a year.")
bool   paintHVQ   = input.bool(true, "Paint HVQ volumes", group = G_PC, tooltip = "Paint price bars with the highest volume in a quarter.")
bool   paintPower = input.bool(false, "Paint Power volumes", group = G_PC, tooltip = "Paint price bars with a power volume, in the power volume colours.")
bool   paintDry   = input.bool(true, "Paint Dry volumes", group = G_PC, tooltip = "Paint price bars with dry or lowest volume.")
bool   paintUp    = input.bool(true, "Paint Green volumes", group = G_PC, tooltip = "Paint up bars with above-average volume.")
bool   paintDown  = input.bool(true, "Paint Red volumes", group = G_PC, tooltip = "Paint down bars with above-average volume.")
 
// ───────────────────────── Helpers ─────────────────────────
// Simple average over `len` bars that falls back to the bars available (IPO stocks).
availSma(float src, int len) =>
    float c = ta.cum(nz(src))
    int n = math.min(len, bar_index + 1)
    (c - nz(c[n])) / n
 
sizeOf(string s) =>
    switch s
        "tiny"   => size.tiny
        "normal" => size.normal
        "large"  => size.large
        => size.small
 
posOf(string v, string h) =>
    switch v
        "top"    => h == "left" ? position.top_left : h == "center" ? position.top_center : position.top_right
        "middle" => h == "left" ? position.middle_left : h == "center" ? position.middle_center : position.middle_right
        => h == "left" ? position.bottom_left : h == "center" ? position.bottom_center : position.bottom_right
 
bool useCr = toUnit == "Crores"
int  toLen = toLenIn == "10 period" ? 10 : toLenIn == "20 period" ? 20 : 50
 
fmtMoney(float v) =>
    string r = ""
    if not na(v)
        if useCr
            r := v >= 1e7 ? str.tostring(v / 1e7, "#.##") + " Cr" : v >= 1e5 ? str.tostring(v / 1e5, "#.##") + " L" : str.tostring(v / 1e3, "#.##") + " K"
        else
            r := v >= 1e9 ? str.tostring(v / 1e9, "#.##") + " B" : v >= 1e6 ? str.tostring(v / 1e6, "#.##") + " M" : str.tostring(v / 1e3, "#.##") + " K"
    r
 
turnoverExpr() =>
    float av  = availSma(volume, toLen)
    float ac  = availSma(close, toLen)
    float atv = availSma(hlc3 * volume, toLen)
    float vwp = av > 0 ? atv / av : na
    av * (toMethod == "SMA" ? ac : vwp)
 
// ───────────────────────── Core volume logic ─────────────────────────
float vol   = nz(volume)
float volMa = availSma(vol, maLen)
 
float ref    = usePrevClose ? nz(close[1], open) : open
bool  isUp   = close > ref
bool  isDown = close < ref
 
// Pocket pivot: up bar with volume above the largest down-bar volume of the previous N bars.
float downVol    = isDown ? vol : 0.0
float maxDownVol = ta.highest(downVol, ppLen)[1]
bool  isPPV      = isUp and not na(maxDownVol) and vol > maxDownVol
 
bool aboveAvg = vol > volMa
bool isDry    = volMa > 0 and vol <= volMa / lowFrac
 
// Highest / lowest volumes, daily and above only.
bool hvOK = timeframe.isdwm
int  qLen = timeframe.ismonthly ? math.max(1, math.round(3 / timeframe.multiplier)) : timeframe.isweekly ? math.max(1, math.round(13 / timeframe.multiplier)) : math.max(1, math.round(63 / timeframe.multiplier))
int  yLen = timeframe.ismonthly ? math.max(2, math.round(12 / timeframe.multiplier)) : timeframe.isweekly ? math.max(2, math.round(52 / timeframe.multiplier)) : math.max(2, math.round(252 / timeframe.multiplier))
 
var float maxVolEver = na
float hiY = ta.highest(vol, yLen)[1]
float hiQ = ta.highest(vol, qLen)[1]
float loY = ta.lowest(vol, yLen)[1]
float loQ = ta.lowest(vol, qLen)[1]
 
bool isIPO = hvOK and bar_index == 0
bool isHVE = hvOK and bar_index > 0 and vol > nz(maxVolEver)
bool isHVY = hvOK and not isIPO and not isHVE and not na(hiY) and vol > hiY
bool isHVQ = hvOK and not isIPO and not isHVE and not isHVY and not na(hiQ) and vol > hiQ
bool isLVY = hvOK and vol > 0 and not na(loY) and vol < loY
bool isLVQ = hvOK and vol > 0 and not isLVY and not na(loQ) and vol < loQ
maxVolEver := math.max(nz(maxVolEver), vol)
 
bool isLow = (showDry and isDry) or (showLV and (isLVQ or isLVY))
 
// Bull Snort (Oliver Kell): 3x average volume, close in the top 35% of the range and above the previous close.
float bsMa = availSma(vol, bsLen)
bool  isBS = bsMa > 0 and vol >= 3 * bsMa and close > close[1] and high > low and close >= high - 0.35 * (high - low)
 
// Power volume: volume beyond the threshold with a price move of at least 5%.
float chgPct      = (close - close[1]) / close[1] * 100
bool  isPower     = vol >= powerVol and math.abs(chgPct) >= 5
bool  isPowerUp   = isPower and chgPct > 0
bool  isPowerDown = isPower and chgPct < 0
 
// ───────────────────────── Colours ─────────────────────────
color noiseCol = darkMode ? noiseDark : noiseLight
color bsCol    = #9C27B0
 
bool  hvColOK = not hvUpOnly or isUp
color volCol  = noiseCol
if isLow
    volCol := dryCol
if isDown and aboveAvg
    volCol := downCol
if isUp and aboveAvg
    volCol := upCol
if isPPV
    volCol := ppvCol
if hvColOK and (isHVE or isHVY or isHVQ)
    volCol := isHVE ? hveCol : isHVY ? hvyCol : hvqCol
if hvColOK and isIPO
    volCol := ipoCol
 
// ───────────────────────── Relative volume, projection, turnover ─────────────────────────
float rvBase = availSma(vol, rvLen)[1]
float rvol   = rvBase > 0 ? vol / rvBase : na
 
float upAvg   = availSma(isUp ? vol : 0.0, udLen)
float dnAvg   = availSma(isDown ? vol : 0.0, udLen)
float udRatio = dnAvg > 0 ? upAvg / dnAvg : na
 
float projVol = na
if barstate.islast and not barstate.isconfirmed and time_close > time
    float frac = math.min(1.0, math.max(0.0, float(timenow - time) / float(time_close - time)))
    if frac > 0
        projVol := vol / frac
float projRvol = rvBase > 0 ? projVol / rvBase : na
 
// Average turnover is a daily figure: intraday charts read it from the daily timeframe.
float avgTurnover = request.security(syminfo.tickerid, timeframe.isintraday ? "D" : "", turnoverExpr())
// 1-minute liquidity: close × average 1-minute volume.
float avgVol1m = request.security(syminfo.tickerid, "1", availSma(volume, 50))
float oneML    = close * avgVol1m
 
float unitDiv = useCr ? 1e7 : 1e6
 
// ───────────────────────── Plots (order matches the original's Style tab) ─────────────────────────
color bgCol = showBS and isBS ? color.new(bsCol, 80) : showPower and isPowerUp ? powerUpCol : showPower and showPowerDown and isPowerDown ? powerDownCol : na
bgcolor(bgCol, title = "Background Color")
 
plot(vol, "Vol", volCol, style = plot.style_columns)
plot(volMa, "SMA", smaCol, display = display.status_line + display.price_scale)
plotshape(showBS and isBS, "Bull Snort", shape.circle, location.bottom, bsCol, size = size.tiny)
plot(not na(projVol) and projVol > vol ? projVol : na, "Projected Volume", color.new(volCol, 70), style = plot.style_columns, display = showProj ? display.pane : display.none)
 
// Hidden plots, for the Pine Screener and data window.
plot(avgTurnover / unitDiv, "Ave₹Vol", display = display.none)
plot(rvol * 100, "RVol", display = display.none)
plot(oneML / unitDiv, "1mL", display = display.none)
 
color paintCol = na
if paintBars
    paintCol := keepOthers ? na : noiseCol
    if isLow and paintDry
        paintCol := dryCol
    if isDown and aboveAvg and paintDown
        paintCol := downCol
    if isUp and aboveAvg and paintUp
        paintCol := upCol
    if isPPV and paintPPV
        paintCol := ppvCol
    if hvColOK and ((isHVE and paintHVE) or (isHVY and paintHVY) or (isHVQ and paintHVQ) or (isIPO and paintHVE))
        paintCol := volCol
    if paintPower and isPowerUp
        paintCol := powerUpCol
    if paintPower and showPowerDown and isPowerDown
        paintCol := powerDownCol
barcolor(paintCol, title = "Bar Color")
 
// ───────────────────────── Labels ─────────────────────────
hvText(string tag) =>
    string s = tag
    if showHvVol
        s := s + " " + str.tostring(vol, format.volume)
    if showHvPct and volMa > 0
        string p = str.tostring(vol / volMa * 100, "#") + "%"
        s := s + (showHvVol ? " (" + p + ")" : " " + p)
    s
 
// Draws a highest-volume label. The previous one of the same kind is removed ("only latest")
// or, when data is wanted on the latest label only, cut back to its bare tag.
drawHV(label prev, bool onlyLatest, string tag) =>
    if onlyLatest
        label.delete(prev)
    else if not showDataAll and not na(prev)
        label.set_text(prev, tag)
    label.new(bar_index, vol, hvText(tag), style = label.style_label_down, color = color(na), textcolor = ppvCol, size = size.small)
 
drawLV(label prev, bool onlyLatest, string tag) =>
    if onlyLatest
        label.delete(prev)
    label.new(bar_index, vol, tag, style = label.style_label_down, color = color(na), textcolor = dryCol, size = size.small)
 
var label lastHVE = na
var label lastHVY = na
var label lastHVQ = na
var label lastLVY = na
var label lastLVQ = na
 
if showHV
    if isIPO
        label.new(bar_index, vol, hvText("IPO"), style = label.style_label_down, color = color(na), textcolor = ppvCol, size = size.small)
    else if isHVE
        lastHVE := drawHV(lastHVE, onlyLastHVE, "HVE")
    else if isHVY
        lastHVY := drawHV(lastHVY, onlyLastHVY, "HVY")
    else if isHVQ
        lastHVQ := drawHV(lastHVQ, onlyLastHVQ, "HVQ")
 
// Lowest volumes are only labelled once the bar is confirmed.
if showLV and barstate.isconfirmed
    if isLVY
        lastLVY := drawLV(lastLVY, onlyLastLVY, "Y")
    else if isLVQ
        lastLVQ := drawLV(lastLVQ, onlyLastLVQ, "Q")
 
// ───────────────────────── Table ─────────────────────────
var table tbl = table.new(posOf(tblVertIn, tblHorzIn), 5, 5, border_width = 2)
color tblGood = #E8F5E9
color tblWeak = #FDECEA
color tblTxt  = darkMode and tblNoCol ? #D1D4DC : #131722
 
addCell(int i, string txt, bool good) =>
    table.cell(tbl, tblHoriz ? i : 0, tblHoriz ? 0 : i, txt, text_color = tblTxt, bgcolor = tblNoCol ? color(na) : good ? tblGood : tblWeak, text_size = sizeOf(tblSizeIn))
    i + 1
 
if barstate.islast and (showTo or showMl or showUd or showRv or showPRv)
    table.clear(tbl, 0, 0, 4, 4)
    int i = 0
    if showTo
        i := addCell(i, (useCr ? "Avg₹Vol: " : "Avg$Vol: ") + fmtMoney(avgTurnover), avgTurnover >= toThresh * unitDiv)
    if showMl
        i := addCell(i, "1mL: " + fmtMoney(oneML), oneML >= mlThresh * unitDiv)
    if showUd
        i := addCell(i, "U/D: " + (na(udRatio) ? "" : str.tostring(udRatio, "0.00")), udRatio >= 1)
    if showRv
        string rvTxt = na(rvol) ? "" : rvAsBuzz ? (rvol >= 1 ? "+" : "") + str.tostring((rvol - 1) * 100, "#") + "%" : rvAsTV ? str.tostring(rvol, "0.00") : str.tostring(rvol * 100, "#") + "%"
        i := addCell(i, (rvAsBuzz ? "Vol Buzz: " : "RVol: ") + rvTxt, rvol * 100 >= rvThresh)
    if showPRv
        i := addCell(i, "Proj RVol: " + (na(projRvol) ? "" : str.tostring(projRvol, "0.0") + "x"), projRvol * 100 >= rvThresh)
 
// ───────────────────────── Alerts / Pine Screener conditions ─────────────────────────
alertcondition(isPPV, "Pocket pivot volume", "Pocket pivot volume on {{ticker}}")
alertcondition(isHVE, "HVE - highest volume ever", "Highest volume ever on {{ticker}}")
alertcondition(isHVY, "HVY - highest volume in a year", "Highest volume in over a year on {{ticker}}")
alertcondition(isHVQ, "HVQ - highest volume in a quarter", "Highest volume in a quarter on {{ticker}}")
alertcondition(isDry, "Dry volume", "Dry volume on {{ticker}}")
alertcondition(isBS, "Bull Snort", "Bull Snort on {{ticker}}")
alertcondition(isPowerUp, "Power volume (up)", "Power volume up day on {{ticker}}")
alertcondition(rvol * 100 >= rvThresh, "High RVol", "High relative volume on {{ticker}}")

← 返回列表