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

SCTI - D14

indicator scti - d14 for tradingview_5969999791206177899.pine

Похожие материалы по тегам

pro +.pineTradingView · 3 общих теговofada_gold_trader_v230.mq5MQL5 / MetaTrader 5 · 3 общих теговmulti strategy algo combined by enigma mode.pineTradingView · 3 общих теговmelona ob strategy 6th update (by 3dots).pineTradingView · 3 общих теговsmc+ict+indicators+scalping master.pineTradingView · 3 общих теговpremium_super_scalping killer algo.pineTradingView · 3 общих тегов
Вы автор или правообладатель?

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

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

О программе

SCTI - D14 — это индикатор для TradingView, написанный на Pine Script v5. Он объединяет несколько групп инструментов анализа на одном графике: набор экспоненциальных скользящих средних (EMA), мультитаймфреймовые EMA (TFMA), дополнительные EMA (PMA), VWAP с полосами, детектор дивергенций, профиль объёма с определением узлов, концепции «умных денег» (структура рынка, равные максимумы/минимумы, гэпы справедливой стоимости) и отображение торговых сессий. Все модули включаются и настраиваются через пользовательские параметры.

Индикатор отображает линии и графические отметки на графике, использует запросы данных других таймфреймов и инструментов, а также формирует условия для оповещений TradingView. Он предназначен для визуального анализа и не является автоматическим советником или стратегией.

Настройки сгруппированы по разделам: базовые переключатели, EMA, TFMA, PMA, VWAP, детектор дивергенций, профиль объёма, «умные деньги» и сессии. Каждый раздел можно включать независимо.

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

НастройкаОписание
showEMA Включает отображение группы EMA.
showTFMA Включает отображение мультитаймфреймовых EMA.
showPMA Включает отображение группы PMA.
showVWAP Включает отображение VWAP.
showDIVERGENCEDETECTOR Включает отображение детектора дивергенций.
showVolumeProfile Включает отображение профиля объёма и узлов.
showSmartMoney Включает отображение концепций «умных денег».
showSESSIONS Включает отображение торговых сессий.
showEMA1 Включает отображение EMA 1.
ema1_len Длина EMA 1.
showEMA2 Включает отображение EMA 2.
ema2_len Длина EMA 2.
showEMA3 Включает отображение EMA 3.
ema3_len Длина EMA 3.
showEMA4 Включает отображение EMA 4.
ema4_len Длина EMA 4.
showEMA5 Включает отображение EMA 5.
ema5_len Длина EMA 5.
showEMA6 Включает отображение EMA 6.
ema6_len Длина EMA 6.
showEMA7 Включает отображение EMA 7.
ema7_len Длина EMA 7.
showEMA8 Включает отображение EMA 8.
ema8_len Длина EMA 8.
showEMA9 Включает отображение EMA 9.
ema9_len Длина EMA 9.
showEMA10 Включает отображение EMA 10.
ema10_len Длина EMA 10.
showEMA11 Включает отображение EMA 11.
ema11_len Длина EMA 11.
showEMA12 Включает отображение EMA 12.
ema12_len Длина EMA 12.
showEMA13 Включает отображение EMA 13.
ema13_len Длина EMA 13.
tfma_len1 Длина EMA 1 для мультитаймфрейма.
tfma_tf1 Таймфрейм для EMA 1.
tfma_label1_bg_color Цвет фона метки EMA 1.
tfma_len2 Длина EMA 2 для мультитаймфрейма.
tfma_tf2 Таймфрейм для EMA 2.
tfma_label2_bg_color Цвет фона метки EMA 2.
tfma_len3 Длина EMA 3 для мультитаймфрейма.
tfma_tf3 Таймфрейм для EMA 3.
tfma_label3_bg_color Цвет фона метки EMA 3.
tfma_show_labels Отображать метки на графике.
tfma_label_format Формат текста метки: горизонтальный или вертикальный.
tfma_show_trend Отображать направление тренда.
tfma_show_price_diff Отображать разницу цены относительно EMA.
tfma_label_size Размер метки.
tfma_label_text_color Цвет текста метки.
ma1_on Включает отображение MA1.
ma2_on Включает отображение MA2.
ma3_on Включает отображение MA3.
ma4_on Включает отображение MA4.
ma5_on Включает отображение MA5.
ma6_on Включает отображение MA6.
ma7_on Включает отображение MA7.
ma1_len Длина MA1.
ma2_len Длина MA2.
ma3_len Длина MA3.
ma4_len Длина MA4.
ma5_len Длина MA5.
ma6_len Длина MA6.
ma7_len Длина MA7.
fill_12_on Включает заливку между MA1 и MA2.
fill_23_on Включает заливку между MA2 и MA3.
fill_34_on Включает заливку между MA3 и MA4.
fill_45_on Включает заливку между MA4 и MA5.
fill_56_on Включает заливку между MA5 и MA6.
fill_67_on Включает заливку между MA6 и MA7.
hideonDWM Скрывать VWAP на дневном, недельном и месячном таймфреймах.
vwapAnchor Период привязки VWAP.
vwapSrc Источник данных для VWAP.
vwapOffset Смещение VWAP.
vwapCalcMode Режим расчёта полос VWAP: стандартное отклонение или процент.
showVWAPBand_1 Включает отображение полосы VWAP.
vwapBandMult_1 Множитель для полосы VWAP.
div_prd Период пивота для детектора дивергенций.
div_source Источник данных для пивотов: цена закрытия или максимум/минимум.
div_searchdiv Тип искомых дивергенций: обычные, скрытые или оба.
div_showindis Отображение названий индикаторов в метках дивергенций.
div_showlimit Минимальное количество дивергенций для отображения.
div_maxpp Максимальное количество проверяемых пивотов.
div_maxbars Максимальное количество баров для проверки при поиске дивергенций.
div_shownum Отображать количество найденных дивергенций.
div_showlast Показывать только последнюю дивергенцию.
div_dontconfirm Не ждать подтверждения дивергенции.
div_showlines Отображать линии, соединяющие точки дивергенций.
div_calcmacd Включает использование MACD в детекторе дивергенций.
div_macd_fast Период быстрой линии MACD.
div_macd_slow Период медленной линии MACD.
div_macd_signal Период сигнальной линии MACD.
div_calcmacda Включает использование гистограммы MACD в детекторе дивергенций.
div_macda_fast Период быстрой линии гистограммы MACD.
div_macda_slow Период медленной линии гистограммы MACD.
div_macda_signal Период сигнальной линии гистограммы MACD.
div_calcrsi Включает использование RSI в детекторе дивергенций.
div_rsi_length Период RSI в детекторе дивергенций.
div_calcstoc Включает использование стохастика в детекторе дивергенций.
div_stoc_k Период K стохастика в детекторе дивергенций.
div_stoc_d Период D стохастика в детекторе дивергенций.
Получить полный код

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

indicator("SCTI - D14", shorttitle="Scout Regiment - 14", overlay=true, max_lines_count=500, max_boxes_count=500, max_labels_count=500, max_bars_back=5000, dynamic_requests=true)

showEMA = input.bool(true, title="Show EMA", group="1. Basic Indicator Settings")
showTFMA = input.bool(false, title="Show TFMA", group="1. Basic Indicator Settings")
showPMA = input.bool(false, title="Show PMA", group="1. Basic Indicator Settings")
showVWAP = input.bool(false, title="Show VWAP", group="1. Basic Indicator Settings")
showDIVERGENCEDETECTOR = input.bool(true, title="Show Divergence Detector", group="1. Basic Indicator Settings")
showVolumeProfile = input.bool(false, title="Show Volume Profile and Node Detection", group="1. Basic Indicator Settings")
showSmartMoney = input.bool(true, title="Show Smart Money Concepts", group="1. Basic Indicator Settings")
showSESSIONS = input.bool(false, title="Show Timezone", group="1. Basic Indicator Settings")

showEMA1 = input.bool(false, title="Show EMA 1", group="2. EMA Settings", inline="EMA1")
ema1_len = input.int(8, title="Length", group="2. EMA Settings", inline="EMA1")
showEMA2 = input.bool(false, title="Show EMA 2", group="2. EMA Settings", inline="EMA2")
ema2_len = input.int(13, title="Length", group="2. EMA Settings", inline="EMA2")
showEMA3 = input.bool(false, title="Show EMA 3", group="2. EMA Settings", inline="EMA3")
ema3_len = input.int(21, title="Length", group="2. EMA Settings", inline="EMA3")
showEMA4 = input.bool(false, title="Show EMA 4", group="2. EMA Settings", inline="EMA4")
ema4_len = input.int(34, title="Length", group="2. EMA Settings", inline="EMA4")
showEMA5 = input.bool(true, title="Show EMA 5", group="2. EMA Settings", inline="EMA5")
ema5_len = input.int(55, title="Length", group="2. EMA Settings", inline="EMA5")
showEMA6 = input.bool(false, title="Show EMA 6", group="2. EMA Settings", inline="EMA6")
ema6_len = input.int(89, title="Length", group="2. EMA Settings", inline="EMA6")
showEMA7 = input.bool(true, title="Show EMA 7", group="2. EMA Settings", inline="EMA7")
ema7_len = input.int(144, title="Length", group="2. EMA Settings", inline="EMA7")
showEMA8 = input.bool(true, title="Show EMA 8", group="2. EMA Settings", inline="EMA8")
ema8_len = input.int(233, title="Length", group="2. EMA Settings", inline="EMA8")
showEMA9 = input.bool(false, title="Show EMA 9", group="2. EMA Settings", inline="EMA9")
ema9_len = input.int(377, title="Length", group="2. EMA Settings", inline="EMA9")
showEMA10 = input.bool(false, title="Show EMA 10", group="2. EMA Settings", inline="EMA10")
ema10_len = input.int(610, title="Length", group="2. EMA Settings", inline="EMA10")
showEMA11 = input.bool(false, title="Show EMA 11", group="2. EMA Settings", inline="EMA11")
ema11_len = input.int(987, title="Length", group="2. EMA Settings", inline="EMA11")
showEMA12 = input.bool(false, title="Show EMA 12", group="2. EMA Settings", inline="EMA12")
ema12_len = input.int(1597, title="Length", group="2. EMA Settings", inline="EMA12")
showEMA13 = input.bool(false, title="Show EMA 13", group="2. EMA Settings", inline="EMA13")
ema13_len = input.int(2584, title="Length", group="2. EMA Settings", inline="EMA13")

ema1 = ta.ema(close, ema1_len) 
ema2 = ta.ema(close, ema2_len) 
ema3 = ta.ema(close, ema3_len) 
ema4 = ta.ema(close, ema4_len) 
ema5 = ta.ema(close, ema5_len) 
ema6 = ta.ema(close, ema6_len) 
ema7 = ta.ema(close, ema7_len) 
ema8 = ta.ema(close, ema8_len) 
ema9 = ta.ema(close, ema9_len) 
ema10 = ta.ema(close, ema10_len)
ema11 = ta.ema(close, ema11_len)
ema12 = ta.ema(close, ema12_len)
ema13 = ta.ema(close, ema13_len)

