Volume Bubble Momentum [NJ]

NJ_Algo · study · 301 行 · 点赞 25 · 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/
// © NJ_Algo
 
//@version=6
indicator("Volume Bubble Momentum [NJ]", "VBM", overlay = true, behind_chart = false, max_labels_count = 500, max_boxes_count = 500)
 
//  ███╗   ██╗     ██╗      █████╗ ██╗      ██████╗  ██████╗
//  ████╗  ██║     ██║     ██╔══██╗██║     ██╔════╝ ██╔═══██╗
//  ██╔██╗ ██║     ██║     ███████║██║     ██║  ███╗██║   ██║
//  ██║╚██╗██║     ██║     ██╔══██║██║     ██║   ██║██║   ██║
//  ██║ ╚████║ ██╗ ██║     ██║  ██║██║     ██║   ██║██║   ██║
//  ██║  ╚███║ ╚████╔╝     ██║  ██║███████╗╚██████╔╝╚██████╔╝
//  ╚═╝   ╚══╝  ╚═══╝      ╚═╝  ╚═╝╚══════╝ ╚═════╝  ╚═════╝
 
// ✧═════════════════✧
// ║      INPUTS      ║
// ✧═════════════════✧
 
const string t1 = "Green or gray candles after a long signal, red or dark candles after a short signal."
const string t2 = "A bubble marks a price where unusually big buying (green) or selling (red) happened. Hover over a bubble to see the volume."
const string t3 = "Shows how the signals would have performed in the past: number of trades, win rate and total profit."
const string t4 = "How big one price level is, in ticks (the smallest price step of the symbol). Smaller = more precise levels. If you see no or too few bubbles, try a bigger number."
const string t5 = "A bubble appears when buying or selling at one price level is at least this many times bigger than normal. Lower = more bubbles and more signals. Higher = fewer, stronger signals."
const string t6 = "Profit target compared to the risk. Example: 2.5 means the take profit is 2.5 times further away than the stop loss."
const string t7 = "Your exchange fee for one order, in %. Example: 0.05 = 0.05%. Used for the results table, and to skip trades whose stop is so small that fees would eat the profit."
 
const string g1 = "✧ DISPLAY ✧"
colorMode   = input.string("Colored", "Color mode", options = ["Colored", "Neutral"], group = g1)
dispCandles = input.bool(true, "Color candles", group = g1, tooltip = t1)
showBubbles = input.bool(true, "Show bubbles", group = g1, tooltip = t2)
showStats   = input.bool(true, "Show results table", group = g1, tooltip = t3)
 
const string g2 = "✧ CALCULATION ✧"
rowTicks = input.int(100, "Price level size (ticks)", minval = 1, group = g2, tooltip = t4)
mult     = input.float(5.0, "Bubble sensitivity", minval = 1, step = 0.5, group = g2, tooltip = t5)
rr       = input.float(2.5, "Reward to risk", minval = 0.5, step = 0.5, group = g2, tooltip = t6)
fee      = input.float(0.0288, "Fee per order %", minval = 0, step = 0.01, group = g2, tooltip = t7)
 
// Fixed settings
const int   AVG_LEN   = 120   // candles used to measure normal volume
const int   WAIT_BARS = 10    // candles a bubble is watched for momentum
const float CONF_ATR  = 0.1   // close must break the bubble candle by this many ATRs
const float SL_ATR    = 1.0   // stop goes this many ATRs beyond the signal candle's wick
const int   EMA_LEN   = 200   // trend filter
const float MAX_FEE_R = 0.2   // skip trades whose fees would cost more than this many R
 
// ✧══════════════════════✧
// ║      CALCULATION      ║
// ✧══════════════════════✧
 
longCol  = colorMode == "Colored" ? color.rgb(0, 136, 100) : color.rgb(179, 179, 179)
shortCol = colorMode == "Colored" ? color.rgb(120, 0, 32) : color.rgb(60, 60, 60)
 
float atr = ta.atr(14)
float ema = ta.ema(close, EMA_LEN)
 
// Footprint rows of this candle (empty if there is no data)
footprint fp = request.footprint(rowTicks)
array<volume_row> rows = array.new<volume_row>()
if not na(fp)
    rows := footprint.rows(fp)
 
// First candle with footprint data = start of the results
var int fpStart = na
if na(fpStart) and not na(fp)
    fpStart := time
 
// Normal volume = average volume per side per row of the last closed candles
var array<float> history = array.new<float>()
float benchmark = history.size() > 0 ? history.avg() * mult : na
 
float total = 0.0
for r in rows
    total += volume_row.buy_volume(r) + volume_row.sell_volume(r)
if rows.size() > 0 and barstate.isconfirmed
    history.push(total / (2 * rows.size()))
    if history.size() > AVG_LEN
        history.shift()
 
// Each candle's heaviest buying row and heaviest selling row are watched for momentum
type Zone
    int   side      // 1 = heavy buying, -1 = heavy selling
    float top
    float bot
    float barHigh
    float barLow
    int   startBar
 
