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

Market Map

indicator market map for tradingview.pine

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

ea12sd.mq4MQL4 / MetaTrader 4 · 1 общих теговconfluenceforge_pro.mq5TradingView · 1 общих теговvolatility_gold_master.mq5MQL5 / MetaTrader 5 · 1 общих теговhamster scalping v 21.0.mq5MQL5 / MetaTrader 5 · 1 общих теговqqe of rsi(oma)(on chart).mq5MQL5 / MetaTrader 5 · 1 общих теговsvestochrsi.mq5MQL5 / MetaTrader 5 · 1 общих тегов
Вы автор или правообладатель?

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

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

О программе

Market Map — это индикатор для TradingView на Pine Script v6, который строит на графике письменный план по текущей рыночной ситуации. Он считывает структуру по свинговым максимумам и минимумам на трёх таймфреймах (контекстный, основной и младший), которые выбираются автоматически по таймфрейму графика и горизонту планирования либо задаются вручную. На основе этих данных формируется направленный сценарий: зона покупки или продажи, условия подтверждения, цели и уровень отмены плана.

Индикатор отображает ключевые уровни: свинговые экстремумы, максимум и минимум предыдущего дня и недели, уровни Фибоначчи последнего свинга, незакрытые тени свечей, равные максимумы и минимумы, а также зоны поддержки и сопротивления с несколькими касаниями. Дополнительно можно включить разрывы справедливой стоимости, полосы премии и дисконта, разметку сломов структуры BOS и CHoCH и окраску свечей по краткосрочной структуре.

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

Это инструмент анализа и планирования, а не торговый сигнал: расчёты не гарантируют результат, а время маршрута условно.

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

НастройкаОписание
useAuto Автоматически подбирает контекстный, основной и младший таймфреймы по таймфрейму графика и горизонту планирования.
horizon Выбор горизонта планирования: краткосрочный держит зоны и цели ближе к цене, свинговый планирует более крупные движения.
htfIn Основной таймфрейм, на котором строятся структура, Фибоначчи, зоны, тени и ликвидность при ручном выборе.
hiTfIn Старший таймфрейм для оценки общего тренда при ручном выборе таймфреймов.
loTfIn Младший таймфрейм для оценки краткосрочного тренда и коррекционных движений при ручном выборе.
pivLen Сколько баров с каждой стороны должен перебить экстремум, чтобы считаться свингом.
useZones Показывает зоны, где цена несколько раз разворачивалась на основном таймфрейме.
zoneSrc Выбор таймфрейма, на котором строятся зоны: основной или тайминг.
minTouches Сколько свинговых экстремумов должно сгруппироваться у цены, чтобы уровень считался зоной.
zoneTol Насколько близко свинги должны быть, чтобы считаться одной зоной, и толщина зоны в единицах ATR.
zoneMemory Сколько последних свингов основного таймфрейма учитывается при поиске зон.
usePD Показывает положение цены между максимумом и минимумом диапазона основного таймфрейма.
pdLen Количество баров основного таймфрейма, задающих диапазон для оценки положения цены.
showEq Рисует линию середины диапазона (50%).
useWicks Показывает последние крупные верхние и нижние тени основного таймфрейма, которые цена ещё не перекрыла.
wickPct Минимальная доля тени от диапазона свечи, чтобы она считалась крупной.
useLiq Показывает равные максимумы и минимумы, за которыми обычно скапливаются стопы.
eqTol Насколько близко два свинга должны быть, чтобы считаться равными.
useConf Отмечает, когда зона покупки или продажи совпадает с другими уровнями.
confTol Насколько близко другой уровень должен находиться к зоне, чтобы считаться совпадением.
useAdr Включает оценку использования среднего дневного диапазона и оставшегося запаса хода.
adrLen Количество дней, по которым рассчитывается средний дневной диапазон.
useRsi Включает оценку импульса по RSI 14 на основном таймфрейме.
useSweep Включает обнаружение ликвидационных свипов через уровни с возвратом закрытия.
showSweepMk Отмечает крестиками свечи, которые совершили ликвидационный свип.
sweepLen Сила локального свинга на баровом таймфрейме для определения локальной ликвидности.
useVol Сравнивает объём свечи со средним объёмом за последние бары.
volExt Позволяет читать объём с другого символа вместо объёма текущего инструмента.
volSym Символ, с которого берётся объём при включённом чтении объёма с другого инструмента.
volLen Количество баров графика для расчёта среднего объёма.
volThr Порог, при котором объём считается сильным относительно среднего.
useStats Отслеживает прошлые планы по истории графика и показывает, как они отработали.
statsN Сколько последних планов в каждом направлении учитывается в статистике.
zoneChoice Выбор полосы Фибоначчи, которая используется как зона покупки или продажи.
rejBody Минимальная доля тела свечи от её диапазона для подтверждающего отказа.
rejBars Сколько баров графика после входа в зону ещё допускается подтверждающий отказ.
exportTr Записывает результат каждой смоделированной сделки и её условия в окно данных и экспорт данных графика.
tgtGap Минимальное расстояние от зоны до первой цели и между целями в единицах ATR.
tgtCapAdr Максимальное расстояние цели от зоны в единицах среднего дневного диапазона.
showTrack Показывает в панели результаты прошлых планов по загруженной истории.
t1Cap Ограничивает первую цель расстоянием, равным этому множителю риска от входа до стопа.
strictConf Требует, чтобы свеча отказа также закрылась за минимумом (для продажи) или максимумом (для покупки) предыдущей свечи.
statsRange Включает боковые сценарии в статистику прошлых результатов.
stopBuf Дополнительный отступ стопа за дальней границей зоны или экстремумом в единицах ATR.
useUsd Включает проверку направления доллара США как внешнего фактора.
usdSym Инструмент, используемый для проверки направления доллара США.
useYld Включает проверку направления доходностей США как внешнего фактора.
yldSym Инструмент, используемый для проверки направления доходностей США.
imLen Длина EMA для оценки направления доллара и доходностей на основном таймфрейме.
volRegLen Количество баров графика для расчёта базовой волатильности.
hiVolThr Порог, при котором текущая волатильность считается высокой относительно базовой.
newsWin Окно в минутах до и после новости, в котором новые сделки не рассматриваются.
news1 Дата и время первого важного новостного события.
news2 Дата и время второго важного новостного события.
news3 Дата и время третьего важного новостного события.
newsTz Часовой пояс, в котором отображается время новостей.
panelMode Уровень детализации панели: простой, компактный или полный.
chartStyle Выбор между упрощённым отображением (только зона, цели, уровень отмены и маршрут) и показом всех уровней.
showPlan Показывает панель с письменным анализом и планом.
planPos Расположение панели анализа на графике.
planSize Размер текста в панели анализа.
showFib Показывает уровни Фибоначчи 0.382, 0.5 и 0.618 последнего свинга основного таймфрейма.
showPrev Показывает максимум и минимум предыдущего дня и недели.
lineExt На сколько баров вправо продлеваются линии уровней.
lineW Толщина линий уровней.
labSizeS Размер подписей цен у уровней.
labBg Добавляет затенённый фон под подписями уровней для лучшей читаемости.
mergeTol Уровни, находящиеся ближе этого расстояния, объединяются в одну подпись.
showAlt Рисует пунктирный альтернативный маршрут без предварительной коррекции.
paceMult Множитель, задающий ширину шагов маршрута во времени.
nearLen Сила свинга на таймфрейме графика для поиска ближайших уровней-ступеней маршрута.
stonesN Максимальное число ближайших свинговых уровней, на которых маршрут делает остановку по пути к цели.
stoneGap Минимальный размер шага между ступенями маршрута в единицах ATR графика.
preMax Максимальная дистанция короткого контрдвижения к ближайшему свингу, если краткосрочный тренд направлен против сценария.
colAlt Цвет альтернативного маршрута.
routeStyle Стиль маршрута: сплошной или сплошной на ближайшем участке и пунктирный далее.
extOnChart Показывает на графике более крупную цель, лежащую за пределом дистанции целей, и продлевает к ней маршрут.
alZone Включает оповещение, когда цена закрывается внутри зоны покупки или продажи.
alReject Включает оповещение, когда после захода в зону свеча закрывается обратно в сторону сценария.
alTarget Включает оповещение при достижении первой цели сценария.
alInvalid Включает оповещение, когда закрытие свечи основного таймфрейма выходит за уровень отмены плана.
alBias Включает оповещение при смене основного направления между бычьим, медвежьим и нейтральным.
alSweep Включает оповещение о ликвидационном свипе в зоне покупки или продажи либо внутри неё.
showStruct Отмечает сломы структуры BOS и CHoCH на таймфрейме графика.
structKeep Сколько сломов структуры остаётся на графике.
showFvg Показывает незакрытые разрывы справедливой стоимости на таймфрейме графика.
fvgMin Минимальный размер разрыва справедливой стоимости в единицах ATR графика.
fvgKeep Сколько незакрытых разрывов справедливой стоимости сохраняется с каждой стороны.
showPDB Затеняет верхнюю и нижнюю четверти диапазона основного таймфрейма как зоны премии и дисконта.
showPrevS Показывает максимум и минимум предыдущего дня в упрощённом режиме графика.
colorBars Включает окраску свечей по краткосрочной структуре.
alStruct Включает оповещение при сломе структуры на таймфрейме графика.
colBull Цвет, используемый для бычьих элементов.
colBear Цвет, используемый для медвежьих элементов.
colFib Цвет линий Фибоначчи.
colPrev Цвет уровней предыдущего дня и недели.
colWick Цвет уровней незакрытых теней.
colLiq Цвет отметок ликвидности и целей.

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

