← К каталогу
Исходный код · ID 4199

HTF Log-Regression Volume Profile [BigBeluga]

indicator_htf_log_regression_volume_profile_bigbeluga_for_tradingview.pine
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

Индикатор «HTF Log-Regression Volume Profile [BigBeluga]» рассчитывает логарифмическую регрессию цены закрытия на сессии более высокого таймфрейма и строит регрессионный канал с границами на основе стандартного отклонения. Внутри канала отображается объёмный профиль с настраиваемым количеством бинов и максимальной шириной в барах.

Индикатор рисует линии максимума, минимума и середины текущей сессии, а также точку контроля (POC) и статистическую метку с объёмами покупок и продаж и дельтой. Поддерживается автоматический выбор таймфрейма на основе разрешения графика или ручной выбор. Уровни могут продлеваться вперёд на заданное количество баров.

Встроена система управления историческими сессиями с ограничением количества сохранённых завершённых сессий на графике. Визуальные элементы (цвета, стили линий, толщина) настраиваются пользователем через соответствующие параметры. Индикатор работает поверх графика (overlay=true).

Настройки программы

НастройкаОписание
auto_htf Автоматически подбирает таймфрейм более высокого периода в зависимости от таймфрейма текущего графика.
manual_htf Вручную задаёт таймфрейм более высокого периода при отключённом автоматическом выборе.
channel_width Число стандартных отклонений, определяющее ширину регрессионного канала и границ объёмного профиля.
line_w Толщина линий максимума и минимума текущей сессии.
mid_disp Включает или отключает отображение средней (эквилибриумной) линии внутри активной сессии.
col_high Цвет линии максимума текущей сессии.
col_mid Цвет средней (эквилибриумной) линии текущей сессии.
col_low Цвет линии минимума текущей сессии.
col_bull Цвет, назначенный бычьим элементам и положительной дельте объёма.
col_bear Цвет, назначенный медвежьим элементам и отрицательной дельте объёма.
col_chan_upper Цвет верхней линии объёмного профиля (границы канала).
style_chan_upper Стиль верхней линии объёмного профиля (канала). Доступные варианты: сплошная, пунктирная, точечная.
col_chan_lower Цвет нижней линии объёмного профиля (границы канала).
style_chan_lower Стиль нижней линии объёмного профиля (канала). Доступные варианты: сплошная, пунктирная, точечная.
show_stats Отображает блок статистики с объёмами покупок, продаж и дельтой текущей сессии.
show_vp Включает или отключает отрисовку логарифмического объёмного профиля внутри канала.
bin_count Количество горизонтальных бинов (гистограмм) внутри объёмного профиля. Допустимые значения от 5 до 100.
max_w Максимальная горизонтальная длина столбцов объёмного профиля, измеряемая в барах графика.
show_poc Включает отображение линии точки контроля (POC), выделяющей бин с наибольшим объёмом.
extend_ch Включает продление уровней максимума, минимума и средней сессии вперёд по будущим барам.
ext_bars Количество баров, на которые продлеваются уровни вперёд при включённом продлении.
max_history Ограничивает количество завершённых исторических сессий, сохраняемых на графике. Допустимые значения от 1 до 50.
Получить полный код

Поиск по коду файла

indicator("HTF Log-Regression Volume Profile [BigBeluga]", overlay=true, max_lines_count=500, max_boxes_count=500, max_polylines_count=100)

group_htf     = "Higher Timeframe Settings"
group_chan    = "Channel & Dimensions"
group_lines   = "Visuals & Colors"
group_stats   = "Volume Profile & Statistics"
group_hist    = "History & Extension"

bool    auto_htf     = input.bool(true, "Auto HTF (Adaptive to Chart Timeframe)", tooltip="Automatically adjusts the higher timeframe based on the current chart resolution.", group=group_htf)
string  manual_htf   = input.timeframe("D", "Manual Higher Timeframe Session", active = not auto_htf, tooltip="Defines the higher timeframe session manually when Auto HTF is disabled.", group=group_htf)

float   channel_width = input.float(1, "Channel Width (StDev for VP)", tooltip="Number of standard deviations used to determine the width of the regression channel and volume profile bounds.", group=group_chan)

int     line_w       = input.int(2, "Line Width", tooltip="Thickness of the session high and low lines.", group=group_lines)
bool    mid_disp     = input.bool(true, "Display Mid/Open Line", tooltip="Toggles the display of the middle/equilibrium line within the active session.", group=group_lines)
color   col_high     = input.color(color.blue, "High Line Color", tooltip="Color assigned to the session high boundary line.", group=group_lines)
color   col_mid      = input.color(color.gray, "Mid Line Color", tooltip="Color assigned to the session middle/equilibrium line.", group=group_lines)
color   col_low      = input.color(color.blue, "Low Line Color", tooltip="Color assigned to the session low boundary line.", group=group_lines)
color   col_bull     = input.color(color.green, "Bullish Color", tooltip="Color assigned to bullish elements and positive volume delta.", group=group_lines)
color   col_bear     = input.color(color.red, "Bearish Color", tooltip="Color assigned to bearish elements and negative volume delta.", group=group_lines)

color   col_chan_upper = input.color(color.new(color.gray, 0), "Channel Upper Line Color", group=group_lines)
string  style_chan_upper = input.string(line.style_dashed, "Channel Upper Line Style", options=[line.style_solid, line.style_dashed, line.style_dotted], group=group_lines)
color   col_chan_lower = input.color(color.new(color.gray, 0), "Channel Lower Line Color", group=group_lines)
string  style_chan_lower = input.string(line.style_dashed, "Channel Lower Line Style", options=[line.style_solid, line.style_dashed, line.style_dotted], group=group_lines)

