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

JimHotep Price Action Concepts Premium

jimhotep price action concepts premium @jimhotep.pine

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

#__slope direction line.mq5MQL5 / MetaTrader 5 · 1 общих теговrange breakout @meowforex1.pineTradingView · 1 общих тегов#1.mtf_collider_h4_close_13_v18bar.mq4MQL4 / MetaTrader 4 · 1 общих тегов!mth_fasttmaline_edit3.mq4MQL4 / MetaTrader 4 · 1 общих тегов!mth_fasttmaline_edit2.mq4MQL4 / MetaTrader 4 · 1 общих тегов!mth_fasttmaline_edit.mq4MQL4 / MetaTrader 4 · 1 общих тегов
Вы автор или правообладатель?

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

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

О программе

JimHotep Price Action Concepts Premium — это индикатор анализа для TradingView, работающий поверх графика цены. Он объединяет несколько концепций анализа рыночной структуры: зоны ICT OTE, зоны ликвидности, сигналы рыночной структуры (BOS и CHoCH), ордер-блоки, зоны справедливой стоимости (FVG), зоны накопления и распределения, а также линии тренда Titanium Trendline. Индикатор использует технические расчёты Pine Script, включая расчёт скользящих средних, линейную регрессию и анализ свечей. Он получает данные с других таймфреймов и символов через request.security() для построения мультитаймфреймовых таблиц и сигналов. Отображаются линии, прямоугольники, метки и цветовая индикация свечей на графике. Пользователь может настраивать отображение каждого компонента, цвета, прозрачность, фильтрацию сигналов и параметры расчётов. Индикатор поддерживает динамические оповещения TradingView для различных событий рынка, включая BOS, CHoCH, касания ордер-блоков, ликвидационные захваты и обнаружение зон.

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

НастройкаОписание
show_ote Afficher la zone ICT OTE — Включает или отключает отображение зоны ICT OTE на графике
fib_lower Niveau Fibonacci Inférieur — Нижний уровень Фибоначчи для расчёта границ зоны OTE
fib_upper Niveau Fibonacci Supérieur — Верхний уровень Фибоначчи для расчёта границ зоны OTE
show_lines Afficher les lignes OTE — Включает или отключает отображение горизонтальных линий OTE
line_per_day Une seule ligne par jour — Ограничивает отображение одной линии OTE в день
filter_level Niveau de filtrage — Уровень фильтрации линий OTE по силе движения
line_width Épaisseur des lignes — Толщина линий OTE
line_style Style des lignes — Стиль линий OTE
lookback Pivot Point Length — Длина периода для определения точек разворота
liq_valid Liquidation Validity — Максимальное количество баров для признания ликвидации действительной
liq_bool Use Pivot Length — Использовать длину пивота для параметра ликвидности
show_liquidity_zone Show Liquidity Zone — Включает или отключает отображение зоны ликвидности
lz_redVectorColor Vector: Red — Цвет вектора красного направления
lz_greenVectorColor Green — Цвет вектора зелёного направления
lz_violetVectorColor Violet — Цвет вектора фиолетового направления
lz_blueVectorColor Blue — Цвет вектора синего направления
lz_regularCandleUpColor Regular: Up Candle — Цвет обычной бычьей свечи
lz_regularCandleDownColor Down Candle — Цвет обычной медвежьей свечи
lz_setcandlecolors Set PVSRA candle colors? — Использовать цвета PVSRA для свечей
lz_zonesMax Maximum zones to draw — Максимальное количество зон для отрисовки
lz_zoneType Zone top/bottom is defined with: — Способ определения верхней и нижней границы зоны
lz_zoneUpdateType Zones are cleared using candle: — Условие очистки зон на основе свечи
lz_borderWidth Zone border width — Ширина границы зоны
lz_colorOverride Override color? — Переопределить цвет зоны
lz_zoneColor Color — Цвет зоны при переопределении
lz_transparency Zone Transparency — Прозрачность зон
lz_overrideSym Override chart symbol? — Переопределить символ графика для расчётов
lz_pvsraSym Symbol override — Символ для переопределения расчётов
HH_css HH & HL — Цвет для HH и HL
LL_css LL & LH — Цвет для LL и LH
enable_signals Activer les signaux momentum — Включить или отключить отображение сигналов моментума
momentum_transp Transparence des labels momentum (0=opaque, 100=transparent) — Прозрачность меток моментума
show_LL Afficher LL (Lower Low) — Показывать сигнал Lower Low
show_HL Afficher HL (Higher Low) — Показывать сигнал Higher Low
show_HH Afficher HH (Higher High) — Показывать сигнал Higher High
show_LH Afficher LH (Lower High) — Показывать сигнал Lower High
css_candle Candle Options — Режим окраски свечей
show_liq Hide Liquidity Swipe — Скрыть или показать свайп ликвидности
show_pivot Hide Pivot Point — Скрыть или показать точки разворота
show_wick Hide Liquidation Wicks Point — Скрыть или показать точки ликвидации по теням
css_bull Bull CHoCH — Цвет бычьего CHoCH
css_bear Bear CHoCH — Цвет медвежьего CHoCH
css_up Up Candle — Цвет бычьей свечи
css_dn Down Candle — Цвет медвежьей свечи
major_trans Transp Major Liquidation — Прозрачность основной ликвидации
minor_trans Transp Minor Liquidation — Прозрачность второстепенной ликвидации
liq_bear_minor Bearish Liquidity Minor Swipe — Цвет медвежьего второстепенного свайпа ликвидности
liq_bull_minor Bullish Liquidity Minor Swipe — Цвет бычьего второстепенного свайпа ликвидности
liq_bear_major Bearish Liquidity Major Swipe — Цвет медвежьего основного свайпа ликвидности
liq_bull_major Bullish Liquidity Major Swipe — Цвет бычьего основного свайпа ликвидности
liq_wick_lh Bearish Liquidation wick — Цвет медвежьей ликвидации по теню
liq_wick_hl Bearish Liquidation wick — Цвет медвежьей ликвидации по теню
lbl_size Pivot Text size — Размер текста точек разворота
txt_size Market structure Text size — Размер текста рыночной структуры
BOS_bull_css Bullish BOS — Цвет бычьего BOS
BOS_bear_css Bullish BOS — Цвет медвежьего BOS
CHOCH_bull_css Bullish CHoCH — Цвет бычьего CHoCH
CHOCH_bear_css Bearish CHoCH — Цвет медвежьего CHoCH
show_swing_ms Swing — Отображение свинг-структуры
show_internal_ms Internal — Отображение внутренней структуры
alert_bos_count Alerte après N BOS — Количество BOS для срабатывания оповещения
internal_r_lookback ernal_r_lookback — Внутренний период линейной регрессии
swing_r_lookback swing_r_lookback — Период свинг-линейной регрессии
ms_mode Market Structure Mode — Режим определения рыночной структуры
show_mtf_str MTF Scanner — Включить мультитаймфреймовый сканер структуры
show_eql Show EQH/EQL — Показывать уровни EQH и EQL
plotcandle_bool Plotcandle — Включить альтернативное отображение свечей
barcolor_bool Bar Color — Включить окраску тел свечей по структуре
i_ms_up_BOS i_ms_up_BOS — Цвет внутреннего бычьего BOS
i_ms_dn_BOS i_ms_dn_BOS — Цвет внутреннего медвежьего BOS
s_ms_up_BOS s_ms_up_BOS — Цвет свинг бычьего BOS
s_ms_dn_BOS s_ms_dn_BOS — Цвет свинг медвежьего BOS
lvl_daily Day — Показывать дневные уровни
lvl_weekly Week — Показывать недельные уровни
lvl_monthly Month — Показывать месячные уровни
lvl_yearly Year — Показывать годовые уровни
css_d css_d — Цвет дневных уровней
css_w css_w — Цвет недельных уровней
css_m css_m — Цвет месячных уровней
css_y css_y — Цвет годовых уровней
s_d s_d — Стиль линии дневных уровней
s_w s_w — Стиль линии недельных уровней
s_m s_m — Стиль линии месячных уровней
s_y s_y — Стиль линии годовых уровней
ob_show Show Last — Показывать последние ордер-блоки
ob_num ob_num — Количество отображаемых ордер-блоков
ob_metrics_show Internal Buy/Sell Activity — Показывать метрики объёма ордер-блоков
css_metric_up css_metric_up — Цвет метрики бычьего объёма
css_metric_dn css_metric_dn — Цвет метрики медвежьего объёма
ob_swings Swing Order Blocks — Показывать свинг-ордер-блоки
css_swing_up css_swing_up — Цвет бычьего свинг-ордер-блока
css_swing_dn css_swing_dn — Цвет медвежьего свинг-ордер-блока
ob_filter Filtering — Фильтрация ордер-блоков по сигналам
ob_mitigation Mitigation — Условие удаления ордер-блоков
ob_pos Positioning — Позиционирование ордер-блока на свече
use_grayscale Grayscale — Использовать градации серого для ордер-блоков
use_show_metric Show Metrics — Показывать метрики объёма ордер-блоков
use_middle_line Show Middle-Line — Показывать среднюю линию ордер-блока
use_overlap Hide Overlap — Скрывать перекрывающиеся ордер-блоки
use_overlap_method Overlap Method — Метод обработки перекрывающихся ордер-блоков
Получить полный код

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

