CandelaCharts - Auto Anchored Footprint

CandelaCharts · study · 899 行 · 点赞 249 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CandelaCharts
 
//@version=6
indicator("CandelaCharts - Auto Anchored Footprint", shorttitle = "CandelaCharts - Auto Anchored Footprint", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_bars_back = 5000)
 
 
 
 
 
 
 
 
 
 
 
// # ========================================================================= #
// # |   Colors   | #
// # ========================================================================= #
 
//#region
 
colors_white                        = color.white
colors_black                        = color.black
colors_purple                       = color.purple
colors_red                          = color.red
colors_gray                         = color.gray
colors_blue                         = color.blue
colors_orange                       = color.orange
colors_green                        = color.green
colors_teal                         = color.teal
colors_aqua                         = color.aqua
colors_yellow                       = color.yellow
colors_navy                         = color.navy
colors_brown                        = #C69C6D
colors_pink                         = #FF69B4
colors_cyan                         = #00BCD4
color_transparent                   = #ffffff00
 
//#endregion
 
// # ========================================================================= #
// # |   End   | #
// # ========================================================================= #
 
 
 
 
 
 
 
 
 
 
// # ========================================================================= #
// # |   Inputs   | #
// # ========================================================================= #
 
//#region
 
general_font                        = input.string("Monospace", "Text                        ", options = ["Default", "Monospace"], inline = "1.0", group = "General")
general_text                        = input.string("Tiny", "", options = ["Tiny", "Small", "Normal", "Large", "Huge", "Auto"], inline = "1.0", group = "General", tooltip = "Customize global text size")
general_brand_show                  = input.bool(false, "Hide Brand", group = "General")
 
aaf_anchor_mode                     = input.string("Visible Window", "Anchor Mode         ", options = ["Visible Window", "Fixed Lookback Bars"], group = "Anchor & Window", tooltip = "'Visible Window' automatically recalculates the footprint profile for the exact viewport on screen as you pan, scroll, or zoom across history.")
aaf_fixed_lookback                  = input.int(100, "Lookback Bars       ", minval = 10, maxval = 2000, group = "Anchor & Window", tooltip = "Used only when Anchor Mode is set to 'Fixed Lookback Bars'.")
aaf_ltf_source                      = input.timeframe("1", "LTF Source         ", group = "Anchor & Window", tooltip = "Lower timeframe intra-bar data used to resolve Bid x Ask order flow distribution. Automatically falls back cleanly to chart timeframe price action if historical depth is exhausted.")
aaf_row_resolution                  = input.int(40, "Row Resolution     ", minval = 10, maxval = 80, group = "Anchor & Window", tooltip = "Number of vertical price bins in the footprint profile.")
 
aaf_fp_placement                    = input.string("Right Edge", "Placement          ", options = ["Right Edge", "Left Edge"], group = "Footprint Ladder", tooltip = "'Right Edge' pins the ladder adjacent to the rightmost candle currently visible on screen (even when scrolling back into history). 'Left Edge' pins it to the left edge of the screen.")
aaf_fp_offset                       = input.int(6, "Offset Bars        ", minval = 0, maxval = 100, group = "Footprint Ladder", tooltip = "Horizontal separation (in bars) between the visible edge and the footprint ladder.")
aaf_fp_width_bars                   = input.int(26, "Footprint Width    ", minval = 8, maxval = 80, step = 2, group = "Footprint Ladder", tooltip = "Total horizontal bar width allocated for the Bid x Ask footprint ladder.")
aaf_fp_scale_mode                   = input.string("Linear", "Volume Scaling      ", options = ["Square Root", "Logarithmic", "Linear"], group = "Footprint Ladder", tooltip = "'Square Root' balances high-volume POC clusters with clear differentiation across lower-volume rows. 'Logarithmic' provides maximum low-end expansion.")
aaf_fp_num_mode                     = input.string("All Rows", "Number Display     ", options = ["All Rows", "Significant Only (> Avg)", "POC Only", "Imbalances Only"], group = "Footprint Ladder")
aaf_fp_show_numbers                 = input.bool(true, "Show Volume Numbers", group = "Footprint Ladder", tooltip = "Overlays numerical Bid x Ask volume on each footprint row.")
aaf_fp_compact_num                  = input.bool(true, "Abbreviate Large (K/M)", group = "Footprint Ladder", tooltip = "Abbreviates volumes >= 1,000 as 1.5K and >= 1,000,000 as 1.2M.")
aaf_fp_gradient                     = input.bool(true, "Volume Gradient", group = "Footprint Ladder", tooltip = "Applies dynamic color gradients to the footprint bars based on volume intensity.")
 
