VSA_Accumulation and Distribution_RRR

RickyRicardo18 · study · 322 行 · 点赞 20 · 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/
// © RickyRicardo18
 
//@version=6
indicator("Volume and Structure Analysis / Accumulation and Distribution_RRR ", shorttitle="VSAAD RRR", overlay=true, max_bars_back=2000, max_lines_count=500, max_boxes_count=500, max_labels_count=500)
 
// =========================================================================
// 1. INPUTS & CONFIGURATION
// =========================================================================
grp_struct = "Trend & Structural Engine"
left_bars  = input.int(5, "Pivot Left Bars", group=grp_struct, inline="pivots")
right_bars = input.int(5, "Pivot Right Bars", group=grp_struct, inline="pivots")
use_atr    = input.bool(true, "Use ATR Swing Filter", group=grp_struct)
atr_len    = input.int(14, "ATR Length", group=grp_struct, inline="atr")
atr_mult   = input.float(1.0, "ATR Multiplier", group=grp_struct, inline="atr")
ma_type    = input.string("SMA", "Regime MA Type", options=["SMA", "EMA"], group=grp_struct)
ma_len     = input.int(50, "Regime MA Length", options=[20, 50, 100, 200], group=grp_struct)
 
grp_htf    = "Higher Timeframe Filter"
use_htf    = input.bool(true, "Require HTF Alignment for Signals", group=grp_htf)
htf_res    = input.timeframe("240", "HTF Resolution (e.g., 4H)", group=grp_htf)
 
grp_vol    = "Volume Logic & Thresholds"
vol_len    = input.int(5, "Leg Comparison Lookback (N)", group=grp_vol)
acc_thresh = input.float(20.0, "Accumulation Threshold (%)", group=grp_vol)
dist_thresh= input.float(20.0, "Distribution Threshold (%)", group=grp_vol)
 
grp_surge  = "Delta Surge Markers"
use_surge  = input.bool(true, "Show Delta Surge Arrows", group=grp_surge)
surge_len  = input.int(20, "Surge Z-Score Lookback", group=grp_surge)
surge_mult = input.float(2.0, "Surge StdDev Multiplier", group=grp_surge)
 
grp_ui     = "Visuals & UI"
col_acc    = input.color(color.new(color.teal, 30), "Accumulation Setup", group=grp_ui, inline="theme")
col_dist   = input.color(color.new(color.maroon, 30), "Distribution Setup", group=grp_ui, inline="theme")
col_s_acc  = input.color(color.aqua, "Acc Surge Marker", group=grp_ui, inline="surge")
col_s_dist = input.color(color.fuchsia, "Dist Surge Marker", group=grp_ui, inline="surge")
tab_pos    = input.string(position.bottom_right, "Dashboard Position", options=[position.bottom_right, position.top_right, position.bottom_left, position.top_left], group=grp_ui)
 
grp_live   = "Live Leg Visualization"
show_live  = input.bool(true, "Highlight Live Leg Zones", group=grp_live)
 
float acc_mult  = 1.0 + (acc_thresh / 100.0)
float dist_mult = 1.0 - (dist_thresh / 100.0)
 
// =========================================================================
// 2. HIGHER TIMEFRAME (HTF) REGIME CALCULATION
// =========================================================================
get_htf_data() =>
    float base_ma = ma_type == "SMA" ? ta.sma(close, ma_len) : ta.ema(close, ma_len)
    float htf_hh = ta.highest(close, 20)[1]
    float htf_ll = ta.lowest(close, 20)[1]
    [close, base_ma, htf_hh, htf_ll]
 
[htf_c, htf_ma, htf_hh, htf_ll] = request.security(syminfo.tickerid, htf_res, get_htf_data())
string htf_regime = (htf_c > htf_hh and htf_c > htf_ma) ? "BULLISH" : (htf_c < htf_ll and htf_c < htf_ma) ? "BEARISH" : "NEUTRAL"
 
// =========================================================================
// 3. TYPES & ARRAYS
// =========================================================================
type SwingLeg
    int   start_idx
    int   end_idx
    float start_price
    float end_price
    float cum_vol
    float cum_delta
    bool  is_rally
    line  ln
 
var SwingLeg[] swings = array.new<SwingLeg>()
 
// =========================================================================
// 4. LOCAL REGIME FILTER & DELTA VARIABLES
// =========================================================================
float ma_base = ma_type == "SMA" ? ta.sma(close, ma_len) : ta.ema(close, ma_len)
float atr = ta.atr(atr_len)
 
float local_hh20 = ta.highest(close, 20)[1]
float local_ll20 = ta.lowest(close, 20)[1]
 
var int last_pivot_idx = bar_index
var float last_pivot_price = close
var int last_pivot_type = 0 
 