indicator("JimHotep Price Action Concepts Premium", shorttitle = "JimHotep Price Action Concepts Premium", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_bars_back = 500, max_polylines_count = 100)

ote_group = "ICT OTE Zone"
show_ote = input.bool(false, "Afficher la zone ICT OTE", group=ote_group)
fib_lower = input.float(0.618, title='Lower Fibonacci Level', group=ote_group)
fib_upper = input.float(0.786, title='Upper Fibonacci Level', group=ote_group)

show_lines = input.bool(true, "Afficher les lignes OTE", group=ote_group)
line_per_day = input.bool(true, "Une seule ligne par jour", tooltip="Display only one high and low line per day", group=ote_group)

filter_level = input.string("Moyen", "Niveau de filtrage", 
     options=["Minimum", "Moyen", "High", "Maximum (toutes)"], 
     tooltip="Controls the number of lines displayed based on movement strength",
     group=ote_group)

line_width = input.int(3, "Line thickness", minval=1, maxval=5, group=ote_group)
line_style = input.string("Solid", "Style des lignes", options=["Solid", "Dashed", "Dotted"], group=ote_group)

daily_high = request.security(syminfo.tickerid, 'D', high[1], lookahead=barmerge.lookahead_off)
daily_low = request.security(syminfo.tickerid, 'D', low[1], lookahead=barmerge.lookahead_off)

daily_body_size = math.abs(daily_high - daily_low)
daily_atr = request.security(syminfo.tickerid, 'D', ta.atr(14))[1]
daily_strength = (daily_body_size / daily_atr) * 100

var float min_strength = 1.0  // Seuil bas pour les mouvements faibles
var float med_strength = 2.0  //Average threshold for moderate movements
var float high_strength = 3.0 // Seuil haut pour les mouvements forts

line_style_solid = line_style == "Solid" ? line.style_solid : line_style == "Dashed" ? line.style_dashed : line.style_dotted

var float last_daily_high = na
var float last_daily_low = na
var bool new_day = false

if not na(daily_high) and (na(last_daily_high) or daily_high != last_daily_high)
    last_daily_high := daily_high
    new_day := true
else
    new_day := false

if not na(daily_low) and (na(last_daily_low) or daily_low != last_daily_low)
    last_daily_low := daily_low

ote_upper = daily_high - (daily_high - daily_low) * fib_lower
ote_lower = daily_high - (daily_high - daily_low) * fib_upper

var line ote_high_line = na
var line ote_low_line = na

bool is_strong_day = true
if filter_level == "High"
    is_strong_day := daily_strength >= high_strength
else if filter_level == "Moyen"
    is_strong_day := daily_strength >= med_strength
else if filter_level == "Minimum"
    is_strong_day := daily_strength >= min_strength

bool show_high_line = show_ote and show_lines and (filter_level == "Maximum (toutes)" or is_strong_day) and (not line_per_day or new_day)
bool show_low_line = show_ote and show_lines and (filter_level == "Maximum (toutes)" or is_strong_day) and (not line_per_day or new_day)

if barstate.islast and (show_high_line or show_low_line)
    line.delete(ote_high_line)
    line.delete(ote_low_line)

    if show_high_line
        ote_high_line := line.new(x1=bar_index[1], y1=daily_high, x2=bar_index, y2=daily_high, 
                               color=color.new(color.red, 30), width=line_width, style=line_style_solid, 
                               extend=extend.right)

    if show_low_line
        ote_low_line := line.new(x1=bar_index[1], y1=daily_low, x2=bar_index, y2=daily_low, 
                              color=color.new(color.green, 30), width=line_width, style=line_style_solid, 
                              extend=extend.right)

ote_upper_plot = plot(show_ote ? ote_upper : na, color=color.new(color.gray, 50), linewidth=1, title='OTE Upper', trackprice=false)
ote_lower_plot = plot(show_ote ? ote_lower : na, color=color.new(color.gray, 50), linewidth=1, title='OTE Lower', trackprice=false)
fill(ote_upper_plot, ote_lower_plot, color=color.new(color.silver, 90))

lookback = input.int(12,"Pivot Point Length",minval = 2,group = " Liquidity Concepts")
liq_valid = input.int(7,"Liquidation Validity",minval = 1,tooltip = "Measure how many candles should max pass to count as liquidity. Ex: if set to 7, the liquidation should happen in those 7 bars; otherwise, it is not valid.",inline = "AA",group = "Inputs")
liq_bool = input.bool(true,"Use Pivot Length",inline = "AA",group = "???? Liquidity Concepts")

liquidity_zone_group = "???? Liquidity Zone"
show_liquidity_zone = input.bool(true, "Show Liquidity Zone", group=liquidity_zone_group)