indicator("Market Map [@simpleforextools]", shorttitle="Market Map", overlay=true, max_lines_count=200, max_labels_count=150, max_boxes_count=100, max_polylines_count=10)

grp_a   = "Timeframes"
useAuto = input.bool(true, "Auto-select timeframes from the chart", group=grp_a, display=display.none, tooltip="Picks the context / main / timing timeframes from the chart timeframe and the planning horizon below. Turn off to choose them yourself.")
horizon = input.string("Short-term", "Planning horizon", options=["Short-term", "Swing"], group=grp_a, display=display.none, active=useAuto, tooltip="Short-term (context / main / timing):\n1m: 15m / 5m / 1m\n3m–5m: 1H / 15m / chart\n15m–30m: 4H / 1H / chart\n1H: D / 4H / 1H\n4H: W / D / 4H\n\nSwing:\n1m–3m: 1H / 15m / 5m\n5m: 4H / 1H / 15m\n15m–30m: D / 4H / 1H\n1H: W / D / 4H\n\nShort-term keeps zones and targets close to price. Swing plans bigger moves.")
htfIn   = input.timeframe("240", "Manual: main timeframe", group=grp_a, display=display.none, active=not useAuto, tooltip="The timeframe the plan is built on: structure, Fibonacci, zones, wicks and liquidity.")
hiTfIn  = input.timeframe("D", "Manual: context timeframe (higher)", group=grp_a, display=display.none, active=not useAuto, tooltip="Bigger-picture trend, used for the alignment reading.")
loTfIn  = input.timeframe("60", "Manual: timing timeframe (lower)", group=grp_a, display=display.none, active=not useAuto, tooltip="Shorter-term trend, used to spot corrective moves. Should be lower than the main timeframe.")
pivLen  = input.int(5, "Swing strength (bars each side)", minval=2, maxval=20, group=grp_a, display=display.none, tooltip="How many bars on each side a high or low must beat to count as a swing. Higher = only major swings. Lower = more, smaller swings.")

grp_z      = "Support / Resistance Zones"
useZones   = input.bool(true, "Show multi-touch zones", group=grp_z, display=display.none, tooltip="Zones where price has turned several times on the main timeframe. More touches = a level the market respects. Shows the nearest zone above and below price.")
zoneSrc    = input.string("Main timeframe", "Build zones on", options=["Main timeframe", "Timing timeframe"], group=grp_z, display=display.none, active=useZones, tooltip="Main: zones from the plan's timeframe (e.g. 1H on a 5m chart). Fewer, more significant levels.\nTiming: zones from the lower timeframe (e.g. 15m on a 5m chart). Closer, more frequent levels for intraday trading.")
minTouches = input.int(2, "Minimum touches", minval=2, maxval=10, group=grp_z, display=display.none, active=useZones, tooltip="How many swing highs / lows must cluster at a price before it counts as a zone. 2 = nearest tested level. 3+ = fewer, stronger zones that may sit further from price. The label always shows the touch count.")
zoneTol    = input.float(0.35, "Zone width (x ATR)", minval=0.1, maxval=2.0, step=0.05, group=grp_z, display=display.none, active=useZones, tooltip="How close swings must be to count as the same zone, and how thick the zone is drawn. Measured in main-timeframe ATR.")
zoneMemory = input.int(40, "Swings remembered", minval=10, maxval=100, group=grp_z, display=display.none, active=useZones, tooltip="How many recent main-timeframe swings are used to find zones. Higher = older levels can count.")

grp_l    = "Location (Premium / Discount)"
usePD    = input.bool(true, "Show location in the range", group=grp_l, display=display.none, tooltip="Where price sits between the main-timeframe range high and low. Top quarter = premium (better for sells), bottom quarter = discount (better for buys).")
pdLen    = input.int(100, "Range length (main-timeframe bars)", minval=20, maxval=500, group=grp_l, display=display.none, active=usePD, tooltip="How many main-timeframe bars define the range.")
showEq   = input.bool(true, "Draw the range equilibrium (50%) line", group=grp_l, display=display.none, active=usePD, tooltip="The middle of the range. Above it is premium, below it is discount.")

grp_x    = "Extra data"
useWicks = input.bool(true, "Unfilled wicks", group=grp_x, display=display.none, tooltip="The most recent large upper and lower wicks on the main timeframe that price hasn't traded back through. Price often revisits them.")
wickPct  = input.float(40, "Wick must be at least this % of the candle", minval=10, maxval=90, group=grp_x, display=display.none, active=useWicks, tooltip="Higher = only very large wicks count.") / 100
useLiq   = input.bool(true, "Equal highs / lows (liquidity)", group=grp_x, display=display.none, tooltip="Two swing highs or lows at nearly the same price. Stop losses tend to cluster beyond them.")
eqTol    = input.float(0.15, "Equal if within (x ATR)", minval=0.02, maxval=1.0, step=0.01, group=grp_x, display=display.none, active=useLiq, tooltip="How close two swings must be to count as equal.")
useConf  = input.bool(true, "Confluence check", group=grp_x, display=display.none, tooltip="Flags when the buy / sell zone lines up with other levels. More reasons at one price = a stronger zone.")
confTol  = input.float(0.25, "Confluence distance (x ATR)", minval=0.05, maxval=1.0, step=0.05, group=grp_x, display=display.none, active=useConf, tooltip="How close another level must be to the zone to count as confluence.")
useAdr   = input.bool(true, "ADR (volatility) context", group=grp_x, display=display.none, tooltip="How much of the average daily range has been used today, and how much room is typically left.")
adrLen   = input.int(14, "ADR length (days)", minval=1, maxval=100, group=grp_x, display=display.none, active=useAdr, tooltip="Number of days in the average daily range.")
useRsi   = input.bool(true, "Momentum (RSI 14 on main timeframe)", group=grp_x, display=display.none, tooltip="A quick read on whether momentum supports the bias.")