var float current_leg_vol = 0.0
var float current_leg_delta = 0.0
var float live_leg_hh = high
var float live_leg_ll = low
 
// =========================================================================
// 5. SWING ENGINE & DELTA SURGE CALCULATION
// =========================================================================
float ph = ta.pivothigh(high, left_bars, right_bars)
float pl = ta.pivotlow(low, left_bars, right_bars)
 
float bar_range = high - low
float buy_pct = bar_range == 0 ? 0.5 : (close - low) / bar_range
float sell_pct = bar_range == 0 ? 0.5 : (high - close) / bar_range
float bar_delta = (volume * buy_pct) - (volume * sell_pct)
 
float sum_vol_rb = math.sum(volume, right_bars)
float sum_delta_rb = math.sum(bar_delta, right_bars)
 
current_leg_vol += volume
current_leg_delta += bar_delta
 
float delta_mean = nz(ta.sma(bar_delta, surge_len))
float delta_std  = nz(ta.stdev(bar_delta, surge_len), 1.0)
 
// Inline surge plot triggers to save main body scope lines
plotshape(use_surge and (last_pivot_type == 1) and (bar_delta > (delta_mean + (delta_std * surge_mult))), title="Acc Surge", style=shape.triangleup, location=location.belowbar, color=col_s_acc, size=size.small)
plotshape(use_surge and (last_pivot_type == -1) and (bar_delta < (delta_mean - (delta_std * surge_mult))), title="Dist Surge", style=shape.triangledown, location=location.abovebar, color=col_s_dist, size=size.small)
 
if not na(ph)
    int p_idx = bar_index - right_bars
    bool atr_valid = use_atr ? (math.abs(ph - last_pivot_price) >= (atr[right_bars] * atr_mult)) : true
    
    if last_pivot_type != 1 and atr_valid
        color swing_col = color.new(col_acc, 20)
        line swing_line = line.new(last_pivot_idx, last_pivot_price, p_idx, ph, color=swing_col, width=2)
        swings.push(SwingLeg.new(last_pivot_idx, p_idx, last_pivot_price, ph, current_leg_vol, current_leg_delta, true, swing_line))
        
        current_leg_vol := sum_vol_rb 
        current_leg_delta := sum_delta_rb
        last_pivot_idx := p_idx
        last_pivot_price := ph
        last_pivot_type := 1
        live_leg_hh := high
        live_leg_ll := low
        if swings.size() > 50
            line.delete(swings.shift().ln)
 
if not na(pl)
    int p_idx = bar_index - right_bars
    bool atr_valid = use_atr ? (math.abs(last_pivot_price - pl) >= (atr[right_bars] * atr_mult)) : true
    
    if last_pivot_type != -1 and atr_valid
        color swing_col = color.new(col_dist, 20)
        line swing_line = line.new(last_pivot_idx, last_pivot_price, p_idx, pl, color=swing_col, width=2)
        swings.push(SwingLeg.new(last_pivot_idx, p_idx, last_pivot_price, pl, current_leg_vol, current_leg_delta, false, swing_line))
        
        current_leg_vol := sum_vol_rb
        current_leg_delta := sum_delta_rb
        last_pivot_idx := p_idx
        last_pivot_price := pl
        last_pivot_type := -1
        live_leg_hh := high
        live_leg_ll := low
        if swings.size() > 50
            line.delete(swings.shift().ln)
 
live_leg_hh := math.max(live_leg_hh, high)
live_leg_ll := math.min(live_leg_ll, low)
 
// =========================================================================
// 6. VOLUME SPREAD ANALYSIS (VSA) LOGIC
// =========================================================================
method get_avg_vol(SwingLeg[] arr, bool type_rally, int lookback) =>
    float sum_vol = 0.0
    int count = 0
    if arr.size() > 0
        for i = arr.size() - 1 to 0
            if arr.get(i).is_rally == type_rally
                sum_vol += arr.get(i).cum_vol
                count += 1
                if count >= lookback
                    break
    count > 0 ? (sum_vol / count) : 0.0
 
method get_avg_duration(SwingLeg[] arr, bool type_rally, int lookback) =>
    int sum_bars = 0
    int count = 0
    if arr.size() > 0
        for i = arr.size() - 1 to 0
            if arr.get(i).is_rally == type_rally
                sum_bars += (arr.get(i).end_idx - arr.get(i).start_idx)
                count += 1
                if count >= lookback
                    break
    count > 0 ? (sum_bars / count) : 1
 
float avg_rally_vol  = swings.get_avg_vol(true, vol_len)
float avg_drop_vol   = swings.get_avg_vol(false, vol_len)
int   avg_rally_bars = swings.get_avg_duration(true, vol_len)
int   avg_drop_bars  = swings.get_avg_duration(false, vol_len)
 