lz_redVectorColor = input.color(title='Vector: Red', group=liquidity_zone_group, defval=color.red, inline='vectors')
lz_greenVectorColor = input.color(title='Green', group=liquidity_zone_group, defval=color.lime, inline='vectors')
lz_violetVectorColor = input.color(title='Violet', group=liquidity_zone_group, defval=color.fuchsia, inline='vectors')
lz_blueVectorColor = input.color(title='Blue', group=liquidity_zone_group, defval=color.blue, inline='vectors')
lz_regularCandleUpColor = input.color(title='Regular: Up Candle', group=liquidity_zone_group, defval=#999999, inline='nonVectors')
lz_regularCandleDownColor = input.color(title='Down Candle', group=liquidity_zone_group, defval=#4d4d4d, inline='nonVectors')
lz_setcandlecolors = input.bool(false, title='Set PVSRA candle colors?', group=liquidity_zone_group, inline='setCandle')
lz_zonesMax = input.int(500, 'Maximum zones to draw', group=liquidity_zone_group)
lz_zoneType = input.string(group=liquidity_zone_group, defval='Body only', title='Zone top/bottom is defined with: ', options=['Body only', 'Body with wicks'])
lz_zoneUpdateType = input.string(group=liquidity_zone_group, defval='Body with wicks', title='Zones are cleared using candle: ', options=['Body only', 'Body with wicks'])
lz_borderWidth = input.int(0, 'Zone border width', group=liquidity_zone_group)
lz_colorOverride = input.bool(true, 'Override color?' , group=liquidity_zone_group, inline="vcz1")
lz_zoneColor = input.color(title='Color', group=liquidity_zone_group, defval=color.rgb(255, 230, 75, 90), inline="vcz1", tooltip='the vector candle zones color to use if you dont not want to use the PVSRA Candle Colors.')
lz_transparency = input.int(90, 'Zone Transparency', minval = 0, maxval = 100, group=liquidity_zone_group, tooltip='Transparency for the vector candle zones.')
lz_overrideSym = input.bool(group=liquidity_zone_group, title='Override chart symbol?', defval=false, inline='pvsra')
lz_pvsraSym = input.string(group=liquidity_zone_group, title='Symbol override', defval='INDEX:BTCUSD', tooltip='Override symbol for PVSRA logic.', inline='pvsra')

import TradersReality/Traders_Reality_Lib/1 as trLib

lz_pvsraVolume() => request.security(lz_overrideSym ? lz_pvsraSym : syminfo.tickerid, '', volume, barmerge.gaps_off, barmerge.lookahead_off)
lz_pvsraHigh()   => request.security(lz_overrideSym ? lz_pvsraSym : syminfo.tickerid, '', high,   barmerge.gaps_off, barmerge.lookahead_off)
lz_pvsraLow()    => request.security(lz_overrideSym ? lz_pvsraSym : syminfo.tickerid, '', low,    barmerge.gaps_off, barmerge.lookahead_off)
lz_pvsraClose()  => request.security(lz_overrideSym ? lz_pvsraSym : syminfo.tickerid, '', close,  barmerge.gaps_off, barmerge.lookahead_off)
lz_pvsraOpen()   => request.security(lz_overrideSym ? lz_pvsraSym : syminfo.tickerid, '', open,   barmerge.gaps_off, barmerge.lookahead_off)

color lz_barcolor = na
if show_liquidity_zone
    lz_pvsraVolumeV = lz_pvsraVolume()
    lz_pvsraHighV = lz_pvsraHigh()
    lz_pvsraLowV = lz_pvsraLow()
    lz_pvsraCloseV = lz_pvsraClose()
    lz_pvsraOpenV = lz_pvsraOpen()
    [lz_pvsraColor, lz_alertFlag, lz_averageVolume, lz_volumeSpread, lz_highestVolumeSpread] = trLib.calcPvsra(lz_pvsraVolumeV, lz_pvsraHighV, lz_pvsraLowV, lz_pvsraCloseV, lz_pvsraOpenV, lz_redVectorColor, lz_greenVectorColor, lz_violetVectorColor, lz_blueVectorColor, lz_regularCandleDownColor, lz_regularCandleUpColor)

    var lz_zoneBoxesAbove = array.new_box()
    var lz_zoneBoxesBelow = array.new_box()

    lz_barcolor := lz_setcandlecolors ? lz_pvsraColor : na
    lz_pvsra = trLib.getPvsraFlagByColor(lz_pvsraColor, lz_redVectorColor, lz_greenVectorColor, lz_violetVectorColor, lz_blueVectorColor, lz_regularCandleUpColor)
    trLib.updateZones(lz_pvsra, 0, lz_zoneBoxesBelow, lz_zonesMax, lz_pvsraHighV, lz_pvsraLowV, lz_pvsraOpenV, lz_pvsraCloseV, lz_transparency, lz_zoneUpdateType, lz_zoneColor, lz_zoneType, lz_borderWidth, lz_colorOverride, lz_redVectorColor, lz_greenVectorColor, lz_violetVectorColor, lz_blueVectorColor)
    trLib.updateZones(lz_pvsra, 1, lz_zoneBoxesAbove, lz_zonesMax, lz_pvsraHighV, lz_pvsraLowV, lz_pvsraOpenV, lz_pvsraCloseV, lz_transparency, lz_zoneUpdateType, lz_zoneColor, lz_zoneType, lz_borderWidth, lz_colorOverride, lz_redVectorColor, lz_greenVectorColor, lz_violetVectorColor, lz_blueVectorColor)
    trLib.cleanarr(lz_zoneBoxesAbove)
    trLib.cleanarr(lz_zoneBoxesBelow)

barcolor(lz_barcolor)

switch liq_bool
    true => liq_valid := lookback
    false => na
    => liq_valid

HH_css = input.color(color.white, "HH & HL", inline = "HHLL2", group = "???? Liquidity Concepts")
LL_css = input.color(color.gray , "LL & LH", inline = "HHLL2", group = "???? Liquidity Concepts")

enable_signals = input.bool(true, "Activer les signaux momentum", group="???? Liquidity Concepts")
momentum_transp = input.int(80, minval=0, maxval=100, title="Transparence des labels momentum (0=opaque, 100=transparent)", group="???? Liquidity Concepts")
show_LL = input.bool(true, title="Afficher LL (Lower Low)", group="???? Liquidity Concepts")
show_HL = input.bool(true, title="Afficher HL (Higher Low)", group="???? Liquidity Concepts")
show_HH = input.bool(true, title="Afficher HH (Higher High)", group="???? Liquidity Concepts")
show_LH = input.bool(true, title="Afficher LH (Lower High)", group="???? Liquidity Concepts")

color_LL = color.new(color.blue, momentum_transp)
color_HL = color.new(color.aqua, momentum_transp)
color_HH = color.new(color.red, momentum_transp)
color_LH = color.new(color.orange, momentum_transp)

css_candle = input.string("CHoCH", "Candle Options",options = ["CHoCH","Default"])

show_liq = input.bool(true,"Hide Liquidity Swipe",group = "Settings")
show_pivot = input.bool(false,"Hide Pivot Point",group = "Settings")
show_wick = input.bool(false,"Hide Liquidation Wicks Point",group = "Settings")

css_bull = input.color(#089981  , "Bull CHoCH", inline = "Color 1", group = "Colors trend")
css_bear = input.color(color.red, "Bear CHoCH", inline = "Color 1", group = "Colors trend")

css_up = input.color(color.gray,  "Up Candle", inline = "Color 2", group = "Colors trend")
css_dn = input.color(color.black, "Down Candle", inline = "Color 2", group = "Colors trend")

major_trans = input.int(15,"Transp Major Liquidation",0,100,inline = "trans1",group = "Liquidations Color")
minor_trans = input.int(15,"Transp Minor Liquidation",0,100,inline = "trans2",group = "Liquidations Color")

liq_bear_minor = input.color(color.gray,"Bearish Liquidity Minor Swipe", group = "Liquidations Color")
liq_bull_minor = input.color(color.gray,"Bullish Liquidity Minor Swipe", group = "Liquidations Color")

liq_bear_major = input.color(color.purple,"Bearish Liquidity Major Swipe", group = "Liquidations Color")
liq_bull_major = input.color(color.aqua,"Bullish Liquidity Major Swipe", group = "Liquidations Color")

liq_wick_lh = input.color(color.orange, "Bearish Liquidation wick", group = "Liquidations Color")
liq_wick_hl = input.color(color.new(#2157f3,0), "Bearish Liquidation wick", group = "Liquidations Color")

lbl_size = input.int(1,"Pivot Text size",1,maxval = 5, group = "Text size")
lbl_t = switch lbl_size
    1 => size.tiny
    2 => size.small
    3 => size.normal
    4 => size.large
    5 => size.huge

txt_size = input.int(1,"Market structure Text size",1,maxval = 5, group = "Text size")
txt_t = switch txt_size
    1 => size.tiny
    2 => size.small
    3 => size.normal
    4 => size.large
    5 => size.huge

transline = 0

BOS_bull_css = input.color(color.white, "Bullish BOS", inline = "BOS1", group = "BOS and CHoCH colors")
BOS_bear_css = input.color(color.gray , "Bullish BOS", inline = "BOS2", group = "BOS and CHoCH colors")

CHOCH_bull_css = input.color(color.white, "Bullish CHoCH", inline = "BOS1", group = "BOS and CHoCH colors")
CHOCH_bear_css = input.color(color.gray , "Bearish CHoCH", inline = "BOS2", group = "BOS and CHoCH colors")

switch show_liq
    true => major_trans := 100, minor_trans := 100
    false => na

colinv = color.new(color.white,100) // gay

type barLiq
    float o = open
    float h = high
    float l = low
    float c = close
    float v = volume
    int idx = bar_index
    int t = time

type zBin
    float[] LH
    float[] HL
    float[] LL
    float[] HH

    int[] LHindex
    int[] HLindex
    int[] LLindex
    int[] HHindex

    float[] LHchoch
    float[] HLchoch
    float[] LLchoch
    float[] HHchoch 

    int[] LHchochIndex
    int[] HLchochIndex
    int[] LLchochIndex
    int[] HHchochIndex

    float[] _popl1H 
    int[] _popl1Hidx

var bin = zBin.new(

   array.new<float>()
 , array.new<float>()
 , array.new<float>()
 , array.new<float>()

 , array.new<int>()
 , array.new<int>()
 , array.new<int>()
 , array.new<int>()

 , array.new<float>()
 , array.new<float>()
 , array.new<float>()
 , array.new<float>()

 , array.new<int>()
 , array.new<int>()
 , array.new<int>()
 , array.new<int>()

 , array.new<float>()
 , array.new<int>()

 )

barLiq = barLiq.new()

var int itrendLiq = 0

f_drawLine(x1, y1, x2, y2, color, widh, bBar, txt, down, dashed,transline) =>
    var line id = na

    line.set_x1(id ,x1)
    line.set_y1(id ,y1)
    line.set_x2(id ,x2)
    line.set_y2(id ,y2)

    line.set_color(id, color.new(color,transline))
    line.set_width(id, widh)

    structure_lbl = label.new(int(math.avg(x1, bBar)), y1, txt
      , color = colinv
      , textcolor = color
      , style = down ? label.style_label_down : label.style_label_up
      , size = txt_t)   

f_drawBox(left, top, right, bottom, bgcolor, bcolor, trans) =>
    var box idLiq = na
    idLiq := box.new(left, top, right, bottom)
    box.set_bgcolor(idLiq,color.new(bgcolor,trans))
    box.set_border_width(idLiq, 1)
    box.set_border_color(idLiq, color.new(bcolor,11))

ph1 = ta.pivothigh(lookback, lookback)
pl1 = ta.pivotlow(lookback, lookback)

iff_1 = pl1 ? -1 : na  // Trend direction
hl = ph1 ? 1 : iff_1
iff_2 = pl1 ? pl1 : na  // similar to zigzag but may have multiple highs/lows
zz = ph1 ? ph1 : iff_2
valuewhen_1 = ta.valuewhen(not na(hl), hl, 1)
valuewhen_2 = ta.valuewhen(not na(zz), zz, 1)
zz := pl1 and hl == -1 and valuewhen_1 == -1 and pl1 > valuewhen_2 ? na : zz
valuewhen_3 = ta.valuewhen(not na(hl), hl, 1)
valuewhen_4 = ta.valuewhen(not na(zz), zz, 1)
zz := ph1 and hl == 1 and valuewhen_3 == 1 and ph1 < valuewhen_4 ? na : zz

valuewhen_5 = ta.valuewhen(not na(hl), hl, 1)
valuewhen_6 = ta.valuewhen(not na(zz), zz, 1)
hl := hl == -1 and valuewhen_5 == 1 and zz > valuewhen_6 ? na : hl
valuewhen_7 = ta.valuewhen(not na(hl), hl, 1)
valuewhen_8 = ta.valuewhen(not na(zz), zz, 1)
hl := hl == 1 and valuewhen_7 == -1 and zz < valuewhen_8 ? na : hl
zz := na(hl) ? na : zz

findprevious() =>  // finds previous three points (b, c, d, e)
    opposite_hl = hl == 1 ? -1 : 1
    loc1 = 0.0
    loc2 = 0.0
    loc3 = 0.0
    loc4 = 0.0
    xx = 0
    for x = 1 to 1000 by 1
        if hl[x] == opposite_hl and not na(zz[x])
            loc1 := zz[x]
            xx := x + 1
            break
    opposite_hl := hl
    for x = xx to 1000 by 1
        if hl[x] == opposite_hl and not na(zz[x])
            loc2 := zz[x]
            xx := x + 1
            break
    opposite_hl := hl == 1 ? -1 : 1
    for x = xx to 1000 by 1
        if hl[x] == opposite_hl and not na(zz[x])
            loc3 := zz[x]
            xx := x + 1
            break
    opposite_hl := hl
    for x = xx to 1000 by 1
        if hl[x] == opposite_hl and not na(zz[x])
            loc4 := zz[x]
            break
    [loc1, loc2, loc3, loc4]

isNot() =>
    float a = na
    float b = na
    float c = na
    float d = na
    float e = na

    if not na(hl)
        [loc1, loc2, loc3, loc4] = findprevious()
        a := zz
        b := loc1
        c := loc2
        d := loc3
        e := loc4
        e

    _hh = not na(zz) and a > b and a > c and c > b and c > d
    _ll = not na(zz) and a < b and a < c and c < b and c < d
    _hl = not na(zz) and (a >= c and b > c and b > d and d > c and d > e or a < b and a > c and b < d)
    _lh = not na(zz) and (a <= c and b < c and b < d and d < c and d < e or a > b and a < c and b > d)

    [_hh, _ll, _hl, _lh]

[_hh, _ll, _hl, _lh] = isNot()

if enable_signals

    if show_LL and _ll
        label.new(bar_index, low * 0.999, "LL", style=label.style_label_up, color=color_LL, textcolor=color.white, size=size.small)
    if show_HL and _hl
        label.new(bar_index, low * 0.999, "HL", style=label.style_label_up, color=color_HL, textcolor=color.white, size=size.small)

    if show_HH and _hh
        label.new(bar_index, high * 1.001, "HH", style=label.style_label_down, color=color_HH, textcolor=color.white, size=size.small)
    if show_LH and _lh
        label.new(bar_index, high * 1.001, "LH", style=label.style_label_down, color=color_LH, textcolor=color.white, size=size.small)

float res = na
float sup = na
res := _lh ? zz : res[1]
sup := _hl ? zz : sup[1]

int trendLiq = na
iff_3 = close < sup ? -1 : nz(trendLiq[1])
trendLiq := close > res ? 1 : iff_3

res := trendLiq == 1 and _hh or trendLiq == -1 and _lh ? zz : res
sup := trendLiq == 1 and _hl or trendLiq == -1 and _ll ? zz : sup
rechange = res != res[1]
suchange = sup != sup[1]

var int tot_structure_bull = 0
var int tot_structure_bear = 0
var float tot_bear_liq = 0
var float tot_bull_liq = 0

var float tot_liq_sell = 0
var float tot_liq_buy = 0

var bxHHchOchPoint = array.new<float>()
color onetap = na
float src_onetap_lh = na
float src_onetap_hl = na

bodyLength = math.abs(close - open)
downWickLength = low - math.min(open, close)
downWickBigger = downWickLength > bodyLength

if _hh
    id = show_pivot ? na : label.new(barLiq.idx[lookback], barLiq.h[lookback], text = "HH", style = label.style_label_down, size = lbl_t, color = colinv, textcolor = HH_css)
    bin.HH.push(barLiq.h[lookback])
    bin.HHindex.push(barLiq.idx[lookback])

    bxHHchOchPoint.push(barLiq.h[1])

if bin.HH.size() > 0
    if barLiq.idx % (lookback * 2) == 0
        bin.HHchoch.push(bin.HH.pop())
        bin.HHchochIndex.push(bin.HHindex.pop())

if bin.HH.size() > 0
    for j = 0 to bin.HH.size()
        if bin.HH.size() <= 0
            break
        else
            var _poph1H = array.new<float>()
            var _poph1Hidx = array.new<int>()
            var int barLiqsince = ta.barssince(ta.crossunder(barLiq.c, bin.HH.last()))
            if ta.crossover(barLiq.h, bin.HH.last())
                bool choch = false

                if itrendLiq < 0
                    choch := true
                txt = choch ? "" : ""
                _poph1H.push(bin.HH.pop())
                _poph1Hidx.push(bin.HHindex.pop())
                if math.abs(_poph1Hidx.last() - barLiq.idx) > 500
                    break
                else
                    col = choch ? CHOCH_bull_css : BOS_bull_css
                    itrendLiq := 1
                    tot_structure_bull += 1

                    f_drawLine(_poph1Hidx.last(), _poph1H.last(), barLiq.idx, _poph1H.last(), col, 1, barLiq.idx, txt, true, txt == "" ? true : false, transline)

if bin.HHchoch.size() > 0
    for j = 0 to bin.HHchoch.size()
        if bin.HHchoch.size() <= 0
            break
        else
            var _poph1Hchoch = array.new<float>()
            var _poph1HchochIndex = array.new<int>()
            if ta.crossover(barLiq.c, bin.HHchoch.last())
                bool choch = false

                if itrendLiq < 0
                    choch := true
                txt = choch ? "" : ""

                _poph1Hchoch.push(bin.HHchoch.pop())
                _poph1HchochIndex.push(bin.HHchochIndex.pop())
                if math.abs(_poph1HchochIndex.last() - barLiq.idx) > 500
                    break
                else
                    col = choch ? CHOCH_bull_css : BOS_bull_css
                    f_drawLine(_poph1HchochIndex.last(), _poph1Hchoch.last(), barLiq.idx, _poph1Hchoch.last(), col, 1, barLiq.idx, txt, true, txt == "" ? true : false, transline)
                    itrendLiq := 1
                    tot_structure_bull += 1

if bxHHchOchPoint.size() > 0
    barLiqsince = ta.barssince(ta.crossover(barLiq.h ,bxHHchOchPoint.last()))
    var float lastLvl = na
    var int index = na
    if ta.crossover(barLiq.h, bxHHchOchPoint.last())
        lastLvl := bxHHchOchPoint.last()
        index := barLiq.idx[1]

    if ta.crossunder(barLiq.h, bxHHchOchPoint.last()) and barLiqsince <= liq_valid
        var maxtop = array.new<float>()
        for j = 0 to barLiqsince
            maxtop.push(barLiq.h[j])

        tot_liq_sell += ta.cum(volume)
        lastLvl := na
        index := na
        maxtop.clear()
    else if ta.crossunder(barLiq.h, bxHHchOchPoint.last()) and barLiqsince > liq_valid
        lastLvl := na
        index := na

var bxLLchOch = array.new<float>()

if _ll
    id = show_pivot ? na : label.new(barLiq.idx[lookback], barLiq.l[lookback], text = "LL", style = label.style_label_up, size = lbl_t, color = colinv, textcolor = LL_css)
    bin.LL.push(barLiq.l[lookback])
    bin.LLindex.push(barLiq.idx[lookback])

    bxLLchOch.push(barLiq.l[1])

if bin.LL.size() > 0            
    if barLiq.idx % (lookback * 2) == 0
        bin.LLchoch.push(bin.LL.pop())
        bin.LLchochIndex.push(bin.LLindex.pop())

if bin.LL.size() > 0
    for j = 0 to bin.LL.size()
        if bin.LL.size() <= 0
            break
        else
            var _popl1L = array.new<float>()
            var _popl1Lidx = array.new<int>()
            var int barLiqsince = ta.barssince(ta.crossunder(barLiq.c, bin.LL.last()))
            if ta.crossunder(barLiq.l, bin.LL.last())
                bool choch = false

                if itrendLiq > 0
                    choch := true
                txt = choch ? "" : ""

                _popl1L.push(bin.LL.pop())
                _popl1Lidx.push(bin.LLindex.pop())
                if math.abs(_popl1Lidx.last() - barLiq.idx) > 500
                    break
                else
                    col = choch ? CHOCH_bear_css : BOS_bear_css
                    f_drawLine(_popl1Lidx.last(), _popl1L.last(), barLiq.idx, _popl1L.last(), col, 1, barLiq.idx, txt, false, txt == "" ? true : false, transline)
                    itrendLiq := -1
                    tot_structure_bear += 1

if bin.LLchoch.size() > 0
    for j = 0 to bin.LLchoch.size()
        if bin.LLchoch.size() <= 0
            break
        else
            var _popl1Lchoch = array.new<float>()
            var _popl1LchochIndex = array.new<int>()
            if ta.crossunder(barLiq.c, bin.LLchoch.last())
                bool choch = false

                if itrendLiq > 0
                    choch := true
                txt = choch ? "" : ""

                _popl1Lchoch.push(bin.LLchoch.pop())
                _popl1LchochIndex.push(bin.LLchochIndex.pop())
                if math.abs(_popl1LchochIndex.last() - barLiq.idx) > 500
                    break
                else
                    col = choch ? CHOCH_bear_css : BOS_bear_css
                    f_drawLine(_popl1LchochIndex.last(), _popl1Lchoch.last(), barLiq.idx, _popl1Lchoch.last(), col, 1, barLiq.idx, txt, false, txt == "" ? true : false, transline)
                    itrendLiq := -1
                    tot_structure_bear += 1

if bxLLchOch.size() > 0
    barLiqsince = ta.barssince(ta.crossunder(barLiq.l ,bxLLchOch.last()))
    var float lastLvl = na
    var int index = na
    if ta.crossunder(barLiq.h, bxLLchOch.last())
        lastLvl := bxLLchOch.last()
        index := barLiq.idx[1]

    if ta.crossover(barLiq.h, bxLLchOch.last()) and barLiqsince <= liq_valid
        var maxtop = array.new<float>()
        for j = 0 to barLiqsince
            maxtop.push(barLiq.l[j])

        tot_liq_buy += ta.cum(volume)
        lastLvl := na
        index := na
        maxtop.clear()
    else if ta.crossover(barLiq.l, bxLLchOch.last()) and barLiqsince > liq_valid
        lastLvl := na
        index := na

var bxHLPoint = array.new<float>()

if _hl
    id = show_pivot ? na : label.new(barLiq.idx[lookback], barLiq.l[lookback], text = "HL", style = label.style_label_up, size = lbl_t, color = colinv, textcolor = HH_css)
    bin.HL.push(barLiq.l[lookback])
    bin.HLindex.push(barLiq.idx[lookback])

    bxHLPoint.push(barLiq.l[lookback])

if bin.HL.size() > 0
    for j = 0 to bin.HL.size()
        if bin.HL.size() <= 0
            break
        else
            if bin.HL.size() > 0
                var _poph1L = array.new<float>()
                var _poph1Lidx = array.new<int>()
                var int barLiqsince = ta.barssince(ta.crossunder(barLiq.c, bin.HL.last()))
                if ta.crossunder(barLiq.l, bin.HL.last())
                    _poph1L.push(bin.HL.pop())
                    _poph1Lidx.push(bin.HLindex.pop())
                    if math.abs(_poph1Lidx.last() - barLiq.idx) > 500
                        break
                    else
                        show_pivot ? na : f_drawLine(_poph1Lidx.last(), _poph1L.last(), barLiq.idx, _poph1L.last(), HH_css, 1, barLiq.idx, "", false, false, 0)

                    if barLiq.c > _poph1L.last() and barLiq.o > _poph1L.last() and math.abs(close - open) <= math.abs(low - (close > open ? open : close))
                        src_onetap_hl := low

if bxHLPoint.size() > 0
    barLiqsince = ta.barssince(ta.crossunder(barLiq.l ,bxHLPoint.last()))
    var float lastLvl = na
    var int index = na
    if ta.crossunder(barLiq.h, bxHLPoint.last())
        lastLvl := bxHLPoint.last()
        index := barLiq.idx[1]

    if ta.crossover(barLiq.h, bxHLPoint.last()) and barLiqsince <= liq_valid
        var maxtop = array.new<float>()
        for j = 0 to barLiqsince
            maxtop.push(barLiq.l[j])

        tot_liq_buy += ta.cum(volume)
        lastLvl := na
        index := na
        maxtop.clear()
    else if ta.crossover(barLiq.l, bxHLPoint.last()) and barLiqsince > liq_valid
        lastLvl := na
        index := na

var bxLHPoint = array.new<float>()

if _lh
    id = show_pivot ? na : label.new(barLiq.idx[lookback], barLiq.h[lookback], text = "LH", style = label.style_label_down, size = lbl_t, color = colinv, textcolor = LL_css)
    bin.LH.push(barLiq.h[lookback])
    bin.LHindex.push(barLiq.idx[lookback])

    bxLHPoint.push(barLiq.h[lookback])

if bin.LH.size() > 0
    for j = 0 to bin.LH.size()
        if bin.LH.size() <= 0
            break
        else
            if ta.crossover(barLiq.h, bin.LH.last())
                bin._popl1H.push(bin.LH.pop())
                bin._popl1Hidx.push(bin.LHindex.pop())
                if math.abs(bin._popl1Hidx.last() - barLiq.idx) > 500
                    break
                else
                    show_pivot ? na : f_drawLine(bin._popl1Hidx.last(), bin._popl1H.last(), barLiq.idx, bin._popl1H.last(), LL_css, 1, barLiq.idx, "", false, false, 0)

                if barLiq.c < bin._popl1H.last() and barLiq.o < bin._popl1H.last() and math.abs(close - open) <= math.abs(high - (close > open ? close : open))
                    src_onetap_lh := high

if bxLHPoint.size() > 0
    barLiqsince = ta.barssince(ta.crossover(barLiq.h ,bxLHPoint.last()))
    var float lastLvl = na
    var int index = na
    if ta.crossover(barLiq.h, bxLHPoint.last())
        lastLvl := bxLHPoint.last()
        index := barLiq.idx[1]

    if ta.crossunder(barLiq.h, bxLHPoint.last()) and barLiqsince <= liq_valid
        var maxtop = array.new<float>()
        for j = 0 to barLiqsince
            maxtop.push(barLiq.h[j])

        tot_liq_sell += ta.cum(volume)
        lastLvl := na
        index := na
        maxtop.clear()
    else if ta.crossunder(barLiq.h, bxLHPoint.last()) and barLiqsince > liq_valid
        lastLvl := na
        index := na

css(x) =>
    var color col = na
    if x == "CHoCH"
        col := itrendLiq == 1 ? css_bull : css_bear
    else if x == "Default"
        col := barLiq.c > barLiq.o ? css_up : css_dn
    col

csss = css(css_candle)
c_src = close > open ? close : open
c_csrc = close > open ? open : close

int b_wick = 0

switch show_wick
    false => na
    true => b_wick := 100

plotcandle(src_onetap_lh,c_src, c_src ,c_src, color = colinv,wickcolor = colinv,bordercolor = color.new(liq_wick_lh,b_wick),display = display.pane)
plotcandle(src_onetap_hl,c_src, c_src ,c_src, color = colinv,wickcolor = colinv,bordercolor = color.new(liq_wick_hl,b_wick),display = display.pane)

s_BOS        = 0
s_CHoCH      = 1
i_BOS        = 2
i_CHoCH      = 3
i_pp_CHoCH   = 4
green_candle = 5
red_candle   = 6
s_CHoCHP     = 7
i_CHoCHP     = 8

boolean =
 array.from(
   false
 , false 
 , false 
 , false 
 , false 
 , false 
 , false 
 , false
 , false
 )

show_swing_ms                   = input.string      ("All"                            , "Swing        "               , inline = "1", group = "MARKET STRUCTURE"            , options = ["All", "CHoCH", "CHoCH+", "BOS", "None"])
show_internal_ms                = input.string      ("All"                            , "Internal     "               , inline = "2", group = "MARKET STRUCTURE"            , options = ["All", "CHoCH", "CHoCH+", "BOS", "None"])
alert_bos_count                 = input.int         (1                                , "Alert after N BOS"           , minval=1, maxval=10, group="ALERTES")
internal_r_lookback             = input.int         (5                                , ""                            , inline = "2", group = "MARKET STRUCTURE"            , minval = 2)
swing_r_lookback                = input.int         (50                               , ""                            , inline = "1", group = "MARKET STRUCTURE"            , minval = 2)
ms_mode                         = input.string      ("Manual"                         , "Market Structure Mode"       , inline = "a", group = "MARKET STRUCTURE"            , tooltip = "[Manual] Use selected lenght\n[Dynamic] Use automatic lenght" ,options = ["Manual", "Dynamic"])
show_mtf_str                    = input.bool        (false                             , "MTF Scanner"                 , inline = "9", group = "MARKET STRUCTURE"            , tooltip = "Display Multi-Timeframe Market Structure Trend Directions. Green = Bullish. Red = Bearish")
show_eql                        = input.bool        (true                            , "Show EQH/EQL"                , inline = "6", group = "MARKET STRUCTURE")
plotcandle_bool                 = input.bool        (false                            , "Plotcandle"                  , inline = "3", group = "MARKET STRUCTURE"            , tooltip = "Displays a cleaner colored candlestick chart in place of the default candles. (requires hiding the current ticker candles)")
barcolor_bool                   = input.bool        (false                            , "Bar Color"                   , inline = "4", group = "MARKET STRUCTURE"            , tooltip = "Color the candle bodies according to market strucutre trend")

i_ms_up_BOS                   = input.color       (#089981                          , ""                            , inline = "2", group = "MARKET STRUCTURE")
i_ms_dn_BOS                   = input.color       (#f23645                          , ""                            , inline = "2", group = "MARKET STRUCTURE")
s_ms_up_BOS                   = input.color       (#089981                          , ""                            , inline = "1", group = "MARKET STRUCTURE")
s_ms_dn_BOS                   = input.color       (#f23645                          , ""                            , inline = "1", group = "MARKET STRUCTURE")

lvl_daily                       = input.bool        (true                            , "Day   "                      , inline = "1", group = "HIGHS & LOWS MTF")
lvl_weekly                      = input.bool        (false                            , "Week "                       , inline = "2", group = "HIGHS & LOWS MTF")
lvl_monthly                     = input.bool        (false                            , "Month"                       , inline = "3", group = "HIGHS & LOWS MTF")
lvl_yearly                      = input.bool        (false                            , "Year  "                      , inline = "4", group = "HIGHS & LOWS MTF")
css_d                           = input.color       (color.blue                     , ""                            , inline = "1", group = "HIGHS & LOWS MTF")
css_w                           = input.color       (color.blue                     , ""                            , inline = "2", group = "HIGHS & LOWS MTF")
css_m                           = input.color       (color.blue                     , ""                            , inline = "3", group = "HIGHS & LOWS MTF")
css_y                           = input.color       (color.blue                     , ""                            , inline = "4", group = "HIGHS & LOWS MTF")
s_d                             = input.string      ('⎯⎯⎯'                            , ''                            , inline = '1', group = 'HIGHS & LOWS MTF'                , options = ['⎯⎯⎯', '----', '····'])
s_w                             = input.string      ('⎯⎯⎯'                            , ''                            , inline = '2', group = 'HIGHS & LOWS MTF'                , options = ['⎯⎯⎯', '----', '····'])
s_m                             = input.string      ('⎯⎯⎯'                            , ''                            , inline = '3', group = 'HIGHS & LOWS MTF'                , options = ['⎯⎯⎯', '----', '····'])
s_y                             = input.string      ('⎯⎯⎯'                            , ''                            , inline = '4', group = 'HIGHS & LOWS MTF'                , options = ['⎯⎯⎯', '----', '····'])

ob_show                         = input.bool        (true                             , "Show Last    "               , inline = "1", group = "VOLUMETRIC ORDER BLOCKS"         , tooltip = "Display volumetric order blocks on the chart \n\n[Input] Ammount of volumetric order blocks to show")
ob_num                          = input.int         (5                                , ""                            , inline = "1", group = "VOLUMETRIC ORDER BLOCKS"         , tooltip = "Orderblocks number", minval = 1, maxval = 10)
ob_metrics_show                 = input.bool        (true                             , "Internal Buy/Sell Activity"  , inline = "2", group = "VOLUMETRIC ORDER BLOCKS"         , tooltip = "Display volume metrics that have formed the orderblock")
css_metric_up                   = input.color       (color.new(#089981,  50)        , "         "                   , inline = "2", group = "VOLUMETRIC ORDER BLOCKS")
css_metric_dn                   = input.color       (color.new(#f23645 , 50)        , ""                            , inline = "2", group = "VOLUMETRIC ORDER BLOCKS")
ob_swings                       = input.bool        (true                            , "Swing Order Blocks"          , inline = "a", group = "VOLUMETRIC ORDER BLOCKS"         , tooltip = "Display swing volumetric order blocks")
css_swing_up                    = input.color       (color.new(color.gray  , 90)    , "                 "           , inline = "a", group = "VOLUMETRIC ORDER BLOCKS")
css_swing_dn                    = input.color       (color.new(color.silver, 90)    , ""                            , inline = "a", group = "VOLUMETRIC ORDER BLOCKS")
ob_filter                       = input.string      ("None"                           , "Filtering             "      , inline = "d", group = "VOLUMETRIC ORDER BLOCKS"         , tooltip = "Filter out volumetric order blocks by BOS/CHoCH/CHoCH+", options = ["None", "BOS", "CHoCH", "CHoCH+"])
ob_mitigation                   = input.string      ("Absolute"                       , "Mitigation           "       , inline = "4", group = "VOLUMETRIC ORDER BLOCKS"         , tooltip = "Trigger to remove volumetric order blocks", options = ["Absolute", "Middle"])
ob_pos                          = input.string      ("Precise"                        , "Positioning          "       , inline = "k", group = "VOLUMETRIC ORDER BLOCKS"         , tooltip = "Position of the Order Block\n[Full] Cover the whole candle\n[Middle] Cover half candle\n[Accurate] Adjust to volatility\n[Precise] Same as Accurate but more precise", options = ["Full", "Middle", "Accurate", "Precise"])
use_grayscale                   = input.bool        (false                            , "Grayscale"                   , inline = "6", group = "VOLUMETRIC ORDER BLOCKS"         , tooltip = "Use gray as basic order blocks color")
use_show_metric                 = input.bool        (true                             , "Show Metrics"                , inline = "7", group = "VOLUMETRIC ORDER BLOCKS"         , tooltip = "Show volume associated with the orderblock and his relevance")
use_middle_line                 = input.bool        (true                             , "Show Middle-Line"            , inline = "8", group = "VOLUMETRIC ORDER BLOCKS"         , tooltip = "Show mid-line order blocks")
use_overlap                     = input.bool        (true                             , "Hide Overlap"                , inline = "9", group = "VOLUMETRIC ORDER BLOCKS"         , tooltip = "Hide overlapping order blocks")
use_overlap_method              = input.string      ("Previous"                       , "Overlap Method    "          , inline = "Z", group = "VOLUMETRIC ORDER BLOCKS"         , tooltip = "[Recent] Preserve the most recent volumetric order blocks\n\n[Previous] Preserve the previous volumetric order blocks", options = ["Recent", "Previous"])
ob_bull_css                     = input.color       (color.new(#089981 ,  90)       , ""                            , inline = "1", group = "VOLUMETRIC ORDER BLOCKS")
ob_bear_css                     = input.color       (color.new(#f23645 ,  90)       , ""                            , inline = "1", group = "VOLUMETRIC ORDER BLOCKS")

show_acc_dist_zone              = input.bool        (false                            , ""                            , inline = "1", group = "Accumulation And Distribution")
zone_mode                       = input.string      ("Fast"                           , ""                            , inline = "1", group = "Accumulation And Distribution"   , tooltip = "[Fast] Find small zone pattern formation\n[Slow] Find bigger zone pattern formation" ,options = ["Slow", "Fast"])
acc_css                         = input.color       (color.new(#089981   , 60)      , ""                            , inline = "1", group = "Accumulation And Distribution")
dist_css                        = input.color       (color.new(#f23645   , 60)      , ""                            , inline = "1", group = "Accumulation And Distribution")

show_lbl                        = input.bool        (true                            , "Show swing point"            , inline = "1", group = "High and Low"                    , tooltip = "Display swing point")
show_mtb                        = input.bool        (true                            , "Show High/Low/Equilibrium"   , inline = "2", group = "High and Low"                    , tooltip = "Display Strong/Weak High And Low and Equilibrium")
toplvl                          = input.color       (color.red                      , "Premium Zone   "             , inline = "3", group = "High and Low")
midlvl                          = input.color       (color.white                    , "Equilibrium Zone"            , inline = "4", group = "High and Low")
btmlvl                          = input.color       (#089981                        , "Discount Zone    "           , inline = "5", group = "High and Low")

fvg_enable                      = input.bool        (true                            , "        "                            , inline = "1", group = "FAIR VALUE GAP"          , tooltip = "Display fair value gap")
what_fvg                        = input.string      ("FVG"                            , ""                            , inline = "1", group = "FAIR VALUE GAP"                  , tooltip = "Display fair value gap", options = ["FVG", "VI", "OG"])
fvg_num                         = input.int         (5                                , "Show Last  "                   , inline = "1a", group = "FAIR VALUE GAP"               , tooltip = "Number of fvg to show")
fvg_upcss                       = input.color       (color.new(#00ff00,  50)        , ""                            , inline = "1", group = "FAIR VALUE GAP")
fvg_dncss                       = input.color       (color.new(#ff0000,  50)     , ""                            , inline = "1", group = "FAIR VALUE GAP")
fvg_extend                      = input.int         (10                               , "Extend FVG"                  , inline = "2", group = "FAIR VALUE GAP"                  , tooltip = "Extend the display of the FVG.")
fvg_src                         = input.string      ("Close"                          , "Mitigation  "                , inline = "3", group = "FAIR VALUE GAP"                  , tooltip = "[Close] Use the close of the body as trigger\n\n[Wick] Use the extreme point of the body as trigger", options = ["Close", "Wick"])
fvg_tf                          = input.timeframe   (""                               , "Timeframe "                  , inline = "4", group = "FAIR VALUE GAP"                  , tooltip = "Timeframe of the fair value gap")

t                               = color.t           (ob_bull_css)
invcol                          = color.new         (color.white                    , 100)
obtxt                           = input.string("Normal"            , "Metric Size"                    , ["Tiny", "Small", "Normal", "Large", "Huge"], inline = "7", group = "VOLUMETRIC ORDER BLOCKS" )

method txSz(string s) =>
    out = switch s
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        "Huge"   => size.huge
    out

type bar
    float   o = open
    float   c = close
    float   h = high
    float   l = low
    float   v = volume
    int     n = bar_index
    int     t = time

type Zphl
    line   top
    line   bottom
    label  top_label
    label  bottom_label
    bool   stopcross
    bool   sbottomcross
    bool   itopcross
    bool   ibottomcross
    string txtup
    string txtdn
    float  topy
    float  bottomy
    float  topx
    float  bottomx
    float  tup
    float  tdn
    int    tupx
    int    tdnx
    float  itopy
    float  itopx
    float  ibottomy
    float  ibottomx
    float  uV
    float  dV

type FVG
    box [] box
    line[] ln
    bool   bull
    float  top
    float  btm
    int    left
    int    right

type ms
    float[] p
    int  [] n
    float[] l

type msDraw
    int    n
    float  p
    color  css
    string txt
    bool   bull

type obC 
    float[] top
    float[] btm
    int  [] left
    float[] avg
    float[] dV 
    float[] cV 
    int  [] wM 
    int  [] blVP 
    int  [] brVP 
    int  [] dir  
    float[] h
    float[] l
    int  [] n

type obD 
    box [] ob 
    box [] eOB
    box [] blB 
    box [] brB 
    line[] mL

type zone
    chart.point points
    float p
    int   c
    int   t

type hqlzone
    box   pbx
    box   ebx
    box   lbx
    label plb
    label elb
    label lbl

type ehl
    float pt
    int   t
    float pb
    int   b

type pattern
    string found = "None"
    bool isfound = false
    int   period = 0
    bool  bull   = false

type alerts
    bool chochswing     = false
    bool chochplusswing = false
    bool swingbos       = false
    bool chochplus      = false
    bool choch          = false
    bool bos            = false
    bool equal          = false
    bool ob             = false
    bool swingob        = false
    bool zone           = false
    bool fvg            = false
    bool obtouch        = false

bar         b      = bar.new()
var pattern p      = pattern.new()

alerts      blalert = alerts.new()
alerts      bralert = alerts.new()

if p.isfound

    p.period += 1

if p.period == 50

    p.period  := 0
    p.found   := "None"
    p.isfound := false
    p.bull    := na

switch

    b.c > b.o => boolean.set(green_candle, true)
    b.c < b.o => boolean.set(red_candle  , true)

f_zscore(src, lookback) =>

    (src - ta.sma(src, lookback)) / ta.stdev(src, lookback)

var int iLen = internal_r_lookback
var int sLen = swing_r_lookback

vv = f_zscore(((close - close[iLen]) / close[iLen]) * 100,iLen)

if ms_mode == "Dynamic"

    switch

        vv >= 1.5 or vv <= -1.5 => iLen := 10
        vv >= 1.6 or vv <= -1.6 => iLen := 9
        vv >= 1.7 or vv <= -1.7 => iLen := 8
        vv >= 1.8 or vv <= -1.8 => iLen := 7
        vv >= 1.9 or vv <= -1.9 => iLen := 6
        vv >= 2.0 or vv <= -2.0 => iLen := 5
        =>                         iLen

var msline = array.new<line>(0)

iH = ta.pivothigh(high, iLen, iLen)
sH = ta.pivothigh(high, sLen, sLen)
iL = ta.pivotlow (low , iLen, iLen)
sL = ta.pivotlow (low , sLen, sLen)

hl  () => [high, low]

[pdh, pdl] = request.security(syminfo.tickerid , 'D'  , hl() , lookahead = barmerge.lookahead_on)
[pwh, pwl] = request.security(syminfo.tickerid , 'W'  , hl() , lookahead = barmerge.lookahead_on)
[pmh, pml] = request.security(syminfo.tickerid , 'M'  , hl() , lookahead = barmerge.lookahead_on)
[pyh, pyl] = request.security(syminfo.tickerid , '12M', hl() , lookahead = barmerge.lookahead_on)

lstyle(style) =>

    out = switch style

        '⎯⎯⎯'  => line.style_solid
        '----' => line.style_dashed
        '····' => line.style_dotted

mtfphl(h, l ,tf ,css, pdhl_style) =>

    var line hl = line.new(
       na
     , na
     , na
     , na
     , xloc      = xloc.bar_time
     , color     = css
     , style     = lstyle(pdhl_style)
     )

    var line ll   = line.new(
       na
     , na
     , na
     , na
     , xloc      = xloc.bar_time
     , color     = css
     , style     = lstyle(pdhl_style)
     )

    var label lbl = label.new(
       na
     , na
     , xloc      = xloc.bar_time
     , text      = str.format('P{0}L', tf)
     , color     = invcol
     , textcolor = css
     , size      = size.small
     , style     = label.style_label_left
     )

    var label hlb = label.new(
       na
     , na
     , xloc      = xloc.bar_time
     , text      = str.format('P{0}H', tf)
     , color     = invcol
     , textcolor = css
     , size      = size.small
     , style     = label.style_label_left
     )

    hy = ta.valuewhen(h != h[1] , h    , 1)
    hx = ta.valuewhen(h == high , time , 1)
    ly = ta.valuewhen(l != l[1] , l    , 1)
    lx = ta.valuewhen(l == low  , time , 1)

    if barstate.islast

        extension = time + (time - time[1]) * 50

        line.set_xy1(hl , hx        , hy)
        line.set_xy2(hl , extension , hy)
        label.set_xy(hlb, extension , hy)
        line.set_xy1(ll , lx        , ly)
        line.set_xy2(ll , extension , ly)
        label.set_xy(lbl, extension , ly)

if lvl_daily

    mtfphl(pdh   , pdl , 'D'  , css_d, s_d)

if lvl_weekly

    mtfphl(pwh   , pwl , 'W'  , css_w, s_w)

if lvl_monthly

    mtfphl(pmh   , pml,  'M'  , css_m, s_m)

if lvl_yearly

    mtfphl(pyh   , pyl , '12M', css_y, s_y)

method darkcss(color css, float factor, bool bull) =>

    blue  = color.b(css) * (1 - factor)
    red   = color.r(css) * (1 - factor)
    green = color.g(css) * (1 - factor)

    color.rgb(red, green, blue, 0)

method f_line(msDraw d, size, style) =>

    var line  id  = na
    var label lbl = na

    id := line.new(
       d.n
     , d.p
     , b.n
     , d.p
     , color = d.css
     , width = 1
     , style = style
     )

    if msline.size() >= 250

        line.delete(msline.shift())

    msline.push(id)

    lbl := label.new(
       int(math.avg(d.n, b.n))
     , d.p
     , d.txt
     , color            = invcol
     , textcolor        = d.css
     , style            = d.bull ? label.style_label_down : label.style_label_up
     , size             = size
     )

structure(bool mtf) =>

    msDraw drw     = na

    bool isdrw     = false
    bool isdrwS   = false

    var color css  = na
    var color icss = na

    var int itrend = 0
    var int  trend = 0

    bool bull_ob   = false
    bool bear_ob   = false

    bool s_bull_ob = false
    bool s_bear_ob = false

    bool newBullBosFlag = false
    bool newBearBosFlag = false

    n = bar_index

    var ms up = ms.new(
           array.new<float>()
         , array.new< int >()
         , array.new<float>()
         )

    var ms dn = ms.new(
           array.new<float>()
         , array.new< int >()
         , array.new<float>()
         )

    var ms sup = ms.new(
           array.new<float>()
         , array.new< int >()
         , array.new<float>()
         )

    var ms sdn = ms.new(
           array.new<float>()
         , array.new< int >()
         , array.new<float>()
         )

    switch show_swing_ms

        "All"      =>  boolean.set(s_BOS , true ),  boolean.set(s_CHoCH, true ) , boolean.set(s_CHoCHP, true  )  
        "CHoCH"    =>  boolean.set(s_BOS , false),  boolean.set(s_CHoCH, true ) , boolean.set(s_CHoCHP, false )   
        "CHoCH+"   =>  boolean.set(s_BOS , false),  boolean.set(s_CHoCH, false) , boolean.set(s_CHoCHP, true  )  
        "BOS"      =>  boolean.set(s_BOS , true ),  boolean.set(s_CHoCH, false) , boolean.set(s_CHoCHP, false )  
        "None"     =>  boolean.set(s_BOS , false),  boolean.set(s_CHoCH, false) , boolean.set(s_CHoCHP, false )  
        => na

    switch show_internal_ms

        "All"      =>  boolean.set(i_BOS, true ),  boolean.set(i_CHoCH, true  ),  boolean.set(i_CHoCHP, true )
        "CHoCH"    =>  boolean.set(i_BOS, false),  boolean.set(i_CHoCH, true  ),  boolean.set(i_CHoCHP, false) 
        "CHoCH+"   =>  boolean.set(i_BOS, false),  boolean.set(i_CHoCH, false ),  boolean.set(i_CHoCHP, true ) 
        "BOS"      =>  boolean.set(i_BOS, true ),  boolean.set(i_CHoCH, false ),  boolean.set(i_CHoCHP, false) 
        "None"     =>  boolean.set(i_BOS, false),  boolean.set(i_CHoCH, false ),  boolean.set(i_CHoCHP, false) 
        => na

    switch
        iH =>

            up.p.unshift(b.h[iLen])
            up.l.unshift(b.h[iLen])
            up.n.unshift(n  [iLen])

        iL =>

            dn.p.unshift(b.l[iLen])
            dn.l.unshift(b.l[iLen])
            dn.n.unshift(n  [iLen])

        sL =>

            sdn.p.unshift(b.l[sLen])
            sdn.l.unshift(b.l[sLen])
            sdn.n.unshift(n  [sLen])

        sH =>

            sup.p.unshift(b.h[sLen])
            sup.l.unshift(b.h[sLen])
            sup.n.unshift(n  [sLen])

    if up.p.size() > 0 and dn.l.size() > 1

        if ta.crossover(b.c, up.p.first())

            bool CHoCH = na
            string txt = na
            var int bosCount = 0
            var bool bullChochActive = false

            if itrend < 0

                CHoCH := true

            switch

                not CHoCH =>

                    if bullChochActive
                        bosCount := bosCount + 1
                        txt := "BOS " + str.tostring(bosCount)

                        newBullBosFlag := true
                    else
                        txt := "eBOS"
                    css := i_ms_up_BOS

                    blalert.bos := true

                    if boolean.get(i_BOS) and mtf == false and na(drw)
                        isdrw := true
                        drw := msDraw.new(
                               up.n.first()
                             , up.p.first()
                             , i_ms_up_BOS
                             , txt
                             , true
                             )	

                CHoCH => 

                    dn.l.first() > dn.l.get(1) ? blalert.chochplus : blalert.choch

                    txt := dn.l.first() > dn.l.get(1) ? "CHoCH+" : "CHoCH"
                    css := i_ms_up_BOS.darkcss(0.25, true)

                    bullChochActive := true
                    bosCount := 0

                    if (dn.l.first() > dn.l.get(1) ? boolean.get(i_CHoCHP) : boolean.get(i_CHoCH)) and mtf == false and na(drw)

                        isdrw := true
                        drw := msDraw.new(
                               up.n.first()
                             , up.p.first()
                             , i_ms_up_BOS.darkcss(0.25, true)
                             , txt
                             , true
                             )				

            if mtf == false

                switch

                    ob_filter == "None" 					    => bull_ob := true
                    ob_filter == "BOS"    and txt == "BOS"      => bull_ob := true
                    ob_filter == "CHoCH"  and txt == "CHoCH"    => bull_ob := true
                    ob_filter == "CHoCH+" and txt == "CHoCH+"   => bull_ob := true

            itrend := 1
            up.n.clear()
            up.p.clear()

    if dn.p.size() > 0 and up.l.size() > 1

        if ta.crossunder(b.c, dn.p.first())

            bool CHoCH = na
            string txt = na
            var int bosBearCount = 0
            var bool bearChochActive = false

            if itrend > 0

                CHoCH := true

            switch

                not CHoCH =>

                    bralert.bos := true

                    if bearChochActive
                        bosBearCount := bosBearCount + 1
                        txt := "BOS " + str.tostring(bosBearCount)

                        newBearBosFlag := true
                    else
                        txt := "eBOS"
                    css := i_ms_dn_BOS

                    if boolean.get(i_BOS) and mtf == false and na(drw)

                        isdrw := true
                        drw := msDraw.new(
                               dn.n.first()
                             , dn.p.first()
                             , i_ms_dn_BOS
                             , txt
                             , false
                             )	

                CHoCH => 

                    if up.l.first() < up.l.get(1)
                        bralert.chochplus := true
                    else 
                        bralert.choch := true

                    bearChochActive := true
                    bosBearCount := 0

                    txt := up.l.first() < up.l.get(1) ? "CHoCH+" : "CHoCH"
                    css := i_ms_dn_BOS.darkcss(0.25, false)

                    if (up.l.first() < up.l.get(1) ? boolean.get(i_CHoCHP) : boolean.get(i_CHoCH)) and mtf == false and na(drw)

                        isdrw := true
                        drw := msDraw.new(
                               dn.n.first()
                             , dn.p.first()
                             , i_ms_dn_BOS.darkcss(0.25, false)
                             , txt
                             , false
                             )			

            if mtf == false

                switch

                    ob_filter == "None" 					    => bear_ob := true
                    ob_filter == "BOS"    and txt == "BOS"      => bear_ob := true
                    ob_filter == "CHoCH"  and txt == "CHoCH"    => bear_ob := true
                    ob_filter == "CHoCH+" and txt == "CHoCH+"   => bear_ob := true

            itrend := -1
            dn.n.clear()
            dn.p.clear()

    if sup.p.size() > 0 and sdn.l.size() > 1

        if ta.crossover(b.c, sup.p.first())

            bool CHoCH = na
            string txt = na

            if trend < 0

                CHoCH := true

            switch

                not CHoCH =>

                    blalert.swingbos := true

                    txt := "eBOS"
                    icss := s_ms_up_BOS

                    if boolean.get(s_BOS) and mtf == false and na(drw)

                        isdrwS := true
                        drw := msDraw.new(
                               sup.n.first()
                             , sup.p.first()
                             , s_ms_up_BOS
                             , txt
                             , true
                             )	

                CHoCH => 

                    if sdn.l.first() > sdn.l.get(1)
                        blalert.chochplusswing := true
                    else 
                        blalert.chochswing := true

                    txt := sdn.l.first() > sdn.l.get(1) ? "eCHoCH+" : "eCHoCH"
                    icss := s_ms_up_BOS.darkcss(0.25, true)

                    if (sdn.l.first() > sdn.l.get(1) ? boolean.get(s_CHoCHP) : boolean.get(s_CHoCH)) and mtf == false and na(drw)

                        isdrwS := true
                        drw := msDraw.new(
                               sup.n.first()
                             , sup.p.first()
                             , s_ms_up_BOS.darkcss(0.25, true)
                             , txt
                             , true
                             )	

            if mtf == false

                switch

                    ob_filter == "None" 					  => s_bull_ob := true
                    ob_filter == "BOS"    and txt == "BOS"    => s_bull_ob := true
                    ob_filter == "CHoCH"  and txt == "CHoCH"  => s_bull_ob := true
                    ob_filter == "CHoCH+" and txt == "CHoCH+" => s_bull_ob := true

            trend := 1
            sup.n.clear()
            sup.p.clear()

    if sdn.p.size() > 0 and sup.l.size() > 1

        if ta.crossunder(b.c, sdn.p.first())

            bool CHoCH = na
            string txt = na

            if trend > 0

                CHoCH := true

            switch

                not CHoCH =>

                    bralert.swingbos := true

                    txt := "eBOS"
                    icss := s_ms_dn_BOS

                    if boolean.get(s_BOS) and mtf == false and na(drw)

                        isdrwS := true
                        drw := msDraw.new(
                               sdn.n.first()
                             , sdn.p.first()
                             , s_ms_dn_BOS
                             , txt
                             , false
                             )	

                CHoCH => 

                    if sup.l.first() < sup.l.get(1)
                        bralert.chochplusswing := true
                    else
                        bralert.chochswing := true

                    txt := sup.l.first() < sup.l.get(1) ? "eCHoCH+" : "eCHoCH"
                    icss := s_ms_dn_BOS.darkcss(0.25, false)

                    if (sup.l.first() < sup.l.get(1) ? boolean.get(s_CHoCHP) : boolean.get(s_CHoCH)) and mtf == false and na(drw)

                        isdrwS := true
                        drw := msDraw.new(
                               sdn.n.first()
                             , sdn.p.first()
                             , s_ms_dn_BOS.darkcss(0.25, false)
                             , txt
                             , false
                             )		

            if mtf == false

                switch

                    ob_filter == "None" 					   => s_bear_ob := true
                    ob_filter == "BOS"     and txt == "BOS"    => s_bear_ob := true
                    ob_filter == "CHoCH"   and txt == "CHoCH"  => s_bear_ob := true
                    ob_filter == "CHoCH+"  and txt == "CHoCH+" => s_bear_ob := true

            trend := -1
            sdn.n.clear()
            sdn.p.clear()

    [css, bear_ob, bull_ob, itrend, drw, isdrw, s_bear_ob, s_bull_ob, trend, icss, isdrwS, newBullBosFlag, newBearBosFlag]

var int lastBullBosCount = 0
var int lastBearBosCount = 0

structureNoAlert(bool mtf) =>
    [css, bear_ob, bull_ob, itrend, drw, isdrw, s_bear_ob, s_bull_ob, trend, icss, isdrwS, _, _] = structure(mtf)
    [css, bear_ob, bull_ob, itrend, drw, isdrw, s_bear_ob, s_bull_ob, trend, icss, isdrwS]

[css, bear_ob, bull_ob, itrend, drw, isdrw, s_bear_ob, s_bull_ob, trend, icss, isdrwS, newBullBos, newBearBos] = structure(false)

if barstate.islast

    if newBullBos
        lastBullBosCount := lastBullBosCount + 1
        if lastBullBosCount == alert_bos_count
            alert("Alerte : " + str.tostring(alert_bos_count) + "th bullish BOS detected!")
            lastBullBosCount := 0  //Reset after alert
        newBullBos := false

    if newBearBos
        lastBearBosCount := lastBearBosCount + 1
        if lastBearBosCount == alert_bos_count
            alert("Alerte : " + str.tostring(alert_bos_count) +

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

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

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

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

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

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

Стоимость полного кода
8 262,30₽ ≈ $100.98