aaf_va_percent                      = input.float(70.0, "Value Area %       ", minval = 50.0, maxval = 95.0, step = 5.0, group = "Auction Market Levels")
aaf_va_show                         = input.bool(true, "Show Value Area", group = "Auction Market Levels", tooltip = "Highlights the Value Area containing 70% of total visible traded volume.")
aaf_poc_highlight                   = input.bool(true, "Highlight POC", group = "Auction Market Levels", tooltip = "Emphasizes the price bin with the highest total traded volume (POC).")
aaf_extend_levels                   = input.bool(true, "Extend Levels", group = "Auction Market Levels", tooltip = "Extends POC, VAH, and VAL horizontal reference lines across the entire visible chart window.")
aaf_show_level_labels               = input.bool(true, "POC / VAH / VAL Labels   ", group = "Auction Market Levels")
aaf_level_label_price               = input.bool(true, "Include Price", group = "Auction Market Levels")
 
aaf_imbalance_highlight             = input.bool(true, "Highlight Imbalances", group = "Order Flow Imbalances", tooltip = "Emphasizes aggressive diagonal buying or selling volume imbalances across adjacent price bins with accent borders.")
aaf_imbalance_ratio                 = input.float(3.0, "Imbalance Ratio    ", minval = 1.5, maxval = 10.0, step = 0.5, group = "Order Flow Imbalances", tooltip = "Threshold multiplier (e.g., 3.0 means buying volume is at least 300% of opposing diagonal selling volume).")
aaf_imbalance_min_vol               = input.float(0.0, "Min Imbalance Vol  ", minval = 0.0, group = "Order Flow Imbalances", tooltip = "Filters out low-volume noise from imbalance detection.")
 
aaf_theme_style                     = input.string("Teal - Red", "Theme                  ", options = ["Teal - Red", "Teal - Orange", "Teal - Navy", "Green - Red", "Blue - Orange", "Blue - Pink", "Cyan - Purple", "Brown - Black", "Custom"], group = "Themes & Styles")
aaf_custom_bull_css                 = input.color(colors_teal, "Bull / Bear                ", inline = "c1", group = "Themes & Styles", tooltip = "Ask (bull) and Bid (bear) colors, used when Theme is set to Custom.")
aaf_custom_bear_css                 = input.color(colors_red, "", inline = "c1", group = "Themes & Styles")
aaf_poc_color                       = input.color(colors_yellow, "POC / Value Area       ", inline = "c2", group = "Themes & Styles")
aaf_va_color                        = input.color(colors_gray, "", inline = "c2", group = "Themes & Styles")
aaf_num_color                       = input.color(colors_black, "Numbers", group = "Themes & Styles")
 
//#endregion
 
// # ========================================================================= #
// # |   End   | #
// # ========================================================================= #
 
 
 
 
 
 
 
 
 
 
// # ========================================================================= #
// # |   UDT   | #
// # ========================================================================= #
 
//#region
 
type UDT_Store
    line[]      bin_lines
    box[]       bin_boxes
    label[]     bin_labels
 
type UDT_Layout
    int         ladder_left
    int         ladder_right
    int         fp_center
    int         half_fp_bars
 
type UDT_Palette
    color       bid_bg_hi
    color       bid_bg_lo
    color       bid_bd_hi
    color       bid_bd_lo
    color       ask_bg_hi
    color       ask_bg_lo
    color       ask_bd_hi
    color       ask_bd_lo
    color       bid_solid_bg
    color       bid_solid_bd
    color       ask_solid_bg
    color       ask_solid_bd
 
type UDT_ProfileStats
    float       tot_vol
    float       buy_vol
    float       sell_vol
    float       net_delta
    float       delta_pct
    float       poc_price
    int         poc_bin
    float       vah_price
    float       val_price
    int         va_high_bin
    int         va_low_bin
    float       max_side_vol
    float       avg_bin_vol
    int         buy_imb_count
    int         sell_imb_count
 
type UDT_ProfileBins
    array<float>    bin_lows
    array<float>    bin_highs
    array<float>    bid_vols
    array<float>    ask_vols
    array<float>    tot_vols
    array<float>    deltas
    array<bool>     buy_imbalances
    array<bool>     sell_imbalances
 
//#endregion
 
// # ========================================================================= #
// # |   End   | #
// # ========================================================================= #
 
 
 
 
 
 
 
 
 
 
// # ========================================================================= #
// # |   Functions   | #
// # ========================================================================= #
 
//#region
 
method text_size(string size) =>
    switch size
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        "Huge"   => size.huge
        "Auto"   => size.auto
 
method font_style(string font) =>
    switch font
        "Default"   => font.family_default
        "Monospace" => font.family_monospace
 