int   live_leg_bars = math.max(1, bar_index - last_pivot_idx)
float live_run_rate = current_leg_vol / live_leg_bars
 
bool is_live_climax    = false
bool is_live_no_demand = false
bool is_early_acc      = false
bool is_early_dist     = false
float live_vol_pct     = 0.0
 
if last_pivot_type == 1 
    live_vol_pct := avg_drop_vol > 0 ? (current_leg_vol / avg_drop_vol) * 100 : 0
    if avg_drop_vol > 0 and current_leg_vol > (avg_drop_vol * acc_mult)
        is_live_climax := true
        if current_leg_delta > 0
            is_early_acc := true
 
if last_pivot_type == -1 
    live_vol_pct := avg_rally_vol > 0 ? (current_leg_vol / avg_rally_vol) * 100 : 0
    float expected_rally_run_rate = avg_rally_bars > 0 ? avg_rally_vol / avg_rally_bars : 0
    if live_leg_bars >= 3 and expected_rally_run_rate > 0 and live_run_rate < (expected_rally_run_rate * dist_mult)
        is_live_no_demand := true
        if current_leg_delta < 0
            is_early_dist := true
 
bool is_accumulation_setup = false
bool is_distribution_setup = false
 
if swings.size() >= 3
    SwingLeg last_leg = swings.last()
    SwingLeg prev_leg = swings.get(swings.size() - 2)
    
    if not last_leg.is_rally and prev_leg.is_rally == false 
        if prev_leg.cum_vol > (avg_drop_vol * acc_mult)
            is_accumulation_setup := true
            
    if last_leg.is_rally and prev_leg.is_rally
        if prev_leg.cum_vol < (avg_rally_vol * dist_mult)
            is_distribution_setup := true
 
// =========================================================================
// 7. CHART VISUALS & SETUP ZONES
// =========================================================================
var box live_box = na
var label live_label = na
 
if show_live
    color live_col = is_early_acc ? col_acc : is_early_dist ? col_dist : is_live_climax ? color.new(col_acc, 40) : is_live_no_demand ? color.new(col_dist, 40) : color.new(color.gray, 90)
    string live_text = is_early_acc ? "Strong Accumulation" : is_early_dist ? "Strong Distribution" : is_live_climax ? "Accumulation Setup" : is_live_no_demand ? "Distribution Setup" : ""
    
    float lbl_y = last_pivot_type == 1 ? live_leg_ll : live_leg_hh
    string lbl_style = last_pivot_type == 1 ? label.style_label_up : label.style_label_down
    color lbl_bg_col = live_text == "" ? color.new(color.white, 100) : live_col
    color lbl_txt_col = live_text == "" ? color.new(color.white, 100) : color.white
    
    if na(live_box)
        live_box := box.new(last_pivot_idx, live_leg_hh, bar_index, live_leg_ll, border_color=color.new(live_col, 50), bgcolor=color.new(live_col, 90), border_style=line.style_dotted)
        live_label := label.new(bar_index, lbl_y, live_text, style=lbl_style, color=lbl_bg_col, textcolor=lbl_txt_col, size=size.small)
    else
        box.set_left(live_box, last_pivot_idx)
        box.set_top(live_box, live_leg_hh)
        box.set_right(live_box, bar_index)
        box.set_bottom(live_box, live_leg_ll)
        box.set_bgcolor(live_box, color.new(live_col, 90))
        box.set_border_color(live_box, color.new(live_col, 50))
        
        label.set_x(live_label, bar_index)
        label.set_y(live_label, lbl_y)
        label.set_text(live_label, live_text)
        label.set_color(live_label, lbl_bg_col)
        label.set_textcolor(live_label, lbl_txt_col)
        label.set_style(live_label, lbl_style)
 
var float acc_level = na
var float dist_level = na
 
if is_accumulation_setup and not na(ph)
    acc_level := ph
    box.new(last_pivot_idx, ph, bar_index, pl, border_color=col_acc, border_width=2, border_style=line.style_solid, bgcolor=color.new(col_acc, 85), text="ACC ZN", text_color=color.new(col_acc, 30), text_halign=text.align_right, text_valign=text.align_bottom, text_size=size.small)
 
if is_distribution_setup and not na(pl)
    dist_level := pl
    box.new(last_pivot_idx, ph, bar_index, pl, border_color=col_dist, border_width=2, border_style=line.style_solid, bgcolor=color.new(col_dist, 85), text="DIST ZN", text_color=color.new(col_dist, 30), text_halign=text.align_right, text_valign=text.align_top, text_size=size.small)
 
