SMC & ICT & Indicators + Scalping Master
Похожие материалы по тегам
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «smc+ict+indicators+scalping master.pine» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Это индикатор для TradingView, написанный на Pine Script v5. Он объединяет несколько групп инструментов визуального анализа: структуру рынка в стиле Smart Money Concepts (внутренняя и свинговая структура, BOS/CHoCH), блоки ордеров, равные максимумы и минимумы, разрывы справедливой стоимости, уровни предыдущих дневных, недельных и месячных максимумов и минимумов, а также зоны премии, равновесия и дисконта.
Дополнительно индикатор строит зоны спроса и предложения с настройками чувствительности, отображения и оповещений, распознаёт ряд свечных моделей (доджи, поглощение, молот и звезда, дракон и надгробие, пинцет, волчок, пронзание и тёмное облако, харами, длинные тени) и выводит информационную таблицу с оценками нескольких осцилляторов и трендовых расчётов (MACD, Stochastic RSI, Vortex, Momentum, RSI, PSAR, DMI, Money Flow Index, Fisher).
Индикатор отображает линии, метки, рамки и стрелки на графике, может окрашивать свечи по направлению структуры и формирует условия для оповещений TradingView по структуре, блокам ордеров, равным экстремумам, разрывам, зонам спроса и предложения, пробоям и свечным моделям. Часть расчётов использует данные других таймфреймов и инструментов через запросы безопасности. Индикатор предназначен для анализа и отображения, а не для автоматической торговли.
Настройки программы
| Настройка | Описание |
|---|---|
| mode | Режим — Отображение всей исторической структуры или только последних значений. |
| style | Стиль — Цветовая тема индикатора. |
| show_trend | Цветные свечи — Отображение дополнительных свечей с цветом, отражающим текущий тренд по структуре. |
| show_internals | Показывать внутреннюю структуру — Отображение внутренней структуры рынка. |
| show_ibull | Бычья внутренняя структура — Выбор отображаемых бычьих сигналов внутренней структуры: все, только BOS или только CHoCH. |
| swing_ibull_css | Цвет бычьей внутренней структуры — Цвет отображения бычьей внутренней структуры. |
| show_ibear | Медвежья внутренняя структура — Выбор отображаемых медвежьих сигналов внутренней структуры: все, только BOS или только CHoCH. |
| swing_ibear_css | Цвет медвежьей внутренней структуры — Цвет отображения медвежьей внутренней структуры. |
| ifilter_confluence | Фильтр совпадений — Фильтрует незначительные пробои внутренней структуры. |
| show_Structure | Показывать свинговую структуру — Отображение свинговой структуры рынка. |
| show_bull | Бычья структура — Выбор отображаемых бычьих сигналов структуры: все, только BOS или только CHoCH. |
| swing_bull_css | Цвет бычьей свинговой структуры — Цвет отображения бычьей свинговой структуры. |
| show_bear | Медвежья структура — Выбор отображаемых медвежьих сигналов структуры: все, только BOS или только CHoCH. |
| swing_bear_css | Цвет медвежьей свинговой структуры — Цвет отображения медвежьей свинговой структуры. |
| show_swings | Показывать свинговые точки — Отображение свинговых точек в виде меток на графике. |
| length | Длина свингов — Количество баров для определения свинговых точек. |
| show_hl_swings | Показывать сильный и слабый максимум и минимум — Подсветка последних сильного и слабого максимума и минимума на графике. |
| show_iob | Внутренние блоки ордеров — Отображение внутренних блоков ордеров на графике. |
| iob_showlast | Показывать последние внутренние OB — Количество внутренних блоков ордеров, отображаемых на графике. |
| show_ob | Свинговые блоки ордеров — Отображение свинговых блоков ордеров на графике. |
| ob_showlast | Показывать последние OB — Количество свинговых блоков ордеров, отображаемых на графике. |
| ob_filter | Фильтр блоков ордеров — Метод фильтрации волатильных блоков ордеров. |
| ibull_ob_css | Цвет бычьего внутреннего OB — Цвет отображения бычьих внутренних блоков ордеров. |
| ibear_ob_css | Цвет медвежьего внутреннего OB — Цвет отображения медвежьих внутренних блоков ордеров. |
| bull_ob_css | Цвет бычьего OB — Цвет отображения бычьих свинговых блоков ордеров. |
| bear_ob_css | Цвет медвежьего OB — Цвет отображения медвежьих свинговых блоков ордеров. |
| show_eq | Равные максимумы и минимумы — Отображение равных максимумов и минимумов на графике. |
| eq_len | Бары подтверждения — Количество баров для подтверждения равных максимумов и минимумов. |
| eq_threshold | Порог — Порог чувствительности в диапазоне от 0 до 1 для обнаружения равных максимумов и минимумов. |
| show_fvg | Разрывы справедливой стоимости — Отображение разрывов справедливой стоимости на графике. |
| fvg_auto | Автоматический порог — Отфильтровывает незначительные разрывы справедливой стоимости. |
| fvg_tf | Таймфрейм — Таймфрейм для расчёта разрывов справедливой стоимости. |
| bull_fvg_css | Цвет бычьего FVG — Цвет отображения бычьих разрывов справедливой стоимости. |
| bear_fvg_css | Цвет медвежьего FVG — Цвет отображения медвежьих разрывов справедливой стоимости. |
| fvg_extend | Продление FVG — Количество баров, на которое продлеваются рамки разрывов справедливой стоимости. |
| show_pdhl | Дневные уровни — Отображение предыдущих дневных максимума и минимума. |
| pdhl_style | Стиль дневных линий — Стиль линий предыдущих дневных максимума и минимума. |
| pdhl_css | Цвет дневных уровней — Цвет линий предыдущих дневных максимума и минимума. |
| show_pwhl | Недельные уровни — Отображение предыдущих недельных максимума и минимума. |
| pwhl_style | Стиль недельных линий — Стиль линий предыдущих недельных максимума и минимума. |
| pwhl_css | Цвет недельных уровней — Цвет линий предыдущих недельных максимума и минимума. |
| show_pmhl | Месячные уровни — Отображение предыдущих месячных максимума и минимума. |
| pmhl_style | Стиль месячных линий — Стиль линий предыдущих месячных максимума и минимума. |
| pmhl_css | Цвет месячных уровней — Цвет линий предыдущих месячных максимума и минимума. |
| show_sd | Зоны премии и дисконта — Отображение зон премии, дисконта и равновесия на графике. |
| premium_css | Цвет зоны премии — Цвет отображения зоны премии. |
| eq_css | Цвет зоны равновесия — Цвет отображения зоны равновесия. |
| discount_css | Цвет зоны дисконта — Цвет отображения зоны дисконта. |
| ds_min_pc_change | Минимальное изменение в процентах — Минимальное процентное изменение, при котором создаётся зона. |
| ds_max_pc_zone | Максимальная высота зоны в процентах — Максимальная высота зоны в процентах; ограничивает слишком крупные зоны. |
| ds_line_pc_display | Процент линии — Процент от линии зоны, в пределах которого отображается линия активной зоны. |
| ds_line_max | Максимум линий — Максимальное число линий, отображаемых для каждого типа зон. |
| ds_max_zones | Максимум зон — Максимальное число зон для каждого типа. |
| ds_hours_offset | Смещение часового пояса (ч) — Смещение часового пояса в часах для отображения времени в подсказках зон. |
| showDemandZone | Зона спроса — Включает отображение зон спроса. |
| demand_bord_col | Граница зоны спроса — Цвет границы зоны спроса. |
| demand_bg_col | Фон зоны спроса — Цвет фона активной зоны спроса; после касания зона становится прозрачной. |
| showSupplyZone | Зона предложения — Включает отображение зон предложения. |
| supply_bord_col | Граница зоны предложения — Цвет границы зоны предложения. |
| supply_bg_col | Фон зоны предложения — Цвет фона активной зоны предложения; после касания зона становится прозрачной. |
| dsAlertDemand | Оповещения по спросу — Включает оповещения по зонам спроса. |
| dsAlertSupply | Оповещения по предложению — Включает оповещения по зонам предложения. |
| ds_alert_mins_no_repeat | Минут без повтора — Интервал в минутах, в течение которого повторное похожее оповещение по той же зоне не отправляется; 0 отключает ограничение. |
| ds_alerts_pc_near | Процент близости — Процент от зоны, при приближении к которому отправляется оповещение о близости цены. |
| left | Поиск влево — Количество баров влево для поиска свингового максимума или минимума при формировании пивота. |
| right | Поиск вправо — Количество баров вправо для поиска свингового максимума или минимума при формировании пивота. |
| nPiv | Количество пивотов — Количество отслеживаемых пивотов (максимумов и минимумов). |
| atrLen | Длина ATR — Количество баров для расчёта ATR, используемого для нормирования ширины зон. |
| mult | Ширина зоны (ATR) — Множитель ATR для задания ширины зоны. |
| per | Максимальный процент зоны — Максимальный размер зоны в процентах от цены. |
| max | Максимум рамок для моделей — Количество рамок для отслеживания свечных моделей. |
| fut | Смещение меток — Смещение меток ценовых уровней в барах. |
| src | Источник для пивотов — Источник для расчёта пивотов. |
| alignZones | Выравнивать зоны — Объединяет пересекающиеся зоны в одну, продлевая её во времени. |
| extend | Продлевать вправо — Продлевает текущие зоны вправо. |
| lLab | Показывать метки уровней — Показывает метки ценовых уровней, продлённых от ключевых зон. |
| dhighs | Обнаруживать пивотные максимумы — Включает отслеживание пивотных максимумов. |
| dlows | Обнаруживать пивотные минимумы — Включает отслеживание пивотных минимумов. |
| detectBO | Обнаруживать пробой вверх — Включает отметку пробоя вверх всех пивотов. |
| detectBD | Обнаруживать пробой вниз — Включает отметку пробоя вниз всех пивотов. |
| breakUp | Обнаруживать пробой сопротивления — Включает отметку пробоя сопротивления. |
| breakDn | Обнаруживать пробой поддержки — Включает отметку пробоя поддержки. |
| falseBull | Обнаруживать ложный пробой вниз — Включает отметку ложного пробоя вниз. |
| falseBear | Обнаруживать ложный пробой вверх — Включает отметку ложного пробоя вверх. |
| supPush | Обнаруживать отталкивание от поддержки — Включает отметку свечей, обнаруженных в зоне поддержки. |
| resPush | Обнаруживать отталкивание от сопротивления — Включает отметку свечей, обнаруженных в зоне сопротивления. |
| repaint | Ждать подтверждённый бар — Ожидание закрытия бара перед обнаружением моделей. |
| labels | Показывать метку — Показывает метку для обнаруженной свечной модели. |
| sBox | Показывать рамки вокруг моделей — Показывает рамку вокруг обнаруженной свечной модели. |
| d_ | Обнаруживать доджи — Включает распознавание моделей доджи. |
| be_ | Обнаруживать поглощение — Включает распознавание моделей поглощения. |
| hs_ | Обнаруживать молот и звезду — Включает распознавание моделей молота и падающей звезды. |
| dg_ | Обнаруживать дракона и надгробие — Включает распознавание моделей дракона и надгробия. |
| tw_ | Обнаруживать пинцет — Включает распознавание моделей пинцета. |
| st_ | Обнаруживать волчок — Включает распознавание моделей волчка. |
| pc_ | Обнаруживать пронзание и облако — Включает распознавание моделей пронзания и тёмного облака. |
| bh_ | Обнаруживать харами — Включает распознавание моделей харами. |
| ls_ | Обнаруживать длинные тени — Включает распознавание моделей длинных теней. |
| alertMode | Режим оповещений — Выбор частоты срабатывания оповещений: на закрытии каждого бара или один раз за бар. |
| ecWick | Поглощение должно перекрывать тень — Требует, чтобы свеча поглощения перекрывала тень предыдущей свечи, а не только тело. |
Поиск по коду файла
indicator(title = "SMC & ICT & Indicators + Scalping Master"
, overlay = true
, max_labels_count = 500
, max_lines_count = 500
, max_boxes_count = 500
, max_bars_back = 500)
color TRANSP_CSS = #ffffff00
string MODE_TOOLTIP = 'Allows to display historical Structure or only the recent ones'
string STYLE_TOOLTIP = 'Indicator color theme'
string COLOR_CANDLES_TOOLTIP = 'Display additional candles with a color reflecting the current trend detected by structure'
string SHOW_INTERNAL = 'Display internal market structure'
string CONFLUENCE_FILTER = 'Filter non significant internal structure breakouts'
string SHOW_SWING = 'Display swing market Structure'
string SHOW_SWING_POINTS = 'Display swing point as labels on the chart'
string SHOW_SWHL_POINTS = 'Highlight most recent strong and weak high/low points on the chart'
string INTERNAL_OB = 'Display internal order blocks on the chart\n\nNumber of internal order blocks to display on the chart'
string SWING_OB = 'Display swing order blocks on the chart\n\nNumber of internal swing blocks to display on the chart'
string FILTER_OB = 'Method used to filter out volatile order blocks \n\nIt is recommended to use the cumulative mean range method when a low amount of data is available'
string SHOW_EQHL = 'Display equal highs and equal lows on the chart'
string EQHL_BARS = 'Number of bars used to confirm equal highs and equal lows'
string EQHL_THRESHOLD = 'Sensitivity threshold in a range (0, 1) used for the detection of equal highs & lows\n\nLower values will return fewer but more pertinent results'
string SHOW_FVG = 'Display fair values gaps on the chart'
string AUTO_FVG = 'Filter out non significant fair value gaps'
string FVG_TF = 'Fair value gaps timeframe'
string EXTEND_FVG = 'Determine how many bars to extend the Fair Value Gap boxes on chart'
string PED_ZONES = 'Display premium, discount, and equilibrium zones on chart'
mode = input.string('Historical'
, options = ['Historical', 'Present']
, group = 'Smart Money Concepts'
, tooltip = MODE_TOOLTIP)
style = input.string('Colored'
, options = ['Colored', 'Monochrome']
, group = 'Smart Money Concepts'
, tooltip = STYLE_TOOLTIP)
show_trend = input(false, 'Color Candles'
, group = 'Smart Money Concepts'
, tooltip = COLOR_CANDLES_TOOLTIP)
show_internals = input(true, 'Show Internal Structure'
, group = 'Real Time Internal Structure'
, tooltip = SHOW_INTERNAL)
show_ibull = input.string('All', 'Bullish Structure'
, options = ['All', 'BOS', 'CHoCH']
, inline = 'ibull'
, group = 'Real Time Internal Structure')
swing_ibull_css = input(#1900ff, ''
, inline = 'ibull'
, group = 'Real Time Internal Structure')
show_ibear = input.string('All', 'Bearish Structure'
, options = ['All', 'BOS', 'CHoCH']
, inline = 'ibear'
, group = 'Real Time Internal Structure')
swing_ibear_css = input(#ffee00, ''
, inline = 'ibear'
, group = 'Real Time Internal Structure')
ifilter_confluence = input(false, 'Confluence Filter'
, group = 'Real Time Internal Structure'
, tooltip = CONFLUENCE_FILTER)
show_Structure = input(true, 'Show Swing Structure'
, group = 'Real Time Swing Structure'
, tooltip = SHOW_SWING)
show_bull = input.string('All', 'Bullish Structure'
, options = ['All', 'BOS', 'CHoCH']
, inline = 'bull'
, group = 'Real Time Swing Structure')
swing_bull_css = input(#2f00ff, ''
, inline = 'bull'
, group = 'Real Time Swing Structure')
show_bear = input.string('All', 'Bearish Structure'
, options = ['All', 'BOS', 'CHoCH']
, inline = 'bear'
, group = 'Real Time Swing Structure')
swing_bear_css = input(#f8e800, ''
, inline = 'bear'
, group = 'Real Time Swing Structure')
show_swings = input(false, 'Show Swings Points'
, inline = 'swings'
, group = 'Real Time Swing Structure'
, tooltip = SHOW_SWING_POINTS)
length = input.int(50, ''
, minval = 10
, inline = 'swings'
, group = 'Real Time Swing Structure')
show_hl_swings = input(true, 'Show Strong/Weak High/Low'
, group = 'Real Time Swing Structure'
, tooltip = SHOW_SWHL_POINTS)
show_iob = input(true, 'Internal Order Blocks'
, inline = 'iob'
, group = 'Order Blocks'
, tooltip = INTERNAL_OB)
iob_showlast = input.int(5, ''
, minval = 1
, inline = 'iob'
, group = 'Order Blocks')
show_ob = input(false, 'Swing Order Blocks'
, inline = 'ob'
, group = 'Order Blocks'
, tooltip = SWING_OB)
ob_showlast = input.int(5, ''
, minval = 1
, inline = 'ob'
, group = 'Order Blocks')
ob_filter = input.string('Atr', 'Order Block Filter'
, options = ['Atr', 'Cumulative Mean Range']
, group = 'Order Blocks'
, tooltip = FILTER_OB)
ibull_ob_css = input.color(color.new(#3179f5, 80), 'Internal Bullish OB'
, group = 'Order Blocks')
ibear_ob_css = input.color(color.new(#f77c80, 80), 'Internal Bearish OB'
, group = 'Order Blocks')
bull_ob_css = input.color(color.new(#1848cc, 80), 'Bullish OB'
, group = 'Order Blocks')
bear_ob_css = input.color(color.new(#b22833, 80), 'Bearish OB'
, group = 'Order Blocks')
show_eq = input(true, 'Equal High/Low'
, group = 'EQH/EQL'
, tooltip = SHOW_EQHL)
eq_len = input.int(3, 'Bars Confirmation'
, minval = 1
, group = 'EQH/EQL'
, tooltip = EQHL_BARS)
eq_threshold = input.float(0.1, 'Threshold'
, minval = 0
, maxval = 0.5
, step = 0.1
, group = 'EQH/EQL'
, tooltip = EQHL_THRESHOLD)
show_fvg = input(false, 'Fair Value Gaps'
, group = 'Fair Value Gaps'
, tooltip = SHOW_FVG)
fvg_auto = input(true, "Auto Threshold"
, group = 'Fair Value Gaps'
, tooltip = AUTO_FVG)
fvg_tf = input.timeframe('', "Timeframe"
, group = 'Fair Value Gaps'
, tooltip = FVG_TF)
bull_fvg_css = input.color(color.new(#00ff68, 70), 'Bullish FVG'
, group = 'Fair Value Gaps')
bear_fvg_css = input.color(color.new(#ff0008, 70), 'Bearish FVG'
, group = 'Fair Value Gaps')
fvg_extend = input.int(1, "Extend FVG"
, minval = 0
, group = 'Fair Value Gaps'
, tooltip = EXTEND_FVG)
show_pdhl = input(false, 'Daily'
, inline = 'daily'
, group = 'Highs & Lows MTF')
pdhl_style = input.string('⎯⎯⎯', ''
, options = ['⎯⎯⎯', '----', '····']
, inline = 'daily'
, group = 'Highs & Lows MTF')
pdhl_css = input(#2157f3, ''
, inline = 'daily'
, group = 'Highs & Lows MTF')
show_pwhl = input(false, 'Weekly'
, inline = 'weekly'
, group = 'Highs & Lows MTF')
pwhl_style = input.string('⎯⎯⎯', ''
, options = ['⎯⎯⎯', '----', '····']
, inline = 'weekly'
, group = 'Highs & Lows MTF')
pwhl_css = input(#2157f3, ''
, inline = 'weekly'
, group = 'Highs & Lows MTF')
show_pmhl = input(false, 'Monthly'
, inline = 'monthly'
, group = 'Highs & Lows MTF')
pmhl_style = input.string('⎯⎯⎯', ''
, options = ['⎯⎯⎯', '----', '····']
, inline = 'monthly'
, group = 'Highs & Lows MTF')
pmhl_css = input(#2157f3, ''
, inline = 'monthly'
, group = 'Highs & Lows MTF')
show_sd = input(false, 'Premium/Discount Zones'
, group = 'Premium & Discount Zones'
, tooltip = PED_ZONES)
premium_css = input.color(#f9fd00, 'Premium Zone'
, group = 'Premium & Discount Zones')
eq_css = input.color(#b2b5be, 'Equilibrium Zone'
, group = 'Premium & Discount Zones')
discount_css = input.color(#0004f3, 'Discount Zone'
, group = 'Premium & Discount Zones')
n = bar_index
atr = ta.atr(200)
cmean_range = ta.cum(high - low) / n
hl() => [high, low]
get_ohlc()=> [close[1], open[1], high, low, high[2], low[2]]
display_Structure(x, y, txt, css, dashed, down, lbl_size)=>
structure_line = line.new(x, y, n, y
, color = css
, style = dashed ? line.style_dashed : line.style_solid)
structure_lbl = label.new(int(math.avg(x, n)), y, txt
, color = TRANSP_CSS
, textcolor = css
, style = down ? label.style_label_down : label.style_label_up
, size = lbl_size)
if mode == 'Present'
line.delete(structure_line[1])
label.delete(structure_lbl[1])
swings(len)=>
var os = 0
upper = ta.highest(len)
lower = ta.lowest(len)
os := high[len] > upper ? 0 : low[len] < lower ? 1 : os[1]
top = os == 0 and os[1] != 0 ? high[len] : 0
btm = os == 1 and os[1] != 1 ? low[len] : 0
[top, btm]
ob_coord(use_max, loc, target_top, target_btm, target_left, target_type)=>
min = 99999999.
max = 0.
idx = 1
ob_threshold = ob_filter == 'Atr' ? atr : cmean_range
if use_max
for i = 1 to (n - loc)-1
if (high[i] - low[i]) < ob_threshold[i] * 2
max := math.max(high[i], max)
min := max == high[i] ? low[i] : min
idx := max == high[i] ? i : idx
else
for i = 1 to (n - loc)-1
if (high[i] - low[i]) < ob_threshold[i] * 2
min := math.min(low[i], min)
max := min == low[i] ? high[i] : max
idx := min == low[i] ? i : idx
array.unshift(target_top, max)
array.unshift(target_btm, min)
array.unshift(target_left, time[idx])
array.unshift(target_type, use_max ? -1 : 1)
display_ob(boxes, target_top, target_btm, target_left, target_type, show_last, swing, size)=>
for i = 0 to math.min(show_last-1, size-1)
get_box = array.get(boxes, i)
box.set_lefttop(get_box, array.get(target_left, i), array.get(target_top, i))
box.set_rightbottom(get_box, array.get(target_left, i), array.get(target_btm, i))
box.set_extend(get_box, extend.right)
color css = na
if swing
if style == 'Monochrome'
css := array.get(target_type, i) == 1 ? color.new(#b2b5be, 80) : color.new(#5d606b, 80)
border_css = array.get(target_type, i) == 1 ? #b2b5be : #5d606b
box.set_border_color(get_box, border_css)
else
css := array.get(target_type, i) == 1 ? bull_ob_css : bear_ob_css
box.set_border_color(get_box, css)
box.set_bgcolor(get_box, css)
else
if style == 'Monochrome'
css := array.get(target_type, i) == 1 ? color.new(#b2b5be, 80) : color.new(#5d606b, 80)
else
css := array.get(target_type, i) == 1 ? ibull_ob_css : ibear_ob_css
box.set_border_color(get_box, css)
box.set_bgcolor(get_box, css)
get_line_style(style) =>
out = switch style
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted
phl(h, l, tf, css)=>
var line high_line = line.new(na,na,na,na
, xloc = xloc.bar_time
, color = css
, style = get_line_style(pdhl_style))
var label high_lbl = label.new(na,na
, xloc = xloc.bar_time
, text = str.format('P{0}H', tf)
, color = TRANSP_CSS
, textcolor = css
, size = size.small
, style = label.style_label_left)
var line low_line = line.new(na,na,na,na
, xloc = xloc.bar_time
, color = css
, style = get_line_style(pdhl_style))
var label low_lbl = label.new(na,na
, xloc = xloc.bar_time
, text = str.format('P{0}L', tf)
, color = TRANSP_CSS
, 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
ext = time + (time - time[1])*20
line.set_xy1(high_line, hx, hy)
line.set_xy2(high_line, ext, hy)
label.set_xy(high_lbl, ext, hy)
line.set_xy1(low_line, lx, ly)
line.set_xy2(low_line, ext, ly)
label.set_xy(low_lbl, ext, ly)
var trend = 0, var itrend = 0
var top_y = 0., var top_x = 0
var btm_y = 0., var btm_x = 0
var itop_y = 0., var itop_x = 0
var ibtm_y = 0., var ibtm_x = 0
var trail_up = high, var trail_dn = low
var trail_up_x = 0, var trail_dn_x = 0
var top_cross = true, var btm_cross = true
var itop_cross = true, var ibtm_cross = true
var txt_top = '', var txt_btm = ''
bull_choch_alert = false
bull_bos_alert = false
bear_choch_alert = false
bear_bos_alert = false
bull_ichoch_alert = false
bull_ibos_alert = false
bear_ichoch_alert = false
bear_ibos_alert = false
bull_iob_break = false
bear_iob_break = false
bull_ob_break = false
bear_ob_break = false
eqh_alert = false
eql_alert = false
var bull_css = style == 'Monochrome' ? #b2b5be
: swing_bull_css
var bear_css = style == 'Monochrome' ? #b2b5be
: swing_bear_css
var ibull_css = style == 'Monochrome' ? #b2b5be
: swing_ibull_css
var ibear_css = style == 'Monochrome' ? #b2b5be
: swing_ibear_css
[top, btm] = swings(length)
[itop, ibtm] = swings(5)
var line extend_top = na
var label extend_top_lbl = label.new(na, na
, color = TRANSP_CSS
, textcolor = bear_css
, style = label.style_label_down
, size = size.tiny)
if top
top_cross := true
txt_top := top > top_y ? 'HH' : 'LH'
if show_swings
top_lbl = label.new(n-length, top, txt_top
, color = TRANSP_CSS
, textcolor = bear_css
, style = label.style_label_down
, size = size.small)
if mode == 'Present'
label.delete(top_lbl[1])
line.delete(extend_top[1])
extend_top := line.new(n-length, top, n, top
, color = bear_css)
top_y := top
top_x := n - length
trail_up := top
trail_up_x := n - length
if itop
itop_cross := true
itop_y := itop
itop_x := n - 5
trail_up := math.max(high, trail_up)
trail_up_x := trail_up == high ? n : trail_up_x
if barstate.islast and show_hl_swings
line.set_xy1(extend_top, trail_up_x, trail_up)
line.set_xy2(extend_top, n + 20, trail_up)
label.set_x(extend_top_lbl, n + 20)
label.set_y(extend_top_lbl, trail_up)
label.set_text(extend_top_lbl, trend < 0 ? 'Strong High' : 'Weak High')
var line extend_btm = na
var label extend_btm_lbl = label.new(na, na
, color = TRANSP_CSS
, textcolor = bull_css
, style = label.style_label_up
, size = size.tiny)
if btm
btm_cross := true
txt_btm := btm < btm_y ? 'LL' : 'HL'
if show_swings
btm_lbl = label.new(n - length, btm, txt_btm
, color = TRANSP_CSS
, textcolor = bull_css
, style = label.style_label_up
, size = size.small)
if mode == 'Present'
label.delete(btm_lbl[1])
line.delete(extend_btm[1])
extend_btm := line.new(n - length, btm, n, btm
, color = bull_css)
btm_y := btm
btm_x := n-length
trail_dn := btm
trail_dn_x := n-length
if ibtm
ibtm_cross := true
ibtm_y := ibtm
ibtm_x := n - 5
trail_dn := math.min(low, trail_dn)
trail_dn_x := trail_dn == low ? n : trail_dn_x
if barstate.islast and show_hl_swings
line.set_xy1(extend_btm, trail_dn_x, trail_dn)
line.set_xy2(extend_btm, n + 20, trail_dn)
label.set_x(extend_btm_lbl, n + 20)
label.set_y(extend_btm_lbl, trail_dn)
label.set_text(extend_btm_lbl, trend > 0 ? 'Strong Low' : 'Weak Low')
var iob_top = array.new_float(0)
var iob_btm = array.new_float(0)
var iob_left = array.new_int(0)
var iob_type = array.new_int(0)
var ob_top = array.new_float(0)
var ob_btm = array.new_float(0)
var ob_left = array.new_int(0)
var ob_type = array.new_int(0)
var bull_concordant = true
if ifilter_confluence
bull_concordant := high - math.max(close, open) > math.min(close, open - low)
if ta.crossover(close, itop_y) and itop_cross and top_y != itop_y and bull_concordant
bool choch = na
if itrend < 0
choch := true
bull_ichoch_alert := true
else
bull_ibos_alert := true
txt = choch ? 'CHoCH' : 'BOS'
if show_internals
if show_ibull == 'All' or (show_ibull == 'BOS' and not choch) or (show_ibull == 'CHoCH' and choch)
display_Structure(itop_x, itop_y, txt, ibull_css, true, true, size.tiny)
itop_cross := false
itrend := 1
if show_iob
ob_coord(false, itop_x, iob_top, iob_btm, iob_left, iob_type)
if ta.crossover(close, top_y) and top_cross
bool choch = na
if trend < 0
choch := true
bull_choch_alert := true
else
bull_bos_alert := true
txt = choch ? 'CHoCH' : 'BOS'
if show_Structure
if show_bull == 'All' or (show_bull == 'BOS' and not choch) or (show_bull == 'CHoCH' and choch)
display_Structure(top_x, top_y, txt, bull_css, false, true, size.small)
if show_ob
ob_coord(false, top_x, ob_top, ob_btm, ob_left, ob_type)
top_cross := false
trend := 1
var bear_concordant = true
if ifilter_confluence
bear_concordant := high - math.max(close, open) < math.min(close, open - low)
if ta.crossunder(close, ibtm_y) and ibtm_cross and btm_y != ibtm_y and bear_concordant
bool choch = false
if itrend > 0
choch := true
bear_ichoch_alert := true
else
bear_ibos_alert := true
txt = choch ? 'CHoCH' : 'BOS'
if show_internals
if show_ibear == 'All' or (show_ibear == 'BOS' and not choch) or (show_ibear == 'CHoCH' and choch)
display_Structure(ibtm_x, ibtm_y, txt, ibear_css, true, false, size.tiny)
ibtm_cross := false
itrend := -1
if show_iob
ob_coord(true, ibtm_x, iob_top, iob_btm, iob_left, iob_type)
if ta.crossunder(close, btm_y) and btm_cross
bool choch = na
if trend > 0
choch := true
bear_choch_alert := true
else
bear_bos_alert := true
txt = choch ? 'CHoCH' : 'BOS'
if show_Structure
if show_bear == 'All' or (show_bear == 'BOS' and not choch) or (show_bear == 'CHoCH' and choch)
display_Structure(btm_x, btm_y, txt, bear_css, false, false, size.small)
if show_ob
ob_coord(true, btm_x, ob_top, ob_btm, ob_left, ob_type)
btm_cross := false
trend := -1
var iob_boxes = array.new_box(0)
var ob_boxes = array.new_box(0)
for element in iob_type
index = array.indexof(iob_type, element)
if close < array.get(iob_btm, index) and element == 1
array.remove(iob_top, index)
array.remove(iob_btm, index)
array.remove(iob_left, index)
array.remove(iob_type, index)
bull_iob_break := true
else if close > array.get(iob_top, index) and element == -1
array.remove(iob_top, index)
array.remove(iob_btm, index)
array.remove(iob_left, index)
array.remove(iob_type, index)
bear_iob_break := true
for element in ob_type
index = array.indexof(ob_type, element)
if close < array.get(ob_btm, index) and element == 1
array.remove(ob_top, index)
array.remove(ob_btm, index)
array.remove(ob_left, index)
array.remove(ob_type, index)
bull_ob_break := true
else if close > array.get(ob_top, index) and element == -1
array.remove(ob_top, index)
array.remove(ob_btm, index)
array.remove(ob_left, index)
array.remove(ob_type, index)
bear_ob_break := true
iob_size = array.size(iob_type)
ob_size = array.size(ob_type)
if barstate.isfirst
if show_iob
for i = 0 to iob_showlast-1
array.push(iob_boxes, box.new(na,na,na,na, xloc = xloc.bar_time))
if show_ob
for i = 0 to ob_showlast-1
array.push(ob_boxes, box.new(na,na,na,na, xloc = xloc.bar_time))
if iob_size > 0
if barstate.islast
display_ob(iob_boxes, iob_top, iob_btm, iob_left, iob_type, iob_showlast, false, iob_size)
if ob_size > 0
if barstate.islast
display_ob(ob_boxes, ob_top, ob_btm, ob_left, ob_type, ob_showlast, true, ob_size)
var eq_prev_top = 0.
var eq_top_x = 0
var eq_prev_btm = 0.
var eq_btm_x = 0
if show_eq
eq_top = ta.pivothigh(eq_len, eq_len)
eq_btm = ta.pivotlow(eq_len, eq_len)
if eq_top
max = math.max(eq_top, eq_prev_top)
min = math.min(eq_top, eq_prev_top)
if max < min + atr * eq_threshold
eqh_line = line.new(eq_top_x, eq_prev_top, n-eq_len, eq_top
, color = bear_css
, style = line.style_dotted)
eqh_lbl = label.new(int(math.avg(n-eq_len, eq_top_x)), eq_top, 'EQH'
, color = #00000000
, textcolor = bear_css
, style = label.style_label_down
, size = size.tiny)
if mode == 'Present'
line.delete(eqh_line[1])
label.delete(eqh_lbl[1])
eqh_alert := true
eq_prev_top := eq_top
eq_top_x := n-eq_len
if eq_btm
max = math.max(eq_btm, eq_prev_btm)
min = math.min(eq_btm, eq_prev_btm)
if min > max - atr * eq_threshold
eql_line = line.new(eq_btm_x, eq_prev_btm, n-eq_len, eq_btm
, color = bull_css
, style = line.style_dotted)
eql_lbl = label.new(int(math.avg(n-eq_len, eq_btm_x)), eq_btm, 'EQL'
, color = #00000000
, textcolor = bull_css
, style = label.style_label_up
, size = size.tiny)
eql_alert := true
if mode == 'Present'
line.delete(eql_line[1])
label.delete(eql_lbl[1])
eq_prev_btm := eq_btm
eq_btm_x := n-eq_len
var bullish_fvg_max = array.new_box(0)
var bullish_fvg_min = array.new_box(0)
var bearish_fvg_max = array.new_box(0)
var bearish_fvg_min = array.new_box(0)
float bullish_fvg_avg = na
float bearish_fvg_avg = na
bullish_fvg_cnd = false
bearish_fvg_cnd = false
[src_c1, src_o1, src_h, src_l, src_h2, src_l2] =
request.security(syminfo.tickerid, fvg_tf, get_ohlc())
if show_fvg
delta_per = (src_c1 - src_o1) / src_o1 * 100
change_tf = timeframe.change(fvg_tf)
threshold = fvg_auto ? ta.cum(math.abs(change_tf ? delta_per : 0)) / n * 2
: 0
bullish_fvg_cnd := src_l > src_h2
and src_c1 > src_h2
and delta_per > threshold
and change_tf
bearish_fvg_cnd := src_h < src_l2
and src_c1 < src_l2
and -delta_per > threshold
and change_tf
if bullish_fvg_cnd
array.unshift(bullish_fvg_max, box.new(n-1, src_l, n + fvg_extend, math.avg(src_l, src_h2)
, border_color = bull_fvg_css
, bgcolor = bull_fvg_css))
array.unshift(bullish_fvg_min, box.new(n-1, math.avg(src_l, src_h2), n + fvg_extend, src_h2
, border_color = bull_fvg_css
, bgcolor = bull_fvg_css))
if bearish_fvg_cnd
array.unshift(bearish_fvg_max, box.new(n-1, src_h, n + fvg_extend, math.avg(src_h, src_l2)
, border_color = bear_fvg_css
, bgcolor = bear_fvg_css))
array.unshift(bearish_fvg_min, box.new(n-1, math.avg(src_h, src_l2), n + fvg_extend, src_l2
, border_color = bear_fvg_css
, bgcolor = bear_fvg_css))
for bx in bullish_fvg_min
if low < box.get_bottom(bx)
box.delete(bx)
box.delete(array.get(bullish_fvg_max, array.indexof(bullish_fvg_min, bx)))
for bx in bearish_fvg_max
if high > box.get_top(bx)
box.delete(bx)
box.delete(array.get(bearish_fvg_min, array.indexof(bearish_fvg_max, bx)))
[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)
if show_pdhl
phl(pdh, pdl, 'D', pdhl_css)
if show_pwhl
phl(pwh, pwl, 'W', pwhl_css)
if show_pmhl
phl(pmh, pml, 'M', pmhl_css)
var premium = box.new(na, na, na, na
, bgcolor = color.new(premium_css, 80)
, border_color = na)
var premium_lbl = label.new(na, na
, text = 'Premium'
, color = TRANSP_CSS
, textcolor = premium_css
, style = label.style_label_down
, size = size.small)
var eq = box.new(na, na, na, na
, bgcolor = color.rgb(120, 123, 134, 80)
, border_color = na)
var eq_lbl = label.new(na, na
, text = 'Equilibrium'
, color = TRANSP_CSS
, textcolor = eq_css
, style = label.style_label_left
, size = size.small)
var discount = box.new(na, na, na, na
, bgcolor = color.new(discount_css, 80)
, border_color = na)
var discount_lbl = label.new(na, na
, text = 'Discount'
, color = TRANSP_CSS
, textcolor = discount_css
, style = label.style_label_up
, size = size.small)
if barstate.islast and show_sd
avg = math.avg(trail_up, trail_dn)
box.set_lefttop(premium, math.max(top_x, btm_x), trail_up)
box.set_rightbottom(premium, n, .95 * trail_up + .05 * trail_dn)
label.set_xy(premium_lbl, int(math.avg(math.max(top_x, btm_x), n)), trail_up)
box.set_lefttop(eq, math.max(top_x, btm_x), .525 * trail_up + .475*trail_dn)
box.set_rightbottom(eq, n, .525 * trail_dn + .475 * trail_up)
label.set_xy(eq_lbl, n, avg)
box.set_lefttop(discount, math.max(top_x, btm_x), .95 * trail_dn + .05 * trail_up)
box.set_rightbottom(discount, n, trail_dn)
label.set_xy(discount_lbl, int(math.avg(math.max(top_x, btm_x), n)), trail_dn)
var color trend_css = na
if show_trend
if style == 'Colored'
trend_css := itrend == 1 ? bull_css : bear_css
else if style == 'Monochrome'
trend_css := itrend == 1 ? #b2b5be : #5d606b
plotcandle(open, high, low, close
, color = trend_css
, wickcolor = trend_css
, bordercolor = trend_css
, editable = false)
alertcondition(bull_ibos_alert, 'Internal Bullish BOS', 'Internal Bullish BOS formed')
alertcondition(bull_ichoch_alert, 'Internal Bullish CHoCH', 'Internal Bullish CHoCH formed')
alertcondition(bear_ibos_alert, 'Internal Bearish BOS', 'Internal Bearish BOS formed')
alertcondition(bear_ichoch_alert, 'Internal Bearish CHoCH', 'Internal Bearish CHoCH formed')
alertcondition(bull_bos_alert, 'Bullish BOS', 'Internal Bullish BOS formed')
alertcondition(bull_choch_alert, 'Bullish CHoCH', 'Internal Bullish CHoCH formed')
alertcondition(bear_bos_alert, 'Bearish BOS', 'Bearish BOS formed')
alertcondition(bear_choch_alert, 'Bearish CHoCH', 'Bearish CHoCH formed')
alertcondition(bull_iob_break, 'Bullish Internal OB Breakout', 'Price broke bullish iternal OB')
alertcondition(bear_iob_break, 'Bearish Internal OB Breakout', 'Price broke bearish iternal OB')
alertcondition(bull_ob_break, 'Bullish OB Breakout', 'Price broke bullish iternal OB')
alertcondition(bear_ob_break, 'bearish OB Breakout', 'Price broke bearish iternal OB')
alertcondition(eqh_alert, 'Equal Highs', 'Equal highs detected')
alertcondition(eql_alert, 'Equal Lows', 'Equal lows detected')
alertcondition(bullish_fvg_cnd, 'Bullish FVG', 'Bullish FVG formed')
alertcondition(bearish_fvg_cnd, 'Bearish FVG', 'Bearish FVG formed')
ds_min_pc_change = input.float(title='Min % change', defval=0.05, minval=0, step=0.2, group='Demand & Supply',
tooltip=' --- Min % change ---' + '\n\n' + 'A zone is added if one candle or a run of bullish/bearish candles meets this minimum % change.' + '\n\n' +
'The change is from the open to the close when the time period is complete. Adjust the % for the pair and the timeframe.' + '\n' +
'e.g. Crypto 15m 0.8% 1m 0.5%, Forex 15m 0.4%')
ds_max_pc_zone = input.float(title='Max % zone height', defval=0.05, minval=0, step=0.2, group='Demand & Supply',
tooltip=' --- Max % zone height ---' + '\n\n' + 'The zone height is decided by the size of the candle before a significant drop or rally.' + '\n\n' +
'Setting a higher max % will keep the height closer to candle height.' + '\n' +
'Setting a lower max % makes the boxes look a bit tidier.')
ds_line_pc_display = input.float(title='% line', defval=3.0, step=0.5, minval=0, maxval=5, inline='line', group='Demand & Supply')
ds_line_max = input.int(title='Max line', defval=3, minval=0, maxval=5, inline='line', group='Demand & Supply',
tooltip=' --- % Line --- ' + '\n' + 'Display lines of active zones when the close is within this % of the line. Max is 5%.' + '\n\n' +
' --- Max Line --- ' + '\n' + 'The maximum number of lines to display for each zone type.')
ds_max_zones = input.int(title='Max number of zones', defval=100, step=50, maxval=200, group='Demand & Supply',
tooltip=' --- Max number of zones ---' + '\n\n' + 'The maximum number of zones for each zone type.\nUp to 200 boxes can be displayed for each zone type.')
ds_hours_offset = input.float(0.0, "Timezone offset (H)", minval=-12, maxval=14, group='Demand & Supply',
tooltip=' --- Timezone offset (H) --- ' + '\n' + 'If your chart timezone is not set set to UTC, set the offset in hours.' + '\n' +
'Range: -12 to +14.'+ '\n\n' +
'Time information is displayed when hovering over zone labels.')
showDemandZone = input.bool(title='Demand', defval=true, inline='demand_1', group='Demand & Supply')
demand_bord_col = input.color(title='Border', defval=color.rgb(11, 255, 2), inline='demand_1', group='Demand & Supply')
demand_bg_col = input.color(title='Background', defval=color.rgb(2, 2, 2), inline='demand_1', group='Demand & Supply',
tooltip='This background colour applies when the zone is active. Once the zone has been hit, it becomes transparent.')
showSupplyZone = input.bool(title='Supply', defval=true, inline='supply_1', group='Demand & Supply')
supply_bord_col = input.color(title='Border', defval=color.rgb(255, 0, 0), inline='supply_1', group='Demand & Supply')
supply_bg_col = input.color(title='Background', defval=color.rgb(255, 254, 254), inline='supply_1', group='Demand & Supply',
tooltip='This background colour applies when the zone is active. Once the zone has been hit, it becomes transparent.')
dsAlertDemand = input.bool(true, title='Demand', inline='ds_alert_1', group='Demand & Supply Alerts')
dsAlertSupply = input.bool(true, title='Supply', inline='ds_alert_1', group='Demand & Supply Alerts',
tooltip=' --- Demand & Supply Alerts ---' + '\n\n' + 'Two types of alerts are sent:' + '\n' +
'1. Hit: The price hits an active zone.' + '\n' + '2. Near: The price approaches the active zone.' + '\n\n' +
' --- Supply Example ---' + '\n' +
'1. When the price is below the supply zone and the high hits the zone, an alert is sent.' + '\n' +
'2. When the price is below the supply zone and the high is within the Near %, an alert is sent.')
ds_alert_mins_no_repeat = input.int(60, minval=0, maxval=120, title='Mins no repeat', group='Demand & Supply Alerts',
tooltip=' --- Mins No Repeat ---' + '\n\n' + 'Wait x mins before sending a similar alert type for the same zone.' + '\n\n' +
'Setting this to 0 will turn this feature off.' + '\n' +
'Max = 120mins.')
ds_alerts_pc_near = input.float(1.5, title='Near %', step=0.1, maxval=5, group='Demand & Supply Alerts',
tooltip=' --- Near % ---' +
'\n' + 'The alert is sent when the high or low is within this % of the zone. Max is 5%.')
get_pc_diff_abs(x_start, y_end) =>
math.abs((y_end - x_start) / x_start * 100)
get_amount_by_pc(amount, pc, add_minus) =>
pc_amount = amount * (pc / 100)
add_minus == 'add' ? amount + pc_amount : amount - pc_amount
var milli_secs_per_bar =
timeframe.isseconds ? timeframe.multiplier * 1000 :
timeframe.isminutes ? timeframe.multiplier * 60 * 1000 :
timeframe.isdaily ? timeframe.multiplier * 24 * 60 * 60 * 1000 :
timeframe.isweekly ? timeframe.multiplier * 7 * 24 * 60 * 60 * 1000 : na
var demand_zones_alert = array.new_float(0)
var demand_zones_time = array.new_int(0)
var demand_zones_s1_active = array.new_bool(0)
var demand_zones_s1 = array.new_float(0)
var demand_zones_box = array.new_box(0)
var supply_zones_alert = array.new_float(0)
var supply_zones_time = array.new_int(0)
var supply_zones_s1 = array.new_float(0)
var supply_zones_s1_active = array.new_bool(0)
var supply_zones_box = array.new_box(0)
var demand_zones_s1_line = array.new_line(ds_line_max)
var demand_zones_s1_line_price = array.new_label(ds_line_max)
var supply_zones_s1_line = array.new_line(ds_line_max)
var supply_zones_s1_line_price = array.new_label(ds_line_max)
var demand_zones_time_all = array.new_int(0)
var demand_zones_s1_all = array.new_float(0)
var supply_zones_time_all = array.new_int(0)
var supply_zones_s1_all = array.new_float(0)
var demand_zones_label_all = array.new_label(ds_line_max)
var demand_zones_line_all = array.new_line(ds_line_max)
var supply_zones_label_all = array.new_label(ds_line_max)
var supply_zones_line_all = array.new_line(ds_line_max)
if barstate.isfirst
for i = 0 to ds_line_max - 1
array.set(demand_zones_s1_line, i, line.new(na, na, na, na, xloc=xloc.bar_time, color=demand_bord_col, style=line.style_solid))
array.set(supply_zones_s1_line, i, line.new(na, na, na, na, xloc=xloc.bar_time, color=supply_bord_col, style=line.style_solid))
array.set(demand_zones_s1_line_price, i, label.new(na, na, textcolor=color.new(color.white, 0), style=label.style_label_left))
array.set(supply_zones_s1_line_price, i, label.new(na, na, textcolor=color.new(color.white, 0), style=label.style_label_left))
array.set(demand_zones_label_all, i, label.new(na, na, textcolor=color.new(color.white, 0), style=label.style_label_left))
array.set(supply_zones_label_all, i, label.new(na, na, textcolor=color.new(color.white, 0), style=label.style_label_left))
array.set(demand_zones_line_all, i, line.new(na, na, na, na, color=color.new(color.white, 100), style=line.style_solid))
array.set(supply_zones_line_all, i, line.new(na, na, na, na, color=color.new(color.white, 100), style=line.style_solid))
bear_run = ta.barssince(open < close)
bull_run = ta.barssince(open > close)
var float s1_level = na
var int s1_time = na
s1_level :=
get_pc_diff_abs(open[1], close[1]) < 0.02 and
((bull_run == 1 and open[2] > close[2]) or (bear_run == 1 and open[2] < close[2])) ? open[2] :
bull_run == 1 or bear_run == 1 ? open[1] :
bull_run > 1 or bear_run > 1 ? s1_level : na
s1_time :=
bull_run == 1 or bear_run == 1 ? time[1] :
bull_run > 1 or bear_run > 1 ? s1_time : na
get_month_bar_time(_bar_start, _add_minus, _num_bars) =>
_add_minus_sign = _add_minus == 'add' ? 1 : -1
_year_start = year(_bar_start)
_month_start = month(_bar_start)
_months_div_year = _num_bars / 12
_year_change = _months_div_year >= 1 ? math.floor(_months_div_year) : 0
_year = _year_start + (_year_change * _add_minus_sign)
_month_change = _num_bars % 12
_month = _month_start + (_month_change * _add_minus_sign)
_year += _month > 12 ? 1 : _month < 1 ? -1 : 0
_month += _month > 12 ? -12 : _month < 1 ? 12 : 0
timestamp(_year, _month, 1, 0, 0, 0)
get_bar_time(_bar_start, _add_minus, _num_bars) =>
_add_minus_sign = _add_minus == 'add' ? 1 : -1
_bar_time =
not na(milli_secs_per_bar) ? _bar_start + ((milli_secs_per_bar * _num_bars) * _add_minus_sign) :
timeframe.ismonthly ? get_month_bar_time(_bar_start, _add_minus, _num_bars) : na
add_ds_zone(_zone_type) =>
_showZone = (_zone_type == 'S' and showSupplyZone) or (_zone_type == 'D' and showDemandZone)
_zones_time = _zone_type == 'S' ? supply_zones_time : demand_zones_time
_bars_to_s1 = _zone_type == 'S' ? bear_run : bull_run
_pc_change = _bars_to_s1 >= 1 ? get_pc_diff_abs(close, open[_bars_to_s1 - 1]) : 0
if not array.includes(_zones_time, s1_time) and _pc_change >= ds_min_pc_change and barstate.isconfirmed
_box_left_time = get_bar_time(s1_time, 'minus', 1)
_box_right_time = get_bar_time(s1_time, 'add', 2)
_zones_s1_active = _zone_type == 'S' ? supply_zones_s1_active : demand_zones_s1_active
_zones_s1 = _zone_type == 'S' ? supply_zones_s1 : demand_zones_s1
_zones_box = _zone_type == 'S' ? supply_zones_box : demand_zones_box
_zones_time_all = _zone_type == 'S' ? supply_zones_time_all : demand_zones_time_all
_zones_s1_all = _zone_type == 'S' ? supply_zones_s1_all : demand_zones_s1_all
array.unshift(_zones_time, s1_time)
array.unshift(_zones_time_all, s1_time)
_top = _zone_type == 'S' ? math.max(high[_bars_to_s1], high[_bars_to_s1-1]) : s1_level
_bot = _zone_type == 'S' ? s1_level : math.min(low[_bars_to_s1], low[_bars_to_s1-1])
_top_bot_pc_diff = get_pc_diff_abs(_top, _bot)
_candle_before_run_pc = get_pc_diff_abs(open[_bars_to_s1], close[_bars_to_s1])
_bot :=
_zone_type == 'S' and _top_bot_pc_diff > ds_max_pc_zone and _candle_before_run_pc <= ds_max_pc_zone ? s1_level :
_zone_type == 'S' and _top_bot_pc_diff > ds_max_pc_zone ? get_amount_by_pc(close[_bars_to_s1], ds_max_pc_zone/5, 'minus') :
_zone_type == 'D' and _top_bot_pc_diff > ds_max_pc_zone ? get_amount_by_pc(_top, ds_max_pc_zone, 'minus') : _bot
_top :=
_zone_type == 'S' and _top_bot_pc_diff > ds_max_pc_zone ? get_amount_by_pc(_bot, ds_max_pc_zone, 'add') :
_zone_type == 'D' and _top_bot_pc_diff > ds_max_pc_zone and _candle_before_run_pc <= ds_max_pc_zone ? s1_level :
_zone_type == 'D' and _top_bot_pc_diff > ds_max_pc_zone ? get_amount_by_pc(close[_bars_to_s1], ds_max_pc_zone/5, 'add') : _top
_bot := math.round_to_mintick(_bot)
_top := math.round_to_mintick(_top)
_s1 = _zone_type == 'S' ? _bot : _top
array.unshift(_zones_s1, _s1)
array.unshift(_zones_s1_active, true)
array.unshift(_zones_s1_all, _s1)
_bord_col = _zone_type == 'S' ? supply_bord_col : demand_bord_col
_bg_col = _zone_type == 'S' ? supply_bg_col : demand_bg_col
if _showZone
array.unshift(_zones_box, box.new(_box_left_time, _top, _box_right_time, _bot, xloc=xloc.bar_time, border_color=_bord_col, border_width=1, bgcolor=_bg_col))
if array.size(_zones_time) > ds_max_zones
for i = array.size(_zones_time) - 1 to (array.size(_zones_time) == 0 ? na : 0)
_s1Active = array.size(_zones_s1_active) > i ? array.get(_zones_s1_active, i) : na
if not na(_s1Active) and not _s1Active
array.remove(_zones_time, i)
array.remove(_zones_s1_active, i)
array.remove(_zones_s1, i)
if _showZone
array.remove(_zones_box, i)
if array.size(_zones_time) == ds_max_zones
break
if array.size(_zones_time_all) > 90000
array.pop(_zones_time_all)
array.pop(_zones_s1_all)
add_ds_alert(_type, _time_unix, _price) =>
_zones_alert = _type == 'S' ? supply_zones_alert : demand_zones_alert
array.unshift(_zones_alert, _time_unix)
array.unshift(_zones_alert, _price)
remove_ds_alerts(_type, _time_unix) =>
int _slice_start = na
_zones_alert = _type == 'S' ? supply_zones_alert : demand_zones_alert
_noRepeatOff = ds_alert_mins_no_repeat == 0
for i = 0 to (array.size(_zones_alert) == 0 or _noRepeatOff ? na : array.size(_zones_alert) - 1) by 2
_price = array.size(_zones_alert) > i ? array.get(_zones_alert, i) : na
_time = array.size(_zones_alert) > i+1 ? array.get(_zones_alert, i+1) : na
_mins_diff = (_time_unix - _time) / (1000 * 60)
if _mins_diff >= ds_alert_mins_no_repeat
_slice_start := i
break
if not na(_slice_start)
_sliceArr = array.slice(_zones_alert, _slice_start, array.size(_zones_alert))
array.clear(_sliceArr)
check_repeat_alert(_type, _price) =>
_zones_alert = _type == 'S' ? supply_zones_alert : demand_zones_alert
_repeatAlert = array.includes(_zones_alert, _price)
_repeatAlert
get_ds_zone_info(_zone_type, _s1, _s1_time) =>
_info = _zone_type == 'S' ? 'Supply Zone ' : 'Demand Zone '
_info += str.tostring(_s1) + '\n'
_info += 'from UTC'
_info += ds_hours_offset > 0 ? '+' + str.tostring(ds_hours_offset) : ds_hours_offset < 0 ? str.tostring(ds_hours_offset) : ''
_info += str.format(': {0,date,yyyy/MM/dd HH:mm}', _s1_time + (60 * 60 * 1000 * ds_hours_offset)) + '\n'
_info
alert_ds(_do, _zone_type, _s1, _s1_time, _alert_type) =>
_repeatAlert = false
if _do and _alert_type == 'N' and ds_alert_mins_no_repeat > 0
_time_unix = time
remove_ds_alerts(_zone_type, _time_unix)
_repeatAlert := check_repeat_alert(_zone_type, _s1)
if not _repeatAlert
add_ds_alert(_zone_type, _time_unix, _s1)
if _do and not _repeatAlert
_msg = _alert_type == 'H' ? 'Zone hit' : 'Near zone'
_msg += '\n' + get_ds_zone_info(_zone_type, _s1, _s1_time)
alert(_msg)
deactivate_ds_box(_box) =>
box.set_bgcolor(_box, color.rgb(0, 0, 0, 100))
box.set_border_style(_box, line.style_dotted)
deactivate_ds_limited(_do, _zone_type, _s1, _s1_time) =>
if _do
_zones_time = _zone_type == 'S' ? supply_zones_time : demand_zones_time
_zones_s1 = _zone_type == 'S' ? supply_zones_s1 : demand_zones_s1
_zones_s1_active = _zone_type == 'S' ? supply_zones_s1_active : demand_zones_s1_active
_zones_box = _zone_type == 'S' ? supply_zones_box : demand_zones_box
_index = array.indexof(_zones_time, _s1_time)
if _index >= 0
array.set(_zones_s1_active, _index, false)
if showDemandZone and _index >= 0
_box = array.size(_zones_box) > _index ? array.get(_zones_box, _index) : na
deactivate_ds_box(_box)
check_ds_zone_hit() =>
loop_break_pc = 5
for i = 0 to (array.size(demand_zones_s1_all) == 0 ? na : array.size(demand_zones_s1_all) - 1)
_s1 = array.size(demand_zones_s1_all) > i ? array.get(demand_zones_s1_all, i) : na
_s1_time = array.size(demand_zones_time_all) > i ? array.get(demand_zones_time_all, i) : na
_price_near = get_amount_by_pc(_s1, ds_alerts_pc_near, 'add')
_alert_type = low <= _s1 ? 'H' : low <= _price_near ? 'N' : ''
if _alert_type == 'H'
array.remove(demand_zones_s1_all, i)
array.remove(demand_zones_time_all, i)
alert_ds(_alert_type=='H' or _alert_type=='N', 'D', _s1, _s1_time, _alert_type)
deactivate_ds_limited(_alert_type=='H', 'D', _s1, _s1_time)
if low > _s1 and get_pc_diff_abs(low, _s1) > loop_break_pc
break
for i = 0 to (array.size(supply_zones_s1_all) == 0 ? na : array.size(supply_zones_s1_all) - 1)
_s1 = array.size(supply_zones_s1_all) > i ? array.get(supply_zones_s1_all, i) : na
_s1_time = array.size(supply_zones_time_all) > i ? array.get(supply_zones_time_all, i) : na
_price_near = get_amount_by_pc(_s1, ds_alerts_pc_near, 'minus')
_alert_type = high >= _s1 ? 'H' : high >= _price_near ? 'N' : ''
if _alert_type == 'H'
array.remove(supply_zones_s1_all, i)
array.remove(supply_zones_time_all, i)
alert_ds(_alert_type=='H' or _alert_type=='N', 'S', _s1, _s1_time, _alert_type)
deactivate_ds_limited(_alert_type=='H', 'S', _s1, _s1_time)
if high < _s1 and get_pc_diff_abs(high, _s1) > loop_break_pc
break
add_ds_lbl_tooltip(_lbl, _zone_type, _s1, _s1_time) =>
_info = get_ds_zone_info(_zone_type, _s1, _s1_time)
label.set_tooltip(_lbl, _info)
draw_nearby_ds_s1() =>
if barstate.isconfirmed and (showDemandZone or showSupplyZone)
_color_transparent = color.new(color.white, 100)
for i = 0 to ds_line_max - 1
line.set_xy1(array.get(demand_zones_s1_line, i), na, na)
line.set_xy1(array.get(supply_zones_s1_line, i), na, na)
_lbl_demand = array.get(demand_zones_s1_line_price, i)
label.set_text(_lbl_demand, '')
label.set_color(_lbl_demand, _color_transparent)
_lbl_supply = array.get(supply_zones_s1_line_price, i)
label.set_text(_lbl_supply, '')
label.set_color(_lbl_supply, _color_transparent)
_lbl_demand_all = array.get(demand_zones_label_all, i)
label.set_text(_lbl_demand_all, '')
label.set_color(_lbl_demand_all, _color_transparent)
_lbl_supply_all = array.get(supply_zones_label_all, i)
label.set_text(_lbl_supply_all, '')
label.set_color(_lbl_supply_all, _color_transparent)
_line_demand_all = array.get(demand_zones_line_all, i)
line.set_color(_line_demand_all, _color_transparent)
_line_supply_all = array.get(supply_zones_line_all, i)
line.set_color(_line_supply_all, _color_transparent)
_demand_line_index = 0
_s1_displayed = array.new_float(0)
float _s1_prev = na
_extra_bars = 0
_bars_out = 25
for i = 0 to (array.size(demand_zones_s1) == 0 or not showDemandZone ? na : array.size(demand_zones_s1) - 1)
_s1 = array.get(demand_zones_s1, i)
if array.get(demand_zones_s1_active, i) and get_pc_diff_abs(close, _s1) <= ds_line_pc_display
line.set_xy1(array.get(demand_zones_s1_line, _demand_line_index), get_bar_time(array.get(demand_zones_time, i), 'add', 2), _s1)
line.set_xy2(array.get(demand_zones_s1_line, _demand_line_index), get_bar_time(time, 'add', 1), _s1)
_lbl_demand = array.get(demand_zones_s1_line_price, _demand_line_index)
label.set_color(_lbl_demand, demand_bord_col)
_diff_to_prev = not na(_s1_prev) ? get_pc_diff_abs(_s1_prev, _s1) : na
_extra_bars := _extra_bars > 0 ? 0 : _diff_to_prev < 0.7 ? _bars_out : 0
label.set_xy(_lbl_demand, bar_index + 4 + _extra_bars, _s1)
label.set_text(_lbl_demand, str.tostring(_s1))
_s1_time = array.size(demand_zones_time) > i ? array.get(demand_zones_time, i) : na
add_ds_lbl_tooltip(_lbl_demand, 'D', _s1, _s1_time)
_demand_line_index += 1
_s1_prev := _s1
array.unshift(_s1_displayed, _s1)
if _demand_line_index == ds_line_max
break
_demand_line_count = _demand_line_index
_demand_line_index := 0
for i = 0 to (array.size(demand_zones_s1_all) == 0 or _demand_line_count == ds_line_max ? na : array.size(demand_zones_s1_all) - 1)
_s1 = array.size(demand_zones_s1_all) > i ? array.get(demand_zones_s1_all, i) : na
_diff = get_pc_diff_abs(close, _s1)
_s1Displayed = array.includes(_s1_displayed, _s1)
if not _s1Displayed and _diff <= ds_line_pc_display
_lbl_demand = array.get(demand_zones_label_all, _demand_line_index)
label.set_color(_lbl_demand, demand_bord_col)
label.set_xy(_lbl_demand, bar_index + _bars_out, _s1)
label.set_text(_lbl_demand, str.tostring(_s1))
_s1_time = array.size(demand_zones_time_all) > i ? array.get(demand_zones_time_all, i) : na
add_ds_lbl_tooltip(_lbl_demand, 'S', _s1, _s1_time)
_line_demand = array.get(demand_zones_line_all, _demand_line_index)
line.set_color(_line_demand, demand_bord_col)
line.set_xy1(_line_demand, bar_index - 10, _s1)
line.set_xy2(_line_demand, bar_index + _bars_out, _s1)
_demand_line_index += 1
_demand_line_count += 1
if _demand_line_index == ds_line_max or _demand_line_count == ds_line_max or _diff > ds_line_pc_display
break
_supply_line_index = 0
array.clear(_s1_displayed)
_s1_prev := na
_extra_bars := 0
for i = 0 to (array.size(supply_zones_s1) == 0 or not showSupplyZone ? na : array.size(supply_zones_s1) - 1)
_s1 = array.get(supply_zones_s1, i)
if array.get(supply_zones_s1_active, i) and get_pc_diff_abs(close, _s1) <= ds_line_pc_display
line.set_xy1(array.get(supply_zones_s1_line, _supply_line_index), get_bar_time(array.get(supply_zones_time, i), 'add', 2), _s1)
line.set_xy2(array.get(supply_zones_s1_line, _supply_line_index), get_bar_time(time, 'add', 1), _s1)
_lbl_supply = array.get(supply_zones_s1_line_price, _supply_line_index)
label.set_color(_lbl_supply, supply_bord_col)
_diff_to_prev = not na(_s1_prev) ? get_pc_diff_abs(_s1_prev, _s1) : na
_extra_bars := _extra_bars > 0 ? 0 : _diff_to_prev < 0.7 ? _bars_out : 0
label.set_xy(_lbl_supply, bar_index + 4 + _extra_bars, _s1)
label.set_text(_lbl_supply, str.tostring(_s1))
_s1_time = array.size(supply_zones_time) > i ? array.get(supply_zones_time, i) : na
add_ds_lbl_tooltip(_lbl_supply, 'S', _s1, _s1_time)
_supply_line_index += 1
_s1_prev := _s1
array.unshift(_s1_displayed, _s1)
if _supply_line_index == ds_line_max
break
_supply_line_count = _supply_line_index
_supply_line_index := 0
for i = 0 to (array.size(supply_zones_s1_all) == 0 or _supply_line_count == ds_line_max ? na : array.size(supply_zones_s1_all) - 1)
_s1 = array.size(supply_zones_s1_all) > i ? array.get(supply_zones_s1_all, i) : na
_diff = get_pc_diff_abs(close, _s1)
_s1Displayed = array.includes(_s1_displayed, _s1)
if not _s1Displayed and _diff <= ds_line_pc_display
_lbl_supply = array.get(supply_zones_label_all, _supply_line_index)
label.set_color(_lbl_supply, supply_bord_col)
label.set_xy(_lbl_supply, bar_index + _bars_out, _s1)
label.set_text(_lbl_supply, str.tostring(_s1))
_s1_time = array.size(supply_zones_time_all) > i ? array.get(supply_zones_time_all, i) : na
add_ds_lbl_tooltip(_lbl_supply, 'S', _s1, _s1_time)
_line_supply = array.get(supply_zones_line_all, _supply_line_index)
line.set_color(_line_supply, supply_bord_col)
line.set_xy1(_line_supply, bar_index - 10, _s1)
line.set_xy2(_line_supply, bar_index + _bars_out, _s1)
_supply_line_index += 1
_supply_line_count += 1
if _supply_line_index == ds_line_max or _supply_line_count == ds_line_max or _diff > ds_line_pc_display
break
check_ds_zone_hit()
add_ds_zone('D')
add_ds_zone('S')
draw_nearby_ds_s1()
import Bjorgum/BjCandlePatterns/2 as bj
leftTip = "Look left for swing high/low in x number of bars to form pivot. The higher the number, the higher the script looks to the left for the highest/lowest point before drawing pivot"
rightTip = "Look right for swing high/low in x number of bars to form pivot. The higher the number, the higher the script looks to the right for the highest/lowest point before drawing pivot"
nPivTip = "This sets the array size, or the number of pivots to track at a time (x highs, and x number of lows)"
atrLenTip = "Number of bars to average. ATR is used to standardize zone width between assets and timeframes"
multTip = "ATR multiplier to set zone width. Default is half of one ATR from box bottom to box top"
perTip = "Max zone size as a percent of price. Some assets can be too volatile at low prices creating an unreasonably sized zone"
maxTip = "Number of boxes for candlestick patterns to track historically. Note: the higher the number the less pivot zones will be tracked when looking back in time due to the limitation on the number of box elements allowed at once"
futTip = "Number of bars to offset labels for price levels"
srcTip = "Source input for pivots. Default tracks the highest and lowest bodies of HA candles to average price action, which can result in a level that sits in the overlap of support and resistance"
alignZonesTip = "Aligns recurring zones who's edges overlap an existing zone creating a zone that ages in time and intensifies visually"
extendTip = "Extends current zones right"
lLabTip = "Show labels for price levels extended off Key Levels"
dhighsTip = "Disabling will prevent highs from being tracked"
dlowsTip = "Disabling will prevent lows from being tracked"
detectBOTip = "Show points that price action breaks above all pivots. An arrow from below is displayed"
detectBDTip = "Show points that price action breaks below all pivots. An arrow from above is displayed"
breakUpTip = "Show points that price action breaks above resistance. An arrow from below is displayed"
breakDnTip = "Show points that price action breaks below support. An arrow from above is displayed"
falseBullTip = "Show points that price action initially breaks below support before reversing. False moves can lead to fast moves in the opposite direction (bear trap). A large arrow from below is displayed"
falseBearTip = "Show points that price action initially breaks above resistance before reversing. False moves can lead to fast moves in the opposite direction (bull trap). A large arrow from aboveПоказано первые 50% кода (символов: 75683)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.