method table_position(string pos) =>
    switch pos
        "Top Right"    => position.top_right
        "Bottom Right" => position.bottom_right
        "Top Left"     => position.top_left
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
is_dark() =>
    chart.bg_color == color.black or chart.bg_color == #131722
 
format_volume(float vol, bool compact) =>
    if not compact
        str.tostring(math.round(vol))
    else if vol >= 1000000000
        str.tostring(vol / 1000000000, "#.##") + "B"
    else if vol >= 1000000
        str.tostring(vol / 1000000, "#.#") + "M"
    else if vol >= 1000
        str.tostring(vol / 1000, "#.#") + "K"
    else
        str.tostring(math.round(vol))
 
pad_volume(string txt) =>
    int len = str.length(txt)
    switch
        len == 1 => "   "
        len == 2 => "  "
        len == 3 => " "
        => ""
 
format_bid_ask(float bid_v, float ask_v, bool compact) =>
    string s_bid = format_volume(bid_v, compact)
    string s_ask = format_volume(ask_v, compact)
    pad_volume(s_bid) + s_bid + " " + s_ask + pad_volume(s_ask)
 
calc_volume_ratio(float vol, float ref_max, string mode) =>
    float ratio = 0.0
    if vol > 0.0 and ref_max > 0.0
        float raw = math.min(1.0, vol / ref_max)
        ratio := switch mode
            "Square Root" => math.sqrt(raw)
            "Logarithmic" => math.log(1.0 + 9.0 * raw) / math.log(10.0)
            "Linear"      => raw
            => math.sqrt(raw)
    ratio
 
bar_length(float ratio, int half_bars) =>
    int(math.max(1, math.round(ratio * half_bars)))
 
bar_colors(UDT_Palette pal, bool is_bid, float ratio, bool use_gradient) =>
    color bg = is_bid ? pal.bid_solid_bg : pal.ask_solid_bg
    color bd = is_bid ? pal.bid_solid_bd : pal.ask_solid_bd
 
    if use_gradient
        bg := color.from_gradient(ratio, 0.0, 1.0, is_bid ? pal.bid_bg_lo : pal.ask_bg_lo, is_bid ? pal.bid_bg_hi : pal.ask_bg_hi)
        bd := color.from_gradient(ratio, 0.0, 1.0, is_bid ? pal.bid_bd_lo : pal.ask_bd_lo, is_bid ? pal.bid_bd_hi : pal.ask_bd_hi)
 
    [bg, bd]
 
get_theme_palette(string theme, color custom_bull, color custom_bear) =>
    color bull_c = switch theme
        "Teal - Navy"   => colors_teal
        "Teal - Orange" => colors_teal
        "Teal - Red"    => colors_teal
        "Blue - Orange" => colors_blue
        "Green - Red"   => colors_green
        "Brown - Black" => colors_brown
        "Blue - Pink"   => colors_blue
        "Cyan - Purple" => colors_cyan
        => custom_bull
    color bear_c = switch theme
        "Teal - Navy"   => colors_navy
        "Teal - Orange" => colors_orange
        "Teal - Red"    => colors_red
        "Blue - Orange" => colors_orange
        "Green - Red"   => colors_red
        "Brown - Black" => colors_black
        "Blue - Pink"   => colors_pink
        "Cyan - Purple" => colors_purple
        => custom_bear
    [bull_c, bear_c]
 
new_palette(color bull_c, color bear_c) =>
    UDT_Palette.new(
       bid_bg_hi = color.new(bear_c, 15),
       bid_bg_lo = color.new(bear_c, 75),
       bid_bd_hi = color.new(bear_c, 20),
       bid_bd_lo = color.new(bear_c, 60),
       ask_bg_hi = color.new(bull_c, 15),
       ask_bg_lo = color.new(bull_c, 75),
       ask_bd_hi = color.new(bull_c, 20),
       ask_bd_lo = color.new(bull_c, 60),
       bid_solid_bg = color.new(bear_c, 25),
       bid_solid_bd = color.new(bear_c, 45),
       ask_solid_bg = color.new(bull_c, 25),
       ask_solid_bd = color.new(bull_c, 45)
       )
 
make_box(int left, float top, int right, float bottom, color bg, color border, int border_width) =>
    box.new(left = left, top = top, right = right, bottom = bottom, bgcolor = bg, border_color = border, border_width = border_width)
 
make_line(int x1, float y1, int x2, float y2, color css, int width, string ln_style = line.style_solid) =>
    line.new(x1 = x1, y1 = y1, x2 = x2, y2 = y2, color = css, width = width, style = ln_style)
 
make_label(int x, float y, string txt, color txt_color, string lbl_style, string size_name, string font_name, string tip = "") =>
    label.new(
       x = x,
       y = y,
       text = txt,
       tooltip = tip,
       color = color_transparent,
       textcolor = txt_color,
       style = lbl_style,
       size = text_size(size_name),
       text_font_family = font_style(font_name)
       )
 