plot(showEMA and showEMA1 ? ema1 : na, title="EMA 1", color=color.new(#FF00FF, 0) , linewidth=2) 
plot(showEMA and showEMA2 ? ema2 : na, title="EMA 2", color=color.new(#FF00FF, 0) , linewidth=2) 
plot(showEMA and showEMA3 ? ema3 : na, title="EMA 3", color=color.new(#00FF00, 0) , linewidth=2) 
plot(showEMA and showEMA4 ? ema4 : na, title="EMA 4", color=color.new(#FFFF00, 0) , linewidth=2) 
plot(showEMA and showEMA5 ? ema5 : na, title="EMA 5", color=color.new(#7F00FF, 0) , linewidth=2) 
plot(showEMA and showEMA6 ? ema6 : na, title="EMA 6", color=color.new(#0080FF, 0) , linewidth=2) 
plot(showEMA and showEMA7 ? ema7 : na, title="EMA 7", color=color.new(#FF007F, 0) , linewidth=3) 
plot(showEMA and showEMA8 ? ema8 : na, title="EMA 8", color=color.new(#ffffff, 0) , linewidth=4) 
plot(showEMA and showEMA9 ? ema9 : na, title="EMA 9", color=color.new(#FFFF66, 34) , linewidth=1) 
plot(showEMA and showEMA10 ? ema10 : na, title="EMA 10", color=color.new(#33FF33, 34) , linewidth=1)
plot(showEMA and showEMA11 ? ema11 : na, title="EMA 11", color=color.new(#33FFFF, 34) , linewidth=1)
plot(showEMA and showEMA12 ? ema12 : na, title="EMA 12", color=color.new(#FF33FF, 34) , linewidth=1)
plot(showEMA and showEMA13 ? ema13 : na, title="EMA 13", color=color.new(#c0c0c0, 34) , linewidth=1)

tfma_len1 = input.int(55, minval=1, title="EMA 1", group="3. TFMA")
tfma_tf1 = input.timeframe("1D", title="EMA 1 Timeframe", group="3. TFMA")
tfma_label1_bg_color = input.color(color.new(#7F00FF, 50), title="EMA 1 Label", group="3. TFMA")

tfma_len2 = input.int(144, minval=1, title="EMA 2", group="3. TFMA") 
tfma_tf2 = input.timeframe("1D", title="EMA 2 Timeframe", group="3. TFMA")
tfma_label2_bg_color = input.color(color.new(#FF007F, 50), title="EMA 2 Label", group="3. TFMA")

tfma_len3 = input.int(233, minval=1, title="EMA 3", group="3. TFMA")
tfma_tf3 = input.timeframe("1D", title="EMA 3 Timeframe", group="3. TFMA")
tfma_label3_bg_color = input.color(color.new(#ffffff, 50), title="EMA 3 Label", group="3. TFMA")

tfma_show_labels = input.bool(true, title="Show Labels", group="TFMA Label")
tfma_label_format = input.string("Horizontal", title="Label Text Format", options=["Horizontal", "Vertical"], group="TFMA Label")
tfma_show_trend = input.bool(true, title="Show Trend Direction", group="TFMA Label")
tfma_show_price_diff = input.bool(true, title="Show Price Relative Position", group="TFMA Label")
tfma_label_size = input.string("normal", title="Label Size", options=["tiny", "small", "normal", "large", "huge"], group="TFMA Label")
tfma_label_text_color = input.color(color.white, title="Label Text Color", group="TFMA Label")

tfma_ema1 = request.security(syminfo.tickerid, tfma_tf1, ta.ema(close, tfma_len1), lookahead=barmerge.lookahead_off)
tfma_ema2 = request.security(syminfo.tickerid, tfma_tf2, ta.ema(close, tfma_len2), lookahead=barmerge.lookahead_off)
tfma_ema3 = request.security(syminfo.tickerid, tfma_tf3, ta.ema(close, tfma_len3), lookahead=barmerge.lookahead_off)

plot(showTFMA ? tfma_ema1 : na, title="TFMA EMA 1", color=color.new(#7F00FF, 50), linewidth=4)
plot(showTFMA ? tfma_ema2 : na, title="TFMA EMA 2", color=color.new(#FF007F, 50), linewidth=4)
plot(showTFMA ? tfma_ema3 : na, title="TFMA EMA 3", color=color.new(#ffffff, 50), linewidth=4)

tfma_get_label_size(size_str) =>
    switch size_str
        "tiny" => size.tiny
        "small" => size.small
        "normal" => size.normal
        "large" => size.large
        "huge" => size.huge
        => size.normal

tfma_get_trend_direction(current_ema, previous_ema) =>
    if current_ema > previous_ema
        "↗️"
    else if current_ema < previous_ema
        "↘️"
    else
        "→"

tfma_get_price_difference(current_price, ema_value) =>
    diff_percent = (current_price - ema_value) / ema_value * 100
    if diff_percent > 0
        "+" + str.tostring(diff_percent, "#.#") + "%"
    else
        str.tostring(diff_percent, "#.#") + "%"

tfma_get_label_text(tf, length, price, format, trend_arrow, price_diff, show_trend_option, show_diff_option) =>
    price_str = str.tostring(price, "#.##")
    trend_part = show_trend_option ? trend_arrow + " " : ""
    diff_part = show_diff_option ? price_diff + " " : ""

    if format == "Horizontal"
        "TF:" + tf + "  L:" + str.tostring(length) + "  " + trend_part + diff_part + price_str
    else
        "TF:" + tf + "\nL:" + str.tostring(length) + "\n" + trend_part + diff_part + price_str

if barstate.islast and tfma_show_labels and showTFMA
    tfma_ema1_prev = request.security(syminfo.tickerid, tfma_tf1, ta.ema(close[1], tfma_len1), lookahead=barmerge.lookahead_off)
    tfma_ema2_prev = request.security(syminfo.tickerid, tfma_tf2, ta.ema(close[1], tfma_len2), lookahead=barmerge.lookahead_off)
    tfma_ema3_prev = request.security(syminfo.tickerid, tfma_tf3, ta.ema(close[1], tfma_len3), lookahead=barmerge.lookahead_off)

    tfma_trend1 = tfma_get_trend_direction(tfma_ema1, tfma_ema1_prev)
    tfma_trend2 = tfma_get_trend_direction(tfma_ema2, tfma_ema2_prev)
    tfma_trend3 = tfma_get_trend_direction(tfma_ema3, tfma_ema3_prev)

    tfma_diff1 = tfma_get_price_difference(close, tfma_ema1)
    tfma_diff2 = tfma_get_price_difference(close, tfma_ema2)
    tfma_diff3 = tfma_get_price_difference(close, tfma_ema3)

    label.new(x=bar_index, y=tfma_ema1, text=tfma_get_label_text(tfma_tf1, tfma_len1, tfma_ema1, tfma_label_format, tfma_trend1, tfma_diff1, tfma_show_trend, tfma_show_price_diff), 
              style=label.style_label_left, 
              color=tfma_label1_bg_color, 
              textcolor=tfma_label_text_color, 
              size=tfma_get_label_size(tfma_label_size))

    label.new(x=bar_index, y=tfma_ema2, text=tfma_get_label_text(tfma_tf2, tfma_len2, tfma_ema2, tfma_label_format, tfma_trend2, tfma_diff2, tfma_show_trend, tfma_show_price_diff), 
              style=label.style_label_left, 
              color=tfma_label2_bg_color, 
              textcolor=tfma_label_text_color, 
              size=tfma_get_label_size(tfma_label_size))

    label.new(x=bar_index, y=tfma_ema3, text=tfma_get_label_text(tfma_tf3, tfma_len3, tfma_ema3, tfma_label_format, tfma_trend3, tfma_diff3, tfma_show_trend, tfma_show_price_diff), 
              style=label.style_label_left, 
              color=tfma_label3_bg_color, 
              textcolor=tfma_label_text_color, 
              size=tfma_get_label_size(tfma_label_size))

ma1_on = input.bool(inline='MA1', title='Enable Moving Average 1', defval=false, group="4. PMA Settings") 
ma2_on = input.bool(inline='MA2', title='Enable Moving Average 2', defval=true, group="4. PMA Settings") 
ma3_on = input.bool(inline='MA3', title='Enable Moving Average 3', defval=true, group="4. PMA Settings") 
ma4_on = input.bool(inline='MA4', title='Enable Moving Average 4', defval=true, group="4. PMA Settings") 
ma5_on = input.bool(inline='MA5', title='Enable Moving Average 5', defval=true, group="4. PMA Settings") 
ma6_on = input.bool(inline='MA6', title='Enable Moving Average 6', defval=true, group="4. PMA Settings") 
ma7_on = input.bool(inline='MA7', title='Enable Moving Average 7', defval=true, group="4. PMA Settings") 
ma1_len = input.int(inline='MA1', title='', defval=12, minval=1, group="4. PMA Settings") 
ma2_len = input.int(inline='MA2', title='', defval=144, minval=1, group="4. PMA Settings") 
ma3_len = input.int(inline='MA3', title='', defval=169, minval=1, group="4. PMA Settings") 
ma4_len = input.int(inline='MA4', title='', defval=288, minval=1, group="4. PMA Settings") 
ma5_len = input.int(inline='MA5', title='', defval=338, minval=1, group="4. PMA Settings") 
ma6_len = input.int(inline='MA6', title='', defval=576, minval=1, group="4. PMA Settings") 
ma7_len = input.int(inline='MA7', title='', defval=676, minval=1, group="4. PMA Settings") 

fill_12_on = input.bool(title='Enable MA1-2 Fill', defval=false, group="4. PMA Settings") 
fill_23_on = input.bool(title='Enable MA2-3 Fill', defval=true, group="4. PMA Settings") 
fill_34_on = input.bool(title='Enable MA3-4 Fill', defval=false, group="4. PMA Settings") 
fill_45_on = input.bool(title='Enable MA4-5 Fill', defval=true, group="4. PMA Settings") 
fill_56_on = input.bool(title='Enable MA5-6 Fill', defval=false, group="4. PMA Settings") 
fill_67_on = input.bool(title='Enable MA6-7 Fill', defval=true, group="4. PMA Settings") 

ma1 = ta.ema(close, ma1_len)
ma2 = ta.ema(close, ma2_len)
ma3 = ta.ema(close, ma3_len)
ma4 = ta.ema(close, ma4_len)
ma5 = ta.ema(close, ma5_len)
ma6 = ta.ema(close, ma6_len)
ma7 = ta.ema(close, ma7_len)

p1 = plot(series=showPMA and ma1_on ? ma1 : na, title="MA1", color=color.new(color.fuchsia, 0), trackprice=false, linewidth=2) 
p2 = plot(series=showPMA and ma2_on ? ma2 : na, title="MA2", color=color.new(color.aqua, 0), trackprice=false, linewidth=2) 
p3 = plot(series=showPMA and ma3_on ? ma3 : na, title="MA3", color=color.new(color.yellow, 0), trackprice=false, linewidth=2) 
p4 = plot(series=showPMA and ma4_on ? ma4 : na, title="MA4", color=color.new(color.blue, 0), trackprice=false, linewidth=2) 
p5 = plot(series=showPMA and ma5_on ? ma5 : na, title="MA5", color=color.new(color.orange, 0), trackprice=false, linewidth=2) 
p6 = plot(series=showPMA and ma6_on ? ma6 : na, title="MA6", color=color.new(color.green, 0), trackprice=false, linewidth=2) 
p7 = plot(series=showPMA and ma7_on ? ma7 : na, title="MA7", color=color.new(color.red, 0), trackprice=false, linewidth=2) 

fill(p1, p2, color=showPMA and ma1_on and ma2_on and fill_12_on ? color.new(color.purple, 70) : na, title="MA1-2 Fill") 
fill(p2, p3, color=showPMA and ma2_on and ma3_on and fill_23_on ? color.new(color.blue, 70) : na, title="MA2-3 Fill") 
fill(p3, p4, color=showPMA and ma3_on and ma4_on and fill_34_on ? color.new(color.teal, 70) : na, title="MA3-4 Fill") 
fill(p4, p5, color=showPMA and ma4_on and ma5_on and fill_45_on ? color.new(color.green, 70) : na, title="MA4-5 Fill") 
fill(p5, p6, color=showPMA and ma5_on and ma6_on and fill_56_on ? color.new(color.yellow, 70) : na, title="MA5-6 Fill") 
fill(p6, p7, color=showPMA and ma6_on and ma7_on and fill_67_on ? color.new(color.orange, 70) : na, title="MA6-7 Fill") 

hideonDWM = input(true, title="Hide VWAP on daily and higher timeframes", group="5. VWAP Settings") 
vwapAnchor = input.string(defval = "Session", title="Anchor Period", options=["Session", "Week", "Month", "Quarter", "Year", "Decade", "Century", "Earnings", "Dividends", "Splits"], group="5. VWAP Settings") 
vwapSrc = input(title = "Data Source", defval = hlc3, group="5. VWAP Settings") 
vwapOffset = input.int(0, title="Offset", group="5. VWAP Settings", minval=0) 

BANDS_GROUP = "5. VWAP Settings" 
CALC_MODE_TOOLTIP = "Determines the unit used to calculate band distance. When 'Percent' is selected, multiplier 1 means 1%." 
vwapCalcMode = input.string("Standard Deviation", "Band Calculation Mode", options = ["Standard Deviation", "Percentage"], group = BANDS_GROUP, tooltip = CALC_MODE_TOOLTIP) 
showVWAPBand_1 = input(true, title = "", group = BANDS_GROUP, inline = "band_1") 
vwapBandMult_1 = input.float(1.0, title = "Band Multiplier #1", group = BANDS_GROUP, inline = "band_1", step = 0.5, minval=0) 

cumVolume = ta.cum(volume) 
if barstate.islast and cumVolume == 0
    runtime.error("The data provider does not supply volume data.") 

new_earnings = request.earnings(syminfo.tickerid, earnings.actual, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true) 
new_dividends = request.dividends(syminfo.tickerid, dividends.gross, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true) 
new_split = request.splits(syminfo.tickerid, splits.denominator, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true) 

isNewPeriod = switch vwapAnchor
	"Earnings"  => not na(new_earnings)
	"Dividends" => not na(new_dividends)
	"Splits"    => not na(new_split)
	"Session"   => timeframe.change("D")
	"Week"      => timeframe.change("W")
	"Month"     => timeframe.change("M")
	"Quarter"   => timeframe.change("3M")
	"Year"      => timeframe.change("12M")
	"Decade"    => timeframe.change("12M") and year % 10 == 0
	"Century"   => timeframe.change("12M") and year % 100 == 0
	=> false 

isEsdAnchor = vwapAnchor == "Earnings" or vwapAnchor == "Dividends" or vwapAnchor == "Splits" 
if na(vwapSrc[1]) and not isEsdAnchor
	isNewPeriod := true 

float vwapValue = na 
float vwapUpperBand1 = na 
float vwapLowerBand1 = na 

if not (hideonDWM and timeframe.isdwm)
    [_vwap, _stdevUpper, _] = ta.vwap(vwapSrc, isNewPeriod, 1) 
	vwapValue := _vwap 
    stdevAbs = _stdevUpper - _vwap 
	vwapBandBasis = vwapCalcMode == "Standard Deviation" ? stdevAbs : _vwap * 0.01 
	vwapUpperBand1 := _vwap + vwapBandBasis * vwapBandMult_1 
	vwapLowerBand1 := _vwap - vwapBandBasis * vwapBandMult_1 

plot(showVWAP ? vwapValue : na, title = "VWAP", color = #FF9933 , offset = vwapOffset , linewidth=2) 

div_prd = input.int(defval = 5, title = "Pivot Period", minval = 1, maxval = 50, group="6. Divergence Detector")
div_source = input.string(defval = "Close", title = "Pivot Point Data Source", options = ["Close", "High/Low"], group="6. Divergence Detector")
div_searchdiv = input.string(defval = "Regular", title = "Divergence Type", options = ["Regular", "Hidden", "Regular/Hidden"], group="6. Divergence Detector")
div_showindis = input.string(defval = "Full", title = "Show Indicator Name", options = ["Full", "Initials", "Do Not Show"], group="6. Divergence Detector")
div_showlimit = input.int(1, title="Minimum Divergence Count", minval = 1, maxval = 11, group="6. Divergence Detector")
div_maxpp = input.int(defval = 10, title = "Maximum Pivot Points to Check", minval = 1, maxval = 20, group="6. Divergence Detector")
div_maxbars = input.int(defval = 100, title = "Maximum Bars to Check", minval = 30, maxval = 200, group="6. Divergence Detector")
div_shownum = input.bool(defval = true, title = "Show Divergence Count", group="6. Divergence Detector")
div_showlast = input.bool(defval = false, title = "Show Only Latest Divergence", group="6. Divergence Detector")
div_dontconfirm = input.bool(defval = false, title = "Do Not Wait for Confirmation", group="6. Divergence Detector")
div_showlines = input.bool(defval = true, title = "Show Divergence Lines", group="6. Divergence Detector")

div_calcmacd = input.bool(defval = false, title = "MACD", group="6. Divergence Detector")
div_macd_fast = input.int(defval = 13, title = "Fast Line", minval = 1, group="6. Divergence Detector")
div_macd_slow = input.int(defval = 34, title = "Slow Line", minval = 1, group="6. Divergence Detector")
div_macd_signal = input.int(defval = 9, title = "Signal Line", minval = 1, group="6. Divergence Detector")

div_calcmacda = input.bool(defval = true, title = "MACD Histogram", group="6. Divergence Detector")
div_macda_fast = input.int(defval = 13, title = "Fast Line", minval = 1, group="6. Divergence Detector")
div_macda_slow = input.int(defval = 34, title = "Slow Line", minval = 1, group="6. Divergence Detector")
div_macda_signal = input.int(defval = 9, title = "Signal Line", minval = 1, group="6. Divergence Detector")

div_calcrsi = input.bool(defval = false, title = "RSI", group="6. Divergence Detector")
div_rsi_length = input.int(defval = 22, title = "Period", minval = 1, group="6. Divergence Detector")

div_calcstoc = input.bool(defval = false, title = "Stochastic", group="6. Divergence Detector")
div_stoc_k = input.int(defval = 13, title = "K Period", minval = 1, group="6. Divergence Detector")
div_stoc_d = input.int(defval = 3, title = "D Period", minval = 1, group="6. Divergence Detector")

div_calccci = input.bool(defval = false, title = "CCI", group="6. Divergence Detector")
div_cci_length = input.int(defval = 55, title = "Period", minval = 1, group="6. Divergence Detector")

div_calcwr = input.bool(defval = false, title = "Williams %R", group="6. Divergence Detector")
div_wr_length = input.int(defval = 13, title = "Period", minval = 1, group="6. Divergence Detector")

div_calcbias = input.bool(defval = true, title = "Bias", group="6. Divergence Detector")
div_bias_length = input.int(defval = 55, title = "Period", minval = 1, group="6. Divergence Detector")

div_calcmom = input.bool(defval = false, title = "Momentum", group="6. Divergence Detector")
div_mom_length = input.int(defval = 10, title = "Period", minval = 1, group="6. Divergence Detector")

div_calcobv = input.bool(defval = false, title = "OBV", group="6. Divergence Detector")

div_calcvwmacd = input.bool(false, title = "VWmacd", group="6. Divergence Detector")
div_vwmacd_fast = input.int(defval = 13, title = "Fast Line", minval = 1, group="6. Divergence Detector")
div_vwmacd_slow = input.int(defval = 34, title = "Slow Line", minval = 1, group="6. Divergence Detector")

div_calccmf = input.bool(false, title = "Chaikin Money Flow", group="6. Divergence Detector")
div_cmf_length = input.int(defval = 21, title = "Period", minval = 1, group="6. Divergence Detector")

div_calcmfi = input.bool(false, title = "Money Flow Index", group="6. Divergence Detector")
div_mfi_length = input.int(defval = 13, title = "Period", minval = 1, group="6. Divergence Detector")

div_calcext = input.bool(false, title = "Check external indicator", group="6. Divergence Detector")
div_externalindi = input.source(defval = close, title = "External indicator", group="6. Divergence Detector")

div_pos_reg_div_col = input.color(defval = color.new(#ffeb3b, 0), title = "Regular positive divergence color", group="6. Divergence Detector")
div_pos_reg_label_col = input.color(defval = color.new(#ffeb3b, 65), title = "Regular positive divergence label color", group="6. Divergence Detector")
div_neg_reg_div_col = input.color(defval = color.new(#2196f3, 0), title = "Regular negative divergence color", group="6. Divergence Detector")
div_neg_reg_label_col = input.color(defval = color.new(#2196f3, 65), title = "Regular negative divergence label color", group="6. Divergence Detector")
div_pos_hid_div_col = input.color(defval = color.new(#08ec32, 0), title = "Hidden positive divergence color", group="6. Divergence Detector")
div_pos_hid_label_col = input.color(defval = color.new(#08ec32, 65), title = "Hidden positive divergence label color", group="6. Divergence Detector")
div_neg_hid_div_col = input.color(defval = color.new(#FF00FF, 0), title = "Hidden negative divergence color", group="6. Divergence Detector")
div_neg_hid_label_col = input.color(defval = color.new(#FF00FF, 65), title = "Hidden negative divergence label color", group="6. Divergence Detector")
div_pos_div_text_col = input.color(defval = color.white, title = "Positive divergence text color", group="6. Divergence Detector")
div_neg_div_text_col = input.color(defval = color.white, title = "Negative divergence text color", group="6. Divergence Detector")

div_reg_div_l_style_ = input.string(defval = "Solid", title = "Regular divergence line style", options = ["Solid", "Dashed", "Dotted"], group="6. Divergence Detector")
div_hid_div_l_style_ = input.string(defval = "Dashed", title = "Hidden divergence line style", options = ["Solid", "Dashed", "Dotted"], group="6. Divergence Detector")
div_reg_div_l_width = input.int(defval = 3, title = "Regular divergence line width", minval = 1, maxval = 5, group="6. Divergence Detector")
div_hid_div_l_width = input.int(defval = 2, title = "Hidden divergence line width", minval = 1, maxval = 5, group="6. Divergence Detector")

var div_reg_div_l_style = div_reg_div_l_style_ == "Solid" ? line.style_solid : 
                       div_reg_div_l_style_ == "Dashed" ? line.style_dashed :
                       line.style_dotted
var div_hid_div_l_style = div_hid_div_l_style_ == "Solid" ? line.style_solid : 
                       div_hid_div_l_style_ == "Dashed" ? line.style_dashed :
                       line.style_dotted

div_rsi = ta.rsi(close, div_rsi_length)
[div_macd, div_signal, div_deltamacd] = ta.macd(close, div_macd_fast, div_macd_slow, div_macd_signal)
[div_macd_a, div_signal_a, div_deltamacd_a] = ta.macd(close, div_macda_fast, div_macda_slow, div_macda_signal)
div_moment = ta.mom(close, div_mom_length)
div_cci = ta.cci(close, div_cci_length)

div_pr(length) =>
    max = ta.highest(length)
    min = ta.lowest(length)
    100 * (close - max) / (max - min)
div_williamsR = div_pr(div_wr_length)

div_ema_bias = ta.ema(close, div_bias_length)
div_bias = (close - div_ema_bias) / div_ema_bias * 100

div_Obv = ta.obv
div_stk = ta.sma(ta.stoch(close, high, low, div_stoc_k), div_stoc_d)
div_maFast = ta.vwma(close, div_vwmacd_fast), div_maSlow = ta.vwma(close, div_vwmacd_slow), div_vwmacd = div_maFast - div_maSlow
div_Cmfm = ((close-low) - (high-close)) / (high - low), div_Cmfv = div_Cmfm * volume, div_cmf = ta.sma(div_Cmfv, div_cmf_length) / ta.sma(volume, div_cmf_length)
div_Mfi = ta.mfi(close, div_mfi_length)

var div_indicators_name = array.new<string>(13)
var div_div_colors = array.new<color>(4)
var div_label_colors = array.new<color>(4)
if barstate.isfirst
    array.set(div_indicators_name, 0, div_showindis == "Full" ? "MACD" : "M")
    array.set(div_indicators_name, 1, div_showindis == "Full" ? "Hist" : "H")
    array.set(div_indicators_name, 2, div_showindis == "Full" ? "RSI" : "E")
    array.set(div_indicators_name, 3, div_showindis == "Full" ? "Stoch" : "S")
    array.set(div_indicators_name, 4, div_showindis == "Full" ? "CCI" : "C")
    array.set(div_indicators_name, 5, div_showindis == "Full" ? "Williams %R" : "W")
    array.set(div_indicators_name, 6, div_showindis == "Full" ? "Bias" : "B")
    array.set(div_indicators_name, 7, div_showindis == "Full" ? "MOM" : "M")
    array.set(div_indicators_name, 8, div_showindis == "Full" ? "OBV" : "O")
    array.set(div_indicators_name, 9, div_showindis == "Full" ? "VWMACD" : "V")
    array.set(div_indicators_name, 10, div_showindis == "Full" ? "CMF" : "C")
    array.set(div_indicators_name, 11, div_showindis == "Full" ? "MFI" : "M")
    array.set(div_indicators_name, 12, div_showindis == "Full" ? "Extrn" : "X")
    array.set(div_div_colors, 0, div_pos_reg_div_col)
    array.set(div_div_colors, 1, div_neg_reg_div_col)
    array.set(div_div_colors, 2, div_pos_hid_div_col)
    array.set(div_div_colors, 3, div_neg_hid_div_col)
    array.set(div_label_colors, 0, div_pos_reg_label_col)
    array.set(div_label_colors, 1, div_neg_reg_label_col)
    array.set(div_label_colors, 2, div_pos_hid_label_col)
    array.set(div_label_colors, 3, div_neg_hid_label_col)

float div_ph = ta.pivothigh((div_source == "Close" ? close : high), div_prd, div_prd)
float div_pl = ta.pivotlow((div_source == "Close" ? close : low), div_prd, div_prd)

var int div_maxarraysize = 20
var div_ph_positions = array.new<int>(div_maxarraysize, 0)
var div_pl_positions = array.new<int>(div_maxarraysize, 0)
var div_ph_vals = array.new<float>(div_maxarraysize, 0.)
var div_pl_vals = array.new<float>(div_maxarraysize, 0.)

if div_ph and showDIVERGENCEDETECTOR
    array.unshift(div_ph_positions, bar_index)
    array.unshift(div_ph_vals, div_ph)
    if array.size(div_ph_positions) > div_maxarraysize
        array.pop(div_ph_positions)
        array.pop(div_ph_vals)

if div_pl and showDIVERGENCEDETECTOR
    array.unshift(div_pl_positions, bar_index)
    array.unshift(div_pl_vals, div_pl)
    if array.size(div_pl_positions) > div_maxarraysize
        array.pop(div_pl_positions)
        array.pop(div_pl_vals)

div_positive_regular_positive_hidden_divergence(src, cond)=>
    divlen = 0
    prsc = div_source == "Close" ? close : low
    if (div_dontconfirm or src > src[1] or close > close[1]) and showDIVERGENCEDETECTOR
        startpoint = div_dontconfirm ? 0 : 1
        for x = 0 to div_maxpp - 1
            len = bar_index - array.get(div_pl_positions, x) + div_prd
            if array.get(div_pl_positions, x) == 0 or len > div_maxbars
                break
            if len > 5 and 
               ((cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(div_pl_vals, x))) or
               (cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(div_pl_vals, x))))
                slope1 = (src[startpoint] - src[len]) / (len - startpoint)
                virtual_line1 = src[startpoint] - slope1
                slope2 = (close[startpoint] - close[len]) / (len - startpoint)
                virtual_line2 = close[startpoint] - slope2
                arrived = true
                for y = 1 + startpoint to len - 1
                    if src[y] < virtual_line1 or nz(close[y]) < virtual_line2
                        arrived := false
                        break
                    virtual_line1 := virtual_line1 - slope1
                    virtual_line2 := virtual_line2 - slope2

                if arrived
                    divlen := len
                    break
    divlen

div_negative_regular_negative_hidden_divergence(src, cond)=>
    divlen = 0
    prsc = div_source == "Close" ? close : high
    if (div_dontconfirm or src < src[1] or close < close[1]) and showDIVERGENCEDETECTOR
        startpoint = div_dontconfirm ? 0 : 1
        for x = 0 to div_maxpp - 1
            len = bar_index - array.get(div_ph_positions, x) + div_prd
            if array.get(div_ph_positions, x) == 0 or len > div_maxbars
                break
            if len > 5 and 
               ((cond == 1 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(div_ph_vals, x))) or 
               (cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(div_ph_vals, x))))
                slope1 = (src[startpoint] - src[len]) / (len - startpoint)
                virtual_line1 = src[startpoint] - slope1
                slope2 = (close[startpoint] - nz(close[len])) / (len - startpoint)
                virtual_line2 = close[startpoint] - slope2
                arrived = true
                for y = 1 + startpoint to len - 1
                    if src[y] > virtual_line1 or nz(close[y]) > virtual_line2
                        arrived := false
                        break
                    virtual_line1 := virtual_line1 - slope1
                    virtual_line2 := virtual_line2 - slope2

                if arrived
                    divlen := len
                    break
    divlen

div_calculate_divs(cond, indicator)=>
    divs = array.new<int>(4, 0)
    array.set(divs, 0, cond and (div_searchdiv == "Regular" or div_searchdiv == "Regular/Hidden") and showDIVERGENCEDETECTOR ? div_positive_regular_positive_hidden_divergence(indicator, 1) : 0)
    array.set(divs, 1, cond and (div_searchdiv == "Regular" or div_searchdiv == "Regular/Hidden") and showDIVERGENCEDETECTOR ? div_negative_regular_negative_hidden_divergence(indicator, 1) : 0)
    array.set(divs, 2, cond and (div_searchdiv == "Hidden" or div_searchdiv == "Regular/Hidden") and showDIVERGENCEDETECTOR ? div_positive_regular_positive_hidden_divergence(indicator, 2) : 0)
    array.set(divs, 3, cond and (div_searchdiv == "Hidden" or div_searchdiv == "Regular/Hidden") and showDIVERGENCEDETECTOR ? div_negative_regular_negative_hidden_divergence(indicator, 2) : 0)
    divs

var div_all_divergences = array.new<int>(52)

div_array_set_divs(div_pointer, index)=>
    for x = 0 to 3
        array.set(div_all_divergences, index * 4 + x, array.get(div_pointer, x))

div_array_set_divs(div_calculate_divs(div_calcmacd, div_macd), 0)
div_array_set_divs(div_calculate_divs(div_calcmacda, div_deltamacd_a), 1)
div_array_set_divs(div_calculate_divs(div_calcrsi, div_rsi), 2)
div_array_set_divs(div_calculate_divs(div_calcstoc, div_stk), 3)
div_array_set_divs(div_calculate_divs(div_calccci, div_cci), 4)
div_array_set_divs(div_calculate_divs(div_calcwr, div_williamsR), 5)
div_array_set_divs(div_calculate_divs(div_calcbias, div_bias), 6)
div_array_set_divs(div_calculate_divs(div_calcmom, div_moment), 7)
div_array_set_divs(div_calculate_divs(div_calcobv, div_Obv), 8)
div_array_set_divs(div_calculate_divs(div_calcvwmacd, div_vwmacd), 9)
div_array_set_divs(div_calculate_divs(div_calccmf, div_cmf), 10)
div_array_set_divs(div_calculate_divs(div_calcmfi, div_Mfi), 11)
div_array_set_divs(div_calculate_divs(div_calcext, div_externalindi), 12)

div_total_div = 0
for x = 0 to array.size(div_all_divergences) - 1
    div_total_div := div_total_div + math.round(math.sign(array.get(div_all_divergences, x)))

if div_total_div < div_showlimit
    array.fill(div_all_divergences, 0)

var div_pos_div_lines = array.new<line>(0)
var div_neg_div_lines = array.new<line>(0)
var div_pos_div_labels = array.new<label>(0)
var div_neg_div_labels = array.new<label>(0) 

div_delete_old_pos_div_lines()=>
    if array.size(div_pos_div_lines) > 0    
        for j = 0 to array.size(div_pos_div_lines) - 1 
            line.delete(array.get(div_pos_div_lines, j))
        array.clear(div_pos_div_lines)

div_delete_old_neg_div_lines()=>
    if array.size(div_neg_div_lines) > 0    
        for j = 0 to array.size(div_neg_div_lines) - 1 
            line.delete(array.get(div_neg_div_lines, j))
        array.clear(div_neg_div_lines)

div_delete_old_pos_div_labels()=>
    if array.size(div_pos_div_labels) > 0 
        for j = 0 to array.size(div_pos_div_labels) - 1 
            label.delete(array.get(div_pos_div_labels, j))
        array.clear(div_pos_div_labels)

div_delete_old_neg_div_labels()=>
    if array.size(div_neg_div_labels) > 0    
        for j = 0 to array.size(div_neg_div_labels) - 1 
            label.delete(array.get(div_neg_div_labels, j))
        array.clear(div_neg_div_labels)

div_delete_last_pos_div_lines_label(n)=>
    if n > 0 and array.size(div_pos_div_lines) >= n    
        asz = array.size(div_pos_div_lines)
        for j = 1 to n
            line.delete(array.get(div_pos_div_lines, asz - j))
            array.pop(div_pos_div_lines)
        if array.size(div_pos_div_labels) > 0  
            label.delete(array.get(div_pos_div_labels, array.size(div_pos_div_labels) - 1))
            array.pop(div_pos_div_labels)

div_delete_last_neg_div_lines_label(n)=>
    if n > 0 and array.size(div_neg_div_lines) >= n    
        asz = array.size(div_neg_div_lines)
        for j = 1 to n
            line.delete(array.get(div_neg_div_lines, asz - j))
            array.pop(div_neg_div_lines)
        if array.size(div_neg_div_labels) > 0  
            label.delete(array.get(div_neg_div_labels, array.size(div_neg_div_labels) - 1))
            array.pop(div_neg_div_labels)

div_pos_reg_div_detected = false
div_neg_reg_div_detected = false
div_pos_hid_div_detected = false
div_neg_hid_div_detected = false

var div_last_pos_div_lines = 0
var div_last_neg_div_lines = 0
var div_remove_last_pos_divs = false 
var div_remove_last_neg_divs = false
if div_pl
    div_remove_last_pos_divs := false
    div_last_pos_div_lines := 0
if div_ph
    div_remove_last_neg_divs := false
    div_last_neg_div_lines := 0

div_divergence_text_top = ""
div_divergence_text_bottom = ""
div_distances = array.new<int>(0)
div_dnumdiv_top = 0
div_dnumdiv_bottom = 0
div_top_label_col = color.white
div_bottom_label_col = color.white
div_old_pos_divs_can_be_removed = true
div_old_neg_divs_can_be_removed = true
div_startpoint = div_dontconfirm ? 0 : 1

for x = 0 to 12
    div_div_type = -1
    for y = 0 to 3
        if array.get(div_all_divergences, x * 4 + y) > 0 and showDIVERGENCEDETECTOR
            div_div_type := y
            if (y % 2) == 1 
                div_dnumdiv_top := div_dnumdiv_top + 1
                div_top_label_col := array.get(div_label_colors, y)
            if (y % 2) == 0
                div_dnumdiv_bottom := div_dnumdiv_bottom + 1
                div_bottom_label_col := array.get(div_label_colors, y)
            if not array.includes(div_distances, array.get(div_all_divergences, x * 4 + y))
                array.push(div_distances, array.get(div_all_divergences, x * 4 + y))
                div_new_line = div_showlines and showDIVERGENCEDETECTOR ? line.new(x1 = bar_index - array.get(div_all_divergences, x * 4 + y), 
                          y1 = (div_source == "Close" ? close[array.get(div_all_divergences, x * 4 + y)] : 
                                           (y % 2) == 0 ? low[array.get(div_all_divergences, x * 4 + y)] : 
                                                          high[array.get(div_all_divergences, x * 4 + y)]),
                          x2 = bar_index - div_startpoint,
                          y2 = (div_source == "Close" ? close[div_startpoint] : 
                                           (y % 2) == 0 ? low[div_startpoint] : 
                                                          high[div_startpoint]),
                          color = array.get(div_div_colors, y),
                          style = y < 2 ? div_reg_div_l_style : div_hid_div_l_style,
                          width = y < 2 ? div_reg_div_l_width : div_hid_div_l_width
                          )
                          : na
                if (y % 2) == 0
                    if div_old_pos_divs_can_be_removed
                        div_old_pos_divs_can_be_removed := false
                        if not div_showlast and div_remove_last_pos_divs
                            div_delete_last_pos_div_lines_label(div_last_pos_div_lines)
                            div_last_pos_div_lines := 0
                        if div_showlast
                            div_delete_old_pos_div_lines()
                    array.push(div_pos_div_lines, div_new_line)
                    div_last_pos_div_lines := div_last_pos_div_lines + 1
                    div_remove_last_pos_divs := true

                if (y % 2) == 1
                    if div_old_neg_divs_can_be_removed
                        div_old_neg_divs_can_be_removed := false
                        if not div_showlast and div_remove_last_neg_divs
                            div_delete_last_neg_div_lines_label(div_last_neg_div_lines)
                            div_last_neg_div_lines := 0
                        if div_showlast
                            div_delete_old_neg_div_lines()
                    array.push(div_neg_div_lines, div_new_line)
                    div_last_neg_div_lines := div_last_neg_div_lines + 1
                    div_remove_last_neg_divs := true

            if y == 0
                div_pos_reg_div_detected := true
            if y == 1
                div_neg_reg_div_detected := true
            if y == 2
                div_pos_hid_div_detected := true
            if y == 3
                div_neg_hid_div_detected := true
    if div_div_type >= 0
        div_divergence_text_top    := div_divergence_text_top    + ((div_div_type % 2) == 1 ? (div_showindis != "Do Not Show" ? array.get(div_indicators_name, x) + "\n" : "") : "")
        div_divergence_text_bottom := div_divergence_text_bottom + ((div_div_type % 2) == 0 ? (div_showindis != "Do Not Show" ? array.get(div_indicators_name, x) + "\n" : "") : "")

if (div_showindis != "Do Not Show" or div_shownum) and showDIVERGENCEDETECTOR
    if div_shownum and div_dnumdiv_top > 0
        div_divergence_text_top := div_divergence_text_top + str.tostring(div_dnumdiv_top)
    if div_shownum and div_dnumdiv_bottom > 0
        div_divergence_text_bottom := div_divergence_text_bottom + str.tostring(div_dnumdiv_bottom)
    if div_divergence_text_top != ""
        if div_showlast
            div_delete_old_neg_div_labels()
        array.push(div_neg_div_labels, 
                      label.new( x = bar_index, 
                                 y = math.max(high, high[1]), 
                                 text = div_divergence_text_top,
                                 color = div_top_label_col,
                                 textcolor = div_neg_div_text_col,
                                 style = label.style_label_down
                                 ))

    if div_divergence_text_bottom != ""
        if div_showlast
            div_delete_old_pos_div_labels()
        array.push(div_pos_div_labels, 
                      label.new( x = bar_index, 
                                 y = math.min(low, low[1]), 
                                 text = div_divergence_text_bottom,
                                 color = div_bottom_label_col, 
                                 textcolor = div_pos_div_text_col,
                                 style = label.style_label_up
                                 ))

alertcondition(div_pos_reg_div_detected and showDIVERGENCEDETECTOR, title='Regular positive divergence detected', message='Regular positive divergence detected')
alertcondition(div_neg_reg_div_detected and showDIVERGENCEDETECTOR, title='Regular negative divergence detected', message='Regular negative divergence detected')
alertcondition(div_pos_hid_div_detected and showDIVERGENCEDETECTOR, title='Hidden positive divergence detected', message='Hidden positive divergence detected')
alertcondition(div_neg_hid_div_detected and showDIVERGENCEDETECTOR, title='Hidden negative divergence detected', message='Hidden negative divergence detected')

alertcondition((div_pos_reg_div_detected or div_pos_hid_div_detected) and showDIVERGENCEDETECTOR, title='Positive divergence detected', message='Positive divergence detected')
alertcondition((div_neg_reg_div_detected or div_neg_hid_div_detected) and showDIVERGENCEDETECTOR, title='Negative divergence detected', message='Negative divergence detected')

vn_volumeNodesGroup = '7. Volume Profile and Node Detection'

vn_peakTTip = 'When the volume profile nodes of the N preceding and N succeeding nodes of the evaluated node are all lower than this node, it is identified as a volume peak node, where N is determined by the "Node Detection Percentage %" option'
vn_peaksShow = input.string('Peak', 'Volume Peak', options = ['Peak', 'Cluster', 'None'], inline = 'vnP', tooltip = vn_peakTTip, group = vn_volumeNodesGroup)
vn_peakVolumeColor = color.blue
vn_peaksNumberOfNodes = input.int(9, '  Node Detection Percentage %', minval = 0, maxval = 100, group = vn_volumeNodesGroup) / 100
vn_peaksShow := vn_peaksNumberOfNodes == 0 ? 'None' : vn_peaksShow

vn_troughsTTip = 'When the volume profile nodes of the N preceding and N succeeding nodes of the evaluated node all exceed this node, it is identified as a volume trough node, where N is determined by the "Node Detection Percentage %" option'
vn_troughsShow = input.string('None', 'Volume Trough', options = ['Trough', 'Cluster', 'None'], inline = 'vnT', tooltip = vn_troughsTTip, group = vn_volumeNodesGroup)
vn_troughVolumeColor = color.gray
vn_troughsNumberOfNodes = input.int(7, '  Node Detection Percentage %', minval = 0, maxval = 100, group = vn_volumeNodesGroup) / 100
vn_troughsShow := vn_troughsNumberOfNodes == 0 ? 'None' : vn_troughsShow

vn_thresholdTTip = 'The threshold specified as a percentage is used to detect peak/trough volume nodes. If a value is set, detection will ignore volume node values below the specified threshold.'
vn_VolumeNodeThreshold = input.int(1, 'Volume Node Threshold %', minval = 0, maxval = 100, tooltip = vn_thresholdTTip, group = vn_volumeNodesGroup) / 100

vn_highestNVolumeNodes = input.int(0, 'Highest Volume Node', minval = 0, maxval = 31, inline = 'vnL', group = vn_volumeNodesGroup)
vn_highestVolumeColor = color.orange

vn_lowestNVolumeNodes = input.int(0, 'Lowest Volume Node', minval = 0, maxval = 31, inline = 'vnH', group = vn_volumeNodesGroup)
vn_lowestVolumeColor = color.navy

vp_componentsGroup = 'Volume Profile - Components'

vp_profileShow = input.bool(true, 'Volume Profile', inline = 'vp', group = vp_componentsGroup)
vp_valueAreaUpColor = #2962ff
vp_valueAreaDwonColor = #fbc02d
vp_profileUpVolumeColor = #5d606b
vp_profileDownVolumeColor = #d1d4dc

vp_pocShow = input.string('None', 'Point of Control', options = ['Developing', 'Regular', 'None'], inline = 'poc', group = vp_componentsGroup)
vp_pocColor = #fbc02d
vp_pocWidth = input.int(2, 'Width', inline = 'poc', group = vp_componentsGroup)

vp_vahShow = input.bool(false, 'Value Area High (VAH)', inline = 'vah', group = vp_componentsGroup)
vp_vahColor = #2962ff

vp_valShow = input.bool(false, 'Value Area Low (VAL)', inline = 'val', group = vp_componentsGroup)
vp_valColor = #2962ff

vp_profileLevels = input.string('Small', 'Profile Price Labels', options = ['Tiny', 'Small', 'Normal', 'None'], group = vp_componentsGroup)

vp_displayGroup = 'Volume Profile - Display Settings'

vp_profileLength = input.int(360, 'Profile Lookback Length', minval = 10, maxval = 5000, step = 10, group = vp_displayGroup)
vp_profileLength := last_bar_index < vp_profileLength ? last_bar_index : vp_profileLength - 1

vp_valueAreaThreshold = input.float(70, 'Value Area (%)', minval = 0, maxval = 100, group = vp_displayGroup) / 100

vp_profilePlracment = input.string('Right', 'Profile Position', options = ['Right', 'Left'], group = vp_displayGroup)
profilePlacementRight = vp_profilePlracment == 'Right'
vp_profileNumberOfRows = input.int(100, 'Profile Rows', minval = 30, maxval = 130, step = 10, group = vp_displayGroup)
vp_profileWidth = input.float(31, 'Profile Width', minval = 0, maxval = 250, group = vp_displayGroup) / 100
vp_profileHorizontalOffset = input.int(13, 'Profile Horizontal Offset', maxval = 50, group = vp_displayGroup)

vp_valueAreaBackground = input.bool(false, 'Value Area Background  ', inline = 'vBG', group = vp_displayGroup)
vp_valueAreaBackgroundColor = #2962ff

vp_profileBackground = input.bool(false, 'Profile Range Background ', inline = 'pBG', group = vp_displayGroup)
vp_profileBackgroundColor = #2962ff

type BAR
    float open   = open
    float high   = high
    float low    = low
    float close  = close
    float volume = volume
    int   index  = bar_index

type barData
    float [] barHigh
    float [] barLow
    float [] barVolume
    bool  [] barPolarity
    int   [] barCount

type volumeData
    float [] totalVolume
    float [] bullishVolume
    float [] bearishVolume
    int   [] endProfileIndex
    bool  [] peakVolume
    bool  [] troughVolume

type volumeProfile
    box         []  boxes
    chart.point []  pocPoints
    polyline        pocPolyline
    int             pocLevel
    int             vahLevel
    int             valLevel
    int             startIndex

BAR bar = BAR.new()
BAR [] ltfBarData = array.new<BAR> (1, BAR.new())

var barData barDataArray = barData.new(
     array.new <float> (na), 
     array.new <float> (na), 
     array.new <float> (na), 
     array.new <bool>  (na), 
     array.new <int>   (na)
 )

volumeData volumeDataArray = volumeData.new(
     array.new <float> (vp_profileNumberOfRows, 0.), 
     array.new <float> (vp_profileNumberOfRows, 0.), 
     array.new <float> (vp_profileNumberOfRows, 0.),
     array.new <int>   (vp_profileNumberOfRows, 0 ),
     array.new <bool>  (vp_profileNumberOfRows, 0.),
     array.new <bool>  (vp_profileNumberOfRows, 0.)
 )

var volumeProfile VP = volumeProfile.new(
     array.new<box>         (na),
     array.new<chart.point> (na),
     polyline.new           (na), na, na, na, na
 )

var float highestPrice = na
var float lowestPrice = na

renderLine(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) =>
    var id = line.new(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width)
    line.set_xy1(id, _x1, _y1)
    line.set_xy2(id, _x2, _y2)
    line.set_color(id, _color)

renderLabel(_x, _y, _text, _color, _style, _textcolor, _size, _tooltip) =>
    var lb = label.new(_x, _y, _text, xloc.bar_index, yloc.price, _color, _style, _textcolor, _size, text.align_left, _tooltip)
    lb.set_xy(_x, _y)
    lb.set_text(_text)
    lb.set_tooltip(_tooltip)
    lb.set_textcolor(_textcolor)

requestBarData(_lowerTimeframe) => request.security_lower_tf(syminfo.tickerid, _lowerTimeframe, BAR.new(), ignore_invalid_timeframe = true)

calculateTimeframe(_depth) => 
    int tfInMs = timeframe.in_seconds(timeframe.period)
    int  mInMS = 60

    if _depth == 2
        switch
            tfInMs <                 30  =>  '1S'
            tfInMs <          1 * mInMS  =>  '5S'

            tfInMs <=        15 * mInMS  =>   '1'
            tfInMs <=        60 * mInMS  =>   '5'
            tfInMs <=       240 * mInMS  =>  '15'
            tfInMs <=      1440 * mInMS  =>  '60'
            => 'D'

    else if _depth == 1
        switch
            tfInMs <                 15  =>  '1S'
            tfInMs <                 30  =>  '5S'
            tfInMs <          1 * mInMS  => '15S'

            tfInMs <=         5 * mInMS  =>   '1'
            tfInMs <=        15 * mInMS  =>   '5'
            tfInMs <=        60 * mInMS  =>  '15'
            tfInMs <=       240 * mInMS  =>  '60'
            tfInMs <=      1440 * mInMS  => '240'
            => 'D'

getTextSize(_text) =>
    if _text != 'None'
        switch _text
            'Tiny'   => size.tiny
            'Small'  => size.small 
            'Normal' => size.normal
            => size.auto

profileLevesSize  = getTextSize(vp_profileLevels)

if bar.index == last_bar_index - vp_profileLength
    VP.startIndex := bar.index
    lowestPrice := bar.low 
    highestPrice := bar.high
else if bar.index > last_bar_index - vp_profileLength
    lowestPrice := math.min(bar.low, lowestPrice)
    highestPrice := math.max(bar.high, highestPrice)

if vp_profileLength <= 700
    ltfBarData := requestBarData(calculateTimeframe(2)) 
else
    ltfBarData := array.new<BAR> (1, BAR.new(bar.open, bar.high, bar.low, bar.close, bar.volume))

if barstate.ishistory and (bar.index >= last_bar_index - vp_profileLength) and bar.index < last_bar_index and ltfBarData.size() > 0

    if ltfBarData.size() > 0 and not na(nz(ltfBarData.get(0).volume))
        for currentLtfBar = 0 to ltfBarData.size() - 1
            barDataArray.barHigh.push(ltfBarData.get(currentLtfBar).high)
            barDataArray.barLow.push(ltfBarData.get(currentLtfBar).low)
            barDataArray.barVolume.push(ltfBarData.get(currentLtfBar).volume)
            barDataArray.barPolarity.push(ltfBarData.get(currentLtfBar).close > ltfBarData.get(currentLtfBar).open)

        barDataArray.barCount.push(ltfBarData.size())

priceStep = (highestPrice - lowestPrice) / vp_profileNumberOfRows

if barstate.islast and ltfBarData.size() > 0 and showVolumeProfile

    if VP.boxes.size() > 0
        for boxIndex = 0 to VP.boxes.size() - 1
            box.delete(VP.boxes.shift())

    if barDataArray.barCount.size() > vp_profileLength
        barCount = barDataArray.barCount.shift()
        for barCountIndex = 0 to barCount - 1
            barDataArray.barHigh.shift()
            barDataArray.barLow.shift()
            barDataArray.barVolume.shift()
            barDataArray.barPolarity.shift()

    VP.pocPoints.clear()
    VP.pocPolyline.delete()

    if ltfBarData.size() > 0 and not na(nz(ltfBarData.get(0).volume))
        for currentLtfBar = 0 to ltfBarData.size() - 1
            barDataArray.barHigh.push(ltfBarData.get(currentLtfBar).high)
            barDataArray.barLow.push(ltfBarData.get(currentLtfBar).low)
            barDataArray.barVolume.push(ltfBarData.get(currentLtfBar).volume)
            barDataArray.barPolarity.push(ltfBarData.get(currentLtfBar).close > ltfBarData.get(currentLtfBar).open)

        barDataArray.barCount.push(ltfBarData.size())

    barIndex = vp_profileLength
    numberOfBars = 0
    arraySize = barDataArray.barVolume.size()

    for arrayIndex = 0 to arraySize - 1

        levelHigh = barDataArray.barHigh.get(arrayIndex)
        levelLow = barDataArray.barLow.get(arrayIndex)
        levelVolume = barDataArray.barVolume.get(arrayIndex)

        int startSlotIndex = math.max(math.floor((levelLow - lowestPrice) / priceStep), 0)
        int endSlotIndex = math.min(math.floor((levelHigh - lowestPrice) / priceStep), vp_profileNumberOfRows - 1)

        for priceLevelIndex = startSlotIndex to endSlotIndex

            float priceLevel = lowestPrice + priceLevelIndex * priceStep

            volumeProportion = switch
                levelLow >= priceLevel and levelHigh > priceLevel + priceStep => (priceLevel + priceStep - levelLow) / (levelHigh - levelLow)
                levelHigh <= priceLevel + priceStep and levelLow < priceLevel => (levelHigh - priceLevel) / (levelHigh - levelLow)
                levelLow >= priceLevel and levelHigh <= priceLevel + priceStep => 1
                => priceStep / (levelHigh - levelLow)

            volumeDataArray.totalVolume.set(priceLevelIndex, volumeDataArray.totalVolume.get(priceLevelIndex) + levelVolume * volumeProportion)

            if barDataArray.barPolarity.get(arrayIndex)
                volumeDataArray.bullishVolume.set(priceLevelIndex, volumeDataArray.bullishVolume.get(priceLevelIndex) + levelVolume * volumeProportion)

        if vp_pocShow == 'Developing'
            if arrayIndex == barDataArray.barCount.get(vp_profileLength - barIndex)
                VP.pocPoints.push(chart.point.from_index(bar.index[barIndex], math.avg(bar.high[barIndex], bar.low[barIndex])))
                VP.pocPoints.push(chart.point.from_index(bar.index[barIndex] + 1, lowestPrice + (volumeDataArray.totalVolume.indexof(volumeDataArray.totalVolume.max()) + .5) * priceStep))
                numberOfBars += barDataArray.barCount.get(vp_profileLength - barIndex)
                barIndex  -= 1
            else if arrayIndex == (numberOfBars + barDataArray.barCount.get(vp_profileLength - barIndex)) and numberOfBars != 0
                VP.pocPoints.push(chart.point.from_index(bar.index[barIndex] + 1, lowestPrice + (volumeDataArray.totalVolume.indexof(volumeDataArray.totalVolume.max()) + .5) * priceStep))
                numberOfBars += barDataArray.barCount.get(vp_profileLength - barIndex)
                barIndex  -= 1
            else if barIndex == 0
                VP.pocPoints.push(chart.point.from_index(bar.index[barIndex] + 1, lowestPrice + (volumeDataArray.totalVolume.indexof(volumeDataArray.totalVolume.max()) + .5) * priceStep))
                numberOfBars += barDataArray.barCount.get(vp_profileLength - barIndex)

    VP.pocPolyline := polyline.new(VP.pocPoints, false, false, xloc.bar_index, vp_pocColor, color(na), line.style_solid, vp_pocWidth)

    for volumeIndex = 0 to vp_profileNumberOfRows - 1
        bearishVolume = 2 * volumeDataArray.bullishVolume.get(volumeIndex) - volumeDataArray.totalVolume.get(volumeIndex)
        volumeDataArray.bearishVolume.set(volumeIndex, volumeDataArray.bearishVolume.get(volumeIndex) + bearishVolume * (bearishVolume > 0 ? 1 : -1) )

    VP.pocLevel := volumeDataArray.totalVolume.indexof(volumeDataArray.totalVolume.max())
    totalTradedVolume = volumeDataArray.totalVolume.sum() * vp_valueAreaThreshold
    valueAreaVolume = VP.pocLevel != -1 ? volumeDataArray.totalVolume.get(VP.pocLevel) : 0
    VP.vahLevel := VP.pocLevel
    VP.valLevel := VP.pocLevel

    while valueAreaVolume < totalTradedVolume
        if VP.valLevel == 0 and VP.vahLevel == vp_profileNumberOfRows - 1
            break

        volumeAbovePOC = 0.
        if VP.vahLevel < vp_profileNumberOfRows - 1 
            volumeAbovePOC := volumeDataArray.totalVolume.get(VP.vahLevel + 1)

        volumeBelowPOC = 0.
        if VP.valLevel > 0
            volumeBelowPOC := volumeDataArray.totalVolume.get(VP.valLevel - 1)

        if volumeBelowPOC == 0 and volumeAbovePOC == 0
            break

        if volumeAbovePOC >= volumeBelowPOC
            valueAreaVolume  += volumeAbovePOC
            VP.vahLevel += 1
        else
            valueAreaVolume  += volumeBelowPOC
            VP.valLevel -= 1

    vahPrice = lowestPrice + (VP.vahLevel + 1.) * priceStep
    pocPrice = lowestPrice + (VP.pocLevel + .5) * priceStep
    valPrice = lowestPrice + (VP.valLevel + .0) * priceStep

    profilePlottingLength = vp_profileLength > 360 ? 360 : vp_profileLength
    profileWidth = profilePlottingLength * vp_profileWidth
    profileHorizontalOffset = int(profileWidth + vp_profileHorizontalOffset)

    if vp_profileShow and profilePlacementRight and vp_pocShow == 'Developing'
        renderLine(last_bar_index, pocPrice, profileHorizontalOffset + int(last_bar_index - profileWidth + 1), pocPrice, xloc.bar_index, extend.none, vp_pocColor, line.style_solid, vp_pocWidth)

    if vp_vahShow
        renderLine(VP.startIndex, vahPrice, 
                   profilePlacementRight ? (vp_profileShow ? profileHorizontalOffset : 0) + last_bar_index : last_bar_index, 
                   vahPrice, xloc.bar_index, extend.none, vp_vahColor, line.style_solid, 1)

    if vp_pocShow == 'Regular'
        renderLine(VP.startIndex, pocPrice, profilePlacementRight ? vp_profileShow ? profileHorizontalOffset + int(last_bar_index - profileWidth + 1) : last_bar_index : last_bar_index, pocPrice, xloc.bar_index, extend.none, vp_pocColor, line.style_solid, vp_pocWidth)

    if vp_valShow
        renderLine(VP.startIndex, valPrice, 
                   profilePlacementRight ? (vp_profileShow ? profileHorizontalOffset : 0) + last_bar_index : last_bar_index, 
                   valPrice, xloc.bar_index, extend.none, vp_valColor, line.style_solid, 1)

    if vp_valueAreaBackground
        VP.boxes.push(box.new(VP.startIndex, valPrice, last_bar_index, vahPrice, vp_valueAreaBackgroundColor, 1, line.style_dotted, bgcolor = vp_valueAreaBackgroundColor))

    if vp_profileBackground
        VP.boxes.push(box.new(VP.startIndex, lowestPrice, last_bar_index, highestPrice, vp_profileBackgroundColor, 1, line.style_dotted, bgcolor = vp_profileBackgroundColor))

    if vp_profileLevels != 'None' and VP.pocLevel != -1 
        renderLabel(profilePlacementRight ? (vp_profileShow ? profileHorizontalOffset : 0) + last_bar_index : vp_profileShow ? VP.startIndex : last_bar_index, 
                     highestPrice, str.tostring(highestPrice, format.mintick), color.new(color.black, 89), label.style_label_down, chart.fg_color, profileLevesSize, 'Profile High')

        renderLabel(profilePlacementRight ? (vp_profileShow ? profileHorizontalOffset : 0) + last_bar_index : last_bar_index, 
                     vahPrice, str.tostring(vahPrice, format.mintick), color.new(vp_vahColor, 89), label.style_label_left, vp_vahColor, profileLevesSize, 'Value Area High')

        renderLabel(profilePlacementRight ? (vp_profileShow ? profileHorizontalOffset : 0) + last_bar_index : last_bar_index, 
                     pocPrice, str.tostring(pocPrice, format.mintick), color.new(vp_pocColor, 89), label.style_label_left, vp_pocColor, profileLevesSize, 'Point of Control')

        renderLabel(profilePlacementRight ? (vp_profileShow ? profileHorizontalOffset : 0) + last_bar_index : last_bar_index, 
                     valPrice, str.tostring(valPrice, format.mintick), color.new(vp_valColor, 89), label.style_label_left, vp_valColor, profileLevesSize, 'Value Area Low')

        renderLabel(profilePlacementRight ? (vp_profileShow ? profileHorizontalOffset : 0) + last_bar_index : vp_profileShow ? VP.startIndex : last_bar_index, 
                     lowestPrice, str.tostring(lowestPrice, format.mintick), color.new(color.black, 89), label.style_label_up, chart.fg_color, profileLevesSize, 'Profile Low')

    for volumeNodeLevel = 0 to vp_profileNumberOfRows - 1

        if vp_profileShow
            startProfileIndex = profilePlacementRight ? 
                                 profileHorizontalOffset + int(last_bar_index - volumeDataArray.bullishVolume.get(volumeNodeLevel) / volumeDataArray.totalVolume.max() * profileWidth) :
                                 VP.startIndex
            endProfileIndex   = profilePlacementRight ? 
                                 profileHorizontalOffset + last_bar_index : 
                                 int(startProfileIndex + volumeDataArray.bullishVolume.get(volumeNodeLevel) / volumeDataArray.totalVolume.max() * profileWidth)

            VP.boxes.push(box.new(startProfileIndex, lowestPrice + (volumeNodeLevel + .1) * priceStep, endProfileIndex, lowestPrice + (volumeNodeLevel + .9) * priceStep, 
                                   color(na), bgcolor = volumeNodeLevel >= VP.valLevel and volumeNodeLevel <= VP.vahLevel ? vp_valueAreaUpColor : vp_profileUpVolumeColor))

            startProfileIndex := profilePlacementRight ? startProfileIndex : endProfileIndex
            endProfileIndex   := profilePlacementRight ? 
                                 startProfileIndex - int( (volumeDataArray.totalVolume.get(volumeNodeLevel) - volumeDataArray.bullishVolume.get(volumeNodeLevel)) / volumeDataArray.totalVolume.max() * profileWidth) : 
                                 startProfileIndex + int( (volumeDataArray.totalVolume.get(volumeNodeLevel) - volumeDataArray.bullishVolume.get(volumeNodeLevel)) / volumeDataArray.totalVolume.max() * profileWidth)

            VP.boxes.push(box.new(startProfileIndex, lowestPrice + (volumeNodeLevel + .1) * priceStep, endProfileIndex, lowestPrice + (volumeNodeLevel + .9) * priceStep, 
                                   color(na), bgcolor = volumeNodeLevel >= VP.valLevel and volumeNodeLevel <= VP.vahLevel ? vp_valueAreaDwonColor : vp_profileDownVolumeColor))
            volumeDataArray.endProfileIndex.set(volumeNodeLevel, endProfileIndex)

    if  vn_peaksShow != 'None' or  vn_troughsShow != 'None'
        var int startVolumeNodeIndex = na, var int endVolumeNodeIndex = na
        var bool peakUpperNth = na, var bool peakLowerNth = na

        peaksNumberOfNodes = int(vp_profileNumberOfRows * vn_peaksNumberOfNodes)

        tempPeakTotalVolume = volumeDataArray.totalVolume.copy()

        for index = 1 to peaksNumberOfNodes
            tempPeakTotalVolume.unshift(0.)
            tempPeakTotalVolume.push(0.)

        for volumeNodeLevel = 0 to vp_profileNumberOfRows - 1 + 2 * peaksNumberOfNodes 

            if vn_peaksShow != 'None' and volumeNodeLevel >= 2 * peaksNumberOfNodes 

                for currentVolumeNode = volumeNodeLevel - 2 * peaksNumberOfNodes to volumeNodeLevel - peaksNumberOfNodes - 1
                    if tempPeakTotalVolume.get(volumeNodeLevel - peaksNumberOfNodes) <= tempPeakTotalVolume.get(currentVolumeNode)
                        peakUpperNth := false
                        break
                    else
                        peakUpperNth := true

                for currentVolumeNode = volumeNodeLevel - peaksNumberOfNodes + 1 to volumeNodeLevel
                    if tempPeakTotalVolume.get(volumeNodeLevel - peaksNumberOfNodes) <= tempPeakTotalVolume.get(currentVolumeNode)
                        peakLowerNth := false
                        break
                    else
                        peakLowerNth := true

                if peakUpperNth and peakLowerNth and tempPeakTotalVolume.get(volumeNodeLevel - peaksNumberOfNodes) / tempPeakTotalVolume.max() > vn_VolumeNodeThreshold

                    startVolumeNodeIndex := vp_profileShow ? profilePlacementRight ? 
                                                             VP.startIndex : 
                                                             volumeDataArray.endProfileIndex.get(volumeNodeLevel - 2 * peaksNumberOfNodes) : 
                                             VP.startIndex

                    endVolumeNodeIndex   := vp_profileShow ? profilePlacementRight ? 
                                                             volumeDataArray.endProfileIndex.get(volumeNodeLevel - 2 * peaksNumberOfNodes) : 
                                                             last_bar_index : 
                                             last_bar_index

                    VP.boxes.push(box.new(startVolumeNodeIndex, lowestPrice + (volumeNodeLevel - 2 * peaksNumberOfNodes + .1) * priceStep, endVolumeNodeIndex, lowestPrice + (volumeNodeLevel - 2 * peaksNumberOfNodes + .9) * priceStep, 
                                          color(na), bgcolor = vn_peakVolumeColor))

                    if vn_peaksShow == 'Cluster'

                        for currentVolumeNode = volumeNodeLevel - 2 * peaksNumberOfNodes to volumeNodeLevel

                            if currentVolumeNode >= peaksNumberOfNodes and currentVolumeNode <= vp_profileNumberOfRows - 1 + peaksNumberOfNodes
                                if not volumeDataArray.peakVolume.get(currentVolumeNode - peaksNumberOfNodes)

                                    startVolumeNodeIndex := vp_profileShow ? profilePlacementRight ? 
                                                                         VP.startIndex : 
                                                                         volumeDataArray.endProfileIndex.get(currentVolumeNode - peaksNumberOfNodes) : 
                                                         VP.startIndex

                                    endVolumeNodeIndex   := vp_profileShow ? profilePlacementRight ? 
                                                                         volumeDataArray.endProfileIndex.get(currentVolumeNode - peaksNumberOfNodes) : 
                                                                         last_bar_index : 
                                                         last_bar_index

                                    VP.boxes.push(box.new(startVolumeNodeIndex, lowestPrice + (currentVolumeNode - peaksNumberOfNodes + .0) * priceStep, endVolumeNodeIndex, lowestPrice + (currentVolumeNode - peaksNumberOfNodes + 1.) * priceStep, 
                                                       color(na), bgcolor = vn_peakVolumeColor))
                                    volumeDataArray.peakVolume.set(currentVolumeNode - peaksNumberOfNodes, true)

        tempPeakTotalVolume.clear()

        var bool troughUpperNth = na, var bool troughLowerNth = na
        troughsNumberOfNodes = int(vp_profileNumberOfRows * vn_troughsNumberOfNodes)

        tempTroughTotalVolume = volumeDataArray.totalVolume.copy()

        for index = 1 to troughsNumberOfNodes
            tempTroughTotalVolume.unshift(volumeDataArray.totalVolume.max())
            tempTroughTotalVolume.push(volumeDataArray.totalVolume.max())

        for volumeNodeLevel = 0 to vp_profileNumberOfRows - 1 + 2 * troughsNumberOfNodes 

            if vn_troughsShow != 'None' and volumeNodeLevel >= 2 * troughsNumberOfNodes 

                for currentVolumeNode = volumeNodeLevel - 2 * troughsNumberOfNodes to volumeNodeLevel - troughsNumberOfNodes - 1
                    if tempTroughTotalVolume.get(volumeNodeLevel - troughsNumberOfNodes) >= tempTroughTotalVolume.get(currentVolumeNode)
                        troughUpperNth := false
                        break
                    else
                        troughUpperNth := true

                for currentVolumeNode = volumeNodeLevel - troughsNumberOfNodes + 1 to volumeNodeLevel
                    if tempTroughTotalVolume.get(volumeNodeLevel - troughsNumberOfNodes) >= tempTroughTotalVolume.get(currentVolumeNode)
                        troughLowerNth := false
                        break
                    else
                        troughLowerNth := true

                if troughUpperNth and troughLowerNth and tempTroughTotalVolume.get(volumeNodeLevel - troughsNumberOfNodes) / tempTroughTotalVolume.max() > vn_VolumeNodeThreshold

                    startVolumeNodeIndex := vp_profileShow ? profilePlacementRight ? 
                                                             VP.startIndex : 
                                                             volumeDataArray.endProfileIndex.get(volumeNodeLevel - 2 * troughsNumberOfNodes) : 
                                             VP.startIndex

                    endVolumeNodeIndex   := vp_profileShow ? profilePlacementRight ? 
                                                             volumeDataArray.endProfileIndex.get(volumeNodeLevel - 2 * troughsNumberOfNodes) : 
                                                             last_bar_index : 
                                             last_bar_index

                    VP.boxes.push(box.new(startVolumeNodeIndex, lowestPrice + (volumeNodeLevel - 2 * troughsNumberOfNodes + .1) * priceStep, endVolumeNodeIndex, lowestPrice + (volumeNodeLevel - 2 * troughsNumberOfNodes + .9) * priceStep, 
                                          color(na), bgcolor = vn_troughVolumeColor))

                    if vn_troughsShow == 'Cluster'

                        for currentVolumeNode = volumeNodeLevel - 2 * troughsNumberOfNodes to volumeNodeLevel

                            if currentVolumeNode >= troughsNumberOfNodes and currentVolumeNode <= vp_profileNumberOfRows - 1 + troughsNumberOfNodes

                                if not volumeDataArray.troughVolume.get(currentVolumeNode - troughsNumberOfNodes)
                                    startVolumeNodeIndex := vp_profileShow ? profilePlacementRight ? 
                                                                         VP.startIndex : 
                                                                         volumeDataArray.endProfileIndex.get(currentVolumeNode - troughsNumberOfNodes) : 
                                                         VP.startIndex

                                    endVolumeNodeIndex   := vp_profileShow ? profilePlacementRight ? 
                                                                         volumeDataArray.endProfileIndex.get(currentVolumeNode - troughsNumberOfNodes) : 
                                                                         last_bar_index : 
                                                         last_bar_index

                                    VP.boxes.push(box.new(startVolumeNodeIndex, lowestPrice + (currentVolumeNode - troughsNumberOfNodes + .0) * priceStep, endVolumeNodeIndex, lowestPrice + (currentVolumeNode - troughsNumberOfNodes + 1.) * priceStep, 
                                                      color(na), bgcolor = vn_troughVolumeColor))
                                    volumeDataArray.troughVolume.set(currentVolumeNode - troughsNumberOfNodes, true)

        tempTroughTotalVolume.clear()

    if vn_highestNVolumeNodes > 0
        for highestNode = 0 to vn_highestNVolumeNodes - 1
            startVolumeNodeIndex = vp_profileShow ? profilePlacementRight ? 
                                                     VP.startIndex : 
                                                     volumeDataArray.endProfileIndex.get(volumeDataArray.totalVolume.indexof(volumeDataArray.totalVolume.max(highestNode))) : 
                                     VP.startIndex
            endVolumeNodeIndex   = vp_profileShow ? profilePlacementRight ? 
                                                     volumeDataArray.endProfileIndex.get(volumeDataArray.totalVolume.indexof(volumeDataArray.totalVolume.max(highestNode))) : 
                                                     last_bar_index : 
                                     last_bar_index

            VP.boxes.push(box.new(startVolumeNodeIndex, lowestPrice + (volumeDataArray.totalVolume.indexof(volumeDataArray.totalVolume.max(highestNode)) + .1) * priceStep, endVolumeNodeIndex, lowestPrice + (volumeDataArray.totalVolume.indexof(volumeDataArray.totalVolume.max(highestNode)) + .9) * priceStep, color(na), bgcolor = vn_highestVolumeColor))

    if vn_lowestNVolumeNodes > 0

        lowestNVolumeNodeCount = 0
        lowestNVolumeNodeIndex = 0
        lowestNVolumeNodeValue = 0.

        while lowestNVolumeNodeCount < vn_lowestNVolumeNodes

            if lowestNVolumeNodeIndex == vp_profileNumberOfRows
                break

            if volumeDataArray.totalVolume.min(lowestNVolumeNodeIndex) != lowestNVolumeNodeValue
                lowestNVolumeNodeValue := volumeDataArray.totalVolume.min(lowestNVolumeNodeIndex)

                startVolumeNodeIndex = vp_profileShow ? profilePlacementRight ? 
                                                     VP.startIndex : 
                                                     volumeDataArray.endProfileIndex.get(volumeDataArray.totalVolume.indexof(volumeDataArray.totalVolume.min(lowestNVolumeNodeIndex))) : 
                                     VP.startIndex

                endVolumeNodeIndex   = vp_profileShow ? profilePlacementRight ? 
                                                     volumeDataArray.endProfileIndex.get(volumeDataArray.totalVolume.indexof(volumeDataArray.totalVolume.min(lowestNVolumeNodeIndex))) : 
                                                     last_bar_index : 
                                     last_bar_index

                VP.boxes.push(box.new(startVolumeNodeIndex, lowestPrice + (volumeDataArray.totalVolume.indexof(volumeDataArray.totalVolume.min(lowestNVolumeNodeIndex)) + .1) * priceStep, endVolumeNodeIndex, lowestPrice + (volumeDataArray.totalVolume.indexof(volumeDataArray.totalVolume.min(lowestNVolumeNodeIndex)) + .9) * priceStep, color(na), bgcolor = vn_lowestVolumeColor))
                lowestNVolumeNodeCount += 1
            lowestNVolumeNodeIndex += 1

BULLISH_LEG                     = 1
BEARISH_LEG                     = 0
BULLISH                         = +1
BEARISH                         = -1
GREEN                           = #089981
RED                             = #F23645
BLUE                            = #2157f3
GRAY                            = #878b94
MONO_BULLISH                    = #b2b5be
MONO_BEARISH                    = #5d606b
HISTORICAL                      = 'Historical Mode'
PRESENT                         = 'Current Mode'
COLORED                         = 'Colored'
MONOCHROME                      = 'Monochrome'
ALL                             = 'All'
BOS                             = 'Break of Structure'
CHOCH                           = 'Change of Character'
TINY                            = size.tiny
SMALL                           = size.small
NORMAL                          = size.normal
ATR                             = 'ATR'
RANGE                           = 'Cumulative Average Range'
CLOSE                           = 'Close'
HIGHLOW                         = 'High/Low'
SOLID                           = '⎯⎯⎯'
DASHED                          = '----'
DOTTED                          = '····'

SMART_GROUP                     = '8. Smart Money Concepts'
INTERNAL_GR

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

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

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

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

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

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

Стоимость полного кода
11 755,70₽ ≈ $143.68