bool    show_stats   = input.bool(true, "Show Statistics Label", tooltip="Displays buy volume, sell volume, and delta statistics box.", group=group_stats)
bool    show_vp      = input.bool(true, "Show Volume Profile", tooltip="Toggles the rendering of the logarithmic regression volume profile inside the channel.", group=group_stats)
int     bin_count    = input.int(30, "Volume Profile Bins", minval=5, maxval=100, tooltip="Resolution and number of horizontal histogram bins inside the volume profile.", group=group_stats)
int     max_w        = input.int(15, "Volume Profile Max Width (Bars)", tooltip="Maximum horizontal length of the volume profile bars measured in chart bars.", group=group_stats)
bool    show_poc     = input.bool(true, "Show POC Line", tooltip="Toggles the Point of Control (POC) line highlighting the highest volume bin.", group=group_stats)

bool    extend_ch    = input.bool(true, "Extend Levels Forward", tooltip="Extends session high, low, and mid levels forward into future bars.", group=group_hist)
int     ext_bars     = input.int(25, "Extension Bars", tooltip="Number of bars to project the levels forward when extension is enabled.", group=group_hist)
int     max_history  = input.int(10, "Max Historical Sessions to Keep", minval=1, maxval=50, tooltip="Limits the number of historical finished sessions kept on the chart.", group=group_hist)

f_get_auto_htf() =>
    string tf = timeframe.period
    string res = "D"

    int_val = str.tonumber(tf)
    if not na(int_val)
        if int_val <= 1
            res := "240" 
        else if int_val < 15
            res := "720"    
        else if int_val >= 15 and int_val < 60
            res := "2D"    
        else if int_val >= 60 and int_val < 240
            res := "W"     
        else if int_val >= 240 and int_val < 1440
            res := "M"      
        else
            res := "12M"   
    else
        if tf == "D" 
            res := "2M"
        if tf == "2D" 
            res := "3M"
        else if tf == "W" or tf == "1W"
            res := "12M"
        else
            res := "D"
    res

string htf_period = auto_htf ? f_get_auto_htf() : manual_htf

f_format_vol(val) =>
    val >= 1e9 ? str.tostring(val / 1e9, "#.##") + "B" :
     val >= 1e6 ? str.tostring(val / 1e6, "#.##") + "M" :
     val >= 1e3 ? str.tostring(val / 1e3, "#.##") + "K" :
     str.tostring(val, "#.##")

f_get_tf_label(tf_str) =>
    string res = tf_str
    if tf_str == "D" or tf_str == "1D"
        res := "Daily"
    else if tf_str == "W" or tf_str == "1W"
        res := "Weekly"
    else if tf_str == "M" or tf_str == "1M"
        res := "Monthly"
    else
        int_val = str.tonumber(tf_str)
        if not na(int_val)
            if int_val >= 60 and int_val % 60 == 0
                res := str.tostring(int_val / 60) + "h"
            else
                res := tf_str + "m"
    res

f_log_regression(src, length) =>
    float sum_X    = 0.0
    float sum_Y    = 0.0
    float sumXSqr = 0.0
    float sumXY   = 0.0

    for i = 0 to length - 1
        val = math.log(src[i])
        per = i + 1.0
        sum_X    += per
        sum_Y    += val
        sumXSqr += per * per
        sumXY   += val * per

    slope     = (length * sumXY - sum_X * sum_Y) / (length * sumXSqr - sum_X * sum_X)
    intercept = (sum_Y - slope * sum_X) / length

    [slope, intercept]

type SessionDrawings
    line high_line
    line low_line
    line mid_line
    label stats_lbl
    polyline vp_poly
    line poc_line
    line vp_upper_line
    line vp_lower_line

var SessionDrawings[] historical_sessions = array.new<SessionDrawings>()

var line active_high = na
var line active_low  = na
var line active_mid  = na
var line active_high_ext = na
var line active_low_ext  = na
var line active_mid_ext  = na
var label active_stats = na
var polyline active_vp = na
var line active_poc  = na
var line active_vp_upper = na
var line active_vp_lower = na
var table wm = table.new(position.bottom_right, 1, 1)
if barstate.isfirst
    table.cell(wm, 0, 0, "Telegram @SimpleForexTools", text_color = color.new(color.gray, 70), text_size = size.large)

bool is_new_htf = timeframe.change(htf_period)

var int htf_length = 1
if is_new_htf
    if not na(active_high)
        array.unshift(historical_sessions, SessionDrawings.new(active_high, active_low, active_mid, active_stats, active_vp, active_poc, active_vp_upper, active_vp_lower))

        if array.size(historical_sessions) > max_history
            SessionDrawings removed = array.pop(historical_sessions)
            line.delete(removed.high_line)
            line.delete(removed.low_line)
            line.delete(removed.mid_line)
            label.delete(removed.stats_lbl)
            polyline.delete(removed.vp_poly)
            line.delete(removed.poc_line)
            line.delete(removed.vp_upper_line)
            line.delete(removed.vp_lower_line)

    active_high := na
    active_low  := na
    active_mid  := na
    active_stats:= na
    active_vp   := na
    active_poc  := na
    active_vp_upper := na
    active_vp_lower := na
    htf_length  := 1
else
    htf_length  += 1

int start_idx = bar_index[htf_length - 1]
int mid_bar_idx = start_idx + math.round((htf_length - 1) / 2)

[slope, intercept] = f_log_regression(close, htf_length)

float reg_start    = math.exp(intercept + s

Показано первые 50% кода (символов: 12364)

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
1 236,40₽ ≈ $15.11