//#endregion
 
// # ========================================================================= #
// # |   End   | #
// # ========================================================================= #
 
 
 
 
 
 
 
 
 
 
// # ========================================================================= #
// # |   Store   | #
// # ========================================================================= #
 
//#region
 
var UDT_Store store = UDT_Store.new(
   bin_lines = array.new<line>(),
   bin_boxes = array.new<box>(),
   bin_labels = array.new<label>()
   )
 
method clean(UDT_Store s) =>
    for obj in s.bin_lines
        obj.delete()
    for obj in s.bin_boxes
        obj.delete()
    for obj in s.bin_labels
        obj.delete()
    s.bin_lines.clear()
    s.bin_boxes.clear()
    s.bin_labels.clear()
 
//#endregion
 
// # ========================================================================= #
// # |   End   | #
// # ========================================================================= #
 
 
 
 
 
 
 
 
 
 
// # ========================================================================= #
// # |   Variables   | #
// # ========================================================================= #
 
//#region
 
// Dynamic intra-bar tape accumulation across visible window
var array<float> tape_c = array.new<float>()
var array<float> tape_o = array.new<float>()
var array<float> tape_h = array.new<float>()
var array<float> tape_l = array.new<float>()
var array<float> tape_v = array.new<float>()
 
// Visible range boundary metrics
var float win_high = -1.0e10
var float win_low = 1.0e10
var int win_left_idx = 999999999
var int win_right_idx = -999999999
var int win_left_time = 0
var int win_right_time = 0
var int win_bars_count = 0
var float win_total_vol = 0.0
var int hist_tape_size = 0
 
[theme_bull_color, theme_bear_color] = get_theme_palette(aaf_theme_style, aaf_custom_bull_css, aaf_custom_bear_css)
palette = new_palette(theme_bull_color, theme_bear_color)
 
//#endregion
 
// # ========================================================================= #
// # |   End   | #
// # ========================================================================= #
 
 
 
 
 
 
 
 
 
 
// # ========================================================================= #
// # |   Constants   | #
// # ========================================================================= #
 
//#region
 
const string default_tz = "America/New_York"
 
// Pine caps a single array at 100,000 elements: the visible window therefore shares a
// fixed intra-bar sample budget, with a hard ceiling kept as a last line of defense.
const int tape_budget_samples = 30000
const int tape_hard_limit = 90000
 
//#endregion
 
// # ========================================================================= #
// # |   End   | #
// # ========================================================================= #
 
 
 
 
 
 
 
 
 
 
// # ========================================================================= #
// # |   Core Logic   | #
// # ========================================================================= #
 
//#region
 
// Timeframe Validation
ltf_valid = timeframe.in_seconds(timeframe.period) >= timeframe.in_seconds(aaf_ltf_source)
 
// Lower Timeframe Data Request
[ltf_cL, ltf_oP, ltf_hI, ltf_lO, ltf_vO] = request.security_lower_tf("", ltf_valid ? aaf_ltf_source : timeframe.period, [close, open, high, low, volume])
 
// Window Boundary Resolution
bool has_visible_bounds = not na(chart.left_visible_bar_time) and chart.left_visible_bar_time > 0
int left_boundary_time = has_visible_bounds ? chart.left_visible_bar_time : time[math.min(bar_index, aaf_fixed_lookback)]
int right_boundary_time = not na(chart.right_visible_bar_time) and chart.right_visible_bar_time > 0 ? chart.right_visible_bar_time : time
 
// Tape Budget Resolution
// The window's bar span is an upper bound of how many bars will feed the tape, so each
// bar may only contribute its slice of the budget. Wider windows or lower LTF sources
// coarsen the intra-bar resolution instead of overflowing the arrays.
int chart_tf_secs = timeframe.in_seconds(timeframe.period)
int ltf_tf_secs = timeframe.in_seconds(ltf_valid ? aaf_ltf_source : timeframe.period)
int window_span_bars = aaf_anchor_mode == "Visible Window" and has_visible_bounds ? int(math.ceil((right_boundary_time - left_boundary_time) / (chart_tf_secs * 1000.0))) + 1 : aaf_fixed_lookback + 1
window_span_bars := math.max(1, window_span_bars)
int ltf_per_bar_max = math.max(1, int(math.ceil(chart_tf_secs / float(math.max(1, ltf_tf_secs)))))
int tape_cap_per_bar = math.max(1, math.min(ltf_per_bar_max, int(tape_budget_samples / float(window_span_bars))))
 
bool is_in_window = false
if aaf_anchor_mode == "Visible Window"
    if has_visible_bounds
        is_in_window := (time >= left_boundary_time and time <= right_boundary_time)
    else
        is_in_window := (bar_index >= last_bar_index - aaf_fixed_lookback)