var array<Zone> zones = array.new<Zone>()
 
// 0 = waiting, 1 = failed (price closed back through the level), 2 = momentum
check(Zone z, float buf) =>
    int res = 0
    if z.side == 1
        if close < z.bot - buf
            res := 1
        else if bar_index > z.startBar and close > z.barHigh + buf
            res := 2
    else
        if close > z.top + buf
            res := 1
        else if bar_index > z.startBar and close < z.barLow - buf
            res := 2
    res
 
bool longSig  = false
bool shortSig = false
 
if barstate.isconfirmed and not na(atr)
    float buf = atr * CONF_ATR
 
    // 1. New zones from this candle's bubbles
    if not na(benchmark) and benchmark > 0
        float bestBuy  = 0.0
        float bestSell = 0.0
        float buyUp  = na
        float buyDn  = na
        float sellUp = na
        float sellDn = na
        for r in rows
            float bV = volume_row.buy_volume(r)
            float sV = volume_row.sell_volume(r)
            if bV > bestBuy
                bestBuy := bV
                buyUp := volume_row.up_price(r)
                buyDn := volume_row.down_price(r)
            if sV > bestSell
                bestSell := sV
                sellUp := volume_row.up_price(r)
                sellDn := volume_row.down_price(r)
        if bestBuy >= benchmark
            zones.push(Zone.new(1, math.min(buyUp, high), math.max(buyDn, low), high, low, bar_index))
        if bestSell >= benchmark
            zones.push(Zone.new(-1, math.min(sellUp, high), math.max(sellDn, low), high, low, bar_index))
        while zones.size() > 100
            zones.shift()
 
    // 2. Momentum: price breaks the bubble candle in the bubble's direction, with the trend
    if zones.size() > 0
        for i = zones.size() - 1 to 0
            Zone z = zones.get(i)
            int res = check(z, buf)
            if res == 2
                if z.side == 1 and close > ema
                    longSig := true
                else if z.side == -1 and close < ema
                    shortSig := true
                zones.remove(i)
            else if res == 1 or bar_index - z.startBar >= WAIT_BARS
                zones.remove(i)
 
// ✧═══════════════════════✧
// ║      FINAL SIGNAL      ║
// ✧═══════════════════════✧
 
var int NJ = 0
 
if longSig and not shortSig
    NJ := 1
else if shortSig and not longSig
    NJ := -1
 
// ✧═════════════════✧
// ║      TRADES      ║
// ✧═════════════════✧
 
// One trade at a time, entry at the signal candle's close
var int   pos      = 0
var float entry    = na
var float sl       = na
var float tp       = na
var int   entryBar = na
var box   tpBox    = na
var box   slBox    = na
var int   wins     = 0
var int   losses   = 0
var float netR     = 0.0
 
bool goLong  = false
bool goShort = false
 
if barstate.isconfirmed
    // Manage the open trade (TP and SL on the same candle counts as a loss)
    if pos != 0 and bar_index > entryBar
        bool hitSL = pos == 1 ? low <= sl : high >= sl
        bool hitTP = pos == 1 ? high >= tp : low <= tp
        box.set_right(tpBox, bar_index)
        box.set_right(slBox, bar_index)
        if hitSL or hitTP
            bool  win    = hitTP and not hitSL
            float exitPx = win ? tp : sl
            netR += (win ? rr : -1.0) - (entry + exitPx) * fee / 100 / math.abs(entry - sl)
            if win
                wins += 1
            else
                losses += 1
            label.new(bar_index, exitPx, win ? "TP" : "SL", style = label.style_label_left,
                 color = color.new(win ? longCol : shortCol, 10), textcolor = color.white, size = size.tiny)
            pos := 0
 
    // Open a new trade
    if pos == 0 and longSig != shortSig
        bool  isLong = longSig
        float newSl  = isLong ? low - SL_ATR * atr : high + SL_ATR * atr
        float risk   = math.abs(close - newSl)
        if risk > 0 and close * 2 * fee / 100 / risk <= MAX_FEE_R
            goLong   := isLong
            goShort  := not isLong
            pos      := isLong ? 1 : -1
            entry    := close
            sl       := newSl
            tp       := close + (close - newSl) * rr
            entryBar := bar_index
            tpBox := box.new(bar_index, math.max(entry, tp), bar_index, math.min(entry, tp), border_color = color.new(longCol, 50), bgcolor = color.new(longCol, 80))
            slBox := box.new(bar_index, math.max(entry, sl), bar_index, math.min(entry, sl), border_color = color.new(shortCol, 50), bgcolor = color.new(shortCol, 80))
            string tip = (isLong ? "LONG" : "SHORT") +
                 "\nEntry: " + str.tostring(entry, format.mintick) +
                 "\nSL: " + str.tostring(sl, format.mintick) +
                 "\nTP: " + str.tostring(tp, format.mintick)
            label.new(bar_index, na, isLong ? "LONG" : "SHORT",
                 yloc = isLong ? yloc.belowbar : yloc.abovebar,
                 style = isLong ? label.style_label_up : label.style_label_down,
                 color = isLong ? longCol : shortCol, textcolor = color.white, size = size.small, tooltip = tip)
            alert((isLong ? "LONG " : "SHORT ") + syminfo.ticker + " " + timeframe.period +
                 " | Entry " + str.tostring(entry, format.mintick) +
                 " | SL " + str.tostring(sl, format.mintick) +
                 " | TP " + str.tostring(tp, format.mintick), alert.freq_once_per_bar_close)
 
