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

ICT Structure Engine

indicator ict structure engine for tradingview.pine

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

confluenceforge_pro.mq5TradingView · 2 общих теговvolatility_gold_master.mq5MQL5 / MetaTrader 5 · 2 общих теговxu_rsi_ma1_mtf.mq5MQL5 / MetaTrader 5 · 2 общих теговsmart money concept fvg pattern.pineTradingView · 2 общих теговindicator tolag apex v1.3 - precision edition for tradingview.pineTradingView · 2 общих теговindicator stormcore smc & divergence master for tradingview.pineTradingView · 2 общих тегов
Вы автор или правообладатель?

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

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

О программе

ICT Structure Engine — это индикатор для TradingView, написанный на Pine Script v6. Он отображается поверх графика и предназначен для анализа рыночной структуры и связанных с ней понятий в рамках подхода ICT (Inner Circle Trader). Индикатор рассчитывает технические показатели и может получать данные с другого таймфрейма или инструмента.

В индикаторе реализованы модули для определения внешней и внутренней структуры рынка (BOS/CHoCH), свингов, ордер-блоков, Fair Value Gaps, ликвидности (равные максимумы/минимумы), блоков отторжения и продвижения, ключевых уровней, дневного смещения и Judas Swing, стандартных отклонений, киллзон, а также сетапов по схеме «свип → CHoCH». Предусмотрены настройки визуализации, панель управления, оповещения и параметры управления риском.

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

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

НастройкаОписание
swingLenInput Количество баров с каждой стороны для подтверждения внешнего свинга.
intLenInput Длина свинга для внутренней (минорной) структуры.
breakByInput Определяет, что считается пробоем структуры: закрытие свечи за уровнем свинга или прокол фитилём.
showExtInput Включает или выключает отображение внешних пробоев структуры (BOS/CHoCH).
showIntInput Включает или выключает отображение внутренних пробоев структуры (BOS/CHoCH).
showSwingsInput Включает или выключает отображение меток подтверждённых внешних свингов (HH, LH, HL, LL).
htfOnInput Включает использование данных старшего таймфрейма.
htfInput Старший таймфрейм, данные которого используются для анализа.
htfLenInput Длина свинга для подтверждения структуры на старшем таймфрейме.
htfShowInput Отображает ордер-блоки со старшего таймфрейма.
obOnInput Включает или выключает обнаружение и отображение ордер-блоков.
obFromInput Выбирает, какой тип пробоя структуры создаёт ордер-блок: внешний или внутренний.
obEdgeInput Определяет, какой край ордер-блока считать проксимальным: тело или фитиль свечи.
obMaxAtrInput Максимальная высота зоны ордер-блока в единицах ATR.
obNeedImbInput Требует наличия FVG в импульсе для создания ордер-блока.
obMinScoreInput Минимальный балл зоны для отображения.
obMitigInput Определяет условие, при котором ордер-блок считается пробитым.
obBreakerInput Преобразует пробитый ордер-блок в Breaker Block.
obMaxInput Максимальное количество активных ордер-блоков с каждой стороны.
obKeepInput Оставляет пробитые ордер-блоки на графике в сером цвете как историю.
obMidInput Отображает пунктирную линию на уровне 50% внутри ордер-блока.
fvgOnInput Включает или выключает обнаружение и отображение Fair Value Gaps.
fvgMinAtrInput Минимальный размер FVG в единицах ATR для отображения.
fvgFillInput Определяет, когда FVG считается заполненным: при касании, при достижении середины или при полном прохождении.
fvgShrinkInput Отображает только незаполненную часть FVG по мере заполнения.
fvgMaxInput Максимальное количество активных FVG с каждой стороны.
liqOnInput Включает или выключает отображение ликвидности.
liqLenInput Длина свинга для определения пулов ликвидности.
eqTolInput Допуск для определения равных максимумов или минимумов, выраженный в единицах ATR.
liqSingleInput Включает отображение и оповещения для одиночных свингов.
liqMaxInput Максимальное количество активных пулов ликвидности с каждой стороны.
rbOnInput Включает или выключает отображение Rejection Blocks.
rbWickInput Минимальная доля фитиля в диапазоне свечи для определения Rejection Block.
rbMaxInput Максимальное количество активных Rejection Blocks с каждой стороны.
pbOnInput Включает или выключает отображение Propulsion Blocks.
pbConfirmInput Количество баров, в течение которых цена должна закрыться за свечой касания для подтверждения Propulsion Block.
pbMaxInput Максимальное количество активных Propulsion Blocks с каждой стороны.
sessLiqInput Включает или выключает отображение максимумов и минимумов торговых сессий.
kzShowInput Включает или выключает отображение киллзон.
asiaOnInput Включает или выключает отображение азиатской торговой сессии в киллзонах.
asiaSessInput Задаёт временной диапазон азиатской торговой сессии.
lonOnInput Включает или выключает отображение лондонской торговой сессии в киллзонах.
lonSessInput Задаёт временной диапазон лондонской торговой сессии.
nyamOnInput Включает или выключает отображение утренней сессии Нью-Йорка в киллзонах.
nyamSessInput Задаёт временной диапазон утренней сессии Нью-Йорка.
nypmOnInput Включает или выключает отображение дневной сессии Нью-Йорка в киллзонах.
nypmSessInput Задаёт временной диапазон дневной сессии Нью-Йорка.
kzTzInput Часовой пояс, используемый для расчёта киллзон.
timeFilterInput Временной фильтр для сетапов.
showSbInput Включает или выключает подсветку Silver Bullet.
biasOnInput Включает или выключает расчёт и отображение дневного смещения.
biasFilterInput Фильтр сетапов по дневному смещению. Определяет, какие сетапы разрешены в зависимости от направления смещения.
judasOnInput Включает или выключает отображение Judas Swing.
judasSessInput Временное окно для Judas Swing.
judasSweepInput Требует свипа азиатского диапазона для подтверждения Judas Swing.
sdShowInput Включает или выключает отображение проекций стандартных отклонений.
sdLevelsInput Выбор уровней стандартных отклонений для отображения.
setupOnInput Включает или выключает механизм сетапов.
setupWinInput Количество баров между свипом и CHoCH для активации сетапа.
setupTtlInput Количество баров ожидания ретеста после CHoCH.
dispReqInput Требует наличия смещения (displacement) для активации сетапа.
entryArrayInput Выбор типа PD-массива (зоны) для входа в сделку.
entryFilterInput Фильтр местоположения входа в сделку.
pdOnInput Включает или выключает отображение зон Premium и Discount.
oteOnInput Включает или выключает отображение зоны OTE (62–79%).
themeInput Цветовая тема индикатора.
showSignalsInput Включает или выключает отображение меток покупки и продажи.
showSetupLblInput Включает или выключает отображение меток сетапов.
signalFontSizeInput Размер шрифта меток сигналов.
labelFontSizeInput Размер шрифта меток SL/TP.
textFontSizeInput Размер шрифта текста структуры и зон.
showZoneTextInput Включает или выключает отображение текстовых меток на зонах.
showSweepLblInput Включает или выключает отображение меток свипов.
zoneTranspInput Прозрачность заливки зон.
showWatermarkInput Включает или выключает отображение водяного знака.
riskPresetInput Предустановка параметров управления риском.
slModeInput Режим расчёта стоп-лосса.
tpModeInput Режим расчёта тейк-профитов.
atrLenRiskInput Длина периода ATR, используемого для расчёта стоп-лосса.
slMultInput Множитель стоп-лосса в единицах ATR.
tp1MultInput Множитель первого тейк-профита относительно риска.
tp2MultInput Множитель второго тейк-профита относительно риска.
tp3MultInput Множитель третьего тейк-профита относительно риска.
beInput Включает перевод стоп-лосса в безубыток после достижения первого тейк-профита.
beOffsetInput Смещение стоп-лосса в безубытке, выраженное в единицах ATR.
showSlTpInput Включает или выключает отображение линий SL и TP.
showSlTpLabelsInput Включает или выключает отображение меток SL и TP.
showPctOnLabelsInput Отображает процентное расстояние на метках SL/TP.
entryLineStyleInput Стиль линии, отображающей уровень входа.
slLineStyleInput Стиль линии стоп-лосса.
tpLineStyleInput Стиль линий тейк-профитов.
showDashInput Включает или выключает отображение панели управления.
dashPosInput Положение панели управления на графике.
dashFontSizeInput Размер шрифта текста на панели управления.
showMarketSecInput Включает или выключает секцию Market на панели управления.
showIctSecInput Включает или выключает секцию ICT на панели управления.
showTradeSecInput Включает или выключает секцию Trade на панели управления.
showStatsSecInput Включает или выключает секцию статистики на панели управления.
statsPeriodInput Период для расчёта статистики выигрышей.
webhookInput Включает формат JSON для оповещений через вебхук.

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

indicator(
     title            = "ICT Structure Engine",
     shorttitle       = "ICT-SE",
     overlay          = true,
     max_lines_count  = 500,
     max_labels_count = 500,
     max_boxes_count  = 500,
     max_bars_back    = 500)

const string INDICATOR_VERSION = "v6.3.0"
const string SHORT_NAME        = "ICT-SE"
const string BRAND             = "WillyAlgoTrader"