else
    is_in_window := (bar_index >= last_bar_index - aaf_fixed_lookback)
 
// Reset state on chart re-execution (triggered automatically when user scrolls/zooms)
if barstate.isfirst
    tape_c.clear()
    tape_o.clear()
    tape_h.clear()
    tape_l.clear()
    tape_v.clear()
    win_high := -1.0e10
    win_low := 1.0e10
    win_left_idx := 999999999
    win_right_idx := -999999999
    win_left_time := 0
    win_right_time := 0
    win_bars_count := 0
    win_total_vol := 0.0
    hist_tape_size := 0
 
// Accumulate visible bars data
if is_in_window
    // Tick-safe rollback on real-time bar updates
    if barstate.islast
        while tape_c.size() > hist_tape_size
            tape_c.pop()
            tape_o.pop()
            tape_h.pop()
            tape_l.pop()
            tape_v.pop()
 
    win_high := math.max(win_high, high)
    win_low := math.min(win_low, low)
    win_left_idx := math.min(win_left_idx, bar_index)
    win_right_idx := math.max(win_right_idx, bar_index)
    if win_left_time == 0
        win_left_time := time
    win_right_time := time
    win_bars_count += 1
    win_total_vol += nz(volume)
 
    // Ingest LTF tape samples with automatic fallback
    if not na(ltf_cL) and ltf_cL.size() > 0
        int ltf_n = ltf_cL.size()
        if ltf_n <= tape_cap_per_bar
            for i = 0 to ltf_n - 1
                if tape_c.size() >= tape_hard_limit
                    break
                tape_c.push(ltf_cL.get(i))
                tape_o.push(ltf_oP.get(i))
                tape_h.push(ltf_hI.get(i))
                tape_l.push(ltf_lO.get(i))
                tape_v.push(ltf_vO.get(i))
        else
            // Group the bar's LTF samples into OHLCV slices: traded volume and the price
            // envelope are preserved, only the intra-bar resolution is coarsened.
            int grp = int(math.max(1, math.ceil(ltf_n / float(tape_cap_per_bar))))
            int grp_cnt = int(math.ceil(ltf_n / float(grp)))
            for g = 0 to grp_cnt - 1
                if tape_c.size() >= tape_hard_limit
                    break
                int g_from = g * grp
                int g_to = math.min(ltf_n - 1, g_from + grp - 1)
                float g_high = ltf_hI.get(g_from)
                float g_low = ltf_lO.get(g_from)
                float g_vol = 0.0
                for k = g_from to g_to
                    g_high := math.max(g_high, ltf_hI.get(k))
                    g_low := math.min(g_low, ltf_lO.get(k))
                    g_vol += nz(ltf_vO.get(k))
                tape_c.push(ltf_cL.get(g_to))
                tape_o.push(ltf_oP.get(g_from))
                tape_h.push(g_high)
                tape_l.push(g_low)
                tape_v.push(g_vol)
    else
        if tape_c.size() < tape_hard_limit
            tape_c.push(close)
            tape_o.push(open)
            tape_h.push(high)
            tape_l.push(low)
            tape_v.push(nz(volume))
 
    if not barstate.islast or barstate.isconfirmed
        hist_tape_size := tape_c.size()
 
// Initialize profile bins
method seed_profile_bins(UDT_ProfileBins bins, int num_rows, float p_low, float step) =>
    for r = 0 to num_rows - 1
        float b_low = p_low + r * step
        bins.bin_lows.push(b_low)
        bins.bin_highs.push(b_low + step)
        bins.bid_vols.push(0.0)
        bins.ask_vols.push(0.0)
        bins.tot_vols.push(0.0)
        bins.deltas.push(0.0)
        bins.buy_imbalances.push(false)
        bins.sell_imbalances.push(false)
 