grp_v       = "Liquidity Sweeps & Volume"
useSweep    = input.bool(true, "Detect liquidity sweeps", group=grp_v, display=display.none, tooltip="A sweep is a candle that trades through a level (equal highs / lows, previous day high / low, swing high / low, a zone, an unfilled wick or a recent local swing) and then closes back on the other side. Often a stop hunt before a reversal.")
showSweepMk = input.bool(false, "Mark sweeps on the chart", group=grp_v, display=display.none, active=useSweep, tooltip="Small crosses above / below candles that swept a level.")
sweepLen    = input.int(3, "Local swing strength (chart bars)", minval=2, maxval=10, group=grp_v, display=display.none, active=useSweep, tooltip="Size of the recent chart-timeframe swings that count as local liquidity.")
useVol      = input.bool(true, "Volume confirmation", group=grp_v, display=display.none, tooltip="Compares each candle's volume with its recent average. A rejection on strong volume is more convincing.")
volExt      = input.bool(false, "Read volume from another symbol", group=grp_v, display=display.none, active=useVol, tooltip="Spot gold (XAUUSD) only has broker tick volume. Turn this on to use real exchange volume from gold futures instead.")
volSym      = input.symbol("COMEX:GC1!", "Volume symbol", group=grp_v, display=display.none, active=useVol and volExt, tooltip="COMEX:GC1! = gold futures. Futures trading hours differ slightly from spot.")
volLen      = input.int(20, "Average volume length (bars)", minval=5, maxval=200, group=grp_v, display=display.none, active=useVol, tooltip="Number of chart bars in the average volume.")
volThr      = input.float(1.3, "Strong volume = at least x average", minval=1.0, maxval=5.0, step=0.1, group=grp_v, display=display.none, active=useVol, tooltip="1.3 = at least 30% above average volume.")

grp_t    = "Track Record"
useStats = input.bool(true, "Track the plan's past results", group=grp_t, display=display.none, tooltip="Follows every past plan on the loaded chart history, bar by bar, and reports how it played out. Results depend on how much history is loaded.")
statsN   = input.int(30, "Plans per direction to count", minval=5, maxval=200, group=grp_t, display=display.none, active=useStats, tooltip="How many of the most recent bearish and bullish plans are included. Simulated trades keep the last 2x this number.")
zoneChoice = input.string("0.5 – 0.618", "Buy / sell zone", options=["0.5 – 0.618", "0.618 – 0.786", "0.382 – 0.618"], group=grp_t, display=display.none, tooltip="Which Fibonacci retracement band is the zone. Compare the track record for each to see which suits the market and timeframe.")
rejBody  = input.float(50, "Rejection candle: body at least % of its range", minval=0, maxval=100, step=5, group=grp_t, display=display.none, tooltip="Filters out weak, indecisive candles. 0 = any candle closing back out of the zone counts.") / 100
rejBars  = input.int(24, "Rejection must come within N bars of entering the zone", minval=1, maxval=500, group=grp_t, display=display.none, tooltip="Chart bars. A close back out of the zone much later is no longer treated as a reaction to it.")
exportTr = input.bool(false, "Export simulated trades to chart data", group=grp_t, display=display.none, tooltip="Writes each simulated trade's result (in R) and its conditions to the Data Window and Export chart data, on the bar where the trade closed. Nothing is drawn on the chart.")
tgtGap   = input.float(0.3, "Minimum target distance (x ATR)", minval=0.0, maxval=2.0, step=0.05, group=grp_t, display=display.none, tooltip="How far beyond the entry area Target 1 must be, and how far apart targets must be (main-timeframe ATR). Lower = closer targets, higher win rate, smaller wins. Higher = the opposite. Compare the win rate AND average R in the track record.")
tgtCapAdr = input.float(1.0, "Max target distance (x average daily range)", minval=0.0, maxval=5.0, step=0.25, group=grp_t, display=display.none, tooltip="Targets further than this from the entry area are not used as plan targets. The nearest one beyond it is shown separately as a 'larger target'. 0 = no limit.")
showTrack  = input.bool(false, "Show past results in the panel", group=grp_t, display=display.none, tooltip="Shows how past plans on the loaded chart history played out (win rate and average R). Results exclude spread, slippage and news, and are for testing settings, not a forecast.")
t1Cap      = input.float(1.0, "Quick target: at most x the risk (R)", minval=0.0, maxval=3.0, step=0.25, group=grp_t, display=display.none, tooltip="Target 1 is the nearest level OR this multiple of the risk (entry to stop), whichever is closer. 1.0 = a 1:1 quick target. 0 = off (nearest level only). Closer = higher win rate, smaller wins.")
strictConf = input.bool(true, "Strict confirmation", group=grp_t, display=display.none, tooltip="The rejection candle must also close beyond the previous candle's low (sell) or high (buy). Filters out weak rejections.")
statsRange = input.bool(false, "Include sideways setups in the track record", group=grp_t, display=display.none, tooltip="Sideways markets get a 'leaning' setup. Turn this off to judge only setups taken in a clear trend.")
stopBuf  = input.float(0.1, "Stop buffer beyond zone / wick (x ATR)", minval=0.0, maxval=2.0, step=0.05, group=grp_t, display=display.none, tooltip="Simulated stop = the zone's far edge or the highest / lowest price since entering the zone, whichever is further, plus this buffer (main-timeframe ATR).")

grp_m     = "Outside Markets & Conditions"
useUsd    = input.bool(true, "Dollar check", group=grp_m, display=display.none, tooltip="Gold usually moves opposite to the US Dollar. A rising dollar supports sell plans; a falling dollar supports buy plans.")
usdSym    = input.symbol("TVC:DXY", "Dollar symbol", group=grp_m, display=display.none, active=useUsd)
useYld    = input.bool(true, "Yield check", group=grp_m, display=display.none, tooltip="Rising US yields usually weigh on gold. Rising yields support sell plans; falling yields support buy plans.")
yldSym    = input.symbol("TVC:US10Y", "Yield symbol", group=grp_m, display=display.none, active=useYld)
imLen     = input.int(50, "Trend length for dollar / yields (EMA, main timeframe)", minval=10, maxval=200, group=grp_m, display=display.none, tooltip="Above its EMA = rising, below = falling. Uses completed main-timeframe bars only.")
volRegLen = input.int(100, "Volatility baseline (chart bars)", minval=20, maxval=500, group=grp_m, display=display.none, tooltip="Current ATR is compared with its average over this many bars.")
hiVolThr  = input.float(1.3, "High volatility = ATR at least x normal", minval=1.0, maxval=3.0, step=0.1, group=grp_m, display=display.none)

grp_n     = "News (enter each day)"
newsWin   = input.int(30, "Avoid trades within N minutes of news", minval=5, maxval=240, group=grp_n, display=display.none, tooltip="Pine Script can't read the economic calendar. Each morning, check a calendar (e.g. ForexFactory) and enter today's high-impact USD events below.")
news1     = input.time(0, "News 1 (date and time)", group=grp_n, display=display.none, tooltip="Click to pick the date and time of a high-impact event. Leave at the default (1970) for none.")
news2     = input.time(0, "News 2 (date and time)", group=grp_n, display=display.none)
news3     = input.time(0, "News 3 (date and time)", group=grp_n, display=display.none)
newsTz    = input.string("UTC", "Show news times in", options=["Australia/Sydney", "Australia/Melbourne", "Asia/Tokyo", "Asia/Singapore", "Europe/London", "America/New_York", "UTC"], group=grp_n, display=display.none)