const string GRP_STRUCT = "🧭 Market Structure"
const string GRP_HTF    = "🕐 Higher Timeframe"
const string GRP_OB     = "🧱 Order Blocks"
const string GRP_FVG    = "⚡ Fair Value Gaps"
const string GRP_LIQ    = "💧 Liquidity"
const string GRP_RBPB   = "🧩 Rejection & Propulsion Blocks"
const string GRP_KEYS   = "🗝️ Key Levels"
const string GRP_BIAS   = "📅 Daily Bias & Judas Swing"
const string GRP_SD     = "📐 Standard Deviations"
const string GRP_TIME   = "🕒 Killzones"
const string GRP_SETUP  = "🎯 Setup (Sweep → CHoCH)"
const string GRP_PD     = "⚖️ Premium / Discount"
const string GRP_VISUAL = "🎨 Visual Settings"
const string GRP_RISK   = "🛡️ Risk Management"
const string GRP_DASH   = "📊 Dashboard"
const string GRP_ALERT  = "🔔 Alerts"
const string GRP_COLORS = "🎨 Colors"
const string GRP_ADV    = "🔧 Advanced"

const string O_CLOSE = "Close"
const string O_WICK  = "Wick"
const string O_BODY  = "Body"
const string O_HALF  = "50%"
const string O_TOUCH = "Touch"
const string O_FULL  = "Full"
const string O_EXT   = "External"
const string O_INT   = "Internal"
const string SL_WICK = "Wick-Anchored"
const string SL_ZONE = "Zone-Anchored"
const string SL_ATR  = "ATR"
const string SL_SWEEP = "Sweep-Anchored"
const string TP_R     = "R-Multiples"
const string TP_LIQ   = "Liquidity"
const string TP_SD    = "Std Deviations"
const string BF_OFF   = "Off"
const string BF_STR   = "With bias only"
const string BF_NA    = "Not against bias"
const string EA_FVG1  = "FVG first"
const string EA_OB1   = "OB first"
const string EA_FVG0  = "FVG only"
const string EA_OB0   = "OB only"
const string F_OFF    = "Off"
const string F_PD     = "Discount / Premium"
const string F_OTE    = "OTE (≥ 62%)"
const string T_OFF    = "Off"
const string T_KZ     = "Killzones"
const string T_SB     = "Silver Bullet"
const string SB_1     = "0300-0400"
const string SB_2     = "1000-1100"
const string SB_3     = "1400-1500"

const int   LINE_FORWARD_BARS = 20      // длина линий сделки при входе
const int   LINE_UPDATE_BARS  = 5       // запас продления за текущий бар
const int   LABEL_OFFSET_BARS = 1       // отступ меток от конца линий
const int   BE_DIM_TRANSP     = 70      // затемнение SL при BE
const int   FORM_LEN          = 10      // длина Form-строки
const int   MS_DAY            = 86400000
const int   STATS_MAX_TRADES  = 10000   // предел буфера сделок по количеству (кроме предела по времени)
const int   STATS_PRUNE_DAYS  = 31      // горизонт rolling-буфера статистики
const int   OB_SCAN_BARS      = 300     // глубина поиска экстремума импульса
const int   HTF_SCAN_BARS     = 200     // то же на старшем ТФ
const int   ATR_HIST_LEN      = 305     // глубина буфера ATR: покрывает поиск OB и displacement (до 300 баров)
const int   OB_SRC_BARS       = 2       // насколько старше экстремума ищем противоположную свечу
const int   X_BACK_LIMIT      = 9999    // рисунок по bar_index нельзя начинать дальше 10 000 баров назад
const int   SWEEP_NEAR_BARS   = 2       // Sweep засчитывается в рейтинг в пределах ±N баров от экстремума
const int   PD_FORWARD_BARS   = 10
const int   SD_FORWARD_BARS   = 40      // длина линий стандартных отклонений
const int   SD_MAX_LEVELS     = 8       // не больше 8 уровней SD
const float SD_MAX_MULT       = 10.0    // и не дальше 10 длин ноги
const int   KEY_LABEL_OFFSET  = 2       // подписи ключевых уровней — правее последнего бара
const float JUDAS_LABEL_ATR   = 0.3     // метка Judas смещена от экстремума, чтобы не наложиться на Sweep
const int   RSI_LEN           = 14
const int   SCORE_MAX         = 4
const float WICK_BUFFER_ATR   = 0.25    // буфер стопа за фитилём / зоной
const float MIN_SL_ATR        = 0.5     // минимальная дистанция стопа
const float THIN_ZONE_ATR     = 0.1     // тоньше — берём тень вместо тела
const float OVERLAP_SHARE     = 0.5     // доля перекрытия, при которой новая зона не создаётся
const float OTE_NEAR          = 0.618
const float OTE_FAR           = 0.79

swingLenInput   = input.int(10, "External Swing Length", minval = 3, maxval = 50, group = GRP_STRUCT, tooltip = "Bars on each side required to confirm an external swing (main structure, CHoCH).\n• Higher = fewer, more significant swings\n• Lower = faster, noisier structure\n• Recommended: 8–20")
intLenInput     = input.int(3, "Internal Swing Length", minval = 2, maxval = 10, group = GRP_STRUCT, tooltip = "Bars on each side for internal (minor) swings. Must be smaller than the external length.\n• Recommended: 2–5")
breakByInput    = input.string(O_CLOSE, "Break Confirmation", options = [O_CLOSE, O_WICK], group = GRP_STRUCT, tooltip = "What counts as a structure break.\n• Close: the candle must close beyond the swing; a wick pierce is a liquidity sweep, not a break (recommended)\n• Wick: any pierce breaks. If one bar pierces both swings, the close decides; otherwise there is no event")
showExtInput    = input.bool(true, "Show External BOS / CHoCH", group = GRP_STRUCT, tooltip = "Draw lines and labels for external structure breaks")
showIntInput    = input.bool(false, "Show Internal BOS / CHoCH", group = GRP_STRUCT, tooltip = "Draw internal structure breaks (dashed). Off by default to reduce noise")
showSwingsInput = input.bool(true, "Show HH / LH / HL / LL", group = GRP_STRUCT, tooltip = "Label confirmed external swings. A label appears N bars after its swing (confirmation lag)")

htfOnInput   = input.bool(true, "Use Higher Timeframe", group = GRP_HTF, tooltip = "Use the HTF trend and dealing range in the zone score.\nData comes from the last CLOSED HTF bar (no repaint)")
htfInput     = input.timeframe("240", "Higher Timeframe", group = GRP_HTF, tooltip = "Must be greater than or equal to the chart timeframe (equal = HTF ignored).\n• 5–15M chart → 1H–4H\n• 1H chart → 4H–D")
htfLenInput  = input.int(5, "HTF Swing Length", minval = 2, maxval = 30, group = GRP_HTF, tooltip = "Swing confirmation length on the HTF. HTF breaks are always close-confirmed; ATR length and max zone height are shared with the chart.\n• Recommended: 3–8")
htfShowInput = input.bool(true, "Show HTF Order Blocks", group = GRP_HTF, tooltip = "Draw the latest live HTF order block of each side (dashed). Visual only — HTF data still feeds the score when hidden")

obOnInput       = input.bool(true, "Show Order Blocks", group = GRP_OB, tooltip = "Detect and draw order blocks. Turning this off also removes OBs from the setup engine (setups then use FVGs only)")
obFromInput     = input.string(O_EXT, "Build From", options = [O_EXT, O_INT], group = GRP_OB, tooltip = "Which structure break creates an order block.\n• External: fewer, stronger zones (recommended)\n• Internal: more zones, more noise")
obEdgeInput     = input.string(O_BODY, "Proximal Edge", options = [O_BODY, O_WICK], group = GRP_OB, tooltip = "The distal edge is always the impulse extreme. The proximal edge is the body or wick of the opposite candle at the extreme (up to 2 bars older). No opposite candle — no order block.\n• Body: tighter zone (recommended)\n• Wick: wider zone, earlier touches")
obMaxAtrInput   = input.float(1.5, "Max Zone Height (×ATR)", minval = 0.0, maxval = 5.0, step = 0.1, group = GRP_OB, tooltip = "Wider zones are trimmed from the distal edge to this height. 0 = no limit.\nThis changes zone geometry (touches, midpoint), not only visuals.\n• Recommended: 1.0–2.0")
obNeedImbInput  = input.bool(false, "Require FVG in Impulse", group = GRP_OB, tooltip = "Create an OB only if the impulse left a fair value gap (same rule and size as displayed FVGs).\nOff by default: an FVG already adds +1 to the score")
obMinScoreInput = input.int(0, "Min Score to Show (★)", minval = 0, maxval = 4, group = GRP_OB, tooltip = "Zone score 0–4 is a sum of factors, not a probability:\n+1 FVG in the impulse\n+1 liquidity sweep at the impulse extreme (±2 bars)\n+1 aligned with the HTF trend\n+1 zone midpoint in Discount (demand) / Premium (supply)\nWithout HTF the maximum is ★★★. A zone needed by a setup is shown even below this threshold")
obMitigInput    = input.string(O_CLOSE, "Invalidation", options = [O_CLOSE, O_WICK, O_HALF], group = GRP_OB, tooltip = "When an OB is considered broken.\n• Close: close beyond the distal edge (recommended)\n• Wick: any pierce of the distal edge\n• 50%: close beyond the zone midpoint\nA Breaker forms only on a close beyond the whole zone")
obBreakerInput  = input.bool(true, "Convert to Breaker", group = GRP_OB, tooltip = "A broken OB flips polarity and lives on as a Breaker Block.\nThe breaker score is recalculated from 2 factors (HTF trend, range half), max ★★")
obMaxInput      = input.int(4, "Max Active Zones per Side", minval = 1, maxval = 20, group = GRP_OB, tooltip = "Including breakers. The oldest zones are removed first.\n• Lower = cleaner chart\n• Recommended: 3–6")
obKeepInput     = input.bool(false, "Keep Mitigated Zones", group = GRP_OB, tooltip = "Leave broken zones on the chart in gray as history (limited by History Size)")
obMidInput      = input.bool(true, "Show 50% Line", group = GRP_OB, tooltip = "Dotted midline (mean threshold) inside each OB, Rejection Block and Propulsion Block")