// Distribute LTF sample across price bins
method add_tape_slice(UDT_ProfileBins bins, int num_rows, float p_low, float step, int idx) =>
    float s_close = tape_c.get(idx)
    float s_open = tape_o.get(idx)
    float s_high = tape_h.get(idx)
    float s_low = tape_l.get(idx)
    float s_vol = tape_v.get(idx)
 
    bool is_buy = s_close > s_open
    bool is_sell = s_close < s_open
    float buy_v = is_buy ? s_vol : is_sell ? 0.0 : s_vol * 0.5
    float sell_v = is_sell ? s_vol : is_buy ? 0.0 : s_vol * 0.5
 
    float s_range = s_high - s_low
    if s_range <= 0.0
        int b_idx = int(math.floor((s_close - p_low) / step))
        int target = math.max(0, math.min(num_rows - 1, b_idx))
        bins.bid_vols.set(target, bins.bid_vols.get(target) + sell_v)
        bins.ask_vols.set(target, bins.ask_vols.get(target) + buy_v)
    else
        // Only bins overlapping the slice's price envelope can receive volume
        int lo_bin = math.max(0, int(math.floor((s_low - p_low) / step)))
        int hi_bin = math.min(num_rows - 1, int(math.floor((s_high - p_low) / step)))
        for r = lo_bin to hi_bin
            float overlap = math.min(s_high, bins.bin_highs.get(r)) - math.max(s_low, bins.bin_lows.get(r))
            if overlap > 0.0
                float frac = overlap / s_range
                bins.bid_vols.set(r, bins.bid_vols.get(r) + sell_v * frac)
                bins.ask_vols.set(r, bins.ask_vols.get(r) + buy_v * frac)
 
// Resolve order flow statistics, POC, delta, and imbalance metrics
method calculate_profile_stats(UDT_ProfileBins bins, int num_rows, float step, float imb_ratio, float min_imb_vol) =>
    float sum_tot = 0.0
    float sum_buy = 0.0
    float sum_sell = 0.0
    float max_bin = 0.0
    float max_side = 0.0
    int poc_bin = 0
 
    for r = 0 to num_rows - 1
        float b_vol = bins.bid_vols.get(r)
        float a_vol = bins.ask_vols.get(r)
        float t_vol = b_vol + a_vol
        float d_vol = a_vol - b_vol
 
        bins.tot_vols.set(r, t_vol)
        bins.deltas.set(r, d_vol)
        sum_tot += t_vol
        sum_buy += a_vol
        sum_sell += b_vol
 
        if t_vol > max_bin
            max_bin := t_vol
            poc_bin := r
        max_side := math.max(max_side, math.max(b_vol, a_vol))
 
    // Detect Diagonal Order Flow Imbalances
    int buy_imb_cnt = 0
    int sell_imb_cnt = 0
    if num_rows > 1
        for r = 0 to num_rows - 2
            float curr_bid = bins.bid_vols.get(r)
            float next_ask = bins.ask_vols.get(r + 1)
 
            // Buying Imbalance: aggressive ask volume outweighs diagonal lower bid
            if next_ask >= curr_bid * imb_ratio and next_ask >= min_imb_vol and next_ask > 0.0
                bins.buy_imbalances.set(r + 1, true)
                buy_imb_cnt += 1
 
            // Selling Imbalance: aggressive bid volume outweighs diagonal higher ask
            if curr_bid >= next_ask * imb_ratio and curr_bid >= min_imb_vol and curr_bid > 0.0
                bins.sell_imbalances.set(r, true)
                sell_imb_cnt += 1
 
    float poc_p = bins.bin_lows.get(poc_bin) + step * 0.5
    float net_d = sum_buy - sum_sell
    float d_pct = sum_tot > 0.0 ? (net_d / sum_tot) * 100.0 : 0.0
    float avg_v = num_rows > 0 ? sum_tot / num_rows : 0.0
 
    UDT_ProfileStats.new(
       tot_vol = sum_tot,
       buy_vol = sum_buy,
       sell_vol = sum_sell,
       net_delta = net_d,
       delta_pct = d_pct,
       poc_price = poc_p,
       poc_bin = poc_bin,
       vah_price = bins.bin_highs.last(),
       val_price = bins.bin_lows.first(),
       va_high_bin = num_rows - 1,
       va_low_bin = 0,
       max_side_vol = max_side > 0.0 ? max_side : max_bin,
       avg_bin_vol = avg_v,
       buy_imb_count = buy_imb_cnt,
       sell_imb_count = sell_imb_cnt
       )
 
// Value Area (Auction Market Theory): expanding outward from POC to cover target volume
method calculate_value_area(UDT_ProfileBins bins, UDT_ProfileStats stats, int num_rows, float target_pct) =>
    int va_hi = stats.poc_bin
    int va_lo = stats.poc_bin
 
    if stats.tot_vol > 0.0 and num_rows > 0
        float target_vol = stats.tot_vol * (target_pct / 100.0)
        float acc_vol = bins.tot_vols.get(stats.poc_bin)
 
        while acc_vol < target_vol and (va_hi < num_rows - 1 or va_lo > 0)
            float up_vol = va_hi < num_rows - 1 ? bins.tot_vols.get(va_hi + 1) : 0.0
            float dn_vol = va_lo > 0 ? bins.tot_vols.get(va_lo - 1) : 0.0
 
            if va_hi < num_rows - 1 and (va_lo == 0 or up_vol >= dn_vol)
                va_hi += 1
                acc_vol += up_vol
            else if va_lo > 0
                va_lo -= 1
                acc_vol += dn_vol
            else
                break
 
    stats.va_high_bin := va_hi
    stats.va_low_bin := va_lo
    stats.vah_price := bins.bin_highs.get(va_hi)
    stats.val_price := bins.bin_lows.get(va_lo)
 