bool trigger_acc = ta.crossover(close, acc_level) and (not use_htf or htf_regime == "BULLISH")
bool trigger_dist = ta.crossunder(close, dist_level) and (not use_htf or htf_regime == "BEARISH")
 
if trigger_acc
    label.new(bar_index, low, "🚀 ACC BREAKOUT", style=label.style_label_up, color=col_acc, textcolor=color.white, size=size.normal)
    acc_level := na 
 
if trigger_dist
    label.new(bar_index, high, "🩸 DIST BREAKDOWN", style=label.style_label_down, color=col_dist, textcolor=color.white, size=size.normal)
    dist_level := na 
 
// =========================================================================
// 8. DASHBOARD (WIDGET UI) - ENCAPSULATED TO CLEAR COMPILER LIMITS
// =========================================================================
var table dash = table.new(tab_pos, 2, 6, bgcolor=color.new(color.black, 40), border_width=1, border_color=color.gray)
 
draw_dashboard(table t, string res, string h_reg, bool h_hh, bool h_ll, float ma, int p_type, float v_pct, float dlt, bool e_acc, bool e_dist, bool l_clim, bool l_nod, float a_lvl, float d_lvl) =>
    if barstate.islast
        table.cell(t, 0, 0, "VSA ENGINE", text_color=color.white, text_halign=text.align_center, bgcolor=color.new(color.gray, 80))
        table.merge_cells(t, 0, 0, 1, 0)
 
        string regime = (h_hh and close > ma) ? "BULLISH" : (h_ll and close < ma) ? "BEARISH" : "NEUTRAL"
        string trend_txt = res + ": " + h_reg + " | Local: " + regime
        string dash_swing = (p_type == -1 ? "Rallying" : p_type == 1 ? "Dropping" : "Forming") + " (" + str.tostring(v_pct, "#") + "% Vol)"
        string dash_delta = dlt > 0 ? "Buyers Control" : dlt < 0 ? "Sellers Control" : "Neutral"
        color delta_col = dlt > 0 ? col_acc : dlt < 0 ? col_dist : color.white
        string dash_vsa = e_acc ? "Strong Accumulation" : e_dist ? "Strong Distribution" : l_clim ? "Accumulation Setup" : l_nod ? "Distribution Setup" : "Normal"
        color vsa_col = e_acc or l_clim ? col_acc : e_dist or l_nod ? col_dist : color.silver
        string dash_level = not na(a_lvl) ? "> " + str.tostring(a_lvl, format.mintick) : not na(d_lvl) ? "< " + str.tostring(d_lvl, format.mintick) : "Waiting for Setup"
        color lvl_col = not na(a_lvl) ? col_acc : not na(d_lvl) ? col_dist : color.silver
 
        table.cell(t, 0, 1, "Trend Align:", text_color=color.silver, text_halign=text.align_left)
        table.cell(t, 1, 1, trend_txt, text_color=color.white, text_halign=text.align_right)
        table.cell(t, 0, 2, "Current Swing:", text_color=color.silver, text_halign=text.align_left)
        table.cell(t, 1, 2, dash_swing, text_color=color.white, text_halign=text.align_right)
        table.cell(t, 0, 3, "Internal Delta:", text_color=color.silver, text_halign=text.align_left)
        table.cell(t, 1, 3, dash_delta, text_color=delta_col, text_halign=text.align_right)
        table.cell(t, 0, 4, "Live VSA Status:", text_color=color.silver, text_halign=text.align_left)
        table.cell(t, 1, 4, dash_vsa, text_color=vsa_col, text_halign=text.align_right)
        table.cell(t, 0, 5, "Breakout Target:", text_color=color.silver, text_halign=text.align_left)
        table.cell(t, 1, 5, dash_level, text_color=lvl_col, text_halign=text.align_right)
 
// Execute the encapsulated dashboard rendering
draw_dashboard(dash, htf_res, htf_regime, close > local_hh20, close < local_ll20, ma_base, last_pivot_type, live_vol_pct, current_leg_delta, is_early_acc, is_early_dist, is_live_climax, is_live_no_demand, acc_level, dist_level)
 
// =========================================================================
// 9. ALERTS
// =========================================================================
alertcondition(trigger_acc, title="Accumulation Breakout", message="[VSA] {{ticker}} Accumulation Triggered on {{interval}}")
alertcondition(trigger_dist, title="Distribution Breakdown", message="[VSA] {{ticker}} Distribution Triggered on {{interval}}")
alertcondition(is_early_acc, title="Early Accumulation Warning", message="[VSA] {{ticker}} Institutional absorption detected (Delta +) on forming drop.")
alertcondition(is_early_dist, title="Early Distribution Warning", message="[VSA] {{ticker}} Institutional selling detected (Delta -) on forming rally.")

← 返回列表