本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// Volume Profile section: this Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Volume Profile © kv4coins (merged in 2026-10-26 at Martin's request; logic unchanged, lines drawn on the price chart)
//@version=6
indicator("Buy vs Sell Volume", shorttitle = "Buy/Sell Vol", overlay = false, format = format.volume, max_bars_back = 5000, max_lines_count = 500, max_labels_count = 500)
// Splits each bar's volume into buy and sell volume and compares it with the
// average volume of the previous X bars (relative volume). In this pane: buy volume
// as green columns above the zero line, sell volume as red columns below it, a
// line of volume minus its 90-bar average with a dot on every bar (orange high, grey
// average, blue low), and the values in the pane's legend line (Buy %, Sell %,
// % above/below average, average volume).
// Since 2026-10-26 (Martin): mirrored around zero, solid colours, no average line; then a volume-vs-60-day-average
// line with high / average / low dots (previous: archive/buy-sell-volume-before-pct-line.pine).
// Then the average became the past 365 bars, then 50, then 90 bars by default (Martin's pick) (or calendar days, a setting) instead of 60 bars (previous: archive/buy-sell-volume-before-365d-avg.pine).
// Previous layout (stacked columns, faded bars): archive/buy-sell-volume-before-mirror.pine.
// Estimate mode: buy share = where the close sits in the bar's range
// (close at the high = 100% buy, at the low = 100% sell). Works on full history.
// Precise mode: buy share from lower-timeframe bars (up bars = buy, down bars = sell).
// Only covers the history TradingView has for that lower timeframe; bars without
// intrabar data fall back to the estimate.
// On the price chart (force_overlay): kv4coins' Volume Profile, and lines at the
// prices that traded the most volume (key volume levels).
// Since 2026-10-26 (Martin): the key volume lines come from the Volume Profile itself, so
// #1 is the PoC and #2, #3 are the next busiest Volume Profile rows (same look-back,
// 300 bars by default). Then (Martin, same day) Volume Profile defaults set to his own
// VP settings: look-back 300, 300 rows, red PoC line on, value area and its lines off
// (previous: archive/buy-sell-volume-before-vp-defaults.pine). Then lines must be at
// least 0.5% in price apart instead of 9 rows (previous: archive/buy-sell-volume-before-pct-gap.pine).
// Previous (own 365-day profile): archive/buy-sell-volume-before-poc-lines.pine.
// Previous version without the price-chart parts: archive/buy-sell-volume-before-vp.pine.
// ───────── Inputs ─────────
string grpM = "Buy / sell split"
string MODE_EST = "Estimate (close in range)"
string MODE_LTF = "Precise (lower timeframe)"
string mode = input.string(MODE_EST, "Method", options = [MODE_EST, MODE_LTF], group = grpM, tooltip = "Estimate: uses where the close sits in the bar's range and works on all history. Precise: adds up buy and sell volume from lower-timeframe bars; history is limited and older bars fall back to the estimate.")
string ltf = input.timeframe("5", "Lower timeframe (precise mode)", group = grpM, tooltip = "Must be lower than the chart timeframe. Smaller = more precise but less history.")
float domPct = input.float(60, "Buyers / sellers dominant at %", minval = 50, maxval = 100, step = 1, group = grpM)
string grpA = "Average volume"
int avgDays = input.int(90, "Average over past X", minval = 1, maxval = 5000, inline = "avg", group = grpA, tooltip = "Each bar's volume is compared with the average volume of the X bars (default 90, Martin's pick) or X calendar days before it. Calendar days: 365 is about 252 trading days for stocks. Uses at most 5,000 bars.")
string avgUnit = input.string("Bars", "", options = ["Bars", "Calendar days"], inline = "avg", group = grpA)
int avgMinN = input.int(20, "Min bars before showing the average", minval = 1, group = grpA, tooltip = "Early in the chart's history there are fewer bars in the window; the average stays blank until there are at least this many.")
float hiPct = input.float(15, "High volume at % above avg", minval = 0, step = 5, group = grpA, tooltip = "High-volume dots go from light orange at this level to dark orange at the level below.")
float hiDeep = input.float(60, "Darkest orange at % above avg", minval = 1, step = 5, group = grpA)
float loPct = input.float(15, "Low volume at % below avg", minval = 0, maxval = 100, step = 5, group = grpA, tooltip = "Low-volume dots go from light blue at this level to dark blue at the level below.")
float loDeep = input.float(60, "Darkest blue at % below avg", minval = 1, maxval = 100, step = 5, group = grpA)
string grpV = "Display"
color buyCol = input.color(#26a69a, "Buy volume", group = grpV)
color sellCol = input.color(#ef5350, "Sell volume", group = grpV)
bool showDots = input.bool(true, "Show volume vs average line and dots", group = grpV, tooltip = "A line of each bar's volume minus its average (above zero = busier than average, below = quieter), with a dot on every bar: high volume, average (grey) or low volume. The legend shows the % above or below the average.")
color diffCol = input.color(#d1d4dc, "Volume vs average line", group = grpV)
string dotSizeIn = input.string("Tiny", "Dot size", options = ["Auto (smallest)", "Tiny", "Small"], group = grpV)
bool showPct = input.bool(false, "Write the % next to high and low dots", group = grpV, tooltip = "Off: hover over any dot to see its %. On: the % is also printed above every high and below every low volume dot (busier chart).")
color hiLightCol = input.color(#ffcc80, "High volume dot: light (just above)", group = grpV)
color hiDarkCol = input.color(#e65100, "High volume dot: dark (far above)", group = grpV)
color midDotCol = input.color(#787b86, "Average volume dot", group = grpV)
color loLightCol = input.color(#a8d1ff, "Low volume dot: light (just below)", group = grpV)
color loDarkCol = input.color(#1848cc, "Low volume dot: dark (far below)", group = grpV)
bool showTag = input.bool(false, "Show tag on the latest bar", group = grpV, tooltip = "A small label on the right edge, e.g. \"62% buy · 1.40× avg\".")
string grpK = "Key volume levels (price chart)"
bool showKey = input.bool(true, "Lines at the highest-volume prices", group = grpK, tooltip = "Lines at the busiest rows of the Volume Profile (same look-back as the profile). #1 is the PoC.")
int keyCount = input.int(3, "Number of lines", minval = 1, maxval = 20, group = grpK)
float keyGapPct = input.float(0.5, "Min distance between lines (%)", minval = 0, step = 0.1, group = grpK, tooltip = "A busy price only gets a line if it is at least this % away from every line above it, so #2 and #3 never sit right next to #1.")
color keyCol = input.color(color.orange, "Line color", group = grpK)
int keyWidth = input.int(2, "Line width", minval = 1, maxval = 10, group = grpK)
bool keyLabels = input.bool(true, "Show price labels", group = grpK)
// ───────── Volume Profile inputs (kv4coins) ─────────
bool showVP = input.bool(true, "Show Volume Profile on the price chart", group = 'Lookback Period')
vp_use_visible_range = input.bool(
defval = false,
title = 'Use Visible Range',
group = 'Lookback Period',
tooltip = 'Calculate Volume Profile using all visible bars in the current chart'
)
vp_lookback_depth = input.int(
defval = 300,
minval = 10,
maxval = 3000,
title = 'Fixed Range Lookback Depth [10-3000]',
group = 'Lookback Period',
tooltip = 'Number of historical bars to include in the calculation. Ignored if "Use Visible Range" is enabled'
)
vp_num_bars = input.int(
defval = 300,
minval = 10,
maxval = 470,
title = 'Number of Volume Bars [10-470]',
group = 'Volume Bars',
tooltip = 'Number of Volume Profile bars (max 470 so the key volume lines still fit)'
)
vp_bar_thickness = input.int(
defval = 1,
minval = 1,
maxval = 30,
title = 'Volume Bar Thickness [1-30]',
group = 'Volume Bars',
tooltip = 'Width of each volume bar in the Volume Profile'
)
vp_bar_len_mult = input.int(
defval = 20,
minval = 1,
maxval = 50,
title = 'Bar Length Multiplier [1-50]',
group = 'Volume Bars',
tooltip = 'Volume Profile Bar length multiplier'
)
vp_right_offset = input.int(
defval = 70,
minval = 0,
maxval = 400,
title = 'Right Offset [0-400]',
group = 'Volume Bars',
tooltip = 'Space between the right bar of the chart and the Volume Profile'
)
vp_volume_type = input.string(
defval = 'Both',
title = 'Volume Type',
options = ['Both', 'Bullish', 'Bearish'],
group = 'Volume Bars',
tooltip = 'Select the type of Volume to include'
)
vp_bar_color = input.color(
defval = color.new(color.gray, 50),
title = 'Volume Bar Color',
group = 'Volume Bars',
tooltip = 'Color of the volume bars in the Volume Profile'
)
vp_display_poc = input.bool(
defval = true,
title = 'Display Point of Control (PoC)',
group = 'Point of Control',
tooltip = 'Enable or disable the display of the Point of Control (PoC)'
)
vp_poc_line_thickness = input.int(
defval = 1,
minval = 1,
maxval = 30,
title = 'PoC Line Thickness [1-30]',
group = 'Point of Control',
tooltip = 'Width of the PoC line'
)
vp_poc_line_color = input.color(
defval = color.red,
title = 'PoC Line Color',
group = 'Point of Control',
tooltip = 'Color of the Point of Control (PoC) line'
)
vp_display_va = input.bool(
defval = false,
title = 'Display Value Area',
group = 'Value Area',
tooltip = 'Enable or disable the display of the Value Area'
)
vp_va_percent = input.int(
defval = 68,
minval = 5,
maxval = 95,
title = 'Value Area Percentage(%) [5-95]',
group = 'Value Area',
tooltip = 'Percentage of the Value Area'
)
vp_va_bar_color = input.color(
defval = color.blue,
title = 'Value Area Bar Color',
group = 'Value Area',
tooltip = 'Color of the volume bars in the Value Area'
)
vp_display_va_lines = input.bool(
defval = false,
title = 'Display Value Area Lines',
group = 'Value Area',
tooltip = 'Enable or disable the display of the Value Area lines. Ignored if "Display Value Area" is disabled'
)
vp_va_lines_thickness = input.int(
defval = 1,
minval = 1,
maxval = 20,
title = 'Value Area Lines Thickness [1-20]',
group = 'Value Area',
tooltip = 'Width of the Value Area lines'
)
// ───────── Volume check ─────────
var bool anyVol = false
if not na(volume) and volume > 0
anyVol := true
if barstate.islast and not anyVol
runtime.error("This symbol has no volume data.")
// ───────── Buy / sell split ─────────
// Estimate: close location in the bar's range.
float rng = high - low
float estShare = rng > 0 ? (close - low) / rng : 0.5
// Precise: up/down volume from lower-timeframe bars (flat bars split 50/50).
f_ltfSplit() =>
float dir = close > open ? 1.0 : close < open ? -1.0 : close > close[1] ? 1.0 : close < close[1] ? -1.0 : 0.0
float v = nz(volume)
float b = dir > 0 ? v : dir == 0 ? v / 2 : 0.0
[b, v - b]
bool wantLtf = mode == MODE_LTF
bool ltfOk = timeframe.in_seconds(ltf) < timeframe.in_seconds(timeframe.period)
string reqTf = wantLtf and ltfOk ? ltf : timeframe.period
[ltfBuyArr, ltfSellArr] = request.security_lower_tf(syminfo.tickerid, reqTf, f_ltfSplit())
float ltfBuy = wantLtf and ltfOk ? ltfBuyArr.sum() : 0.0
float ltfSell = wantLtf and ltfOk ? ltfSellArr.sum() : 0.0
bool usedLtf = wantLtf and ltfOk and ltfBuy + ltfSell > 0
float buyShare = usedLtf ? ltfBuy / (ltfBuy + ltfSell) : estShare
float vol = nz(volume)
float buyVol = vol * buyShare
float sellVol = vol - buyVol
float buyPct = buyShare * 100
// ───────── Relative volume ─────────
// Average of the previous avgDays bars, or of the bars in the previous avgDays calendar days (the current bar is not included).
var array<int> avgT = array.new_int()
var array<float> avgV = array.new_float()
var float avgS = 0.0
int avgCut = time - avgDays * 86400000
int avgCap = avgUnit == "Bars" ? avgDays : 5000
while avgT.size() > 0 and ((avgUnit == "Calendar days" and avgT.first() < avgCut) or avgT.size() >= avgCap)
avgT.shift()
avgS -= avgV.shift()
float avgVol = avgT.size() >= avgMinN ? avgS / avgT.size() : na
avgT.push(time)
avgV.push(vol)
avgS += vol
float rvol = avgVol > 0 ? vol / avgVol : na
float diffPct = na(rvol) ? na : (rvol - 1) * 100 // % above (+) or below (-) the average
float diffVol = na(rvol) ? na : vol - avgVol // same thing in volume, so it fits the pane's scale
bool isHigh = not na(diffPct) and diffPct >= hiPct
bool isLow = not na(diffPct) and diffPct <= -loPct
bool buyDom = buyPct >= domPct
bool sellDom = buyPct <= 100 - domPct
color domCol = buyDom ? buyCol : sellDom ? sellCol : color.gray
// Low volume: light blue at loPct below the average, getting darker down to loDeep below
color loDotCol = color.from_gradient(-nz(diffPct), loPct, math.max(loDeep, loPct + 1), loLightCol, loDarkCol)
// High volume: light orange at hiPct above the average, getting darker up to hiDeep above
color hiDotCol = color.from_gradient(nz(diffPct), hiPct, math.max(hiDeep, hiPct + 1), hiLightCol, hiDarkCol)
color rvolCol = isHigh ? hiDotCol : isLow ? loDotCol : midDotCol
// ───────── Plots in the pane ─────────
// Buy volume above the zero line, sell volume below it (plotted as a negative number,
// so the scale reads e.g. 40M above zero and -40M below).
plot(buyVol, "Buy volume", buyCol, style = plot.style_columns, display = display.pane + display.data_window)
plot(-sellVol, "Sell volume", sellCol, style = plot.style_columns, display = display.pane + display.data_window)
hline(0, "Zero line", color.new(#787b86, 30), hline.style_solid)
// Volume vs average: the line is volume minus the average (drawn in volume so it shares the pane's scale);
// a dot on every bar shows high / average / low volume. The % itself is in the legend.
plot(showDots ? diffVol : na, "Volume vs average", diffCol, 1, display = display.pane)
// Dots are drawn as small shapes. On the last 450 bars an invisible label sits on each dot,
// so hovering it shows its % vs the average (TradingView keeps at most 500 labels).
int hoverBars = 450
bool hoverDot = showDots and not na(diffVol) and bar_index > last_bar_index - hoverBars
// plotshape needs a fixed size, so there is one call per size and the input picks which one draws
float dotY = showDots ? diffVol : na
plotshape(dotSizeIn == "Auto (smallest)" ? dotY : na, "Volume dot (auto)", shape.circle, location.absolute, rvolCol, size = size.auto, display = display.pane)
plotshape(dotSizeIn == "Tiny" ? dotY : na, "Volume dot (tiny)", shape.circle, location.absolute, rvolCol, size = size.tiny, display = display.pane)
plotshape(dotSizeIn == "Small" ? dotY : na, "Volume dot (small)", shape.circle, location.absolute, rvolCol, size = size.small, display = display.pane)
if hoverDot
string pctTxt = str.tostring(diffPct, "+0;-0") + "%"
string tip = pctTxt + " vs " + str.tostring(avgDays) + (avgUnit == "Bars" ? "-bar" : "-day") + " average\nVolume " + str.tostring(vol, format.volume) + " · average " + str.tostring(avgVol, format.volume) + "\nBuy " + str.tostring(buyPct, "0") + "% · Sell " + str.tostring(100 - buyPct, "0") + "%"
bool withTxt = showPct and (isHigh or isLow)
label.new(bar_index, diffVol, withTxt ? pctTxt : "", style = withTxt ? (isHigh ? label.style_label_down : label.style_label_up) : label.style_circle, color = withTxt ? rvolCol : color.new(rvolCol, 100), textcolor = color.white, size = size.tiny, tooltip = tip)
// ───────── Values in the pane's legend line ─────────
// Shown next to the indicator name; they follow the cursor when you hover a past bar.
plot(buyPct, "Buy %", buyCol, display = display.status_line + display.data_window, format = format.percent, precision = 0)
plot(100 - buyPct, "Sell %", sellCol, display = display.status_line + display.data_window, format = format.percent, precision = 0)
plot(diffPct, "% vs average", rvolCol, display = display.status_line + display.data_window, format = format.percent, precision = 0)
plot(avgVol, "Avg volume", color.gray, display = display.status_line + display.data_window, format = format.volume)
// ───────── Optional tag on the latest bar ─────────
var label tag = na
if showTag and barstate.islast
string method = usedLtf ? "precise " + ltf : wantLtf ? "estimate (no intrabar data)" : "estimate"
string txt = str.tostring(buyPct, "#") + "% buy · " + (na(diffPct) ? "n/a" : str.tostring(diffPct, "+0;-0") + "% vs avg")
label.delete(tag)
tag := label.new(bar_index, buyVol, txt, style = label.style_label_left, color = color.new(domCol, 20), textcolor = color.white, size = size.small, tooltip = "Buy / sell method: " + method + "\nAverage: past " + str.tostring(avgDays) + (avgUnit == "Bars" ? " bars" : " days"))
// ───────── Volume Profile (kv4coins, MPL 2.0) ─────────
// Same calculation as the original; every line is drawn on the price chart with force_overlay.
var int timeframe_minutes = 1000 * timeframe.in_seconds()
var int lookback_bars = vp_use_visible_range ? math.round((last_bar_time - chart.left_visible_bar_time) / timeframe_minutes) : vp_lookback_depth
var line poc = na
var line vah = na
var line val = na
var array<line> bars = array.new_line()
var array<float> volumes = array.new_float(vp_num_bars, 0)
float highest_price = ta.highest(lookback_bars)
float lowest_price = ta.lowest(lookback_bars)
float price_interval = (highest_price - lowest_price) / (vp_num_bars - 1)
scale_volume(float v, float maxVol) =>
float d = maxVol / lookback_bars / (vp_bar_len_mult / 100)
int scaled_vol = math.round(v / d)
scaled_vol
calculate_vp() =>
array.fill(volumes, 0)
for i = 0 to (lookback_bars - 1)
for j = 0 to (vp_num_bars - 1)
float price_level = lowest_price + price_interval * j
bool is_bullish = close[i] >= open[i]
bool include_vol = vp_volume_type == 'Both' ? true : (vp_volume_type == 'Bullish' ? is_bullish : not is_bullish)
if (price_level >= low[i] and price_level < high[i] and include_vol)
array.set(volumes, j, volumes.get(j) + volume[i])
calculate_va(int max_idx, float max_vol) =>
float sum_vol = volumes.sum()
float va_vol = sum_vol * vp_va_percent / 100
int va_up = max_idx
int va_dn = max_idx
float va_sum = max_vol
while va_sum < va_vol
float v_up = (va_up < vp_num_bars - 1) ? volumes.get(va_up + 1) : 0.0
float v_dn = (va_dn > 0) ? volumes.get(va_dn - 1) : 0.0
if v_up == 0 and v_dn == 0
break
if v_up >= v_dn
va_sum += v_up
va_up += 1
else
va_sum += v_dn
va_dn -= 1
[va_dn, va_up]
draw_vp() =>
float max_vol = volumes.max()
int max_idx = volumes.indexof(max_vol)
int x2 = bar_index + vp_right_offset
for i = 0 to (vp_num_bars - 1)
int len = scale_volume(volumes.get(i), max_vol)
int x1 = x2 - len
float y = lowest_price + price_interval * i
line.set_xy1(bars.get(i), x1, y)
line.set_xy2(bars.get(i), x2, y)
line.set_color(bars.get(i), max_idx == i ? vp_poc_line_color : vp_bar_color)
if vp_display_poc
int len = scale_volume(max_vol, max_vol)
int poc_x1 = bar_index - lookback_bars
int poc_x2 = x2 - len - 10
float y = lowest_price + price_interval * max_idx
line.set_xy1(poc, poc_x1, y)
line.set_xy2(poc, poc_x2, y)
if vp_display_va
[va_dn, va_up] = calculate_va(max_idx, max_vol)
for i = va_dn to va_up
if i != max_idx
line.set_color(bars.get(i), vp_va_bar_color)
if vp_display_va_lines
int vah_len = scale_volume(volumes.get(va_up), max_vol)
int val_len = scale_volume(volumes.get(va_dn), max_vol)
int va_x1 = bar_index - lookback_bars
int vah_x2 = x2 - vah_len - 10
int val_x2 = x2 - val_len - 10
float vah_y1 = lowest_price + price_interval * va_up
float val_y1 = lowest_price + price_interval * va_dn
line.set_xy1(vah, va_x1, vah_y1)
line.set_xy1(val, va_x1, val_y1)
line.set_xy2(vah, vah_x2, vah_y1)
line.set_xy2(val, val_x2, val_y1)
if showVP and barstate.isfirst
for i = 0 to (vp_num_bars - 1)
array.push(bars, line.new(x1 = bar_index, y1 = close, x2 = bar_index, y2 = close, width = vp_bar_thickness, force_overlay = true))
if vp_display_poc
poc := line.new(x1 = bar_index, y1 = close, x2 = bar_index, y2 = close, color = vp_poc_line_color, width = vp_poc_line_thickness, force_overlay = true)
if vp_display_va and vp_display_va_lines
vah := line.new(x1 = bar_index, y1 = close, x2 = bar_index, y2 = close, color = vp_va_bar_color, width = vp_va_lines_thickness, force_overlay = true)
val := line.new(x1 = bar_index, y1 = close, x2 = bar_index, y2 = close, color = vp_va_bar_color, width = vp_va_lines_thickness, force_overlay = true)
if (showVP or showKey) and barstate.islast
calculate_vp()
if showVP
draw_vp()
// ───────── Key volume levels (price chart) ─────────
// Taken from the Volume Profile rows above: #1 = the PoC (busiest row), then rows within
// "Min distance between lines" (0.5% of price) are skipped and the next busiest gets #2, and so on.
var array<line> keyLines = array.new_line()
var array<label> keyLbls = array.new_label()
if showKey and barstate.islast
for l in keyLines
l.delete()
keyLines.clear()
for lb in keyLbls
lb.delete()
keyLbls.clear()
array<float> work = volumes.copy()
array<float> chosen = array.new_float()
int k = 0
while k < keyCount
float mx = work.max()
if mx <= 0
break
int j = work.indexof(mx)
float y = lowest_price + price_interval * j
work.set(j, 0.0)
bool tooClose = false
for c in chosen
if math.abs(y - c) / c * 100 < keyGapPct
tooClose := true
if tooClose
continue
chosen.push(y)
k += 1
string name = k == 1 ? "#1 PoC" : "#" + str.tostring(k)
keyLines.push(line.new(bar_index - lookback_bars + 1, y, bar_index, y, extend = extend.right, color = keyCol, width = keyWidth, force_overlay = true))
if keyLabels
keyLbls.push(label.new(bar_index + 3, y, name + " " + str.tostring(y, format.mintick), style = label.style_label_left, color = color.new(keyCol, 25), textcolor = color.white, size = size.tiny, tooltip = "Key volume level " + name + "\nVolume traded at this price: " + str.tostring(volumes.get(j), format.volume) + "\nLook-back: the Volume Profile's " + str.tostring(lookback_bars) + " bars", force_overlay = true))
// ───────── Alerts ─────────
bool highVol = isHigh
alertcondition(highVol and buyDom, "High volume, buyers in control", "{{ticker}}: volume above average with buyers dominant")
alertcondition(highVol and sellDom, "High volume, sellers in control", "{{ticker}}: volume above average with sellers dominant")
alertcondition(highVol, "High volume", "{{ticker}}: volume above average")