//#endregion
 
// # ========================================================================= #
// # |   End   | #
// # ========================================================================= #
 
 
 
 
 
 
 
 
 
 
// # ========================================================================= #
// # |   Visuals   | #
// # ========================================================================= #
 
//#region
 
method should_show_numbers(UDT_ProfileBins bins, UDT_ProfileStats stats, int r, string mode) =>
    bool show = false
    float t_vol = bins.tot_vols.get(r)
    switch mode
        "All Rows"                 => show := t_vol > 0.0
        "Significant Only (> Avg)" => show := t_vol >= stats.avg_bin_vol
        "POC Only"                 => show := r == stats.poc_bin
        "Imbalances Only"          => show := bins.buy_imbalances.get(r) or bins.sell_imbalances.get(r)
    show
 
method draw_ladder_row(UDT_Store s, UDT_ProfileBins bins, UDT_ProfileStats stats, int r, UDT_Layout layout, UDT_Palette pal, float ref_max) =>
    float b_low = bins.bin_lows.get(r)
    float b_high = bins.bin_highs.get(r)
    float bid_v = bins.bid_vols.get(r)
    float ask_v = bins.ask_vols.get(r)
 
    float ratio_b = calc_volume_ratio(bid_v, ref_max, aaf_fp_scale_mode)
    float ratio_a = calc_volume_ratio(ask_v, ref_max, aaf_fp_scale_mode)
    int bid_len = bid_v > 0.0 ? bar_length(ratio_b, layout.half_fp_bars) : 0
    int ask_len = ask_v > 0.0 ? bar_length(ratio_a, layout.half_fp_bars) : 0
 
    // Bid volume bar (extends left from center)
    if bid_len > 0
        [b_bg, b_bd] = bar_colors(pal, true, ratio_b, aaf_fp_gradient)
        s.bin_boxes.push(make_box(layout.fp_center - bid_len, b_high, layout.fp_center, b_low, b_bg, b_bd, 1))
 
    // Ask volume bar (extends right from center)
    if ask_len > 0
        [a_bg, a_bd] = bar_colors(pal, false, ratio_a, aaf_fp_gradient)
        s.bin_boxes.push(make_box(layout.fp_center, b_high, layout.fp_center + ask_len, b_low, a_bg, a_bd, 1))
 
    // Imbalance accent highlight
    if aaf_imbalance_highlight
        if bins.buy_imbalances.get(r)
            int ask_imb_len = math.max(1, ask_len)
            s.bin_boxes.push(make_box(layout.fp_center, b_high, layout.fp_center + ask_imb_len, b_low, color.new(theme_bull_color, 80), theme_bull_color, 2))
        if bins.sell_imbalances.get(r)
            int bid_imb_len = math.max(1, bid_len)
            s.bin_boxes.push(make_box(layout.fp_center - bid_imb_len, b_high, layout.fp_center, b_low, color.new(theme_bear_color, 80), theme_bear_color, 2))
 
    // High Volume Node (POC) accent border
    if aaf_poc_highlight and r == stats.poc_bin
        int poc_left = layout.fp_center - math.max(1, bid_len)
        int poc_right = layout.fp_center + math.max(1, ask_len)
        s.bin_boxes.push(make_box(poc_left, b_high, poc_right, b_low, color.new(aaf_poc_color, 80), aaf_poc_color, 2))
 
    // Bid x Ask monospace overlay text
    if aaf_fp_show_numbers and (bid_v > 0.0 or ask_v > 0.0) and bins.should_show_numbers(stats, r, aaf_fp_num_mode)
        color lbl_css = r == stats.poc_bin ? aaf_poc_color : (bins.buy_imbalances.get(r) ? theme_bull_color : (bins.sell_imbalances.get(r) ? theme_bear_color : aaf_num_color))
        s.bin_labels.push(make_label(
           layout.fp_center,
           (b_low + b_high) * 0.5,
           format_bid_ask(bid_v, ask_v, aaf_fp_compact_num),
           lbl_css,
           label.style_label_center,
           general_text,
           general_font
           ))
 
