Total Waves [LTW]

LoopTheWave · study · 306 行 · 点赞 1 · TradingView 原页

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

Pine Script

//@version=6
//© LoopTheWave (Modified for 5 Tickers Stacked Volume + Watermark Auto-Align)
indicator('Total Waves [LTW]', shorttitle = '🌊TW [LTW]', overlay = false, format = format.volume)
 
// =====================================================================
// 1. Tooltip Strings
// =====================================================================
string tooltip_length = 'Wave Length Adjustment: You can adjust the smoothing length here. Using Fibonacci sequence numbers like 21, 34, or 55 will group the market\'s large volume cycles into smooth, flowing waves.\n\nLow Volatility: In consolidation zones where trading volume is minimal, the line stays completely flat near the bottom. This indicates that energy is condensing for the next expansion.\n\nVolume Spike: The wave gradually rises, peaks, and then falls. Near the absolute peak of this wave, a trend climax or Liquidity Sweep is highly probable.'
 
string tooltip_smooth = 'ALMA (Arnaud Legoux): Uses a Gaussian filter to draw an exceptionally smooth, sine-wave-like curve with minimal lag. Highly recommended for volume.\n\nHMA (Hull): Extremely fast and responsive. Eliminates lag almost completely, but can look slightly sharper on sudden spikes.\n\nEMA (Exponential): Places more weight on recent volume data. Faster than SMA.\n\nSMA (Simple): Standard average. Smooth, but suffers from the most significant lag.'
 
string tooltip_unit = 'Coin: Sums the raw volume of each ticker (base asset units). Use when all tickers share the same base asset (e.g. BTC spot pairs).\n\nUSD (Notional): Converts each ticker to volume x close before summing. Use when mixing different assets or contract units (e.g. inverse futures).'
 
string tooltip_excl = 'ON: Multiplier lines are built from the smoothed volume up to the PREVIOUS bar. Prevents a huge current bar from lifting its own threshold and hiding the breakout.\n\nOFF: v1.0 behaviour (current bar included).'
 
string tooltip_peak = 'Cluster Max: Records the highest volume inside a consecutive breakout cluster.\n\nLast Breakout: Records the volume of the most recent breakout bar (v1.0 behaviour).'
 
string tooltip_dir = 'Chart Candle: Bull/Bear is decided by the chart symbol candle.\n\nAggregated: Bull if bullish-candle volume across all enabled tickers is 50% or more.'
 