grp_d     = "Display"
panelMode = input.string("Simple", "Panel detail", options=["Simple", "Compact", "Full"], group=grp_d, display=display.none, tooltip="Simple: the plan in plain language with a status line. Best for newer traders.\nCompact: short technical summary.\nFull: every factor, the evidence and the track record.")
chartStyle = input.string("Simple", "Chart drawings", options=["Simple", "All levels"], group=grp_d, display=display.none, tooltip="Simple: only the buy / sell zone, the targets, the cancel level and the main path.\nAll levels: every Fibonacci, previous day / week, wick, liquidity and zone level.")
showPlan  = input.bool(true, "Show analysis panel", group=grp_d, display=display.none, tooltip="The written analysis and plan.")
planPos   = input.string("Bottom Right", "Panel position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=grp_d, display=display.none, active=showPlan, tooltip="Where the panel sits on the chart.")
planSize  = input.string("Small", "Panel text size", options=["Tiny", "Small", "Normal"], group=grp_d, display=display.none, active=showPlan, tooltip="Smaller text keeps more of the chart visible.")
showFib   = input.bool(true, "Fibonacci levels", group=grp_d, display=display.none, tooltip="0.382, 0.5 and 0.618 of the last main-timeframe swing.")
showPrev  = input.bool(true, "Previous day / week high and low", group=grp_d, display=display.none, tooltip="Yesterday's and last week's high and low.")
lineExt   = input.int(25, "Line length (bars to the right)", minval=5, maxval=200, group=grp_d, display=display.none, tooltip="How far level lines extend to the right of the last candle. Labels sit at the end.")
lineW     = input.int(2, "Level line width", minval=1, maxval=4, group=grp_d, display=display.none, tooltip="Thicker lines are easier to see.")
labSizeS  = input.string("Normal", "Level label size", options=["Small", "Normal", "Large"], group=grp_d, display=display.none, tooltip="Size of the price labels at the end of each level.")
labBg     = input.bool(true, "Shaded background behind level labels", group=grp_d, display=display.none, tooltip="Makes labels easier to read over candles.")
mergeTol  = input.float(0.25, "Combine labels closer than (x ATR)", minval=0.0, maxval=1.0, step=0.01, group=grp_d, display=display.none, tooltip="Levels this close together share one label so text never overlaps. Raise it if labels overlap when zoomed out.")

grp_p     = "Projected Paths"
showPath  = input.bool(true, "Draw main scenario path", group=grp_p, display=display.none, tooltip="A zigzag from the current price through the plan's zone to its targets. A picture of the plan, not a forecast.")
showAlt   = input.bool(true, "Draw alternative path (dashed)", group=grp_p, display=display.none, tooltip="The path if there is no corrective move first. In a range, shows both breakout paths.")
paceMult  = input.float(1.0, "Path pacing", minval=0.3, maxval=3.0, step=0.1, group=grp_p, display=display.none, tooltip="Each step of the path is drawn over a number of bars based on its size compared with the chart's ATR. Higher = wider in time. Timing is illustrative, not a forecast.")
nearLen   = input.int(3, "Near-term swing strength (chart bars)", minval=2, maxval=10, group=grp_p, display=display.none, tooltip="Recent chart-timeframe swings are used as stepping stones for the short-term route.")
stonesN   = input.int(2, "Stepping stones per step", minval=0, maxval=4, group=grp_p, display=display.none, tooltip="Maximum recent swing levels the path pauses at on the way to each destination. 0 = straight to each level.")
stoneGap  = input.float(1.5, "Minimum step size (x chart ATR)", minval=0.5, maxval=5.0, step=0.25, group=grp_p, display=display.none, tooltip="Stepping stones closer than this to each other are skipped, so the path doesn't zigzag on noise.")
preMax    = input.float(2.5, "Max short-term counter-move (x chart ATR)", minval=0.0, maxval=6.0, step=0.25, group=grp_p, display=display.none, tooltip="When the chart's own short-term trend points the other way, the path first shows a small move to the nearest recent swing within this distance. 0 = off.")
pathAuto  = input.bool(true, "Main path colour follows chart theme", group=grp_p, display=display.none, tooltip="Black on a light chart, white on a dark chart. Turn off to pick a colour.")
colPathIn = input.color(#2563EB, "Main path (if not auto)", inline="pc", group=grp_p, display=display.none)
colAlt    = input.color(#F97316, "Alternative", inline="pc", group=grp_p, display=display.none)
routeStyle = input.string("Solid", "Route style", options=["Solid", "Solid near-term, dashed beyond"], group=grp_p, display=display.none, tooltip="Solid: the whole route is one line. The second option draws the move to the first destination solid and the rest dashed.")
extOnChart = input.bool(false, "Show larger target on the chart", group=grp_p, display=display.none, tooltip="The larger target (beyond the target distance limit) is always listed in the panel. Turning this on also draws it and extends the route to it, which can stretch the chart's price scale.")
pathW     = input.int(3, "Main path width", minval=1, maxval=5, group=grp_p, display=display.none, tooltip="Line thickness of the main path. The alternative is one step thinner.")

grp_al     = "Alerts (create one alert with: Any alert() function call)"
alZone     = input.bool(true, "Price enters the buy / sell zone", group=grp_al, display=display.none, tooltip="Fires once when a candle closes inside the zone.")
alReject   = input.bool(true, "Rejection confirmed", group=grp_al, display=display.none, tooltip="After visiting the zone, a candle closes back out of it in the direction of the bias. This is the plan's confirmation condition.")
alTarget   = input.bool(true, "First target reached", group=grp_al, display=display.none, tooltip="Price reaches the swing low (bearish plan) or swing high (bullish plan).")
alInvalid  = input.bool(true, "Structure invalidated", group=grp_al, display=display.none, tooltip="A main-timeframe close beyond the invalidation level.")
alBias     = input.bool(false, "Bias changes", group=grp_al, display=display.none, tooltip="The main-timeframe bias switches between bullish, bearish and neutral.")
alSweep    = input.bool(false, "Liquidity sweep near the zone", group=grp_al, display=display.none, tooltip="A sweep happens at or inside the buy / sell zone: often the first sign of a rejection.")

grp_x2     = "Extra Visuals"
showStruct = input.bool(true, "Structure breaks (BOS / CHoCH)", group=grp_x2, display=display.none, tooltip="Marks where a closed candle breaks the last chart-timeframe swing high or low. BOS = break in the direction of the current structure (continuation). CHoCH = change of character, the first break against it (possible turn).")
structKeep = input.int(6, "Structure breaks kept on chart", minval=1, maxval=30, group=grp_x2, display=display.none, active=showStruct)
showFvg    = input.bool(true, "Fair value gaps (unfilled)", group=grp_x2, display=display.none, tooltip="Three-candle price gaps on the chart timeframe that price hasn't traded back through yet. Removed once filled.")
fvgMin     = input.float(0.3, "Minimum gap size (x chart ATR)", minval=0.05, maxval=2.0, step=0.05, group=grp_x2, display=display.none, active=showFvg, tooltip="Smaller gaps are ignored.")
fvgKeep    = input.int(3, "Gaps kept per side", minval=1, maxval=10, group=grp_x2, display=display.none, active=showFvg)
showPDB    = input.bool(true, "Premium / discount bands", group=grp_x2, display=display.none, tooltip="Shades the top quarter (premium: better for sells) and bottom quarter (discount: better for buys) of the main-timeframe range.")
showPrevS  = input.bool(true, "Previous day high / low on the Simple chart", group=grp_x2, display=display.none)
colorBars  = input.bool(false, "Colour candles by short-term structure", group=grp_x2, display=display.none)
alStruct   = input.bool(false, "Alert on structure breaks", group=grp_x2, display=display.none)

grp_c   = "Colours"
colBull = input.color(#16A34A, "Bullish", inline="c1", group=grp_c, display=display.none)
colBear = input.color(#DC2626, "Bearish", inline="c1", group=grp_c, display=display.none)
colFib  = input.color(#B8860B, "Fibonacci", inline="c1", group=grp_c, display=display.none)
colPrev = input.color(#475569, "Prev day / week", inline="c2", group=grp_c, display=display.none)
colWick = input.color(#7C3AED, "Wicks", inline="c2", group=grp_c, display=display.none)
colLiq  = input.color(#0284C7, "Liquidity", inline="c2", group=grp_c, display=display.none)

f_autoTfs() =>
    int  s  = timeframe.in_seconds()
    bool st = horizon == "Short-term"
    string c = "D"
    string m = "240"
    string t = "60"
    if st
        if s <= 60
            c := "15"
            m := "5"
            t := "1"
        else if s <= 300
            c := "60"
            m := "15"
            t := timeframe.period
        else if s <= 1800
            c := "240"
            m := "60"
            t := timeframe.period
        else if s <= 3600
            c := "D"
            m := "240"
            t := "60"
        else if s <= 14400
            c := "W"
            m := "D"
            t := "240"
        else
            c := "M"
            m := "W"
            t := "D"
    else
        if s <= 180
            c := "60"
            m := "15"
            t := "5"
        else if s <= 300
            c := "240"
            m := "60"
            t := "15"
        else if s <= 1800
            c := "D"
            m := "240"
            t := "60"
        else if s <= 3600
            c := "W"
            m := "D"
            t := "240"
        else
            c := "M"
            m := "W"
            t := "D"
    [c, m, t]

[autoHi, autoMain, autoLo] = f_autoTfs()
string htf  = useAuto ? autoMain : htfIn
string hiTf = useAuto ? autoHi : hiTfIn
string loTf = useAuto ? autoLo : loTfIn

f_struct(int len) =>
    float ph = ta.pivothigh(high, len, len)
    float pl = ta.pivotlow(low, len, len)
    var float h1 = na
    var float h2 = na
    var float l1 = na
    var float l2 = na
    var int   hT = na
    var int   lT = na

    var float loSinceH = na
    var float hiSinceL = na
    float lowAfter  = ta.lowest(low, len)
    float highAfter = ta.highest(high, len)
    loSinceH := na(loSinceH) ? low : math.min(loSinceH, low)
    hiSinceL := na(hiSinceL) ? high : math.max(hiSinceL, high)
    if not na(ph)
        h2 := h1
        h1 := ph
        hT := time[len]
        loSinceH := lowAfter
    if not na(pl)
        l2 := l1
        l1 := pl
        lT := time[len]
        hiSinceL := highAfter
    float atr = ta.atr(14)
    float rsi = ta.rsi(close, 14)
    [h1[1], h2[1], l1[1], l2[1], hT[1], lT[1], close[1], atr[1], rsi[1], loSinceH[1], hiSinceL[1]]

f_wicks(float minPct) =>
    float rng = high - low
    float upW = high - math.max(open, close)
    float dnW = math.min(open, close) - low
    var float uTop = na
    var float uBot = na
    var float lTop = na
    var float lBot = na
    if not na(uTop) and high >= uTop
        uTop := na
        uBot := na
    if not na(lBot) and low <= lBot
        lTop := na
        lBot := na
    if rng > 0 and upW / rng >= minPct
        uTop := high
        uBot := math.max(open, close)
    if rng > 0 and dnW / rng >= minPct
        lTop := math.min(open, close)
        lBot := low
    [uTop[1], uBot[1], lTop[1], lBot[1]]

f_zones(int len, int memory, float tolMult, int minN) =>
    float ph = ta.pivothigh(high, len, len)
    float pl = ta.pivotlow(low, len, len)
    var float[] piv = array.new<float>()
    if not na(ph)
        piv.unshift(ph)
    if not na(pl)
        piv.unshift(pl)
    while piv.size() > memory
        piv.pop()
    float tol    = ta.atr(14) * tolMult
    float resLvl = na
    int   resN   = 0
    float supLvl = na
    int   supN   = 0
    int   sz     = piv.size()
    if sz > 0 and not na(tol)
        for i = 0 to sz - 1
            float p   = piv.get(i)
            int   n   = 0
            float sum = 0.0
            for j = 0 to sz - 1
                float q = piv.get(j)
                if math.abs(q - p) <= tol
                    n   += 1
                    sum += q
            if n >= minN
                float lvl = sum / n
                if lvl > close and (na(resLvl) or lvl < resLvl)
                    resLvl := lvl
                    resN   := n
                else if lvl < close and (na(supLvl) or lvl > supLvl)
                    supLvl := lvl
                    supN   := n
    [resLvl[1], resN[1], supLvl[1], supN[1], tol[1]]

[h1, h2, l1, l2, hT, lT, htfClose, htfAtr, htfRsi, legLo, legHi] = request.security(syminfo.tickerid, htf, f_struct(pivLen), lookahead=barmerge.lookahead_on)
[dh1, dh2, dl1, dl2, dhT, dlT, dClose, dAtr, dRsi, dLegLo, dLegHi] = request.security(syminfo.tickerid, hiTf, f_struct(pivLen), lookahead=barmerge.lookahead_on)
[th1, th2, tl1, tl2, thT, tlT, tClose, tAtr, tRsi, tLegLo, tLegHi] = request.security(syminfo.tickerid, loTf, f_struct(pivLen), lookahead=barmerge.lookahead_on)
[rHiTop, rHiBot, rLoTop, rLoBot] = request.security(syminfo.tickerid, htf, f_wicks(wickPct), lookahead=barmerge.lookahead_on)
[rRes, rResN, rSup, rSupN, rZTol] = request.security(syminfo.tickerid, zoneSrc == "Timing timeframe" ? loTf : htf, f_zones(pivLen, zoneMemory, zoneTol, minTouches), lookahead=barmerge.lookahead_on)
[rngHi, rngLo] = request.security(syminfo.tickerid, htf, [ta.highest(high, pdLen)[1], ta.lowest(low, pdLen)[1]], lookahead=barmerge.lookahead_on)

[pdh, pdl] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead=barmerge.lookahead_on)
[pwh, pwl] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead=barmerge.lookahead_on)
float adr = request.security(syminfo.tickerid, "D", ta.sma(high - low, adrLen)[1], lookahead=barmerge.lookahead_on)
[tdHigh, tdLow] = request.security(syminfo.tickerid, "D", [high, low], lookahead=barmerge.lookahead_off)

f_bias(float a1, float a2, float b1, float b2, float c) =>
    int b = na(a2) or na(b2) ? 0 : a1 < a2 and b1 < b2 ? -1 : a1 > a2 and b1 > b2 ? 1 : 0
    b == -1 and c > a1 ? 0 : b == 1 and c < b1 ? 0 : b

int  rawBias    = na(h2) or na(l2) ? 0 : h1 < h2 and l1 < l2 ? -1 : h1 > h2 and l1 > l2 ? 1 : 0
bool bearBroken = rawBias == -1 and htfClose > h1
bool bullBroken = rawBias == 1 and htfClose < l1
int  structBias = bearBroken or bullBroken ? 0 : rawBias
int  hiBias     = f_bias(dh1, dh2, dl1, dl2, dClose)
int  loBias     = f_bias(th1, th2, tl1, tl2, tClose)

float leanPos   = not na(rngHi) and not na(rngLo) and rngHi > rngLo ? (close - rngLo) / (rngHi - rngLo) : 0.5
bool  legDown   = nz(lT) > nz(hT)
int   rsiVote   = na(htfRsi) ? 0 : htfRsi >= 55 ? 1 : htfRsi <= 45 ? -1 : 0
int   posVote   = leanPos >= 0.7 ? -1 : leanPos <= 0.3 ? 1 : 0
int   brkVote   = bearBroken ? 1 : bullBroken ? -1 : 0
int   leanScore = 2 * hiBias + loBias + (legDown ? -1 : 1) + rsiVote + posVote + brkVote
int   lean      = leanScore > 0 ? 1 : leanScore < 0 ? -1 : (leanPos >= 0.5 ? -1 : 1)
bool  isRange   = structBias == 0
int   bias      = isRange ? lean : structBias
string leanWhy  = ""
if isRange
    leanWhy := (hiBias == lean ? "higher timeframe trend, " : "") + (loBias == lean ? "lower timeframe trend, " : "") + ((legDown ? -1 : 1) == lean ? "last swing, " : "") + (rsiVote == lean ? "momentum, " : "") + (posVote == lean ? "position in the range, " : "") + (brkVote == lean ? "broken structure, " : "")
    leanWhy := str.length(leanWhy) > 2 ? str.substring(leanWhy, 0, str.length(leanWhy) - 2) : "position in the range"
string leanStrength = math.abs(leanScore) >= 3 ? "clearly" : "slightly"

bool  lastLegDown = nz(lT) > nz(hT)
bool  fibFromLow  = bias == -1 or (bias == 0 and lastLegDown)

float fibHi       = fibFromLow ? h1 : math.max(nz(legHi, h1), l1)
float fibLo       = fibFromLow ? math.min(nz(legLo, l1), h1) : l1
float swingRange  = fibHi - fibLo

f_fib(float f) =>
    fibFromLow ? fibLo + swingRange * f : fibHi - swingRange * f

float fib382 = f_fib(0.382)
float fib50  = f_fib(0.5)
float fib618 = f_fib(0.618)
float fib786 = f_fib(0.786)
float zInR   = zoneChoice == "0.618 – 0.786" ? 0.618 : zoneChoice == "0.382 – 0.618" ? 0.382 : 0.5
float zOutR  = zoneChoice == "0.618 – 0.786" ? 0.786 : 0.618
float zIn    = f_fib(zInR)    // zone edge nearest the current swing extreme's opposite (entered first)
float zOut   = f_fib(zOutR)   // far edge of the zone

float wHiTop = useWicks ? rHiTop : na
float wHiBot = useWicks ? rHiBot : na
float wLoTop = useWicks ? rLoTop : na
float wLoBot = useWicks ? rLoBot : na

bool  eqHighs = useLiq and not na(h2) and not na(htfAtr) and math.abs(h1 - h2) <= htfAtr * eqTol
bool  eqLows  = useLiq and not na(l2) and not na(htfAtr) and math.abs(l1 - l2) <= htfAtr * eqTol
float eqHiLvl = eqHighs ? math.max(h1, h2) : na
float eqLoLvl = eqLows ? math.min(l1, l2) : na

float zRes  = useZones ? rRes : na
float zSup  = useZones ? rSup : na
int   zResN = nz(rResN)
int   zSupN = nz(rSupN)

bool  pdOk  = usePD and not na(rngHi) and not na(rngLo) and rngHi > rngLo
float pdPos = pdOk ? (close - rngLo) / (rngHi - rngLo) : na
float pdEq  = pdOk ? (rngHi + rngLo) / 2 : na

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

f_tfName(string tf) =>
    int s = timeframe.in_seconds(tf)
    s >= 2419200 ? "M" : s >= 604800 ? "W" : s >= 86400 ? "D" : s >= 3600 ? str.tostring(int(s / 3600)) + "H" : str.tostring(int(s / 60)) + "m"

f_bname(int b) =>
    b == 1 ? "bullish" : b == -1 ? "bearish" : "neutral"

string tfName = f_tfName(htf)
string chartTfName = f_tfName(timeframe.period)

float nAtr = ta.atr(14)
float nPh  = ta.pivothigh(high, nearLen, nearLen)
float nPl  = ta.pivotlow(low, nearLen, nearLen)
var float[] nLvls = array.new<float>()
var float nH1 = na
var float nH2 = na
var float nL1 = na
var float nL2 = na
var int   nH1Bar = na
var int   nL1Bar = na
var bool  nHiBrk = false
var bool  nLoBrk = false
if not na(nPh)
    nLvls.unshift(nPh)
    nH2 := nH1
    nH1 := nPh
    nH1Bar := bar_index - nearLen
    nHiBrk := false
if not na(nPl)
    nLvls.unshift(nPl)
    nL2 := nL1
    nL1 := nPl
    nL1Bar := bar_index - nearLen
    nLoBrk := false
while nLvls.size() > 60
    nLvls.pop()
float nEmaF = ta.ema(close, 9)
float nEmaS = ta.ema(close, 21)
bool  nStructOk = not na(nH2) and not na(nL2)
int   nearDir = nStructOk and nH1 > nH2 and nL1 > nL2 ? 1 : nStructOk and nH1 < nH2 and nL1 < nL2 ? -1 : nEmaF >= nEmaS ? 1 : -1

var int     sTrend   = 0
var line[]  sLines   = array.new<line>()
var label[] sLabels  = array.new<label>()
bool brkUp = barstate.isconfirmed and not na(nH1) and not nHiBrk and close > nH1
bool brkDn = barstate.isconfirmed and not na(nL1) and not nLoBrk and close < nL1
string brkTag = ""
if brkUp
    brkTag := sTrend == -1 ? "CHoCH" : "BOS"
    nHiBrk := true
    if showStruct
        sLines.push(line.new(nH1Bar, nH1, bar_index, nH1, color=color.new(#16A34A, 20), style=line.style_dashed, width=1))
        sLabels.push(label.new(int((nH1Bar + bar_index) / 2), nH1, brkTag, style=label.style_label_down, color=color(na), textcolor=#16A34A, size=size.small))
    sTrend := 1
if brkDn
    brkTag := sTrend == 1 ? "CHoCH" : "BOS"
    nLoBrk := true
    if showStruct
        sLines.push(line.new(nL1Bar, nL1, bar_index, nL1, color=color.new(#DC2626, 20), style=line.style_dashed, width=1))
        sLabels.push(label.new(int((nL1Bar + bar_index) / 2), nL1, brkTag, style=label.style_label_up, color=color(na), textcolor=#DC2626, size=size.small))
    sTrend := -1
while sLines.size() > structKeep
    line.delete(sLines.shift())
while sLabels.size() > structKeep
    label.delete(sLabels.shift())
if alStruct and (brkUp or brkDn)
    alert(syminfo.ticker + " (" + chartTfName + "): " + brkTag + " " + (brkUp ? "up, broke " + str.tostring(nH1, format.mintick) : "down, broke " + str.tostring(nL1, format.mintick)), alert.freq_once_per_bar_close)
barcolor(colorBars ? (sTrend == 1 ? #16A34A : sTrend == -1 ? #DC2626 : na) : na, title="Structure candle colour")

var box[]   fvgBx  = array.new<box>()
var float[] fvgTop = array.new<float>()
var float[] fvgBot = array.new<float>()
var int[]   fvgDir = array.new<int>()
if showFvg and barstate.isconfirmed and not na(nAtr)
    if low > high[2] and low - high[2] >= nAtr * fvgMin
        fvgBx.push(box.new(bar_index - 2, low, bar_index + 3, high[2], border_color=color.new(#16A34A, 75), bgcolor=color.new(#16A34A, 88), text="FVG", text_size=size.tiny, text_color=color.new(#16A34A, 30), text_halign=text.align_right))
        fvgTop.push(low)
        fvgBot.push(high[2])
        fvgDir.push(1)
    if high < low[2] and low[2] - high >= nAtr * fvgMin
        fvgBx.push(box.new(bar_index - 2, low[2], bar_index + 3, high, border_color=color.new(#DC2626, 75), bgcolor=color.new(#DC2626, 88), text="FVG", text_size=size.tiny, text_color=color.new(#DC2626, 30), text_halign=text.align_right))
        fvgTop.push(low[2])
        fvgBot.push(high)
        fvgDir.push(-1)
if fvgBx.size() > 0
    for i = fvgBx.size() - 1 to 0
        bool filled = fvgDir.get(i) == 1 ? low <= fvgBot.get(i) : high >= fvgTop.get(i)
        if filled
            box.delete(fvgBx.get(i))
            fvgBx.remove(i)
            fvgTop.remove(i)
            fvgBot.remove(i)
            fvgDir.remove(i)
        else
            box.set_right(fvgBx.get(i), bar_index + 3)

int nUpG = 0
int nDnG = 0
if fvgBx.size() > 0
    for i = fvgBx.size() - 1 to 0
        int d = fvgDir.get(i)
        bool drop = false
        if d == 1
            nUpG += 1
            drop := nUpG > fvgKeep
        else
            nDnG += 1
            drop := nDnG > fvgKeep
        if drop
            box.delete(fvgBx.get(i))
            fvgBx.remove(i)
            fvgTop.remove(i)
            fvgBot.remove(i)
            fvgDir.remove(i)
string tfHi   = f_tfName(hiTf)
string tfLo   = f_tfName(loTf)
string zoneTfName = zoneSrc == "Timing timeframe" ? tfLo : tfName

f_conf(float lvl) =>
    string out = ""
    if useConf and not na(lvl) and not na(htfAtr)
        float tol = htfAtr * confTol
        float[]  vals  = array.from(pdh, pdl, pwh, pwl, wHiTop, wHiBot, wLoTop, wLoBot, eqHiLvl, eqLoLvl, zRes, zSup)
        string[] names = array.from("prev day high", "prev day low", "prev week high", "prev week low", "unfilled wick", "unfilled wick", "unfilled wick", "unfilled wick", "equal highs", "equal lows", "resistance zone", "support zone")
        for i = 0 to vals.size() - 1
            float v = vals.get(i)
            string nm = names.get(i)
            if not na(v) and math.abs(v - lvl) <= tol and not str.contains(out, nm)
                out += (out == "" ? "" : ", ") + nm
    out

f_confRange(float lo, float hi) =>
    string out = ""
    if useConf and not na(lo) and not na(hi) and not na(htfAtr)
        float tol = htfAtr * confTol
        float[]  vals  = array.from(pdh, pdl, pwh, pwl, wHiTop, wHiBot, wLoTop, wLoBot, eqHiLvl, eqLoLvl, zRes, zSup)
        string[] names = array.from("prev day high", "prev day low", "prev week high", "prev week low", "unfilled wick", "unfilled wick", "unfilled wick", "unfilled wick", "equal highs", "equal lows", "resistance zone", "support zone")
        for i = 0 to vals.size() - 1
            float v = vals.get(i)
            string nm = names.get(i)
            if not na(v) and v >= lo - tol and v <= hi + tol and not str.contains(out, nm)
                out += (out == "" ? "" : ", ") + nm
    out

f_join(string a, string b) =>
    a == "" ? b : b == "" or str.contains(a, b) ? a : a + ", " + b

f_pick(int dir, float ref = na) =>
    float r0 = na(ref) ? close : ref
    float capD = tgtCapAdr > 0 and not na(adr) ? adr * tgtCapAdr : na
    float[]  vals  = dir == -1 ? array.from(l1, pdl, pwl, eqLoLvl, wLoBot, zSup) : array.from(h1, pdh, pwh, eqHiLvl, wHiTop, zRes)
    string[] names = dir == -1 ? array.from("swing low", "prev day low", "prev week low", "equal lows", "wick low", "support zone") : array.from("swing high", "prev day high", "prev week high", "equal highs", "wick high", "resistance zone")
    bool[]   used   = array.new<bool>(vals.size(), false)
    float[]  picked = array.new<float>()
    string[] pickedNames = array.new<string>()
    float    minGap = math.max(nz(htfAtr, 0) * tgtGap, syminfo.mintick * 10)
    for k = 0 to 2
        int   best     = -1
        float bestDist = na
        for i = 0 to vals.size() - 1
            float v = vals.get(i)
            if not used.get(i) and not na(v) and (dir == -1 ? v < r0 - minGap : v > r0 + minGap) and (na(capD) or math.abs(v - r0) <= capD)
                bool nearPicked = false
                for pv in picked
                    if math.abs(pv - v) <= minGap
                        nearPicked := true
                if nearPicked
                    used.set(i, true)
                else
                    float d = math.abs(v - r0)
                    if best == -1 or d < bestDist
                        best     := i
                        bestDist := d
        if best >= 0
            used.set(best, true)
            picked.push(vals.get(best))
            pickedNames.push(names.get(best))
    [picked, pickedNames]

f_extended(int dir, float ref) =>
    float r0   = na(ref) ? close : ref
    float capD = tgtCapAdr > 0 and not na(adr) ? adr * tgtCapAdr : na
    float best = na
    if not na(capD) and dir != 0
        float[] vals = dir == -1 ? array.from(l1, pdl, pwl, eqLoLvl, wLoBot, zSup) : array.from(h1, pdh, pwh, eqHiLvl, wHiTop, zRes)
        for v in vals
            if not na(v) and math.abs(v - r0) > capD and (dir == -1 ? v < r0 : v > r0)
                if na(best) or math.abs(v - r0) < math.abs(best - r0)
                    best := v
    best

f_targets(int dir, float ref = na) =>
    [pv, pn] = f_pick(dir, ref)
    string out = ""
    if pv.size() > 0
        for i = 0 to pv.size() - 1
            out += (i > 0 ? " → " : "") + f_p(pv.get(i)) + " (" + pn.get(i) + ")"
    pv.size() == 0 ? "no clear level yet, manage the trade manually" : out

f_location() =>
    string out = ""
    if pdOk
        string nm = pdPos >= 0.75 ? "premium (top quarter)" : pdPos >= 0.55 ? "upper half" : pdPos > 0.45 ? "equilibrium (middle)" : pdPos > 0.25 ? "lower half" : "discount (bottom quarter)"
        string rd = bias == -1 ? (pdPos >= 0.55 ? "Good location for sells." : pdPos > 0.25 ? "Weaker location for sells." : "Selling here is late; better to wait for a rally.") : bias == 1 ? (pdPos <= 0.45 ? "Good location for buys." : pdPos < 0.75 ? "Weaker location for buys." : "Buying here is late; better to wait for a pullback.") : (pdPos >= 0.75 ? "Near the top of the range." : pdPos <= 0.25 ? "Near the bottom of the range." : "Middle of the range: avoid.")
        out := "Location: " + str.tostring(math.max(math.min(pdPos, 1.0), 0.0) * 100, "#") + "% of the " + tfName + " range (" + f_p(rngLo) + " to " + f_p(rngHi) + "), " + nm + ". " + rd
    out

float zoneLo = math.min(zIn, zOut)
float zoneHi = math.max(zIn, zOut)

float estEntry = bias == -1 ? zoneLo : zoneHi
float estStop  = bias == -1 ? zoneHi + nz(htfAtr) * stopBuf : zoneLo - nz(htfAtr) * stopBuf
float estT1    = t1Cap > 0 and not na(estEntry) and bias != 0 ? estEntry + bias * math.abs(estStop - estEntry) * t1Cap : na
string estTxt  = na(estT1) ? "" : "quick " + f_p(estT1) + " (" + str.tostring(t1Cap, "#.##") + "R), then "

float refDn  = na(zoneLo) ? close : math.min(close, zoneLo)
float refUp  = na(zoneHi) ? close : math.max(close, zoneHi)
bool  inZone = bias != 0 and not na(zoneLo) and close >= zoneLo and close <= zoneHi

var bool  visited    = false
var int   visitBar   = na
var bool  zoneFailed = false
var bool  rejDone    = false
var float extSince   = na
if bias != nz(bias[1]) or zoneLo != zoneLo[1]
    visited    := false
    visitBar   := na
    zoneFailed := false
    rejDone    := false
    extSince   := na
bool zoneEntered = inZone and not visited and not zoneFailed
if inZone and not visited
    visited  := true
    visitBar := bar_index
if visited
    extSince := bias == -1 ? math.max(nz(extSince, high), high) : bias == 1 ? math.min(nz(extSince, low), low) : extSince

if visited and (bias == -1 ? close > zoneHi : bias == 1 ? close < zoneLo : false)
    zoneFailed := true
float candleRng  = high - low
bool  strongBody = candleRng > 0 and math.abs(close - open) >= candleRng * rejBody
bool  inWindow   = visited and not na(visitBar) and bar_index - visitBar <= rejBars
bool  strongClose = not strictConf or (bias == -1 ? close < low[1] : close > high[1])
bool  rejected   = not rejDone and not zoneFailed and inWindow and strongBody and strongClose and (bias == -1 ? close < zoneLo and close < open : bias == 1 ? close > zoneHi and close > open : false)
if rejected
    rejDone := true
bool tgtHit   = bias == -1 ? low <= l1 and low[1] > l1 : bias == 1 ? high >= h1 and high[1] < h1 : false
bool invalid  = (bearBroken and not bearBroken[1]) or (bullBroken and not bullBroken[1])
bool biasChg  = bar_index > 0 and bias != bias[1]

[xVol, xVolAvg] = request.security(volSym, timeframe.period, [volume, ta.sma(volume, volLen)], ignore_invalid_symbol=true)
float cVolAvg   = ta.sma(volume, volLen)
float vNow      = volExt ? xVol : volume
float vAvg      = volExt ? xVolAvg : cVolAvg
float relVol    = useVol and not na(vNow) and not na(vAvg) and vAvg > 0 ? vNow / vAvg : na
bool  strongVol = not na(relVol) and relVol >= volThr

float cph = ta.pivothigh(high, sweepLen, sweepLen)
float cpl = ta.pivotlow(low, sweepLen, sweepLen)
var float locHi = na
var float locLo = na
if not na(cph)
    locHi := cph
if not na(cpl)
    locLo := cpl

f_swUp(float lvl) =>
    not na(lvl) and high > lvl and close < lvl

f_swDn(float lvl) =>
    not na(lvl) and low < lvl and close > lvl

string swUpName = ""
string swDnName = ""
if useSweep and barstate.isconfirmed
    swUpName := f_swUp(eqHiLvl) ? "equal highs" : f_swUp(pdh) ? "prev day high" : f_swUp(h1) ? "swing high (" + tfName + ")" : f_swUp(zRes) ? "resistance zone" : f_swUp(wHiTop) ? "wick high" : f_swUp(locHi) ? "local swing high" : ""
    swDnName := f_swDn(eqLoLvl) ? "equal lows" : f_swDn(pdl) ? "prev day low" : f_swDn(l1) ? "swing low (" + tfName + ")" : f_swDn(zSup) ? "support zone" : f_swDn(wLoBot) ? "wick low" : f_swDn(locLo) ? "local swing low" : ""
bool sweepUp = swUpName != ""
bool sweepDn = swDnName != ""
if sweepUp
    locHi := na
if sweepDn
    locLo := na

plotshape(showSweepMk and sweepUp, "Sweep of a high", shape.xcross, location.abovebar, colLiq, size=size.tiny, display=display.pane)
plotshape(showSweepMk and sweepDn, "Sweep of a low", shape.xcross, location.belowbar, colLiq, size=size.tiny, display=display.pane)

var int  planDir   = 0
var int  planId    = 0
var bool pReached  = false
var bool pSweep    = false
var bool pRejected = false
var bool pRejVol   = false
var bool pRejSweep = false
var bool pTarget   = false
var bool pStopped  = false
var int[]  sDir      = array.new<int>()
var bool[] sReached  = array.new<bool>()
var bool[] sRejected = array.new<bool>()
var bool[] sTarget   = array.new<bool>()
var bool[] sRejVol   = array.new<bool>()
var bool[] sRejSweep = array.new<bool>()

bool newPlan = bias != planDir or (bias != 0 and zoneLo != zoneLo[1])
if newPlan
    if useStats and planDir != 0
        sDir.push(planDir)
        sReached.push(pReached)
        sRejected.push(pRejected)
        while sDir.size() > statsN * 4
            sDir.shift()
            sReached.shift()
            sRejected.shift()
    planDir   := bias
    planId    += 1
    pReached  := false
    pSweep    := false
    pRejected := false
    pRejVol   := false
    pRejSweep := false
    pTarget   := false
    pStopped  := false

bool nearZone = planDir == -1 ? high >= zoneLo : planDir == 1 ? low <= zoneHi : false
if planDir != 0
    if inZone
        pReached := true
    if nearZone and (planDir == -1 ? sweepUp : sweepDn)
        pSweep := true
    if rejected and not pRejected
        pRejected := true
        pRejVol   := strongVol
        pRejSweep := pSweep

bool sweepAtZone = nearZone and (planDir == -1 ? sweepUp : planDir == 1 ? sweepDn : false)

int usdTrend = request.security(usdSym, htf, close[1] > ta.ema(close, imLen)[1] ? 1 : -1, lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
int yldTrend = request.security(yldSym, htf, close[1] > ta.ema(close, imLen)[1] ? 1 : -1, lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
int usdDir   = useUsd ? nz(usdTrend) : 0
int yldDir   = useYld ? nz(yldTrend) : 0

f_supports(int mktDir, int planD) =>
    mktDir != 0 and planD != 0 and mktDir == -planD

float atrC     = ta.atr(14)
float volRatio = atrC / ta.sma(atrC, volRegLen)
bool  hiVol    = not na(volRatio) and volRatio >= hiVolThr

f_validNews(int t) =>
    t > 946684800000

f_nearNews(int t) =>
    int w = newsWin * 60000
    (f_validNews(news1) and math.abs(t - news1) <= w) or (f_validNews(news2) and math.abs(t - news2) <= w) or (f_validNews(news3) and math.abs(t - news3) <= w)

bool newsBar = f_nearNews(time)
bgcolor(newsBar ? color.new(#F59E0B, 85) : na, title="News window")

bool inLdnNy = not na(time(timeframe.period, "0800-1700", "Europe/London")) or not na(time(timeframe.period, "0800-1700", "America/New_York"))

var bool  tActive = false
var int   tDir    = 0
var float tEntry  = na
var float tStop   = na
var float tTgt    = na
var int   tBar    = na
var bool  tfAlign = false
var bool  tfSweep = false
var bool  tfVol   = false
var bool  tfSess  = false
var bool  tfLoc   = false
var bool  tfUsd   = false
var bool  tfYld   = false
var bool  tfHiVol = false
var bool  tfNews  = false
var bool  tfRange = false
var float tfVolR  = na
var float tfRelV  = na
var int   tTime   = na
var int   tPlan   = na
var int   lastRes   = na
var int   lastDir   = 0
var float lastEntry = na
var float lastExit  = na
var float[] rR     = array.new<float>()
var bool[]  rAlign = array.new<bool>()
var bool[]  rSweep = array.new<bool>()
var bool[]  rVol   = array.new<bool>()
var bool[]  rSess  = array.new<bool>()
var bool[]  rLoc   = array.new<bool>()
var bool[]  rUsd   = array.new<bool>()
var bool[]  rYld   = array.new<bool>()
var bool[]  rHiVol = array.new<bool>()
var bool[]  rNews  = array.new<bool>()
var bool[]  rRange = array.new<bool>()

bool  tradeWin  = false
bool  tradeLoss = false
float closedR   = na
int   heldBars  = na
if tActive and bar_index > tBar
    bool hitS = tDir == -1 ? high >= tStop : low <= tStop
    bool hitT = t

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