fvgOnInput     = input.bool(true, "Show Fair Value Gaps", group = GRP_FVG, tooltip = "Detect and draw FVGs. Turning this off also removes FVGs from the setup engine (setups then use OBs only)")
fvgMinAtrInput = input.float(0.2, "Min Size (×ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = GRP_FVG, tooltip = "Ignore gaps smaller than this. The same threshold defines the FVG factor of the OB score.\n• Higher = only strong displacement\n• Recommended: 0.1–0.4")
fvgFillInput   = input.string(O_FULL, "Filled When", options = [O_TOUCH, O_HALF, O_FULL], group = GRP_FVG, tooltip = "When an FVG is removed.\n• Touch: first contact\n• 50%: midpoint of the ORIGINAL gap\n• Full: price trades through the far edge (recommended)")
fvgShrinkInput = input.bool(true, "Shrink as Filled", group = GRP_FVG, tooltip = "Show only the unfilled part of the gap")
fvgMaxInput    = input.int(5, "Max Active FVGs per Side", minval = 1, maxval = 30, group = GRP_FVG, tooltip = "The oldest gaps are removed first.\n• Recommended: 3–8")

liqOnInput     = input.bool(true, "Show Liquidity", group = GRP_LIQ, tooltip = "Draw equal highs/lows (EQH/EQL) and sweeps. Visual only — pools, sweeps, score and setups are always calculated")
liqLenInput    = input.int(5, "Pool Swing Length", minval = 2, maxval = 30, group = GRP_LIQ, tooltip = "Swing length for liquidity pools.\n• Lower = more pools, more sweeps\n• Recommended: 3–8")
eqTolInput     = input.float(0.1, "Equal Tolerance (×ATR)", minval = 0.01, maxval = 1.0, step = 0.01, group = GRP_LIQ, tooltip = "A new swing joins an untaken pool if the difference is below this share of ATR. A pierced pool is consumed (stops considered taken).\n• Recommended: 0.05–0.2")
liqSingleInput = input.bool(false, "Single Swings: Draw & Alert", group = GRP_LIQ, tooltip = "By default only equal highs/lows are drawn and alerted.\nSweeps of single swings always count for the score and setups")
liqMaxInput    = input.int(6, "Max Active Pools per Side", minval = 1, maxval = 30, group = GRP_LIQ, tooltip = "The oldest pools are removed first")

rbOnInput      = input.bool(true, "Show Rejection Blocks", group = GRP_RBPB, tooltip = "Rejection Block: the long wick of an external swing high/low (from the body to the wick extreme). Price often rejects again at the body edge or the 50% of the wick.\nSkipped where an order block already covers the same area")
rbWickInput    = input.float(0.5, "  └ Min Wick Share", minval = 0.3, maxval = 0.9, step = 0.05, group = GRP_RBPB, tooltip = "Minimum wick length as a share of the swing candle range.\n• Higher = only pronounced rejections\n• Recommended: 0.4–0.6")
rbMaxInput     = input.int(3, "  └ Max per Side", minval = 1, maxval = 10, group = GRP_RBPB, tooltip = "Active rejection blocks per side; the oldest are removed first")
pbOnInput      = input.bool(true, "Show Propulsion Blocks", group = GRP_RBPB, tooltip = "Propulsion Block: an opposite-colored candle that taps an order block, after which price closes beyond that candle (propulsion). The candle range becomes a new, tighter zone")
pbConfirmInput = input.int(3, "  └ Confirm Within (bars)", minval = 1, maxval = 10, group = GRP_RBPB, tooltip = "Price must close beyond the tapping candle within this many bars")
pbMaxInput     = input.int(3, "  └ Max per Side", minval = 1, maxval = 10, group = GRP_RBPB, tooltip = "Active propulsion blocks per side; the oldest are removed first")

keyDayInput  = input.bool(true, "Previous Day High / Low", group = GRP_KEYS, tooltip = "PDH / PDL as liquidity pools (intraday charts only). Their sweeps arm setups and count for the score; untaken levels serve as liquidity targets.\nDay boundary follows the exchange session of the symbol")
keyWeekInput = input.bool(true, "Previous Week High / Low", group = GRP_KEYS, tooltip = "PWH / PWL as liquidity pools (charts below 1W)")
sessLiqInput = input.bool(true, "Session Highs / Lows", group = GRP_KEYS, tooltip = "When a killzone session ends, its high and low become liquidity pools (e.g. Asian range high/low swept in London or New York)")
keyMoInput   = input.bool(true, "Midnight Open", group = GRP_KEYS, tooltip = "Line at the 00:00 open in the killzone timezone. Reference level: in a bullish day ICT prefers buying below it, in a bearish day selling above it.\nShown only when a bar opens exactly at 00:00 (not on RTH-only charts or timeframes not aligned to midnight); without it the Judas Swing is not evaluated that day")

kzShowInput     = input.bool(true, "Show Killzones", group = GRP_TIME, tooltip = "Draw each enabled killzone as a box spanning its high and low. Works on intraday charts up to 1H")
asiaOnInput     = input.bool(true, "Asian", inline = "kzA", group = GRP_TIME)
asiaSessInput   = input.session("2000-0000", "", inline = "kzA", group = GRP_TIME, tooltip = "Asian killzone (default 20:00–00:00 New York)")
lonOnInput      = input.bool(true, "London", inline = "kzL", group = GRP_TIME)
lonSessInput    = input.session("0200-0500", "", inline = "kzL", group = GRP_TIME, tooltip = "London killzone (default 02:00–05:00 New York)")
nyamOnInput     = input.bool(true, "NY AM", inline = "kzN", group = GRP_TIME)
nyamSessInput   = input.session("0700-1000", "", inline = "kzN", group = GRP_TIME, tooltip = "New York AM killzone (default 07:00–10:00 New York)")
nypmOnInput     = input.bool(true, "NY PM", inline = "kzP", group = GRP_TIME)
nypmSessInput   = input.session("1330-1600", "", inline = "kzP", group = GRP_TIME, tooltip = "New York PM killzone (default 13:30–16:00 New York)")
kzTzInput       = input.string("America/New_York", "Timezone", group = GRP_TIME, tooltip = "Timezone of the killzone times and Midnight Open. ICT uses New York time (America/New_York)")
timeFilterInput = input.string(T_KZ, "Setup Time Filter", options = [T_OFF, T_KZ, T_SB], group = GRP_TIME, tooltip = "When a setup may be armed (CHoCH bar):\n• Killzones: inside any enabled killzone (recommended)\n• Silver Bullet: 03–04, 10–11, 14–15 New York only\n• Off: any time\nAutomatically off on timeframes above 1H")
showSbInput     = input.bool(false, "Highlight Silver Bullet", group = GRP_TIME, tooltip = "Faint background during the Silver Bullet hours")

biasOnInput     = input.bool(true, "Daily Bias", group = GRP_BIAS, tooltip = "Daily draw on liquidity from the previous day (intraday charts):\n• Closed above the prior day high → Bullish (draw on PDH)\n• Closed below the prior day low → Bearish (draw on PDL)\n• Swept the prior high but closed back inside → Bearish\n• Swept the prior low but closed back inside → Bullish\n• Swept both sides and closed inside (outside day) → Neutral\n• Otherwise (inside day) → Neutral\nShown in the dashboard and on the Midnight Open label")
biasFilterInput = input.string(BF_OFF, "  └ Setup Filter", options = [BF_OFF, BF_STR, BF_NA], group = GRP_BIAS, tooltip = "Restrict setups by the daily bias.\n• Off: no restriction\n• With bias only: longs only on bullish days, shorts only on bearish days (neutral days: none)\n• Not against bias: neutral days allow both sides")
judasOnInput    = input.bool(true, "Judas Swing", group = GRP_BIAS, tooltip = "False move against the daily bias inside the Judas window: price trades beyond the Midnight Open, then closes back across it. Marked once per day. Requires Daily Bias and an intraday chart up to 1H")
judasSessInput  = input.session("0000-0500", "  └ Window", group = GRP_BIAS, tooltip = "Time window for the Judas Swing (killzone timezone). Default 00:00–05:00 New York (midnight to end of London)")
judasSweepInput = input.bool(true, "  └ Require Asian Range Sweep", group = GRP_BIAS, tooltip = "The false move must also take the Asian session low (bullish day) or high (bearish day). Ignored when the Asian killzone is disabled. If no Asian range from the last 24 hours is available, the Judas Swing is not confirmed")

sdShowInput   = input.bool(true, "Show SD Projections", group = GRP_SD, tooltip = "Project standard deviations of the setup leg (sweep extreme → CHoCH extreme) when a setup is armed: −1, −2, −2.5 … beyond the leg. ICT uses them as targets.\nFar levels widen the price scale — keep the list short")
sdLevelsInput = input.string("1, 2, 2.5", "  └ Levels", group = GRP_SD, tooltip = "Comma-separated multiples of the leg, e.g. '1, 2, 2.5, 4' (up to 8 levels, each up to 10). Duplicates are ignored, invalid values stop the script with an error.\nThese are ICT leg projections, not statistical sigma. Also used by TP Mode 'Std Deviations'")

setupOnInput  = input.bool(true, "Enable Setups", group = GRP_SETUP, tooltip = "Setup = liquidity sweep → CHoCH the other way → first retest of this impulse's OB/FVG.\nThe close of the retest bar is the BUY/SELL signal that opens a trade")
setupWinInput = input.int(20, "Sweep → CHoCH Window (bars)", minval = 1, maxval = 100, group = GRP_SETUP, tooltip = "CHoCH must happen within this many bars after the sweep (same bar allowed).\n• Lower = stricter, fewer setups\n• Recommended: 10–30")
setupTtlInput = input.int(30, "Wait for Retest (bars)", minval = 1, maxval = 300, group = GRP_SETUP, tooltip = "How long an armed setup waits for its first retest before it expires.\n• Recommended: 20–60")
dispReqInput     = input.bool(true, "Require Displacement", group = GRP_SETUP, tooltip = "Arm a setup only if the Sweep → CHoCH leg left a fair value gap (same rule as displayed FVGs). ICT: a market structure shift counts only when made with displacement")
entryArrayInput  = input.string(EA_FVG1, "Entry PD Array", options = [EA_FVG1, EA_OB1, EA_FVG0, EA_OB0], group = GRP_SETUP, tooltip = "Which zone of the impulse is used for the retest entry.\n• FVG first: the displacement FVG, else the OB (ICT 2022 model, recommended)\n• OB first: the order block, else the FVG\n• FVG only / OB only")
entryFilterInput = input.string(F_PD, "Entry Location Filter", options = [F_OFF, F_PD, F_OTE], group = GRP_SETUP, tooltip = "Where the entry close must be, else the setup is skipped.\n• Discount / Premium: longs below, shorts above equilibrium of the dealing range (HTF range if HTF is on). Recommended\n• OTE: at least 62% retracement of the Sweep → CHoCH leg\n• Off: no location filter\nWhile the filter has no data yet (e.g. no HTF dealing range), entries are skipped with the reason in the info alert")

pdOnInput  = input.bool(true, "Show Premium / Discount", group = GRP_PD, tooltip = "Shade the current dealing range (latest external swings): above equilibrium = Premium, below = Discount. Visual only")
oteOnInput = input.bool(true, "Show OTE (62–79%)", group = GRP_PD, tooltip = "Optimal Trade Entry retracement band in the direction of the external trend. Shown together with Premium / Discount")

themeInput          = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], group = GRP_VISUAL, tooltip = "Chart color theme.\n• Auto: detects from chart background\n• Dark: optimized for dark backgrounds\n• Light: optimized for light/white backgrounds")
showSignalsInput    = input.bool(true, "Show Buy/Sell Labels", group = GRP_VISUAL, tooltip = "Mark every trade entry with ▲ BUY / ▼ SELL (score, RSI, SL and TP1 in the tooltip)")
showSetupLblInput   = input.bool(true, "Show Setup Labels", group = GRP_VISUAL, tooltip = "Mark the bar where a setup is armed (Sweep → CHoCH)")
signalFontSizeInput = input.string("Small", "Signal Label Size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = GRP_VISUAL, tooltip = "Font size for BUY/SELL and setup labels")
labelFontSizeInput  = input.string("Small", "SL/TP Label Font Size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = GRP_VISUAL, tooltip = "Font size for Entry / SL / TP labels")
textFontSizeInput   = input.string("Small", "Structure & Zone Text Size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = GRP_VISUAL, tooltip = "Font size for BOS/CHoCH, swing, sweep and zone texts. Internal structure renders one step smaller")
showZoneTextInput   = input.bool(true, "Show Zone Labels", group = GRP_VISUAL, tooltip = "Text inside zones (Bull OB ★★, RB, PB, Breaker). Setup zones keep their SETUP label")
showSweepLblInput   = input.bool(true, "Show Sweep Labels", group = GRP_VISUAL, tooltip = "Mark liquidity sweeps on the chart. Sweeps are still detected for setups and alerts when hidden")
zoneTranspInput     = input.int(85, "Zone Transparency", minval = 70, maxval = 95, group = GRP_VISUAL, tooltip = "Fill transparency of OB/FVG zones.\n• 80–90 keeps candles readable (recommended)")
showWatermarkInput  = input.bool(true, "Show Watermark", group = GRP_VISUAL, tooltip = "Display 'WillyAlgoTrader' watermark on chart")

riskPresetInput      = input.string("Balanced", "Risk Preset", options = ["Conservative", "Balanced", "Aggressive", "Scalping", "Custom"], group = GRP_RISK, tooltip = "Quick risk presets (the SL part applies to ATR mode; Wick and Zone modes anchor the stop to structure):\n• Conservative: SL 2.5×ATR, TP 1R/2R/4R\n• Balanced: SL 1.5×ATR, TP 1R/2R/3R\n• Aggressive: SL 1.0×ATR, TP 1.5R/2.5R/4R\n• Scalping: SL 0.8×ATR, TP 0.8R/1.5R/2R\n• Custom: use the manual multipliers below")
slModeInput          = input.string(SL_WICK, "SL Mode", options = [SL_WICK, SL_ZONE, SL_SWEEP, SL_ATR], group = GRP_RISK, tooltip = "How the stop-loss is placed at entry (all structure modes add 0.25×ATR buffer, min distance 0.5×ATR):\n• Wick-Anchored: beyond the signal bar's wick. Default\n• Zone-Anchored: beyond the setup zone's distal edge\n• Sweep-Anchored: beyond the extreme of the liquidity sweep (ICT placement, widest)\n• ATR: fixed SL Multiplier × ATR from entry")
tpModeInput          = input.string(TP_R, "TP Mode", options = [TP_R, TP_LIQ, TP_SD], group = GRP_RISK, tooltip = "• R-Multiples: TP1–TP3 at the multipliers of the actual SL distance\n• Liquidity: TP1 stays at its R multiple; TP2 and TP3 go to the next untaken opposing liquidity (EQH/EQL, swings, PDH/PDL, PWH/PWL, session H/L) beyond the previous target\n• Std Deviations: TP1 stays at its R multiple; TP2 and TP3 go to the next SD projections of the setup leg\nMissing levels fall back to R-multiples")
atrLenRiskInput      = input.int(14, "ATR Length (SL)", minval = 5, maxval = 50, group = GRP_RISK, tooltip = "ATR period for stop-loss calculation.\n• 14 = standard\n• Lower = tighter stops, more stops hit\n• Higher = wider stops, fewer stops hit")
slMultInput          = input.float(1.5, "SL Multiplier (×ATR)", minval = 0.5, maxval = 5.0, step = 0.1, group = GRP_RISK, tooltip = "Custom preset: stop distance as a multiple of ATR (ATR mode).\n• Scalping: 0.8–1.2 | Swing: 1.5–2.5")
tp1MultInput         = input.float(1.0, "TP1 Multiplier (×Risk)", minval = 0.5, maxval = 5.0, step = 0.1, group = GRP_RISK, tooltip = "Custom preset: take-profit 1 as a multiple of the actual SL distance.\n1.0 = 1:1 Risk:Reward")
tp2MultInput         = input.float(2.0, "TP2 Multiplier (×Risk)", minval = 1.0, maxval = 10.0, step = 0.1, group = GRP_RISK, tooltip = "Custom preset: take-profit 2 as a multiple of risk.\n2.0 = 1:2 Risk:Reward")
tp3MultInput         = input.float(3.0, "TP3 Multiplier (×Risk)", minval = 1.5, maxval = 15.0, step = 0.1, group = GRP_RISK, tooltip = "Custom preset: take-profit 3 as a multiple of risk. TP3 closes the trade.\n3.0 = 1:3 Risk:Reward")
beInput              = input.bool(true, "Break-Even After TP1", group = GRP_RISK, tooltip = "Move stop-loss to entry price once TP1 is reached.\nPositions stopped at break-even after TP1 count as wins")
beOffsetInput        = input.float(0.0, "BE Offset (×ATR)", minval = 0.0, maxval = 1.0, step = 0.05, group = GRP_RISK, tooltip = "Break-even stop offset beyond entry, in ATR at entry.\n0 = exactly at entry (recommended).\nThe offset is capped at half the actual distance from entry to TP1 and rounded to the tick toward entry.\nIf the TP1 bar already closes beyond the break-even level, the trade is closed at that close instead of placing a stop on the wrong side of price")
showSlTpInput        = input.bool(true, "Show SL/TP Lines", group = GRP_RISK, tooltip = "Draw entry, stop-loss and take-profit lines. Lines stay on the chart after the trade closes and are replaced at the next entry")
showSlTpLabelsInput  = input.bool(true, "Show SL/TP Labels", group = GRP_RISK, tooltip = "Price labels at the end of the SL/TP lines")
showPctOnLabelsInput = input.bool(true, "Show % Distance on Labels", group = GRP_RISK, tooltip = "Append % distance from entry to SL/TP labels,\ne.g. 'SL 1.2300 (-0.36%)'")
entryLineStyleInput  = input.string("Dotted", "Entry Line Style", options = ["Solid", "Dashed", "Dotted"], group = GRP_RISK, tooltip = "Entry is a reference, not an action level — keep it subtle")
slLineStyleInput     = input.string("Solid", "SL Line Style", options = ["Solid", "Dashed", "Dotted"], group = GRP_RISK, tooltip = "Style of the stop-loss line (width 2)")
tpLineStyleInput     = input.string("Dashed", "TP Line Style", options = ["Solid", "Dashed", "Dotted"], group = GRP_RISK, tooltip = "Style for TP1/TP2/TP3. On hit, a TP line turns solid teal")

showDashInput      = input.bool(true, "Show Dashboard", group = GRP_DASH, tooltip = "Show the dashboard table")
dashPosInput       = input.string("Top Right", "Dashboard Position", options = ["Top Left", "Top Right", "Bottom Left", "Bottom Right", "Middle Right"], group = GRP_DASH, tooltip = "Chart corner for the dashboard")
dashFontSizeInput  = input.string("Small", "Dashboard Font Size", options = ["Small", "Normal", "Large", "Huge"], group = GRP_DASH, tooltip = "Font size for the dashboard table. Section dividers and the version footer render one step smaller to preserve hierarchy")
showMarketSecInput = input.bool(true, "  ├ Market section", group = GRP_DASH, tooltip = "Trend, trend age, HTF bias, range position, position state, last signal, timeframe")
showIctSecInput    = input.bool(true, "  ├ ICT section", group = GRP_DASH, tooltip = "Active zones, FVGs, nearest demand/supply, setup status")
showTradeSecInput  = input.bool(true, "  ├ Trade section", group = GRP_DASH, tooltip = "Entry, SL, TP1–3, R:R and SL distance of the open trade")
showStatsSecInput  = input.bool(true, "  └ Stats section", group = GRP_DASH, tooltip = "Trades, wins, losses, win rate and form of closed trades. Session statistics — not a backtest")
statsPeriodInput   = input.string("All-Time", "Win Rate Period", options = ["24 Hours", "30 Days", "All-Time"], group = GRP_DASH, tooltip = "Time window for the Stats section (Trades / Wins / Losses / Win rate):\n• 24 Hours: trades closed in the last 24h (relative to the latest bar)\n• 30 Days: trades closed in the last 30 days\n• All-Time: all trades on the loaded chart history\nForm strip always shows the last trades regardless of period.\nStats are recalculated from the loaded chart history on every reload; trade times are bar-close times")

webhookInput    = input.bool(false, "Webhook JSON Format", group = GRP_ALERT, tooltip = "Send alerts as JSON for webhook integrations.\nCreate the alert with condition 'Any alert() function call'")
alSlRevInput    = input.bool(true, "Alert on SL Hit & Reversal", group = GRP_ALERT, tooltip = "SL hit, break-even stop-out and reversal alerts")
alTpBeInput     = input.bool(true, "Alert on TP & Break-Even", group = GRP_ALERT, tooltip = "TP1 / TP2 / TP3 hits and the break-even move")
alStructInput   = input.bool(true, "Alert on BOS / CHoCH", group = GRP_ALERT, tooltip = "Info alert on external structure breaks")
alSetupInput    = input.bool(true, "Alert on Setup Armed / Cancelled", group = GRP_ALERT, tooltip = "Info alert when a Sweep → CHoCH setup is armed or cancelled (with reason). Entries always alert")
alObInput       = input.bool(true, "Alert on First OB Touch", group = GRP_ALERT, tooltip = "Info alert on the first touch of an OB / Breaker that is not a setup zone")
alMinScoreInput = input.int(2, "  └ Min Score (★)", minval = 0, maxval = 4, group = GRP_ALERT, tooltip = "Only zones with at least this score alert on touch. Breakers score at most ★★")
alFvgInput      = input.bool(false, "Alert on New FVG", group = GRP_ALERT, tooltip = "Info alert on every new FVG (can be frequent)")
alSweepInput    = input.bool(true, "Alert on Liquidity Sweep", group = GRP_ALERT, tooltip = "Info alert when equal highs/lows (or single swings, if enabled) are swept")
alRbPbInput     = input.bool(false, "Alert on RB / PB", group = GRP_ALERT, tooltip = "Info alert on new propulsion blocks and on first touches of rejection / propulsion blocks")
alJudasInput    = input.bool(true, "Alert on Judas Swing", group = GRP_ALERT, tooltip = "Info alert when a Judas Swing is confirmed")
alBiasInput     = input.bool(false, "Alert on Daily Bias", group = GRP_ALERT, tooltip = "Info alert with the daily bias at the start of each trading day")

bullColorInput    = input.color(#00E676, "Bull", inline = "clr", group = GRP_COLORS)
bearColorInput    = input.color(#FF5252, "Bear", inline = "clr", group = GRP_COLORS, tooltip = "Signal colors: BUY/SELL label backgrounds and demand/supply zones")
fvgBullColorInput = input.color(#2962FF, "FVG Bull", inline = "fvg", group = GRP_COLORS)
fvgBearColorInput = input.color(#FF9800, "FVG Bear", inline = "fvg", group = GRP_COLORS, tooltip = "Fair value gap fills")
oteColorInput     = input.color(#F9A825, "OTE", group = GRP_COLORS, tooltip = "Optimal Trade Entry band")
rbBullColorInput  = input.color(#00BFA5, "RB Bull", inline = "rb", group = GRP_COLORS)
rbBearColorInput  = input.color(#F06292, "RB Bear", inline = "rb", group = GRP_COLORS, tooltip = "Rejection Block fills. Propulsion Blocks use the OB colors with a dotted border")
kzAsiaColorInput  = input.color(#9C27B0, "Asia", inline = "kzc", group = GRP_COLORS)
kzLonColorInput   = input.color(#3F51B5, "London", inline = "kzc", group = GRP_COLORS)
kzNyamColorInput  = input.color(#795548, "NY AM", inline = "kzc", group = GRP_COLORS)
kzNypmColorInput  = input.color(#607D8B, "NY PM", inline = "kzc", group = GRP_COLORS, tooltip = "Killzone box colors. Defaults avoid the hues used by zones and signals")

atrLenInput  = input.int(50, "Zone ATR Length", minval = 5, maxval = 200, group = GRP_ADV, tooltip = "ATR period for all zone thresholds (FVG size, OB height, equal tolerance, HTF zones).\n• Higher = steadier thresholds")
histMaxInput = input.int(150, "History Size", minval = 20, maxval = 300, group = GRP_ADV, tooltip = "How many historical labels and retired lines/zones are kept (BOS/CHoCH, swings, sweeps, signals). Older ones are deleted so TradingView never evicts active zones")

[effSLMult, effTP1m, effTP2m, effTP3m] = switch riskPresetInput
    "Conservative" => [2.5, 1.0, 2.0, 4.0]
    "Aggressive"   => [1.0, 1.5, 2.5, 4.0]
    "Scalping"     => [0.8, 0.8, 1.5, 2.0]
    "Custom"       => [slMultInput, tp1MultInput, tp2MultInput, tp3MultInput]
    =>                [1.5, 1.0, 2.0, 3.0]

if effTP1m >= effTP2m or effTP2m >= effTP3m
    runtime.error("Invalid TP multipliers: required TP1 < TP2 < TP3")
if effSLMult <= 0
    runtime.error("SL Multiplier must be greater than 0")
if htfOnInput and timeframe.in_seconds(htfInput) < timeframe.in_seconds()
    runtime.error("Higher Timeframe must be greater than or equal to chart timeframe")
if intLenInput >= swingLenInput
    runtime.error("Internal Swing Length must be smaller than External Swing Length")
var table wm = table.new(position.bottom_right, 1, 1)
if barstate.isfirst
    table.cell(wm, 0, 0, "Telegram @SimpleForexTools", text_color = color.new(color.gray, 70), text_size = size.large)

isDark = switch themeInput
    "Dark"  => true
    "Light" => false
    =>         0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color) < 128   // Auto: яркость фона, а не только красный канал

TEXT_COLOR      = isDark ? #E0E0E0 : #1A1A1A
TEXT_MUTED      = isDark ? color.new(#9E9E9E, 0) : color.new(#666666, 0)   // v6.2.0: #757575 → #666666 (≥ 4.5:1 и на строке панели)

BULL_TEXT       = isDark ? #00E676 : #007E33
BEAR_TEXT       = isDark ? #FF5252 : #D32F2F
NEUTRAL_TEXT    = isDark ? #FFEB3B : #A15C00
BULL_LABEL_TEXT = #004D25
BEAR_LABEL_TEXT = #FFFFFF

SELL_LABEL_BG   = bearColorInput == #FF5252 ? #D32F2F : bearColorInput   // v6.2.0: на обеих темах (подложка своя, фон графика не влияет)

TABLE_BG       = isDark ? color.new(#131722, 5) : color.new(#FFFFFF, 5)
TABLE_BORDER   = isDark ? color.new(#2A2E39, 0) : color.new(#D0D0D0, 0)
TABLE_ROW_ALT  = isDark ? color.new(#1C2030, 0) : color.new(#F0F4F8, 0)
HEADER_BG      = isDark ? color.new(#0D47A1, 0) : color.new(#1565C0, 0)
HEADER_BG_BULL = color.new(#0F6E56, 0)
HEADER_BG_BEAR = color.new(#A32D2D, 0)
HEADER_TEXT    = #FFFFFF

LINE_SUBTLE = isDark ? color.new(#666666, 0) : color.new(#999999, 0)
KEY_COLOR   = isDark ? color.new(#B0BEC5, 20) : color.new(#546E7A, 20)
SD_COLOR    = isDark ? color.new(#CE93D8, 0) : color.new(#7B1FA2, 0)

AMBER_TEXT  = isDark ? #FFD54F : #BF360C
JUDAS_BG    = isDark ? #FFB300 : #FFA000
JUDAS_TEXT  = #1A1A1A
DONE_COLOR  = isDark ? color.new(#666666, 85) : color.new(#999999, 85)
WM_COLOR    = isDark ? color.new(#FFFFFF, 80) : color.new(#000000, 80)
TRANSPARENT = color.new(#000000, 100)

SL_COLOR       = isDark ? color.new(#E57373, 0) : color.new(#B71C1C, 0)
TP1_COLOR      = isDark ? color.new(#66BB6A, 30) : color.new(#388E3C, 30)
TP2_COLOR      = isDark ? color.new(#66BB6A, 40) : color.new(#388E3C, 40)
TP3_COLOR      = isDark ? color.new(#66BB6A, 0) : color.new(#388E3C, 0)
ENTRY_COLOR    = isDark ? color.new(#5C8AAE, 0) : color.new(#34495E, 0)
TP_LABEL_COLOR = isDark ? color.new(#66BB6A, 0) : color.new(#2E7D32, 0)   // v6.2.0: белый текст на #388E3C давал 4.1:1
TP_HIT_COLOR   = isDark ? color.new(#4DB6AC, 0) : color.new(#00695C, 0)
BE_COLOR       = isDark ? color.new(#FFA726, 0) : color.new(#C43E00, 0)
LABEL_TEXT     = isDark ? #1A1A1A : #FFFFFF

sizeFromString(string s) =>
    s == "Tiny" ? size.tiny : s == "Small" ? size.small : s == "Normal" ? size.normal : s == "Large" ? size.large : s == "Huge" ? size.huge : size.small

sizeDownFromString(string s) =>
    s == "Tiny" ? size.tiny : s == "Small" ? size.tiny : s == "Normal" ? size.small : s == "Large" ? size.normal : s == "Huge" ? size.large : size.tiny

lineStyleFromString(string s) =>
    s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid

floorTick(float v) => math.floor(v / syminfo.mintick + 1e-9) * syminfo.mintick
ceilTick(float v) => math.ceil(v / syminfo.mintick - 1e-9) * syminfo.mintick

safeDiv(float num, float den, float fallback = 0.0) =>
    den != 0 and not na(num) and not na(den) ? num / den : fallback

fmtPrice(float v) =>
    na(v) ? "—" : str.tostring(v, format.mintick)

formatPctFromEntry(float level, float entry) =>
    string res = ""
    if showPctOnLabelsInput and not na(level) and not na(entry) and entry != 0
        float  pct  = (level - entry) / entry * 100.0
        string sign = pct >= 0 ? "+" : ""
        res := " (" + sign + str.tostring(pct, "#.##") + "%)"
    res

buildGauge(float value, float maxVal, int width) =>
    string result = ""
    int filled = maxVal <= 0 ? 0 : math.round(math.min(width, math.max(0.0, value / maxVal * width)))
    for i = 0 to width - 1
        result += i < filled ? "▰" : "▱"
    result

periodStats(array<int> tms, array<bool> wns, int cutoff) =>
    int w = 0
    int l = 0
    int n = array.size(tms)
    if n > 0
        for i = 0 to n - 1
            if array.get(tms, i) >= cutoff
                if array.get(wns, i)
                    w += 1
                else
                    l += 1
    [w, l]

arrow(int dir) => dir > 0 ? "▲" : "▼"
stars(int s) => str.repeat("★", s) + str.repeat("☆", SCORE_MAX - s)
trendWord(int t) => t > 0 ? "Bullish" : t < 0 ? "Bearish" : "Neutral"
trendTextColor(int t) => t > 0 ? BULL_TEXT : t < 0 ? BEAR_TEXT : TEXT_MUTED
evText(int ev) => (math.abs(ev) == 2 ? "CHoCH " : "BOS ") + arrow(ev)
clampX(int x) => math.max(x, bar_index - X_BACK_LIMIT)

jsonEvent(string ev, int dir, float price) => '{"event":"' + ev + '","ticker":"' + syminfo.tickerid + '","tf":"' + timeframe.period + '","dir":"' + (dir > 0 ? "long" : "short") + '","price":' + (na(price) ? "null" : str.tostring(price, format.mintick)) + '}'

signalSize  = sizeFromString(signalFontSizeInput)
labelSize   = sizeFromString(labelFontSizeInput)
textSize    = sizeFromString(textFontSizeInput)
textSizeSub = sizeDownFromString(textFontSizeInput)
dashFont    = sizeFromString(dashFontSizeInput)
dashFontSub = sizeDownFromString(dashFontSizeInput)

var array<line>  histLines  = array.new<line>()
var array<label> histLabels = array.new<label>()
var array<box>   histBoxes  = array.new<box>()

keepLine(line l) =>
    histLines.push(l)
    if histLines.size() > histMaxInput
        histLines.shift().delete()

keepLabel(label l) =>
    histLabels.push(l)
    if histLabels.size() > histMaxInput
        histLabels.shift().delete()

keepBox(box b) =>
    histBoxes.push(b)
    if histBoxes.size() > histMaxInput
        histBoxes.shift().delete()

dashRow(table t, int row, string k, string v, color vc, string tip) =>
    color bg = row % 2 == 0 ? TABLE_BG : TABLE_ROW_ALT
    table.cell(t, 0, row, k, text_color = TEXT_MUTED, text_size = dashFont, bgcolor = bg, text_halign = text.align_left, tooltip = tip)
    table.cell(t, 1, row, v, text_color = vc, text_size = dashFont, bgcolor = bg, text_halign = text.align_right)

dashDivider(table t, int row, string txt) =>
    table.cell(t, 0, row, txt, text_color = TEXT_MUTED, bgcolor = TABLE_ROW_ALT, text_size = dashFontSub, text_halign = text.align_center)
    table.merge_cells(t, 0, row, 1, row)

type Pivot
    float price
    int   idx
    bool  taken = false

type Structure
    Pivot hi
    Pivot lo
    int   trend = 0

type Zone
    box   bx
    line  mid
    float top
    float btm
    float eq
    int   dir
    int   born
    bool  fvg     = false
    int   score   = 0
    bool  breaker = false
    bool  touched = false
    bool  setup   = false
    bool  entered = false
    bool  alive   = true
    int   kind    = 0       // 0 OB, 1 FVG, 2 Rejection Block, 3 Propulsion Block
    int   pbBar             // кандидат Propulsion Block: бар касания OB
    float pbTop
    float pbBtm

type Pool
    line  ln
    label lb
    float price
    int   side
    int   hits = 1

type KeyLvl
    string name
    float  price
    int    side
    int    start
    bool   taken = false
    line   ln
    label  lb

type Sess
    string name
    box    bx
    float  hi
    float  lo
    int    start
    bool   active = false
    int    startT           // время начала: по нему видно, к какой дате относится диапазон

method track(Sess s, bool inS) =>
    bool started = inS and not s.active
    bool ended   = s.active and not inS
    if started
        s.start  := bar_index
        s.startT := time
        s.hi     := high
        s.lo     := low
    else if inS
        s.hi := math.max(s.hi, high)
        s.lo := math.min(s.lo, low)
    s.active := inS
    [started, ended]

method step(Structure s, float ph, float pl, int len, bool labels, bool byClose) =>
    if not na(ph)
        if labels and not na(s.hi)
            keepLabel(label.new(bar_index - len, ph, ph > s.hi.price ? "HH" : "LH", color = TRANSPARENT, textcolor = TEXT_MUTED, style = label.style_label_down, size = textSize))
        s.hi := Pivot.new(ph, bar_index - len)
    if not na(pl)
        if labels and not na(s.lo)
            keepLabel(label.new(bar_index - len, pl, pl < s.lo.price ? "LL" : "HL", color = TRANSPARENT, textcolor = TEXT_MUTED, style = label.style_label_up, size = textSize))
        s.lo := Pivot.new(pl, bar_index - len)
    bool upB = not na(s.hi) and not s.hi.taken and (byClose ? close : high) > s.hi.price
    bool dnB = not na(s.lo) and not s.lo.taken and (byClose ? close : low) < s.lo.price
    if upB and dnB

        Pivot h = s.hi
        Pivot l = s.lo
        h.taken := true
        l.taken := true
        upB := close > h.price
        dnB := close < l.price
    int ev = 0
    if upB
        Pivot h = s.hi
        h.taken := true
        ev      := s.trend < 0 ? 2 : 1
        s.trend := 1
    else if dnB
        Pivot l = s.lo
        l.taken := true
        ev      := s.trend > 0 ? -2 : -1
        s.trend := -1
    ev

drawBreak(Pivot p, int ev, bool major) =>
    color c  = ev > 0 ? BULL_TEXT : BEAR_TEXT
    int   x1 = clampX(p.idx)
    keepLine(line.new(x1, p.price, bar_index, p.price, color = c, style = major ? line.style_solid : line.style_dashed, width = 1))
    keepLabel(label.new(math.round((x1 + bar_index) / 2), p.price, math.abs(ev) == 2 ? "CHoCH" : "BOS", color = TRANSPARENT, textcolor = c, style = ev > 0 ? label.style_label_down : label.style_label_up, size = major ? textSize : textSizeSub))

htfEngine(int len, int atrL, float maxAtr) =>
    var float hP    = na
    var int   hI    = na
    var bool  hX    = false
    var float lP    = na
    var int   lI    = na
    var bool  lX    = false
    var int   trend = 0
    var float bTop  = na
    var float bBtm  = na
    var int   bT    = na
    var float sTop  = na
    var float sBtm  = na
    var int   sT    = na
    float a  = nz(ta.atr(atrL), ta.tr(true))
    float ph = ta.pivothigh(high, len, len)
    float pl = ta.pivotlow(low, len, len)
    if not na(ph)
        hP := ph
        hI := bar_index - len
        hX := false
    if not na(pl)
        lP := pl
        lI := bar_index - len
        lX := false
    if not na(hP) and not hX and close > hP
        hX    := true
        trend := 1
        int n  = math.max(1, math.min(bar_index - hI, HTF_SCAN_BARS))
        int xi = 1
        for i = 1 to n
            if low[i] < low[xi]
                xi := i
        float body = math.max(open[xi], close[xi])
        float edge = body - low[xi] < THIN_ZONE_ATR * a ? high[xi] : body
        bTop := maxAtr > 0 ? math.min(edge, low[xi] + maxAtr * a) : edge
        bBtm := low[xi]
        bT   := time[xi]
    else if not na(lP) and not lX and close < lP
        lX    := true
        trend := -1
        int n  = math.max(1, math.min(bar_index - lI, HTF_SCAN_BARS))
        int xi = 1
        for i = 1 to n
            if high[i] > high[xi]
                xi := i
        float body = math.min(open[xi], close[xi])
        float edge = high[xi] - body < THIN_ZONE_ATR * a ? low[xi] : body
        sBtm := maxAtr > 0 ? math.max(edge, high[xi] - maxAtr * a) : edge
        sTop := high[xi]
        sT   := time[xi]
    if not na(bBtm) and close < bBtm
        bTop := na
        bBtm := na
        bT   := na
    if not na(sTop) and close > sTop
        sTop := na
        sBtm := na
        sT   := na
    [trend[1], bTop[1], bBtm[1], bT[1], sTop[1], sBtm[1], sT[1], hP[1], lP[1]]

float zoneAtr      = nz(ta.atr(atrLenInput), ta.tr(true))
float riskAtr      = nz(ta.atr(atrLenRiskInput), 0.0)
float rsiValue     = nz(ta.rsi(close, RSI_LEN), 50.0)
bool  byCloseBreak = breakByInput == O_CLOSE
bool  barConfirmed = barstate.isconfirmed
int   barCloseT    = nz(time_close, time)     // время закрытия бара: события и статистика привязаны к закрытию, а не к открытию
bool  htfActive    = htfOnInput and timeframe.in_seconds(htfInput) > timeframe.in_seconds()

int  WARMUP_BARS = math.max(50, atrLenInput, swingLenInput * 2 + 1)
bool isWarmedUp  = bar_index >= WARMUP_BARS

float extPH = ta.pivothigh(high, swingLenInput, swingLenInput)
float extPL = ta.pivotlow(low, swingLenInput, swingLenInput)
float intPH = ta.pivothigh(high, intLenInput, intLenInput)
float intPL = ta.pivotlow(low, intLenInput, intLenInput)
float liqPH = ta.pivothigh(high, liqLenInput, liqLenInput)
float liqPL = ta.pivotlow(low, liqLenInput, liqLenInput)

[hTrend, hbTop, hbBtm, hbT, hsTop, hsBtm, hsT, hHi, hLo] = request.security(syminfo.tickerid, htfInput, htfEngine(htfLenInput, atrLenInput, obMaxAtrInput), lookahead = barmerge.lookahead_on)

[pdh, pdl, pdc, ppdh, ppdl] = request.security(syminfo.tickerid, "D", [high[1], low[1], close[1], high[2], low[2]], lookahead = barmerge.lookahead_on)
[pwh, pwl] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead = barmerge.lookahead_on)
int  dayKey    = time("D")       // идентификатор торгового дня / недели (время открытия D/W-бара)
int  weekKey   = time("W")
bool dayLvlOk  = keyDayInput and timeframe.isintraday
bool weekLvlOk = keyWeekInput and timeframe.in_seconds() < timeframe.in_seconds("W")

bool kzActive  = timeframe.isintraday and timeframe.in_seconds() <= 3600
bool inAsia    = kzActive and asiaOnInput and not na(time(timeframe.period, asiaSessInput, kzTzInput))
bool inLon     = kzActive and lonOnInput and not na(time(timeframe.period, lonSessInput, kzTzInput))
bool inNyam    = kzActive and nyamOnInput and not na(time(timeframe.period, nyamSessInput, kzTzInput))
bool inNypm    = kzActive and nypmOnInput and not na(time(timeframe.period, nypmSessInput, kzTzInput))
bool inSb      = kzActive and (not na(time(timeframe.period, SB_1, kzTzInput)) or not na(time(timeframe.period, SB_2, kzTzInput)) or not na(time(timeframe.period, SB_3, kzTzInput)))
bool inAnyKz   = inAsia or inLon or inNyam or inNypm
bool timeOk    = not kzActive or timeFilterInput == T_OFF or (timeFilterInput == T_KZ ? inAnyKz : inSb)

int  nyDate    = year(time, kzTzInput) * 10000 + month(time, kzTzInput) * 100 + dayofmonth(time, kzTzInput)
bool newNyDay  = nyDate != nz(nyDate[1], -1)

bool moAtMidnight = hour(time, kzTzInput) == 0 and minute(time, kzTzInput) == 0 and second(time, kzTzInput) == 0
string kzName  = inAsia ? "Asian" : inLon ? "London" : inNyam ? "NY AM" : inNypm ? "NY PM" : ""

bool biasActive = biasOnInput and timeframe.isintraday

int  dailyBias  = not biasActive or na(pdc) or na(ppdh) ? 0 : pdc > ppdh ? 1 : pdc < ppdl ? -1 : pdh > ppdh and pdl < ppdl ? 0 : pdh > ppdh ? -1 : pdl < ppdl ? 1 : 0
bool biasLongOk  = not biasActive or biasFilterInput == BF_OFF or (biasFilterInput == BF_STR ? dailyBias == 1 : dailyBias >= 0)
bool biasShortOk = not biasActive or biasFilterInput == BF_OFF or (biasFilterInput == BF_STR ? dailyBias == -1 : dailyBias <= 0)
bool inJudas     = kzActive and judasOnInput and biasActive and not na(time(timeframe.period, judasSessInput, kzTzInput))

bgcolor(showSbInput and inSb ? color.new(NEUTRAL_TEXT, 94) : na, title = "Silver Bullet")

var Structure   sExt  = Structure.new()
var Structure   sInt  = Structure.new()
var array<Zone> obs   = array.new<Zone>()
var array<Zone> fvgs  = array.new<Zone>()
var array<Pool> pools = array.new<Pool>()

var float rHi    = na
var int   rHiIdx = na
var float rLo    = na
var int   rLoIdx = na
var int   seenHi = na
var int   seenLo = na

var int  lastBuySweep  = na
var int  lastSellSweep = na
var int  usedBuySweep  = na
var int  usedSellSweep = na
var Zone setZone       = na
var int  setExpire     = na
var int  prevExtTrend  = 0
var int  trendStartBar = na

var array<KeyLvl> keys = array.new<KeyLvl>()
var string lastBuySweepName  = ""
var string lastSellSweepName = ""
var float  setLegLo          = na
var float  setLegHi          = na
var string setSweepName      = ""

var Sess sAsia = Sess.new("Asian")
var Sess sLon  = Sess.new("London")
var Sess sNyam = Sess.new("NY AM")
var Sess sNypm = Sess.new("NY PM")

var line  moLine  = na
var label moLbl   = na
var float moPrice = na

var array<Zone> rbs = array.new<Zone>()
var array<Zone> pbs = array.new<Zone>()

var int   judasState  = 0       // 0 — нет, 1 — ложный ход идёт, 2 — подтверждён
var float judasExt    = na
var int   judasExtBar = na
var int   judasDir    = 0       // направление кандидата Judas (bias на момент начала ложного хода)

var array<float> sdKs     = array.new<float>()
var array<line>  sdLines  = array.new<line>()
var array<label> sdLabels = array.new<label>()

if barstate.isfirst
    for s in str.split(sdLevelsInput, ",")
        string tok = str.replace_all(s, " ", "")
        if tok != ""
            float v = str.tonumber(tok)
            if na(v) or v <= 0 or v > SD_MAX_MULT
                runtime.error("SD Levels: '" + tok + "' is not a number between 0 and " + str.tostring(SD_MAX_MULT) + ". Use e.g. 1, 2, 2.5")
            if not sdKs.includes(v)
                sdKs.push(v)
    sdKs.sort(order.ascending)
    if sdKs.size() > SD_MAX_LEVELS
        runtime.error("SD Levels: at most " + str.tostring(SD_MAX_LEVELS) + " levels are allowed")
    if sdKs.size() == 0 and (sdShowInput or tpModeInput == TP_SD)
        runtime.error("SD Levels: enter positive numbers separated by commas, e.g. 1, 2, 2.5")

var array<float> atrHist = array.new<float>()
atrHist.unshift(zoneAtr)
if atrHist.size() > ATR_HIST_LEN
    atrHist.pop()

fvgAt(int dir, int k) =>
    float minGap = fvgMinAtrInput * (k < atrHist.size() ? atrHist.get(k) : zoneAtr)
    dir > 0 ? low[k] > high[k + 2] and close[k + 1] > high[k + 2] and low[k] - high[k + 2] >= minGap : high[k] < low[k + 2] and close[k + 1] < low[k + 2] and low[k + 2] - high[k] >= minGap

findOrderBlock(int dir, int fromIdx) =>
    int n  = math.max(1, math.min(bar_index - fromIdx, OB_SCAN_BARS))
    int xi = 1
    for i = 1 to n
        if dir > 0 ? low[i] < low[xi] : high[i] > high[xi]
            xi := i
    int  src   = xi
    bool found = false
    for i = xi to math.min(xi + OB_SRC_BARS, n)
        if dir > 0 ? close[i] < open[i] : close[i] > open[i]
            src   := i
            found := true
            break
    float dist = dir > 0 ? low[xi] : high[xi]
    float prox = dir > 0 ? (obEdgeInput == O_BODY ? math.max(open[src], close[src]) : high[src]) : (obEdgeInput == O_BODY ? math.min(open[src], close[src]) : low[src])
    if math.abs(prox - dist) < THIN_ZONE_ATR * zoneAtr
        prox := dir > 0 ? high[src] : low[src]
    if obMaxAtrInput > 0 and math.abs(prox - dist) > obMaxAtrInput * zoneAtr
        prox := dist + dir * obMaxAtrInput * zoneAtr
    bool imb = false
    for k = 0 to math.max(xi - 1, 0)
        if fvgAt(dir, k)
            imb := true
            break

    bool pre  = false
    bool gone = false
    for k = xi - 1 to 0
        if gone and (dir > 0 ? low[k] <= prox : high[k] >= prox)
            pre := true
            break
        gone := gone or (dir > 0 ? low[k] > prox : high[k] < prox)
    [prox, dist, src, xi, imb, pre, found]

baseColor(int dir, bool isFvg) => isFvg ? (dir > 0 ? fvgBullColorInput : fvgBearColorInput) : (dir > 0 ? bullColorInput : bearColorInput)

zoneScore(int dir, float top, float btm, bool imb, bool liq) =>
    float rTop = htfActive ? hHi : rHi
    float rBot = htfActive ? hLo : rLo
    bool  half = not na(rTop) and not na(rBot) and rTop > rBot and (dir > 0 ? (top + btm) / 2 < (rTop + rBot) / 2 : (top + btm) / 2 > (rTop + rBot) / 2)
    bool  algn = htfActive and hTrend == dir
    (imb ? 1 : 0) + (liq ? 1 : 0) + (algn ? 1 : 0) + (half ? 1 : 0)

zoneText(Zone z) =>
    string side = z.dir > 0 ? "Bull " : "Bear "
    z.setup ? "SETUP " + arrow(z.dir) + (z.fvg ? " FVG" : " " + stars(z.score)) : z.fvg ? "" : z.breaker ? side + "Breaker " + str.repeat("★", z.score) : side + "OB " + stars(z.score) + (z.touched ? " · tested" : "")

zoneLabel(Zone z) => showZoneTextInput or z.setup ? zoneText(z) : ""

zoneRange(Zone z) => na(z) ? "—" : fmtPrice(z.btm) + "–" + fmtPrice(z.top) + (close >= z.btm and close <= z.top ? " (inside)" : "")

newZone(float top, float btm, int dir, int left, bool isFvg, int score, bool touched) =>
    color base = baseColor(dir, isFvg)
    box   b    = box.new(left, top, bar_index + 1, btm, border_color = color.new(base, 50), border_width = score >= 3 ? 2 : 1, border_style = touched ? line.style_dotted : line.style_solid, bgcolor = color.new(base, touched ? math.min(zoneTranspInput + 5, 100) : zoneTranspInput), text_size = textSize, text_color = TEXT_MUTED, text_halign = text.align_right, text_valign = text.align_center)
    line  m    = not isFvg and obMidInput ? line.new(left, (top + btm) / 2, bar_index + 1, (top + btm) / 2, color = color.new(base, 50), style = line.style_dotted) : na
    Zone  z    = Zone.new(b, m, top, btm, (top + btm) / 2, dir, bar_index, isFvg, score)
    z.touched := touched
    b.set_text(zoneLabel(z))
    z

setSetupLook(Zone z, bool on) =>
    z.setup := on
    if z.alive
        color base = baseColor(z.dir, z.fvg)
        z.bx.set_border_width(on or z.score >= 3 ? 2 : 1)
        z.bx.set_border_color(on ? base : color.new(base, 50))
        z.bx.set_text_color(on ? trendTextColor(z.dir) : TEXT_MUTED)
        z.bx.set_text(zoneLabel(z))

dropSetup(Zone z, string why) =>
    setSetupLook(z, false)
    alSetupInput ? "Setup " + arrow(z.dir) + " cancelled: " + why + "; " : ""

claimSetup(array<Zone> arr, int dir, int since) =>
    Zone found = na
    if arr.size() > 0
        for i = arr.size() - 1 to 0
            Zone z = arr.get(i)
            if z.dir == dir and not z.breaker and not z.touched and z.born >= since
                found := z
                break
    found

retire(Zone z, bool keep) =>
    z.alive := false
    if keep
        z.bx.set_right(bar_index)
        z.bx.set_bgcolor(DONE_COLOR)
        z.bx.set_border_color(DONE_COLOR)
        z.bx.set_text_color(color.new(TEXT_MUTED, 50))
        keepBox(z.bx)
        if not na(z.mid)
            z.mid.set_x2(bar_index)
            z.mid.set_color(DONE_COLOR)
            keepLine(z.mid)
    else
        z.bx.delete()
        if not na(z.mid)
            z.mid.delete()

trimZones(array<Zone> arr, int dir, int maxN) =>
    int cnt = 0
    if arr.size() > 0
        for i = arr.size() - 1 to 0
            Zone z = arr.get(i)
            if z.dir == dir
                cnt += 1
                if cnt > maxN
                    retire(z, false)
                    arr.remove(i)

overlaps(array<Zone> arr, int dir, float top, float btm) =>
    bool hit = false
    for z in arr
        if z.dir == dir and not z.breaker and not z.touched
            float ov = math.min(top, z.top) - math.max(btm, z.btm)
            if ov > OVERLAP_SHARE * math.min(top - btm, z.top - z.btm)
                hit := true
                break
    hit

updateOrderBlocks() =>
    string msg = ""
    if obs.size() > 0
        for i = obs.size() - 1 to 0
            Zone z = obs.get(i)
            if bar_index > z.born
                float dist   = z.dir > 0 ? z.btm : z.top
                bool  beyond = z.dir > 0 ? close < dist : close > dist
                bool  broken = z.breaker ? beyond : obMitigInput == O_HALF ? (z.dir > 0 ? close < z.eq : close > z.eq) : obMitigInput == O_WICK ? (z.dir > 0 ? low < dist : high > dist) : beyond
                if broken
                    if obBreakerInput and not z.breaker and beyond
                        z.breaker := true
                        z.setup   := false
                        z.pbBar   := na        // кандидат PB относился к прежнему направлению — сбрасываем
                        z.dir     := -z.dir
                        z.touched := false
                        z.born    := bar_index
                        z.score   := zoneScore(z.dir, z.top, z.btm, false, false)
                        z.bx.set_bgcolor(color.new(baseColor(z.dir, false), zoneTranspInput))
                        z.bx.set_border_color(color.new(baseColor(z.dir, false), 40))
                        z.bx.set_border_style(line.style_dashed)
                        z.bx.set_border_width(1)
                        z.bx.set_text(zoneLabel(z))
                        z.bx.set_text_color(TEXT_MUTED)
                        z.bx.set_right(bar_index + 1)
                        if not na(z.mid)
                            z.mid.set_color(color.new(baseColor(z.dir, false), 50))
                            z.mid.set_x2(bar_index + 1)
                    else
                        obs.remove(i)
                        retire(z, obKeepInput)
                else
                    if not z.touched and low <= z.top and high >= z.btm
                        z.touched := true

                        if pbOnInput and not z.breaker and (z.dir > 0 ? close < open : close > open)
                            z.pbBar := bar_index
                            z.pbTop := high
                            z.pbBtm := low
                        if z.setup
                            z.setup   := false
                            z.entered := true
                            z.bx.set_text(zoneLabel(z))
                            z.bx.set_text_color(TEXT_MUTED)
                        else
                            msg += alObInput and z.score >= alMinScoreInput ? (z.breaker ? "Breaker " : "OB ") + stars(z.score) + " " + arrow(z.dir) + " touch " + fmtPrice(z.btm) + "–" + fmtPrice(z.top) + "; " : ""
                            z.bx.set_text(zoneLabel(z))
                    z.bx.set_right(bar_index + 1)
                    if not na(z.mid)
                        z.mid.set_x2(bar_index + 1)
    msg

newAuxZone(float top, float btm, int dir, int left, int kind, bool touched) =>
    color base = kind == 2 ? (dir > 0 ? rbBullColorInput : rbBearColorInput) : baseColor(dir, false)
    string t   = showZoneTextInput ? (dir > 0 ? "Bull " : "Bear ") + (kind == 2 ? "RB" : "PB") : ""
    box   b    = box.new(left, top, bar_index + 1, btm, border_color = color.new(base, 40), border_width = 1, border_style = kind == 3 or touched ? line.style_dotted : line.style_solid, bgcolor = color.new(base, math.min(zoneTranspInput + 3, 100)), text = t, text_size = textSize, text_color = TEXT_MUTED, text_halign = text.align_left, text_valign = text.align_center)
    line  m    = obMidInput ? line.new(left, (top + btm) / 2, bar_index + 1, (top + btm) / 2, colo

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