// ✧════════════════✧
// ║      PLOTS      ║
// ✧════════════════✧
 
sigCol = NJ == 1 ? longCol : NJ == -1 ? shortCol : na
 
plotcandle(
     open, high, low, close,
     "Colored candles",
     dispCandles ? sigCol : na,
     dispCandles ? sigCol : na,
     bordercolor = dispCandles ? sigCol : na,
     display = display.all - display.status_line - display.price_scale,
     force_overlay = true)
 
// Bubbles
fmt(float v) =>
    float a = math.abs(v)
    a >= 1000 ? str.tostring(v, format.volume) : a >= 1 ? str.tostring(v, "#,##0.##") : str.tostring(v, "0.####")
 
bubbleSize(float ratio) =>
    ratio >= 5 ? size.huge : ratio >= 3 ? size.large : ratio >= 2 ? size.normal : ratio >= 1.5 ? size.small : size.tiny
 
bubble(float price, float ratio, color col, string tip) =>
    label.new(bar_index, price, "", style = label.style_circle, color = color.new(col, 50), size = bubbleSize(ratio), tooltip = tip)
 
if showBubbles and not na(benchmark) and benchmark > 0
    for r in rows
        float buyV  = volume_row.buy_volume(r)
        float sellV = volume_row.sell_volume(r)
        float buyR  = buyV / benchmark
        float sellR = sellV / benchmark
        if buyR >= 1 or sellR >= 1
            float rowUp = volume_row.up_price(r)
            float rowDn = volume_row.down_price(r)
            // Keep the bubble inside the candle
            float price = (math.min(rowUp, high) + math.max(rowDn, low)) / 2
            string tip = "Buy: " + fmt(buyV) + "  (" + str.tostring(buyR, "#.#") + "×)" +
                 "\nSell: " + fmt(sellV) + "  (" + str.tostring(sellR, "#.#") + "×)" +
                 "\nRow: " + str.tostring(rowDn, format.mintick) + " – " + str.tostring(rowUp, format.mintick)
            // Bigger bubble first so the smaller one stays visible on top
            if buyR >= sellR
                bubble(price, buyR, longCol, tip)
                if sellR >= 1
                    bubble(price, sellR, shortCol, tip)
            else
                bubble(price, sellR, shortCol, tip)
                if buyR >= 1
                    bubble(price, buyR, longCol, tip)
 
// Results table
var table stats = table.new(position.top_right, 2, 4, bgcolor = color.new(color.black, 30), border_width = 1)
if showStats and barstate.islast
    if na(fpStart)
        // No footprint data at all: tell the user why nothing shows
        table.cell(stats, 0, 0, "No volume footprint data for this chart.\nIt needs a TradingView Premium plan or higher,\nand a symbol that has volume data.", text_color = color.white, text_size = size.small)
    else
        int n = wins + losses
        table.cell(stats, 0, 0, "Trades", text_color = color.white, text_size = size.small)
        table.cell(stats, 1, 0, str.tostring(n), text_color = color.white, text_size = size.small)
        table.cell(stats, 0, 1, "Win rate", text_color = color.white, text_size = size.small)
        table.cell(stats, 1, 1, n > 0 ? str.tostring(wins * 100.0 / n, "#.#") + "%" : "–", text_color = color.white, text_size = size.small)
        table.cell(stats, 0, 2, "Profit (R)", text_color = color.white, text_size = size.small, tooltip = "Total profit after fees, counted in R. 1R = the amount risked on one trade. Example: 10R with 1% risk per trade = about +10%.")
        table.cell(stats, 1, 2, str.tostring(netR, "#.##"), text_color = color.white, text_size = size.small)
        table.cell(stats, 0, 3, "Tested since", text_color = color.white, text_size = size.small, tooltip = "Results start where TradingView's volume footprint data starts.")
        table.cell(stats, 1, 3, str.format_time(fpStart, "dd.MM.yyyy", syminfo.timezone), text_color = color.white, text_size = size.small)
 
// ✧═════════════════✧
// ║      ALERTS      ║
// ✧═════════════════✧
 
alertcondition(goLong, "Long", "{{ticker}} {{interval}}: LONG")
alertcondition(goShort, "Short", "{{ticker}} {{interval}}: SHORT")

← 返回列表