method draw_profile_levels(UDT_Store s, UDT_ProfileStats stats, UDT_Layout layout, int x_start, int x_end) =>
    // Point of Control (POC)
    s.bin_lines.push(make_line(x_start, stats.poc_price, x_end, stats.poc_price, aaf_poc_color, 2, line.style_solid))
 
    // Value Area High (VAH) & Value Area Low (VAL)
    if aaf_va_show
        s.bin_lines.push(make_line(x_start, stats.vah_price, x_end, stats.vah_price, aaf_va_color, 1, line.style_solid))
        s.bin_lines.push(make_line(x_start, stats.val_price, x_end, stats.val_price, aaf_va_color, 1, line.style_solid))
 
    // Level labels
    if aaf_show_level_labels
        string s_poc = aaf_level_label_price ? "POC " + str.tostring(stats.poc_price, format.mintick) : "POC"
        string s_vah = aaf_level_label_price ? "VAH " + str.tostring(stats.vah_price, format.mintick) : "VAH"
        string s_val = aaf_level_label_price ? "VAL " + str.tostring(stats.val_price, format.mintick) : "VAL"
 
        s.bin_labels.push(make_label(x_end, stats.poc_price, s_poc, aaf_poc_color, label.style_label_left, general_text, general_font))
        if aaf_va_show
            s.bin_labels.push(make_label(x_end, stats.vah_price, s_vah, aaf_va_color, label.style_label_left, general_text, general_font))
            s.bin_labels.push(make_label(x_end, stats.val_price, s_val, aaf_va_color, label.style_label_left, general_text, general_font))
 
// Master Orchestrator Execution
if barstate.islast
    store.clean()
 
    float p_high = win_high > -1.0e9 ? win_high : high
    float p_low = win_low < 1.0e9 ? win_low : low
    int b_cnt = math.max(1, win_bars_count)
 
    float step = (p_high - p_low) / math.max(1, aaf_row_resolution)
 
    if step > 0.0 and tape_v.size() > 0
        UDT_ProfileBins bins = UDT_ProfileBins.new(
           bin_lows = array.new<float>(),
           bin_highs = array.new<float>(),
           bid_vols = array.new<float>(),
           ask_vols = array.new<float>(),
           tot_vols = array.new<float>(),
           deltas = array.new<float>(),
           buy_imbalances = array.new<bool>(),
           sell_imbalances = array.new<bool>()
           )
 
        bins.seed_profile_bins(aaf_row_resolution, p_low, step)
 
        for i = 0 to tape_v.size() - 1
            bins.add_tape_slice(aaf_row_resolution, p_low, step, i)
 
        UDT_ProfileStats stats = bins.calculate_profile_stats(aaf_row_resolution, step, aaf_imbalance_ratio, aaf_imbalance_min_vol)
        bins.calculate_value_area(stats, aaf_row_resolution, aaf_va_percent)
 
        // Resolve Horizontal Placement
        int l_left = 0
        int l_right = 0
        int w_right = win_right_idx > -1000 ? win_right_idx : bar_index
        int w_left = win_left_idx < 99999999 ? win_left_idx : bar_index - b_cnt
 
        switch aaf_fp_placement
            "Right Edge" =>
                l_left := w_right + aaf_fp_offset
                l_right := l_left + aaf_fp_width_bars
            "Left Edge" =>
                l_left := math.max(0, w_left - aaf_fp_offset - aaf_fp_width_bars)
                l_right := l_left + aaf_fp_width_bars
 
        int center_x = math.round((l_left + l_right) * 0.5)
        int half_w = math.max(4, int(aaf_fp_width_bars / 2))
 
        UDT_Layout layout = UDT_Layout.new(
           ladder_left = l_left,
           ladder_right = l_right,
           fp_center = center_x,
           half_fp_bars = half_w
           )
 
        // Draw Center Split Dotted Line
        store.bin_lines.push(make_line(center_x, p_high, center_x, p_low, color.new(colors_gray, 50), 1, line.style_dotted))
 
        // Draw Ladder Rows
        float ref_max = math.max(1.0, stats.max_side_vol)
        for r = 0 to aaf_row_resolution - 1
            store.draw_ladder_row(bins, stats, r, layout, palette, ref_max)
 
        // Draw Extension Levels / Reference Lines
        int ext_start = aaf_extend_levels ? w_left : l_left
        int ext_end = l_right + 4
        store.draw_profile_levels(stats, layout, ext_start, ext_end)
 
//#endregion
 
// # ========================================================================= #
// # |   End   | #
// # ========================================================================= #
 
 
 
 
 
 
 
 
 
 
// # ========================================================================= #
// # |   Brand   | #
// # ========================================================================= #
 
//#region
 
if barstate.isfirst and general_brand_show == false
    var table brand = table.new(position.bottom_right, 1, 1, bgcolor = chart.bg_color)
    table.cell(brand, 0, 0, "© CandelaCharts", text_color = colors_gray, text_halign = text.align_center, text_size = text_size(general_text), text_font_family = font_style(general_font))
 
//#endregion
 
// # ========================================================================= #
// # |   End   | #
// # ========================================================================= #

← 返回列表