// =====================================================================
// 2. Inputs — 5 Tickers & Colors (체크박스로 개별 ON/OFF)
// =====================================================================
grp_tickers = '5 Tickers & Colors Settings'
use1 = input.bool(true, '', inline = 't1', group = grp_tickers)
sym1 = input.symbol('BINANCE:BTCUSDT', 'Ticker 1', inline = 't1', group = grp_tickers)
col1 = input.color(#f3ba2f, '', inline = 't1', group = grp_tickers)
 
use2 = input.bool(true, '', inline = 't2', group = grp_tickers)
sym2 = input.symbol('KRAKEN:BTCUSD', 'Ticker 2', inline = 't2', group = grp_tickers)
col2 = input.color(#673ab7, '', inline = 't2', group = grp_tickers)
 
use3 = input.bool(true, '', inline = 't3', group = grp_tickers)
sym3 = input.symbol('COINBASE:BTCUSDC', 'Ticker 3', inline = 't3', group = grp_tickers)
col3 = input.color(#2962ff, '', inline = 't3', group = grp_tickers)
 
use4 = input.bool(true, '', inline = 't4', group = grp_tickers)
sym4 = input.symbol('OKX:BTCUSDT', 'Ticker 4', inline = 't4', group = grp_tickers)
col4 = input.color(#2e2e2e, '', inline = 't4', group = grp_tickers)
 
use5 = input.bool(true, '', inline = 't5', group = grp_tickers)
sym5 = input.symbol('BYBIT:BTCUSDT', 'Ticker 5', inline = 't5', group = grp_tickers)
col5 = input.color(#f57c00, '', inline = 't5', group = grp_tickers)
 
volUnit = input.string('Coin', 'Volume Unit', options = ['Coin', 'USD (Notional)'], tooltip = tooltip_unit, group = grp_tickers)
bool useUSD = volUnit == 'USD (Notional)'
 
// =====================================================================
// 3. Inputs — Wave / Breakout / Direction
// =====================================================================
grp_wave = 'Wave Calculation Settings'
length         = input.int(55, title = 'Waves Length', minval = 1, tooltip = tooltip_length, group = grp_wave)
smoothTypeBase = input.string('HMA', title = 'Smoothing: Base Wave', options = ['ALMA', 'HMA', 'SMA', 'EMA'], tooltip = tooltip_smooth, group = grp_wave)
smoothTypeA    = input.string('HMA', title = 'Smoothing: Multiplier A', options = ['ALMA', 'HMA', 'SMA', 'EMA'], group = grp_wave)
smoothTypeB    = input.string('ALMA', title = 'Smoothing: Multiplier B', options = ['ALMA', 'HMA', 'SMA', 'EMA'], group = grp_wave)
excludeCur     = input.bool(true, title = 'Exclude Current Bar from Threshold', tooltip = tooltip_excl, group = grp_wave)
 
grp_breakout_mult = 'Breakout Multiplier Settings'
breakoutMultA = input.float(2.0, title = 'Multiplier A', step = 0.1, group = grp_breakout_mult)
breakoutMultB = input.float(3.0, title = 'Multiplier B', step = 0.1, group = grp_breakout_mult)
peakMode      = input.string('Cluster Max', title = 'Peak Recording Mode', options = ['Cluster Max', 'Last Breakout'], tooltip = tooltip_peak, group = grp_breakout_mult)
 
grp_dir = 'Direction Settings'
dirSource = input.string('Aggregated', title = 'Bull/Bear Source', options = ['Aggregated', 'Chart Candle'], tooltip = tooltip_dir, group = grp_dir)
 
// =====================================================================
// 4. Inputs — Watermark / Label / Background
// =====================================================================
grp_wm = 'Watermark Settings'
show_wm       = input.bool(true, title = 'Show Watermark', group = grp_wm)
wm_pos_str    = input.string('Top Right', title = 'Watermark Position', options = ['Top Right', 'Top Left', 'Bottom Right', 'Bottom Left', 'Middle Right', 'Middle Left'], group = grp_wm)
wm_size_str   = input.string('Normal', title = 'Watermark Text Size', options = ['Tiny', 'Small', 'Normal', 'Large', 'Huge'], group = grp_wm)
wm_min_transp = input.int(30, title = 'Watermark Min Transparency', minval = 0, maxval = 100, tooltip = 'Lower value = More visible/solid color when volume is low.', group = grp_wm)
 
grp_label = 'Live Label Settings'
show_lbl       = input.bool(true, title = 'Show Live Label', group = grp_label)
lblTextColor   = input.color(color.white, title = 'Label Text Color', group = grp_label)
lblTextSizeStr = input.string('Small', title = 'Label Text Size', options = ['Tiny', 'Small', 'Normal', 'Large', 'Huge'], group = grp_label)
 
grp_bg = 'Background Highlight Settings'
show_bg_pane  = input.bool(true, title = 'Highlight Breakout B (Indicator Pane)', group = grp_bg)
show_bg_chart = input.bool(false, title = 'Highlight Breakout B (Main Chart)', group = grp_bg)
bg_col_up     = input.color(color.new(#4caf50, 85), title = 'Breakout B Bull BG Color', group = grp_bg)
bg_col_dn     = input.color(color.new(#f44336, 85), title = 'Breakout B Bear BG Color', group = grp_bg)
 
// 문자열 → Pine 표준 타입 변환
f_size(string s) =>
    s == 'Tiny' ? size.tiny : s == 'Small' ? size.small : s == 'Normal' ? size.normal : s == 'Large' ? size.large : size.huge
 
string wm_pos   = wm_pos_str == 'Top Right' ? position.top_right : wm_pos_str == 'Top Left' ? position.top_left : wm_pos_str == 'Bottom Right' ? position.bottom_right : wm_pos_str == 'Bottom Left' ? position.bottom_left : wm_pos_str == 'Middle Right' ? position.middle_right : position.middle_left
string wm_size  = f_size(wm_size_str)
string lblTextSize = f_size(lblTextSizeStr)
// 위치에 따른 동적 텍스트 정렬 (우측 배치는 우측 정렬, 그 외는 좌측 정렬)
string wm_align = str.contains(wm_pos_str, 'Right') ? text.align_right : text.align_left
 
// =====================================================================
// 5. Helper Functions
// =====================================================================
format_vol(float v) =>
    string res = 'N/A'
    if not na(v)
        float v_abs = math.abs(v)
        res := v_abs >= 1e9 ? str.tostring(v / 1e9, '#.##') + 'B' : v_abs >= 1e6 ? str.tostring(v / 1e6, '#.##') + 'M' : v_abs >= 1e3 ? str.tostring(v / 1e3, '#.##') + 'K' : str.tostring(v, '#.##')
    res
 
// 모든 MA를 매 봉 계산 → 조건부 호출로 인한 히스토리 불일치 경고 제거
// HMA 오버슈트로 음수가 나오는 것을 0으로 클램프
f_smooth(float src, int len, string type) =>
    float h = ta.hma(src, len)
    float a = ta.alma(src, len, 0.85, 6)
    float e = ta.ema(src, len)
    float s = ta.sma(src, len)
    float r = type == 'HMA' ? h : type == 'ALMA' ? a : type == 'EMA' ? e : s
    na(r) ? na : math.max(r, 0.0)
 
// 티커당 request.security 1회 (거래량 + 양봉 여부를 튜플로)
f_req(string sym) =>
    request.security(sym, timeframe.period, [useUSD ? volume * close : volume, close >= open], ignore_invalid_symbol = true)
 
f_need(float x) =>
    na(x) ? 'N/A' : x > 0 ? format_vol(x) : 'Breakout!'
 
// =====================================================================
// 6. Security (Volume & Bull/Bear)
// =====================================================================
[rv1, rb1] = f_req(sym1)
[rv2, rb2] = f_req(sym2)
[rv3, rb3] = f_req(sym3)
[rv4, rb4] = f_req(sym4)
[rv5, rb5] = f_req(sym5)
 
float v1 = use1 ? nz(rv1) : 0.0
float v2 = use2 ? nz(rv2) : 0.0
float v3 = use3 ? nz(rv3) : 0.0
float v4 = use4 ? nz(rv4) : 0.0
float v5 = use5 ? nz(rv5) : 0.0
 
bool b1 = use1 and rb1
bool b2 = use2 and rb2
bool b3 = use3 and rb3
bool b4 = use4 and rb4
bool b5 = use5 and rb5
 
// =====================================================================
// 7. Sorting & Stack Levels Calculation
// =====================================================================
float[]  vols  = array.from(v1, v2, v3, v4, v5)
color[]  cols  = array.from(col1, col2, col3, col4, col5)
string[] syms  = array.from(sym1, sym2, sym3, sym4, sym5)
bool[]   bulls = array.from(b1, b2, b3, b4, b5)
bool[]   uses  = array.from(use1, use2, use3, use4, use5)
 
int[] indices = array.sort_indices(vols, order.ascending)
 
float total_vol = array.sum(vols)
 
float level5 = total_vol
float level4 = level5 - array.get(vols, array.get(indices, 4))
float level3 = level4 - array.get(vols, array.get(indices, 3))
float level2 = level3 - array.get(vols, array.get(indices, 2))
float level1 = level2 - array.get(vols, array.get(indices, 1))
 
color sorted_col5 = array.get(cols, array.get(indices, 4))
color sorted_col4 = array.get(cols, array.get(indices, 3))
color sorted_col3 = array.get(cols, array.get(indices, 2))
color sorted_col2 = array.get(cols, array.get(indices, 1))
color sorted_col1 = array.get(cols, array.get(indices, 0))
 
// 거래소 합산 방향성 (양봉 거래소들의 거래량 비중)
float bull_vol = 0.0
for i = 0 to 4
    if array.get(bulls, i)
        bull_vol += array.get(vols, i)
float bear_vol    = total_vol - bull_vol   // 켜진 티커 중 음봉 거래소 거래량
float bull_pct    = total_vol > 0 ? bull_vol / total_vol * 100 : na
float bear_pct    = total_vol > 0 ? bear_vol / total_vol * 100 : na
bool  is_dir_bull = dirSource == 'Chart Candle' ? close >= open : nz(bull_pct, 50) >= 50
 
// =====================================================================
// 8. Smoothing & Threshold Calculations
// =====================================================================
smoothed_volBase = f_smooth(total_vol, length, smoothTypeBase)
smoothed_volA    = f_smooth(total_vol, length, smoothTypeA)
smoothed_volB    = f_smooth(total_vol, length, smoothTypeB)
 
float baseA = excludeCur ? smoothed_volA[1] : smoothed_volA
float baseB = excludeCur ? smoothed_volB[1] : smoothed_volB
 
threshold_volA = baseA * breakoutMultA
threshold_volB = baseB * breakoutMultB
 
bool isBreakA = not na(threshold_volA) and total_vol >= threshold_volA
bool isBreakB = not na(threshold_volB) and total_vol >= threshold_volB
 
var float ext_levelA = na
var float ext_levelB = na
 
if isBreakA
    ext_levelA := peakMode == 'Cluster Max' and isBreakA[1] ? math.max(nz(ext_levelA), total_vol) : total_vol
if isBreakB
    ext_levelB := peakMode == 'Cluster Max' and isBreakB[1] ? math.max(nz(ext_levelB), total_vol) : total_vol
 
// =====================================================================
// 9. Plotting & Dynamic Transparency
// =====================================================================
plot(total_vol, title = 'Total Volume', color = color.gray, display = display.data_window + display.status_line)
plot(bull_pct, title = 'Bull Volume %', color = color.gray, display = display.data_window)
plot(bear_pct, title = 'Bear Volume %', color = color.gray, display = display.data_window)
 
int vol_transp = isBreakB ? 0 : isBreakA ? 40 : 80
 
plot(level5, style = plot.style_columns, color = color.new(sorted_col5, vol_transp), title = 'Volume Rank 1')
plot(level4, style = plot.style_columns, color = color.new(sorted_col4, vol_transp), title = 'Volume Rank 2')
plot(level3, style = plot.style_columns, color = color.new(sorted_col3, vol_transp), title = 'Volume Rank 3')
plot(level2, style = plot.style_columns, color = color.new(sorted_col2, vol_transp), title = 'Volume Rank 4')
plot(level1, style = plot.style_columns, color = color.new(sorted_col1, vol_transp), title = 'Volume Rank 5')
 
p_zero = plot(0, color = na, title = 'Zero Anchor', display = display.none, editable = false)
 
p_wave  = plot(smoothed_volBase, color = color.new(#2e2e2e, 90), linewidth = 1, style = plot.style_line, title = 'Wave Line')
p_multA = plot(threshold_volA, color = color.new(#808080, 90), linewidth = 1, style = plot.style_line, title = 'Mult A Line')
p_multB = plot(threshold_volB, color = color.new(#dbdbdb, 90), linewidth = 1, style = plot.style_line, title = 'Mult B Line')
 
fill(p_wave, p_zero, color = color.new(#2e2e2e, 85), title = 'Wave Area')
fill(p_multA, p_zero, color = color.new(#808080, 85), title = 'Mult A Area')
fill(p_multB, p_zero, color = color.new(#b8b8b8, 85), title = 'Mult B Area')
 
plot(ext_levelA, color = color.new(#ff9800, 30), linewidth = 1, style = plot.style_stepline, linestyle = plot.linestyle_dotted, title = 'Ext Level A (Peak)')
plot(ext_levelB, color = color.new(#591efd, 30), linewidth = 1, style = plot.style_stepline, linestyle = plot.linestyle_solid, title = 'Ext Level B (Peak)')
 
// =====================================================================
// 10. Data Window Label & Live Label
// =====================================================================
needA = threshold_volA - total_vol   // 현재 봉이 Multiplier 라인을 넘기까지 남은 거래량
needB = threshold_volB - total_vol
diffA = ext_levelA - total_vol       // 직전 Peak를 넘기까지 남은 거래량
diffB = ext_levelB - total_vol
 
plot(needA, title = 'Need to Mult A', color = color.new(color.gray, 100), display = display.data_window)
plot(needB, title = 'Need to Mult B', color = color.new(color.gray, 100), display = display.data_window)
plot(diffA, title = 'Diff to Peak A', color = color.new(color.gray, 100), display = display.data_window)
plot(diffB, title = 'Diff to Peak B', color = color.new(color.gray, 100), display = display.data_window)
 
var label diff_label = na
if barstate.islast and show_lbl
    string txt = 'Vol to Mult Line\n'
    txt += 'Mult A: ' + f_need(needA) + '\n'
    txt += 'Mult B: ' + f_need(needB) + '\n'
    txt += '─────────\n'
    txt += 'Vol to Peak\n'
    txt += 'Peak A: ' + f_need(diffA) + '\n'
    txt += 'Peak B: ' + f_need(diffB)
 
    float y_pos = math.max(nz(ext_levelA, total_vol), nz(ext_levelB, total_vol), nz(threshold_volB, total_vol))
 
    if na(diff_label)
        diff_label := label.new(bar_index, y_pos, text = txt, color = color.new(color.gray, 30), style = label.style_label_left, textcolor = lblTextColor, size = lblTextSize, textalign = text.align_left)
    else
        label.set_xy(diff_label, bar_index, y_pos)
        label.set_text(diff_label, txt)
 
// =====================================================================
// 11. Watermark Generation
// =====================================================================
var table wm_tbl = table.new(wm_pos, 1, 6, frame_color = na, frame_width = 0, border_color = na, border_width = 0, bgcolor = color.new(color.black, 100))
 
if barstate.islast and show_wm
    string sign_str   = is_dir_bull ? '+' : '-'
    color  base_color = is_dir_bull ? #089981 : #f23645
    float  g_bottom   = nz(smoothed_volBase)
    float  g_top      = math.max(nz(threshold_volB, total_vol), g_bottom + 1)
    color  grad_color = color.from_gradient(total_vol, g_bottom, g_top, color.new(base_color, wm_min_transp), base_color)
 
    string header = sign_str + format_vol(total_vol) + (na(bull_pct) ? '' : '  (Bull ' + str.tostring(bull_pct, '#.#') + '% / Bear ' + str.tostring(bear_pct, '#.#') + '%)')
    table.cell(wm_tbl, 0, 0, text = header, text_color = grad_color, text_size = wm_size, text_halign = wm_align)
 
    int row = 1
    for i = 0 to 4
        int orig_idx = array.get(indices, 4 - i)
        if array.get(uses, orig_idx)
            float  v   = array.get(vols, orig_idx)
            float  pct = total_vol > 0 ? v / total_vol * 100 : 0
            string tri = array.get(bulls, orig_idx) ? '▲ ' : '▼ '
            string display_text = tri + array.get(syms, orig_idx) + ' (' + format_vol(v) + ' / ' + str.tostring(pct, '#.##') + '%)'
            table.cell(wm_tbl, 0, row, text = display_text, text_color = array.get(cols, orig_idx), text_size = wm_size, text_halign = wm_align)
            row += 1
 
    // 꺼진 티커 자리 비우기
    if row <= 5
        for r = row to 5
            table.cell(wm_tbl, 0, r, text = '')
 
// =====================================================================
// 12. Multiplier B 돌파 배경 강조
// =====================================================================
color bg_color = isBreakB ? (is_dir_bull ? bg_col_up : bg_col_dn) : na
 
bgcolor(show_bg_pane ? bg_color : na, title = 'Breakout B Highlight (Pane)')
bgcolor(show_bg_chart ? bg_color : na, title = 'Breakout B Highlight (Main Chart)', force_overlay = true)
 
// =====================================================================
// 13. Alerts
// =====================================================================
alertcondition(isBreakA, title = 'Waves: Breakout A', message = 'Waves [LTW]: Total volume broke Multiplier A on {{ticker}} ({{interval}})')
alertcondition(isBreakB, title = 'Waves: Breakout B', message = 'Waves [LTW]: Total volume broke Multiplier B on {{ticker}} ({{interval}})')
alertcondition(isBreakB and is_dir_bull, title = 'Waves: Breakout B (Bull)', message = 'Waves [LTW]: Bullish Multiplier B breakout on {{ticker}} ({{interval}})')
alertcondition(isBreakB and not is_dir_bull, title = 'Waves: Breakout B (Bear)', message = 'Waves [LTW]: Bearish Multiplier B breakout on {{ticker}} ({{interval}})')

← 返回列表