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

RaidShift — Liquidity to FVG Reversal Engine

indicator raidshift - liquidity to fvg reversal engine for tradingview.pine
Вы автор или правообладатель?

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

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

О программе

RaidShift — индикатор для TradingView, который строит на графике последовательность «снятие ликвидности → смена структуры → возврат в Fair Value Gap» и отмечает возможные сценарии разворота. Индикатор рассчитывает технические показатели средствами Pine Script, запрашивает данные старшего таймфрейма и другого инструмента, а также задаёт условия для оповещений TradingView. Все расчёты и отрисовка выполняются на стороне клиента, ордера не выставляются.

В основе лежит поиск свинговых экстремумов и проверка, была ли снята ликвидность за таким уровнем. В зависимости от выбранного режима снятие определяется по отбою фитилём или по закрытию тела за уровнем. После снятия индикатор отслеживает смену рыночной структуры (CHoCH или BOS) и формирование Fair Value Gap. Дополнительно поддерживается сравнение с коррелированным символом для отметок SMT-дивергенции.

Пользователь может настроить параметры свингов, пороги снятия ликвидности в единицах ATR, режим структуры, условия входа и выхода, а также фильтры по тренду, зонам премиума/дисконта, сессиям и SMT. На графике отображаются уровни ликвидности, линии структуры, блоки FVG, уровни предыдущего дня, блок свечей старшего таймфрейма и информационная панель со статистикой сценариев. Индикатор формирует оповещения о снятии ликвидности, смене структуры, активации и срабатывании сценариев, достижении цели и стопа.

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

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

НастройкаОписание
swingPeriod Количество баров слева и справа для поиска свинговых точек.
maxScanBack Количество последних свинговых точек, проверяемых на снятие ликвидности на каждом баре.
showSweeps Отображать снятые уровни ликвидности.
showRaidLabels Отображать текст RAID / BREAK у снятий ликвидности.
sweepBuyCol Цвет уровней ликвидности со стороны покупателей.
sweepSelCol Цвет уровней ликвидности со стороны продавцов.
maxSweepDraw Максимальное количество снятий ликвидности, отображаемых на графике.
raidMode Событие у уровня ликвидности, которое активирует последовательность: отбой фитилём, закрытие тела за уровнем или оба варианта.
ctMinPen Минимальная глубина закрытия тела за уровнем в ATR для учёта снятия по закрытию. 0 — без ограничения.
ctInvBuf Дополнительный запас в ATR перед отменой сценария, открытого по закрытию тела за уровнем. Применяется только к таким сценариям.
raidMinPen Минимальная глубина прокола уровня фитилём в ATR для учёта снятия. 0 — без ограничения.
raidMinRej Минимальная глубина возврата закрытия внутрь уровня в ATR. 0 — без ограничения.
smtOn Включает проверку SMT-дивергенции с коррелированным символом.
smtSymbol Коррелированный символ для сравнения. Пустое значение отключает сравнение.
smtBullCol Цвет бычьих отметок SMT.
smtBearCol Цвет медвежьих отметок SMT.
smtLabels Отображать подписи SMT.
structMode Какая структура используется для сценариев: внутренняя или свинговая.
internalLen Длина внутренней структуры.
swingLen Длина свинговой структуры.
shiftRule Правило смены структуры для сценариев: привязка к свингу перед снятием или глобальная классификация CHoCH / BOS.
chochOnly Учитывать только CHoCH и игнорировать BOS. Применяется только к правилу Legacy CHoCH / BOS.
showStruct Отображать линии CHoCH / BOS.
bullStrCol Цвет линий бычьей структуры.
bearStrCol Цвет линий медвежьей структуры.
maxStrDraw Максимальное количество структур, отображаемых на графике.
fvgAutoThr Автоматический порог для отсеивания незначительных гэпов.
fvgMinAtr Минимальная высота гэпа в ATR. 0 — отключено.
showFvg Отображать блоки FVG.
fvgBullCol Цвет бычьих блоков FVG.
fvgBearCol Цвет медвежьих блоков FVG.
showFvgEntry Отображать линию уровня входа в FVG.
maxFvgKeep Количество FVG, хранимых в памяти.
entryTrigger Событие, открывающее сценарий: возврат в FVG или закрытие свечи подтверждения CHoCH.
entryMode Глубина возврата цены в FVG, при которой срабатывает вход. Используется только в режиме FVG Retracement.
entryCustomPct Пользовательская глубина возврата в FVG в процентах. Используется только при выборе Custom.
tpMode Способ расчёта цели: фиксированное кратное R, противоположная ликвидность или процентный прирост.
tpPctMode Процентная цель в режиме Percent Gain.
tpPctCustom Пользовательская процентная цель. Используется только при выборе Custom.
tpPct2 Вторая процентная цель в режиме Percent Gain при включённом частичном закрытии.
rrTarget Целевое соотношение риск/прибыль в R. Используется в режиме R Multiple.
tpMinR Минимальное соотношение прибыль/риск до ближайшего пула ликвидности. Используется в режиме Opposite Liquidity.
tpLiqPullback Отступ цели от уровня ликвидности в ATR. 0 — цель точно на уровне.
slAtrBuf Дополнительный отступ стоп-лосса за снятым экстремумом в ATR.
slTickBuf Дополнительный отступ стоп-лосса в тиках.
maxBarsChoCH Максимальное число баров между снятием ликвидности и CHoCH.
maxBarsFvg Максимальное число баров между CHoCH и формированием FVG.
maxBarsEntry Максимальное число баров между формированием FVG и входом.
oneAtATime Разрешать только один активный сценарий одновременно.
showSetups Отображать блоки сценариев на графике.
drawFilled Отображать на графике только сценарии, по которым был выполнен вход.
riskCol Цвет зоны риска в сценариях.
rewardCol Цвет зоны прибыли в сценариях.
maxSetupDraw Максимальное количество сценариев, отображаемых на графике.
filtTrendOn Требовать соответствия направления сценария тренду старшего таймфрейма.
filtAllowRanging Разрешать сценарии при боковом движении.
filtPdOn Требовать дисконт для длинных и премиум для коротких сценариев.
filtEqPct Порог равновесия в процентах для фильтра премиума/дисконта.
filtMaxRiskAtr Максимальный риск в ATR. 0 — фильтр отключён.
filtSmtOn Требовать наличие SMT-дивергенции для сценария.
filtKzOn Включает фильтр по торговым сессиям (киллзонам).
kzSession1 Первая торговая сессия для фильтра (Лондон).
kzSession2 Вторая торговая сессия для фильтра (Нью-Йорк).
beOn Включает перенос стоп-лосса в безубыток после достижения заданного уровня прибыли в R.
beTrigR Уровень прибыли в R, при достижении которого стоп переносится в безубыток.
partialOn Включает частичное закрытие позиции.
partialPct Доля позиции, закрываемая при частичном тейк-профите, в процентах.
rrTarget2 Вторая цель в R для частичного закрытия.
trailOn Включает трейлинг-стоп.
trailTrigR Уровень прибыли в R, при достижении которого активируется трейлинг-стоп.
trailPct Дистанция трейлинг-стопа в процентах.
showPD Отображать уровни предыдущего дня PDH / PDL.
showPdEq Отображать среднюю линию PD EQ.
pdCol Цвет линий предыдущего дня.
pdWidth Толщина линий предыдущего дня.
pdExtend Продление линий предыдущего дня вправо в барах.
showPdLbl Отображать подписи уровней предыдущего дня.
pdLabelMode Что показывать в подписи PDH: день, дату или оба значения.
showHtfBlock Отображать блок свечей старшего таймфрейма справа.
htfAuto Автоматический выбор таймфрейма для блока свечей.
htfManual Таймфрейм для блока свечей при ручном выборе.
htfCount Количество отображаемых свечей старшего таймфрейма.
htfOffset Смещение блока свечей от текущей цены в барах.
htfSize Ширина свечей в блоке.
htfGap Расстояние между свечами блока.
htfShowEq Показывать линию равновесия (50%) на свечах блока.
htfShowTimer Показывать обратный отсчёт до закрытия свечи старшего таймфрейма.
htfBullBody Цвет тела бычьих свечей блока.
htfBearBody Цвет тела медвежьих свечей блока.
htfBullBorder Цвет границ бычьих свечей блока.
htfBearBorder Цвет границ медвежьих свечей блока.
htfWickCol Цвет фитилей бычьих свечей блока.
htfBearWick Цвет фитилей медвежьих свечей блока.
htfTxtCol Цвет текста в блоке свечей.
showPanel Отображать информационную панель.
panelPos Положение панели на графике.
panelSize Размер текста панели.
panelBg Цвет фона панели.
panelTxt Цвет текста панели.
panelWin Цвет индикации прибыльных сценариев в панели.

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

indicator('RaidShift — Liquidity to FVG Reversal Engine[@simpleforextools]', 'RaidShift [@simpleforextools]', overlay = true,
     max_bars_back = 1000, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500)

const string G_LQ  = '1 · Liquidity Raid'
const string G_SMT = '2 · SMT Divergence'
const string G_MS  = '3 · Market Structure (CHoCH)'
const string G_FVG = '4 · Fair Value Gap'
const string G_SET = '5 · Trade Setup (Entry / SL / TP)'
const string G_PD  = '8 · Previous Day (PDH / PDL)'
const string G_HTF = '9 · Higher Timeframe Candle Block'
const string G_FIL = '6 · Setup Filters (all off by default)'
const string G_MGT = '7 · Trade Management (all off by default)'
const string G_PNL = '10 · Performance Panel'
const string G_AL  = '11 · Alerts'

int   swingPeriod  = input.int(15, 'Swing Period (pivot left/right)', minval = 2, group = G_LQ, tooltip = 'Left and right bar count for the pivot scan. Higher = fewer but more significant liquidity pools. On a 15m chart 10-20 is a good working range.')
int   maxScanBack  = input.int(20, 'Pivots Scanned Back', minval = 1, maxval = 100, group = G_LQ, tooltip = 'How many of the most recent pivots are checked for a raid on every bar.')
bool  showSweeps   = input.bool(true, 'Draw Raided Levels', group = G_LQ)
bool showRaidLabels = input.bool(false, 'Draw RAID / BREAK Text', group = G_LQ)
color sweepBuyCol  = input.color(#f23645, 'Buyside', inline = 'sw', group = G_LQ)
color sweepSelCol  = input.color(#1d4ed8, 'Sellside', inline = 'sw', group = G_LQ)
int   maxSweepDraw = input.int(10, 'Max Raids Kept On Chart', minval = 1, maxval = 50, group = G_LQ)

string raidMode = input.string('Wick rejection', 'Raid Mode', options = ['Wick rejection', 'Close-through reversal', 'Both'], group = G_LQ, tooltip = 'Which event at a liquidity pool arms the sequence.\n\nWick rejection (default) — wick beyond the level, body back inside. The level was defended. A body closing through the level is not a signal; it just retires the pool. This preserves the wick-rejection event definition; pool consumption and setup sequencing include Enhanced corrections.\n\nClose-through reversal — the body closes BEYOND the level, and the setup arms only if structure then shifts back against it. This is the failed-breakout read: the break took the stops and trapped the breakout entries, so its failure carries more behind it. Note what this does NOT do: it does not produce fewer raids (bodies close through levels more often than wicks reject them, so the raid count usually rises) and it does not automatically widen the stop. What thins it out is the invalidation rule, because most breaks keep going. Let the panel tell you the numbers rather than assuming them.\n\nBoth — either event can arm a setup. If both directions qualify on one bar, neither starts a setup. Labels can be enabled separately. Useful for seeing them side by side; less useful for measuring one against the other, which is better done one mode at a time.')
float  ctMinPen = input.float(0.0, 'Min Close-Through Depth (× ATR)', minval = 0.0, step = 0.05, group = G_LQ, tooltip = 'How far BEYOND the level the body must close before a close-through counts as a signal. 0 = off, so any close through it qualifies.\n\nWithout this, a body closing one tick past the level arms a setup, which is noise wearing the shape of a breakout. Measured in ATR rather than percent, for the same reason the raid quality gates are: ATR rescales itself with the market, a percentage of price does not.\n\nThis gate only decides whether the break SIGNALS. The level is retired by a body closing through it either way, in every mode, exactly as before — a pool that has been closed through is not liquidity any more, however shallow the close was.\n\nOnly read when Raid Mode allows close-through raids.')
float  ctInvBuf = input.float(0.0, 'Close-Through Invalidation Buffer (× ATR)', minval = 0.0, step = 0.05, group = G_LQ, tooltip = 'Extra room, in ATR, before a close-through setup is thrown away.\n\nA setup dies when price closes beyond the raiding bar\'s own extreme — the break is working and the reversal thesis is finished. That rule is naturally loose after a WICK raid, because the raiding bar closed back inside the level and left a whole wick of room above the close. After a CLOSE-THROUGH raid there is no such room: the bar closed near its own high, so an ordinary continuation candle trips the rule immediately.\n\nThis buffer gives that case the room the wick case gets for free. 0 = off, and the rule is then identical for both kinds of raid. Raising it keeps setups alive through a second push; raise it too far and the engine sits in setups that have already failed. Watch the Cancelled counter while you move it.\n\nApplies ONLY to setups armed by a close-through raid. Wick setups are never affected by this, whatever it is set to.')

float raidMinPen = input.float(0.0, 'Min Raid Penetration (× ATR)', minval = 0.0, step = 0.05, group = G_LQ, tooltip = 'How far the WICK must trade beyond the level before the sweep counts. 0 = off (any trade beyond it qualifies).\n\nHonest expectation: this mostly just removes setups. The cleanest stop-hunts are frequently shallow — price takes the level by a hair and turns — so a deep-penetration requirement can filter out exactly the raids you want. Measure it against Net R, not win rate.')
float raidMinRej = input.float(0.0, 'Min Rejection (× ATR)', minval = 0.0, step = 0.05, group = G_LQ, tooltip = 'How far back INSIDE the level the candle must close. 0 = off (any close back inside qualifies).\n\nThis is the more informative of the two gates: it measures how hard the level was rejected rather than how far it was pierced. A candle that poked through and closed one tick back inside barely rejected anything; a candle that pierced and closed half an ATR back inside did.')

bool   smtOn      = input.bool(true, 'Show SMT Divergence', group = G_SMT, tooltip = 'At every raid, the correlated symbol is checked: did it take ITS matching swing at the same time? If it did not, the move lacked participation and the raid is marked SMT.\n\nA sellside raid the peer refused to follow is a BULLISH divergence; a buyside raid it refused to follow is BEARISH. The comparison is made against the peer\'s price at the bar that formed the pivot, so it asks the same question the chart does rather than an approximation of it.')
string smtSymbol = input.symbol('', 'Correlated Symbol (empty = disabled)', group = G_SMT, tooltip = 'No automatic pairing. Enter an explicit different symbol to enable comparison.')
color  smtBullCol = input.color(#1d4ed8, 'Bullish', inline = 'sm', group = G_SMT)
color  smtBearCol = input.color(#f23645, 'Bearish', inline = 'sm', group = G_SMT)
bool   smtLabels  = input.bool(true, 'Draw SMT Labels', group = G_SMT)

string structMode  = input.string('Internal', 'Structure Used For Setups', options = ['Internal', 'Swing'], group = G_MS, tooltip = 'Internal = fast inner structure (default 5-bar pivot). Swing = major structure (default 50-bar pivot). The setup trigger reads the selected one; the other is only reported as bias in the panel.')
int    internalLen = input.int(5,  'Internal Structure Length', minval = 2, group = G_MS)
int    swingLen    = input.int(50, 'Swing Structure Length',    minval = 2, group = G_MS)
string shiftRule = input.string('Legacy CHoCH / BOS', 'Setup Shift Rule', options = ['Raid-bound structure', 'Legacy CHoCH / BOS'], group = G_MS, tooltip = 'Raid-bound: freeze the latest known unbroken opposite pivot before the raid; require its close break on a later bar. This is a structural shift, not necessarily a globally classified CHoCH. Legacy uses the global classification. Both require a later confirmed bar.')
bool   chochOnly   = input.bool(true, 'CHoCH only (ignore BOS)', group = G_MS, tooltip = 'Applies only to Legacy CHoCH / BOS setup rule. Raid-bound structure uses its own frozen pivot reference.')
bool   showStruct  = input.bool(true, 'Draw CHoCH / BOS Lines', group = G_MS)
color  bullStrCol  = input.color(#089981, 'Bullish', inline = 'ms', group = G_MS)
color  bearStrCol  = input.color(#f23645, 'Bearish', inline = 'ms', group = G_MS)
int    maxStrDraw  = input.int(10, 'Max Structures Kept On Chart', minval = 1, maxval = 50, group = G_MS)

bool  fvgAutoThr = input.bool(true, 'Auto Threshold', group = G_FVG, tooltip = 'Cumulative mean body-change threshold that filters out insignificant gaps.')
float fvgMinAtr  = input.float(0.0, 'Min Gap Height (× ATR)', minval = 0.0, step = 0.05, group = G_FVG, tooltip = '0 = disabled.')
bool  showFvg    = input.bool(true, 'Draw FVG Boxes', group = G_FVG)
color fvgBullCol = input.color(color.new(#089981, 82), 'Bullish', inline = 'fv', group = G_FVG)
color fvgBearCol = input.color(color.new(#f23645, 82), 'Bearish', inline = 'fv', group = G_FVG)
bool  showFvgEntry = input.bool(true, 'Draw Entry Level Line', group = G_FVG, tooltip = 'Draws the line where an entry would actually trigger, using the Entry Level chosen in the Trade Setup group.')
int   maxFvgKeep = input.int(12, 'FVGs Kept In Memory', minval = 3, maxval = 40, group = G_FVG)

string entryTrigger = input.string('FVG Retracement', 'Entry Trigger', options = ['FVG Retracement', 'CHoCH Candle Close'], group = G_SET, tooltip = 'What actually opens the trade.\n\nFVG Retracement    — wait for price to come back into the gap the shift left behind, and fill at the depth chosen below. Better price, but the setup can expire unfilled.\nCHoCH Candle Close — enter at the close of the candle that confirms the structure shift, with no gap and no wait. Every confirmed shift becomes a trade; the entry is worse and the stop is wider.\n\nThe stop sits beyond the raided extreme in both modes, and the target stays the same multiple of R.')
string entryMode = input.string('0% — Proximal edge', 'FVG Entry Depth', options = ['0% — Proximal edge', '25%', '50% — CE', '75%', '100% — Distal edge', 'Custom'], group = G_SET, tooltip = 'How deep into the gap price must travel before the entry triggers, measured from the edge price enters from. Only read in FVG Retracement mode.\n\n0%   — the very first touch of the gap. Most fills, widest stop, target furthest away.\n50%  — the consequent encroachment, the midpoint of the gap.\n100% — the gap must be fully filled. Fewest fills, tightest stop.\nCustom — any depth you like, set in the field below.')
float entryCustomPct = input.float(40.0, 'Custom Depth (%)', minval = 0, maxval = 100, step = 5, group = G_SET, tooltip = 'Only read when FVG Entry Depth is set to Custom.')
string tpMode      = input.string('R Multiple', 'Take Profit', options = ['R Multiple', 'Opposite Liquidity', 'Percent Gain'], group = G_SET, tooltip = 'Where the target sits.\n\nR Multiple         — a fixed multiple of the stop distance. Simple, but it ignores what is actually in front of the trade: if the nearest pool of opposite liquidity sits closer than the target, price often raids it and turns before the target is ever reached.\nOpposite Liquidity — the target is the nearest still-unraided pool on the far side. A long after a sellside raid aims at the buyside pool above it, which is where price is actually being drawn. The nearest retained live pool is used. If it is too close after pullback, or no pool is available, the setup is rejected. Nearby pools are not skipped in favor of farther targets.\nPercent Gain       — a fixed percentage move from the entry price, ignoring the stop distance entirely. Use it when you think in "I want 1% out of this" rather than in R. The R multiple it happens to produce is whatever the stop width makes it, and the panel reports that real figure — so a wide stop turns a 1% target into a fraction of an R, which is worth watching.')
string tpPctMode   = input.string('1%', 'Percent Target', options = ['0.5%', '0.75%', '1%', '1.5%', '2%', '3%', '5%', 'Custom'], group = G_SET, tooltip = 'How far from the entry the target sits, as a percentage of the entry price. Only read in Percent Gain mode.')
float  tpPctCustom = input.float(1.25, 'Custom Percent (%)', minval = 0.05, maxval = 50, step = 0.05, group = G_SET, tooltip = 'Only read when Percent Target is set to Custom.')
float  tpPct2      = input.float(2.0, 'Second Percent Target (%)', minval = 0.05, maxval = 50, step = 0.05, group = G_SET, tooltip = 'The runner target in Percent Gain mode, used only when Partial Take Profit is on. It must sit beyond the first target; if it does not, it is pushed out automatically.')
float rrTarget     = input.float(2.0,  'Risk / Reward (TP in R)', minval = 0.2, step = 0.1, group = G_SET, tooltip = 'Used in R Multiple mode. Opposite Liquidity requires an actual eligible nearest pool.')
float tpMinR       = input.float(1.0, 'Min R for Liquidity TP', minval = 0.1, step = 0.1, group = G_SET, tooltip = 'Minimum reward/risk at the nearest live pool after pullback. A closer pool rejects the setup; the engine does not skip it. Only read in Opposite Liquidity mode.')
float tpLiqPullback = input.float(0.0, 'TP Pullback From Pool (× ATR)', minval = 0.0, step = 0.05, group = G_SET, tooltip = 'Places the target slightly IN FRONT of the pool rather than exactly on it — below a buyside pool for a long, above a sellside pool for a short. Price frequently reverses in the last ticks before a level rather than tagging it exactly; a small value here fills those trades instead of watching them turn one tick short. 0 = target sits exactly on the level.')
float slAtrBuf     = input.float(0.05, 'SL Buffer (× ATR)', minval = 0.0, step = 0.01, group = G_SET, tooltip = 'Padding added beyond the raided extreme.')
int   slTickBuf    = input.int(0, 'SL Buffer (ticks)', minval = 0, group = G_SET)
int   maxBarsChoCH = input.int(20, 'Raid → CHoCH max bars', minval = 1, group = G_SET)
int   maxBarsFvg   = input.int(10, 'CHoCH → FVG max bars',  minval = 1, group = G_SET)
int   maxBarsEntry = input.int(30, 'FVG → Entry max bars',  minval = 1, group = G_SET, tooltip = 'How long an armed setup waits for price to return before it is written off. Raising this is the second lever on the fill rate, after the entry depth.')
bool  oneAtATime   = input.bool(true, 'One trade at a time', group = G_SET, tooltip = 'No new setup is armed while another one is armed or open. Makes the panel statistics more realistic.')
bool  showSetups   = input.bool(true, 'Draw Setup Boxes', group = G_SET)
bool  drawFilled   = input.bool(false, 'Draw Only Filled Trades', group = G_SET, tooltip = 'OFF — a setup is drawn the moment it arms, and if price never comes back to the entry it stays on the chart greyed out and marked cancelled. You see everything the engine considered.\n\nON — nothing is drawn until the trade actually FILLS. A setup that arms and expires unfilled leaves no drawing at all, so every box behind price is a real trade that ended at its target, its stop or its trail.\n\nThis also stops cancelled setups from consuming the Max Setups Kept On Chart budget, which means raising that number now buys you real trades rather than more grey boxes.\n\nCounts are untouched either way: an expired setup is still counted under Cancelled in the panel whether or not it was ever drawn.')
color riskCol      = input.color(color.new(#f23645, 80), 'Risk', inline = 'st', group = G_SET)
color rewardCol    = input.color(color.new(#089981, 80), 'Reward', inline = 'st', group = G_SET)
int   maxSetupDraw = input.int(30, 'Max Setups Kept On Chart', minval = 3, maxval = 150, group = G_SET, tooltip = 'How many finished setups stay drawn behind price. Raise it to review the engine\'s history on the chart rather than only the last few trades.\n\nThis is a DRAWING limit, not a statistical one — the panel counts every trade on the loaded history whatever this is set to. Trimming here never changes a number in the panel.\n\nFloor of 3 so a concurrent long + short setup can never have its drawings removed by the trim routine. Ceiling of 150 because Pine allows a script 500 boxes, 500 lines and 500 labels in total, and each setup costs 2 boxes, 1 line and 1 label out of a budget it shares with the raid levels, the structure lines, the FVG boxes and the higher-timeframe block. At 150 there is still comfortable headroom with every other drawing setting at its own maximum.')

float fvgEntryPct = switch entryMode
    '25%'                => 25.0
    '50% — CE'           => 50.0
    '75%'                => 75.0
    '100% — Distal edge' => 100.0
    'Custom'             => entryCustomPct
    =>                      0.0

bool useFvgEntry = entryTrigger == 'FVG Retracement'

string entryTag = useFvgEntry ? 'FVG ' + str.tostring(math.round(fvgEntryPct)) + '%' : 'CHoCH close'

float tpPercent = switch tpPctMode
    '0.5%'   => 0.5
    '0.75%'  => 0.75
    '1.5%'   => 1.5
    '2%'     => 2.0
    '3%'     => 3.0
    '5%'     => 5.0
    'Custom' => tpPctCustom
    =>          1.0

bool   filtTrendOn      = input.bool(false, 'Require HTF Trend Alignment', group = G_FIL, tooltip = 'Longs only while the Main Trend row reads Bullish, shorts only while it reads Bearish. Counter-trend raids are the largest structural leak in a reversal setup, so this is the first filter worth measuring.')
bool   filtAllowRanging = input.bool(false, 'Allow trades while Ranging', group = G_FIL, tooltip = 'When the trend filter is on, this decides whether a Ranging read blocks the setup or lets it through. Off = only a clean Bullish/Bearish read trades.')
bool   filtPdOn         = input.bool(false, 'Require Discount (long) / Premium (short)', group = G_FIL, tooltip = 'The entry must sit in the cheap half of the current dealing range for a long, the expensive half for a short. The range is the last confirmed swing high to swing low. Directly blocks buying the top of a leg just because a shift printed.')
float  filtEqPct        = input.float(50.0, 'Equilibrium Threshold (%)', minval = 10, maxval = 90, step = 5, group = G_FIL, tooltip = '50 = the true midpoint of the range. Lower it to demand a deeper discount for longs (and a shallower premium for shorts).')
float  filtMaxRiskAtr   = input.float(0.0, 'Max Risk (× ATR) — 0 = off', minval = 0.0, step = 0.1, group = G_FIL, tooltip = 'Skip any setup whose stop distance exceeds this multiple of ATR. A deep raid wick makes for a wide stop, which pushes the target out of reach — this is a purely mechanical filter that assumes nothing about the market.\n\nWorth recalibrating whenever Raid Mode changes: the stop is measured from a different kind of bar in each mode, so a cap tuned on one will not mean the same thing on the other. Watch the Filtered counter while you move it.')
bool   filtSmtOn = input.bool(false, 'Require SMT Divergence', group = G_FIL, tooltip = 'Requires an explicit comparison symbol. Missing or unaligned peer data rejects the setup; the filter never silently passes.')
bool   filtKzOn         = input.bool(false, 'Killzone / Session Filter', group = G_FIL, tooltip = 'Only arm setups inside the windows below. Times are New York.')
string kzSession1       = input.session('0200-0500', 'Killzone 1 (London)', group = G_FIL)
string kzSession2       = input.session('0830-1100', 'Killzone 2 (New York)', group = G_FIL)

bool  beOn       = input.bool(false, 'Move Stop To Breakeven', group = G_MGT, tooltip = 'Once the trade is this many R in profit, the stop moves to the entry. It raises the WIN RATE mechanically by converting some losses into scratches — but it usually LOWERS expectancy, because winners that would have run get stopped out on the pullback. The panel counts breakeven exits separately so you can see both effects instead of only the flattering one.')
float beTrigR    = input.float(1.0, 'Breakeven Trigger (R)', minval = 0.1, step = 0.1, group = G_MGT)
bool  partialOn  = input.bool(false, 'Partial Take Profit', group = G_MGT, tooltip = 'Bank part of the position at the first target, run the rest to a second one. When on, the stop moves to breakeven the moment the first target fills, so the runner can only end at +R or flat. Every trade then reports a WEIGHTED R, and the panel totals stay comparable with single-target trades.')
float partialPct = input.float(50.0, 'Partial Size (%)', minval = 10, maxval = 90, step = 5, group = G_MGT)
float rrTarget2  = input.float(3.0, 'Second Target (R)', minval = 0.2, step = 0.1, group = G_MGT, tooltip = 'The runner target in R Multiple mode, and the fallback in Opposite Liquidity mode when no second pool qualifies.')

bool  trailOn     = input.bool(false, 'Trailing Stop', group = G_MGT, tooltip = 'Once the trade is far enough in profit, the stop stops sitting still and follows the best price reached, staying a fixed percentage behind it. It only ever moves in the direction of the trade — it never gives back ground it has taken.\n\nThis exists for the case the second target creates: price runs to the opposite liquidity, raids it and turns. A fixed 3R target sits through that entire reversal. A trail banks whatever the move actually gave.\n\nWorks with or without partials. When both are on, the trail governs the runner once it activates.')
float trailTrigR  = input.float(2.0, 'Trail Activation (R)', minval = 0.1, step = 0.1, group = G_MGT, tooltip = 'How far in profit the trade must go before the trail switches on. Until then the stop stays exactly where it was placed. At the default the trade is chased only after it has already paid for itself twice over.')
float trailPct    = input.float(0.5, 'Trail Distance (%)', minval = 0.05, maxval = 20, step = 0.05, group = G_MGT, tooltip = 'How far behind the best price the stop follows, as a percentage of price. 0.5 means the stop sits half a percent under the highest high the trade has seen (over the lowest low, for a short).\n\nTight values react fast to a reversal and are stopped out by ordinary noise; wide values survive noise and give back more at the turn. On a 15m crypto chart 0.3-1.0 is the range worth testing. Measure it — a trail that is too tight converts winners into small winners, which flatters the win rate while lowering Net R.')

bool   showPD      = input.bool(true, 'Show PDH / PDL', group = G_PD)
bool   showPdEq    = input.bool(true, 'Show PD EQ (midpoint)', group = G_PD)
color  pdCol       = input.color(#787b86, 'Color', inline = 'pd', group = G_PD)
int    pdWidth     = input.int(1, 'Width', minval = 1, maxval = 4, inline = 'pd', group = G_PD)
int    pdExtend    = input.int(15, 'Extend Right (bars)', minval = 0, maxval = 100, group = G_PD)
bool   showPdLbl   = input.bool(true, 'Labels', group = G_PD)
string pdLabelMode = input.string('Day + Date', 'PDH Label Shows', options = ['Day', 'Date', 'Day + Date', 'Neither'], group = G_PD, tooltip = 'The stamp carried by the PDH label only — PDL stays clean, since one stamp per session is enough to read the chart. After a weekend or a holiday the previous daily bar can be several calendar days back, which is exactly what the stamp is there to show.')

bool   showHtfBlock = input.bool(true, 'Show HTF Candles On The Right', group = G_HTF)
bool   htfAuto      = input.bool(true, 'Auto-Select Timeframe', group = G_HTF, tooltip = 'Picks one step up automatically: 1H on a 15m chart, 4H on a 1H chart, and so on. Turn this off to use the manual timeframe below.')
string htfManual    = input.timeframe('60', 'Manual Timeframe', group = G_HTF)
int    htfCount     = input.int(8, 'Candles Shown', minval = 1, maxval = 12, group = G_HTF)
int    htfOffset    = input.int(20, 'Offset From Price (bars)', minval = 1, group = G_HTF)
string htfSize      = input.string('Small', 'Candle Width', options = ['Small', 'Medium', 'Large'], group = G_HTF)
int    htfGap       = input.int(1, 'Candle Spacing', minval = 1, maxval = 4, group = G_HTF)
bool   htfShowEq    = input.bool(false, 'Candle EQ (50%) Line', group = G_HTF)
bool   htfShowTimer = input.bool(true, 'Close Countdown', group = G_HTF)
color  htfBullBody   = input.color(color.new(#089981, 0), 'Body · Bull', inline = 'hb', group = G_HTF)
color  htfBearBody   = input.color(color.new(#f23645, 0), 'Bear', inline = 'hb', group = G_HTF)
color  htfBullBorder = input.color(color.new(#089981, 0), 'Borders · Bull', inline = 'hbr', group = G_HTF)
color  htfBearBorder = input.color(color.new(#f23645, 0), 'Bear', inline = 'hbr', group = G_HTF)
color  htfWickCol    = input.color(color.new(#787b86, 0), 'Wick · Bull', inline = 'hw', group = G_HTF)
color  htfBearWick   = input.color(color.new(#787b86, 0), 'Bear', inline = 'hw', group = G_HTF)
color  htfTxtCol     = input.color(#787b86, 'Text', group = G_HTF)

bool   showPanel = input.bool(true, 'Show Panel', group = G_PNL)
string panelPos  = input.string('Top Right', 'Position', options = ['Top Right', 'Top Left', 'Bottom Right', 'Bottom Left'], group = G_PNL)
string panelSize = input.string(size.small, 'Text Size', options = [size.tiny, size.small, size.normal, size.large], group = G_PNL)
color  panelBg   = input.color(color.new(#1e222d, 10), 'Background', inline = 'pn', group = G_PNL)
color  panelTxt  = input.color(#d1d4dc, 'Text', inline = 'pn', group = G_PNL)
color  panelWin  = input.color(#089981, 'Win', inline = 'pn2', group = G_PNL)
color  panelLoss = input.color(#f23645, 'Loss', inline = 'pn2', group = G_PNL)
bool   showTrendRow = input.bool(true, 'Show Main Trend Row', group = G_PNL, tooltip = 'Higher-timeframe directional context, reported in the panel only. Nothing in the setup engine is gated on it — the trend row is a read, not a filter.')
bool   trendAuto    = input.bool(true, 'Trend Timeframe: Auto', group = G_PNL, tooltip = 'Auto picks a timeframe roughly 16x the chart: 1H from a 1m chart, 4H from 5m/15m, 1D from 30m/1H, 1W from 4H/1D. Turn off to set it yourself.')
string trendManual  = input.timeframe('240', 'Trend Timeframe (manual)', group = G_PNL)
int    trendLen     = input.int(50, 'Trend EMA Length', minval = 2, group = G_PNL, tooltip = 'Bullish = HTF close above the EMA and the EMA rising. Bearish = close below and the EMA falling. Anything else reads Ranging.')

bool   alertArmed  = input.bool(true,  'Alert: setup armed',      group = G_AL, tooltip = 'Fires when a setup arms — after the raid and the CHoCH, with the entry, stop, target and R already resolved. In CHoCH Candle Close mode arming and filling happen on the same bar, so this and the entry alert fire together.')
bool   alertEntry  = input.bool(true,  'Alert: entry filled',     group = G_AL, tooltip = 'Fires when price reaches the entry level (FVG mode) or on the confirming close (CHoCH Candle Close mode).')
bool   alertExit   = input.bool(true,  'Alert: trade closed',     group = G_AL, tooltip = 'Fires on the target, the stop, a breakeven stop, a trailed stop, or a banked partial — carrying the R the trade actually ended at, not a nominal one.')
bool   alertRaid   = input.bool(false, 'Alert: raid / break',     group = G_AL, tooltip = 'Fires the moment a liquidity pool is taken, long before there is a trade. Says WHICH kind of raid it was — wick rejection or close-through — which the old named alerts cannot do.\n\nOff by default: a raid is not a signal on its own, and this is the noisiest event in the script.')
bool   alertShift  = input.bool(false, 'Alert: CHoCH',            group = G_AL, tooltip = 'Fires on every structure shift, whether or not a raid preceded it. Off by default for the same reason as the raid alert.')
string alertFormat = input.string('Text', 'Message Format', options = ['Text', 'JSON'], group = G_AL, tooltip = 'Text — two or three readable lines, for a phone notification or an email.\n\nJSON — a flat object with the same fields, for a webhook. Prices are emitted as bare numbers formatted to the symbol\'s tick size, so a consumer can parse them without cleaning up the string first.')
bool   alertOnClose = input.bool(true, 'Only on bar close',       group = G_AL, tooltip = 'ON  — an alert fires only once the bar has closed, so what it reports is final. This is the honest setting and it matches the advice in the notes at the bottom of the source.\n\nOFF — alerts fire during the forming bar. You hear about a setup sooner, and some of what you hear will un-happen when the bar closes on the other side of the level.')

type pivotPt
    float currentLevel = na
    float lastLevel    = na
    bool  crossed      = false
    int   barTime      = 0
    int   barIndex     = 0

type trendState
    int bias = 0

type fvgZone
    float top       = na
    float bot       = na
    int   dir       = 0      // +1 bullish, -1 bearish
    int   bIdx      = 0      // bar_index at formation
    bool  mitigated = false
    box   bx        = na
    line  ceLine    = na

f_tfLabel(simple string tf) =>
    int s = timeframe.in_seconds(tf)
    s < 60 ? str.tostring(s) + 's' : s < 86400 ? (s % 3600 == 0 ? str.tostring(s / 3600) + 'H' : str.tostring(math.round(s / 60.0)) + 'm') : s % 604800 == 0 ? str.tostring(s / 604800) + 'W' : s % 86400 == 0 ? str.tostring(s / 86400) + 'D' : tf

f_fvgEntry(float top, float bot, bool isBull, float pct) =>
    isBull ? top - pct / 100.0 * (top - bot) : bot + pct / 100.0 * (top - bot)

f_dayName(int t) =>
    string res = ''
    if not na(t)
        res := switch dayofweek(t, syminfo.timezone)
            dayofweek.monday    => 'Mon'
            dayofweek.tuesday   => 'Tue'
            dayofweek.wednesday => 'Wed'
            dayofweek.thursday  => 'Thu'
            dayofweek.friday    => 'Fri'
            dayofweek.saturday  => 'Sat'
            =>                     'Sun'
    res

f_smtAutoPeer() =>
    string t   = syminfo.ticker
    string res = na
    string m = str.match(t, '^M?(ES|NQ)[1\\w][!\\d]+$')
    if m != ''
        int    off    = str.startswith(m, 'M') ? 1 : 0
        string prefix = str.substring(m, off, 2 + off)
        string suffix = str.substring(m, 2 + off)
        res := 'CME_MINI:' + (off == 1 ? 'M' : '') + (prefix == 'NQ' ? 'ES' : 'NQ') + suffix
    else if str.contains(t, 'MYM') or str.contains(t, 'M2K')
        res := 'CME_MINI:MES1!'
    else if str.contains(t, 'YM') or str.contains(t, 'RTY')
        res := 'CME_MINI:ES1!'
    else if str.contains(t, 'MGC')
        res := 'COMEX:SIL1!'
    else if str.contains(t, 'GC')
        res := 'COMEX:SI1!'
    else if str.contains(t, 'SIL')
        res := 'COMEX:MGC1!'
    else if str.contains(t, 'SI')
        res := 'COMEX:GC1!'
    else if str.contains(t, 'MBT')
        res := 'CME:MET1!'
    else if str.contains(t, 'MET')
        res := 'CME:MBT1!'
    else if str.startswith(t, 'BTC')
        res := syminfo.prefix + ':' + str.replace(t, 'BTC', 'ETH', 0)
    else if str.startswith(t, 'ETH')
        res := syminfo.prefix + ':' + str.replace(t, 'ETH', 'BTC', 0)
    res

f_leg(simple int size) =>
    var int legv = 0
    bool newLegHigh = high[size] > ta.highest(size)
    bool newLegLow  = low[size]  < ta.lowest(size)
    if newLegHigh
        legv := 0
    else if newLegLow
        legv := 1
    legv

f_updateStructure(pivotPt pHigh, pivotPt pLow, simple int size) =>
    int lg = f_leg(size)
    int ch = ta.change(lg)
    if ch == 1                       // a bullish leg starts → a pivot LOW is confirmed
        pLow.lastLevel    := pLow.currentLevel
        pLow.currentLevel := low[size]
        pLow.crossed      := false
        pLow.barTime      := time[size]
        pLow.barIndex     := bar_index[size]
    else if ch == -1                 // a bearish leg starts → a pivot HIGH is confirmed
        pHigh.lastLevel    := pHigh.currentLevel
        pHigh.currentLevel := high[size]
        pHigh.crossed      := false
        pHigh.barTime      := time[size]
        pHigh.barIndex     := bar_index[size]
    ch                               // explicit return value

f_breaks(pivotPt pHigh, pivotPt pLow, trendState tr) =>
    bool xUp = ta.crossover(close,  pHigh.currentLevel)
    bool xDn = ta.crossunder(close, pLow.currentLevel)
    bool  bullCH  = false
    bool  bullBO  = false
    bool  bearCH  = false
    bool  bearBO  = false
    float bullLvl = na
    float bearLvl = na
    int   bullIdx = 0
    int   bearIdx = 0
    if barstate.isconfirmed and xUp and not pHigh.crossed
        bullCH  := tr.bias == -1
        bullBO  := not bullCH
        bullLvl := pHigh.currentLevel
        bullIdx := pHigh.barIndex
        pHigh.crossed := true
        tr.bias := 1
    if barstate.isconfirmed and xDn and not pLow.crossed
        bearCH  := tr.bias == 1
        bearBO  := not bearCH
        bearLvl := pLow.currentLevel
        bearIdx := pLow.barIndex
        pLow.crossed := true
        tr.bias := -1
    [bullCH, bullBO, bearCH, bearBO, bullLvl, bearLvl, bullIdx, bearIdx]

f_trimBox(array<box> a, int maxN) =>
    while a.size() > maxN
        box b = a.shift()
        b.delete()
    a.size()

f_trimLine(array<line> a, int maxN) =>
    while a.size() > maxN
        line l = a.shift()
        l.delete()
    a.size()

f_trimLabel(array<label> a, int maxN) =>
    while a.size() > maxN
        label l = a.shift()
        l.delete()
    a.size()

f_drawSetup(bool isLong, float entry, float sl, float tp, string tag) =>
    box   rbx = box.new(bar_index, isLong ? entry : sl, bar_index + 1, isLong ? sl : entry, xloc = xloc.bar_index, border_color = color.new(riskCol, 40), bgcolor = riskCol)
    box   wbx = box.new(bar_index, isLong ? tp : entry, bar_index + 1, isLong ? entry : tp, xloc = xloc.bar_index, border_color = color.new(rewardCol, 40), bgcolor = rewardCol)
    line  eln = line.new(bar_index, entry, bar_index + 1, entry, xloc = xloc.bar_index, color = color.new(color.gray, 20), style = line.style_dashed)
    label lbl = label.new(bar_index, tp, (isLong ? 'LONG  ' : 'SHORT  ') + tag, xloc = xloc.bar_index, style = isLong ? label.style_label_down : label.style_label_up, color = color.new(color.white, 100), textcolor = rewardCol, size = size.tiny)
    [rbx, wbx, eln, lbl]

f_alertLevel(string evt, string side, string kind, float lvl) =>
    string sLvl = na(lvl) ? '' : str.tostring(lvl, format.mintick)
    string out  = ''
    if alertFormat == 'JSON'
        out := '{"src":"RaidShift","sym":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","event":"' + evt + '","side":"' + side + '"' + (kind == '' ? '' : ',"kind":"' + kind + '"') + (sLvl == '' ? '' : ',"level":' + sLvl) + '}'
    else
        out := 'RaidShift · ' + syminfo.ticker + ' · ' + timeframe.period + '\n' + str.upper(evt) + ' · ' + side + (kind == '' ? '' : ' · ' + kind) + (sLvl == '' ? '' : '\nlevel ' + sLvl)
    out

f_alertTrade(string evt, string side, string kind, float entry, float sl, float tp, float rVal) =>
    string sE = na(entry) ? '' : str.tostring(entry, format.mintick)
    string sS = na(sl)    ? '' : str.tostring(sl,    format.mintick)
    string sT = na(tp)    ? '' : str.tostring(tp,    format.mintick)
    string sR = na(rVal)  ? '' : str.tostring(rVal, '0.00')
    string out = ''
    if alertFormat == 'JSON'
        out := '{"src":"RaidShift","sym":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","event":"' + evt + '","side":"' + side + '","kind":"' + kind + '","trigger":"' + entryTag + '"' + (sE == '' ? '' : ',"entry":' + sE) + (sS == '' ? '' : ',"sl":' + sS) + (sT == '' ? '' : ',"tp":' + sT) + (sR == '' ? '' : ',"r":' + sR) + '}'
    else
        out := 'RaidShift · ' + syminfo.ticker + ' · ' + timeframe.period + '\n' + str.upper(side) + ' ' + evt + ' · ' + kind + '\nentry ' + sE + ' · SL ' + sS + ' · TP ' + sT + (sR == '' ? '' : ' · ' + sR + 'R')
    out

f_htfCountdown(int openTime, simple string tf) =>
    string result = '--:--'
    if barstate.isrealtime and not na(openTime)
        int remainingSec = math.round((openTime + timeframe.in_seconds(tf) * 1000 - timenow) / 1000)
        if remainingSec > 0
            int hrs  = math.floor(remainingSec / 3600)
            int mins = math.floor((remainingSec % 3600) / 60)
            int secs = remainingSec % 60
            result := (hrs > 0 ? str.tostring(hrs, '00') + ':' : '') + str.tostring(mins, '00') + ':' + str.tostring(secs, '00')
    result

float atr14 = ta.atr(14)
float ph    = ta.pivothigh(swingPeriod, swingPeriod)
float pl    = ta.pivotlow(swingPeriod, swingPeriod)

bool smtConfigured = smtOn and smtSymbol != '' and smtSymbol != syminfo.tickerid
string smtPeerId = smtConfigured ? smtSymbol : syminfo.tickerid
string smtName = smtConfigured ? smtSymbol : 'OFF'
[smtPeerHigh, smtPeerLow, smtPeerTime] = request.security(smtPeerId, timeframe.period, [high, low, time], gaps = barmerge.gaps_on, ignore_invalid_symbol = true)
bool smtLive = smtConfigured and smtPeerTime == time and not na(smtPeerHigh) and not na(smtPeerLow)
if barstate.isfirst and filtSmtOn and not smtConfigured
    runtime.error('SMT filter requires SMT enabled and an explicit different comparison symbol.')

var array<string> alQueue = array.new<string>()
alQueue.clear()

var array<float> pvHiP  = array.new<float>()
var array<int>   pvHiB  = array.new<int>()
var array<bool>  pvHiOn = array.new<bool>()
var array<float> pvLoP  = array.new<float>()
var array<int>   pvLoB  = array.new<int>()
var array<bool>  pvLoOn = array.new<bool>()

var array<float> pvHiPeer = array.new<float>()
var array<float> pvLoPeer = array.new<float>()
var array<float> pvHiPeerMax = array.new<float>()
var array<float> pvLoPeerMin = array.new<float>()
var array<bool> pvHiPeerOk = array.new<bool>()
var array<bool> pvLoPeerOk = array.new<bool>()
float peerWindowMax = ta.highest(smtPeerHigh, swingPeriod + 1)
float peerWindowMin = ta.lowest(smtPeerLow, swingPeriod + 1)
float peerWindowOk = ta.lowest(smtLive ? 1.0 : 0.0, swingPeriod + 1)

if barstate.isconfirmed and not na(ph)
    pvHiP.push(high[swingPeriod])
    pvHiB.push(bar_index[swingPeriod])
    pvHiOn.push(true)
    pvHiPeer.push(smtPeerHigh[swingPeriod])
    pvHiPeerMax.push(peerWindowMax)
    pvHiPeerOk.push(peerWindowOk == 1)
if barstate.isconfirmed and not na(pl)
    pvLoP.push(low[swingPeriod])
    pvLoB.push(bar_index[swingPeriod])
    pvLoOn.push(true)
    pvLoPeer.push(smtPeerLow[swingPeriod])
    pvLoPeerMin.push(peerWindowMin)
    pvLoPeerOk.push(peerWindowOk == 1)

bool  sweepBuy   = false     // buyside liquidity raided (bearish signal)
bool  sweepSell  = false     // sellside liquidity raided (bullish signal)
bool  ctBuy      = false     // that buyside raid was a close-through, not a wick rejection
bool  ctSell     = false     // that sellside raid was a close-through, not a wick rejection
float sweptHiLvl = na
float sweptLoLvl = na
int   sweptHiBar = 0
int   sweptLoBar = 0
bool  smtBear    = false     // buyside raid the peer refused to follow
bool  smtBull    = false     // sellside raid the peer refused to follow

bool ambiguousRaid = false
bool raidWickOn = raidMode != 'Close-through reversal'
bool raidCtOn   = raidMode != 'Wick rejection'

float raidPenAbs = raidMinPen > 0 and not na(atr14) ? atr14 * raidMinPen : 0.0
float raidRejAbs = raidMinRej > 0 and not na(atr14) ? atr14 * raidMinRej : 0.0
float ctPenAbs   = ctMinPen > 0 and not na(atr14) ? atr14 * ctMinPen : 0.0
float ctInvAbs   = ctInvBuf > 0 and not na(atr14) ? atr14 * ctInvBuf : 0.0
var int nRaidSkip = 0        // levels touched and rejected by the quality gates

int nHi = pvHiP.size()
if barstate.isconfirmed and nHi > 0
    int fromI = math.max(0, nHi - maxScanBack)
    for i = nHi - 1 to 0
        if pvHiOn.get(i)
            pvHiPeerOk.set(i, pvHiPeerOk.get(i) and smtLive)
            pvHiPeerMax.set(i, math.max(pvHiPeerMax.get(i), smtPeerHigh))
            float lvl = pvHiP.get(i)
            if high > lvl
                pvHiOn.set(i, false)
            if lvl < high and lvl > close
                bool okPen = high - lvl >= raidPenAbs
                bool okRej = lvl - close >= raidRejAbs
                if i >= fromI and raidWickOn and okPen and okRej
                    pvHiOn.set(i, false)
                    if not sweepBuy or lvl > sweptHiLvl
                        sweepBuy   := true
                        ctBuy      := false
                        sweptHiLvl := lvl
                        sweptHiBar := pvHiB.get(i)
                        float pPk = pvHiPeer.get(i)
                        smtBear := pvHiPeerOk.get(i) and not na(pPk) and pvHiPeerMax.get(i) <= pPk
                else if i >= fromI and raidWickOn
                    nRaidSkip += 1
            else if close > lvl
                pvHiOn.set(i, false)
                if i >= fromI and raidCtOn and close - lvl >= ctPenAbs and (not sweepBuy or lvl > sweptHiLvl)
                    sweepBuy   := true
                    ctBuy      := true
                    sweptHiLvl := lvl
                    sweptHiBar := pvHiB.get(i)
                    float pPkC = pvHiPeer.get(i)
                    smtBear := pvHiPeerOk.get(i) and not na(pPkC) and pvHiPeerMax.get(i) <= pPkC

int nLo = pvLoP.size()
if barstate.isconfirmed and nLo > 0
    int fromJ = math.max(0, nLo - maxScanBack)
    for j = nLo - 1 to 0
        if pvLoOn.get(j)
            pvLoPeerOk.set(j, pvLoPeerOk.get(j) and smtLive)
            pvLoPeerMin.set(j, math.min(pvLoPeerMin.get(j), smtPeerLow))
            float lvl = pvLoP.get(j)
            if low < lvl
                pvLoOn.set(j, false)
            if lvl > low and lvl < close
                bool okPen = lvl - low >= raidPenAbs
                bool okRej = close - lvl >= raidRejAbs
                if j >= fromJ and raidWickOn and okPen and okRej
                    pvLoOn.set(j, false)
                    if not sweepSell or lvl < sweptLoLvl
                        sweepSell  := true
                        ctSell     := false
                        sweptLoLvl := lvl
                        sweptLoBar := pvLoB.get(j)
                        float pPk = pvLoPeer.get(j)
                        smtBull := pvLoPeerOk.get(j) and not na(pPk) and pvLoPeerMin.get(j) >= pPk
                else if j >= fromJ and raidWickOn
                    nRaidSkip += 1
            else if close < lvl
                pvLoOn.set(j, false)
                if j >= fromJ and raidCtOn and lvl - close >= ctPenAbs and (not sweepSell or lvl < sweptLoLvl)
                    sweepSell  := true
                    ctSell     := true
                    sweptLoLvl := lvl
                    sweptLoBar := pvLoB.get(j)
                    float pPkC = pvLoPeer.get(j)
                    smtBull := pvLoPeerOk.get(j) and not na(pPkC) and pvLoPeerMin.get(j) >= pPkC

while pvHiP.size() > 500
    pvHiP.shift()
    pvHiB.shift()
    pvHiOn.shift()
    pvHiPeer.shift()
    pvHiPeerMax.shift()
    pvHiPeerOk.shift()
while pvLoP.size() > 500
    pvLoP.shift()
    pvLoB.shift()
    pvLoOn.shift()
    pvLoPeer.shift()
    pvLoPeerMin.shift()
    pvLoPeerOk.shift()

ambiguousRaid := sweepBuy and sweepSell
if ambiguousRaid
    sweepBuy := false
    sweepSell := false
    smtBull := false
    smtBear := false

while pvHiPeer.size() > pvHiP.size()
    pvHiPeer.shift()
while pvLoPeer.size() > pvLoP.size()
    pvLoPeer.shift()

if alertRaid and sweepBuy
    alQueue.push(f_alertLevel('raid', 'buyside', ctBuy ? 'close-through' : 'wick', sweptHiLvl))
if alertRaid and sweepSell
    alQueue.push(f_alertLevel('raid', 'sellside', ctSell ? 'close-through' : 'wick', sweptLoLvl))

var int nSmt = 0
var string lastSmtDir = '-'
if smtBull
    nSmt += 1
    lastSmtDir := 'Bullish'
if smtBear
    nSmt += 1
    lastSmtDir := 'Bearish'

var array<line>  swLines = array.new<line>()
var array<label> swLabs  = array.new<label>()
if showSweeps and sweepBuy
    swLines.push(line.new(sweptHiBar, sweptHiLvl, bar_index, sweptHiLvl, xloc = xloc.bar_index, color = sweepBuyCol, style = ctBuy ? line.style_dashed : line.style_dotted, width = 1))
    if showRaidLabels
        swLabs.push(label.new(bar_index, sweptHiLvl, ctBuy ? 'BREAK' : 'RAID', xloc = xloc.bar_index, style = label.style_label_down, color = color.new(color.white, 100), textcolor = sweepBuyCol, size = size.tiny))
    f_trimLine(swLines, maxSweepDraw)
    f_trimLabel(swLabs, maxSweepDraw * 2)
if showSweeps and sweepSell
    swLines.push(line.new(sweptLoBar, sweptLoLvl, bar_index, sweptLoLvl, xloc = xloc.bar_index, color = sweepSelCol, style = ctSell ? line.style_dashed : line.style_dotted, width = 1))
    if showRaidLabels
        swLabs.push(label.new(bar_index, sweptLoLvl, ctSell ? 'BREAK' : 'RAID', xloc = xloc.bar_index, style = label.style_label_up, color = color.new(color.white, 100), textcolor = sweepSelCol, size = size.tiny))
    f_trimLine(swLines, maxSweepDraw)
    f_trimLabel(swLabs, maxSweepDraw * 2)

if smtLabels and smtBull
    swLabs.push(label.new(bar_index, low, '\nSMT vs ' + smtName, xloc = xloc.bar_index, style = label.style_label_up, color = color.new(color.white, 100), textcolor = smtBullCol, size = size.tiny))
    f_trimLabel(swLabs, maxSweepDraw * 2)
if smtLabels and smtBear
    swLabs.push(label.new(bar_index, high, 'SMT vs ' + smtName + '\n', xloc = xloc.bar_index, style = label.style_label_down, color = color.new(color.white, 100), textcolor = smtBearCol, size = size.tiny))
    f_trimLabel(swLabs, maxSweepDraw * 2)

var pivotPt intHigh  = pivotPt.new()
var pivotPt intLow   = pivotPt.new()
var pivotPt swgHigh  = pivotPt.new()
var pivotPt swgLow   = pivotPt.new()
var trendState intTr = trendState.new()
var trendState swgTr = trendState.new()

f_updateStructure(intHigh, intLow, internalLen)
f_updateStructure(swgHigh, swgLow, swingLen)

[iBullCH, iBullBO, iBearCH, iBearBO, iBullLvl, iBearLvl, iBullIdx, iBearIdx] = f_breaks(intHigh, intLow, intTr)
[sBullCH, sBullBO, sBearCH, sBearBO, sBullLvl, sBearLvl, sBullIdx, sBearIdx] = f_breaks(swgHigh, swgLow, swgTr)

bool  useInternal = structMode == 'Internal'
bool  bullCHoCH   = useInternal ? iBullCH  : sBullCH
bool  bullBOS     = useInternal ? iBullBO  : sBullBO
bool  bearCHoCH   = useInternal ? iBearCH  : sBearCH
bool  bearBOS     = useInternal ? iBearBO  : sBearBO
float bullBrkLvl  = useInternal ? iBullLvl : sBullLvl
float bearBrkLvl  = useInternal ? iBearLvl : sBearLvl
int   bullBrkIdx  = useInternal ? iBullIdx : sBullIdx
int   bearBrkIdx  = useInternal ? iBearIdx : sBearIdx

bool bullShift = chochOnly ? bullCHoCH : (bullCHoCH or bullBOS)
bool bearShift = chochOnly ? bearCHoCH : (bearCHoCH or bearBOS)

if alertShift and bullCHoCH
    alQueue.push(f_alertLevel('choch', 'bullish', '', bullBrkLvl))
if alertShift and bearCHoCH
    alQueue.push(f_alertLevel('choch', 'bearish', '', bearBrkLvl))

var array<line>  strLines = array.new<line>()
var array<label> strLabs  = array.new<label>()
if showStruct and (bullCHoCH or bullBOS)
    strLines.push(line.new(bullBrkIdx, bullBrkLvl, bar_index, bullBrkLvl, xloc = xloc.bar_index, color = bullStrCol, style = useInternal ? line.style_dashed : line.style_solid))
    strLabs.push(label.new(math.round(math.avg(bullBrkIdx, bar_index)), bullBrkLvl, bullCHoCH ? 'CHoCH' : 'BOS', xloc = xloc.bar_index, style = label.style_label_down, color = color.new(color.white, 100), textcolor = bullStrCol, size = size.tiny))
    f_trimLine(strLines, maxStrDraw)
    f_trimLabel(strLabs, maxStrDraw)
if showStruct and (bearCHoCH or bearBOS)
    strLines.push(line.new(bearBrkIdx, bearBrkLvl, bar_index, bearBrkLvl, xloc = xloc.bar_index, color = bearStrCol, style = useInternal ? line.style_dashed : line.style_solid))
    strLabs.push(label.new(math.round(math.avg(bearBrkIdx, bar_index)), bearBrkLvl, bearCHoCH ? 'CHoCH' : 'BOS', xloc = xloc.bar_index, style = label.style_label_up, color = color.new(color.white, 100), textcolor = bearStrCol, size = size.tiny))
    f_trimLine(strLines, maxStrDraw)
    f_trimLabel(strLabs, maxStrDraw)

float barDelta  = (close[1] - open[1]) / (open[1] * 100)
float thrAccum  = ta.cum(math.abs(nz(barDelta)))
float fvgThr    = fvgAutoThr and bar_index > 0 ? thrAccum / bar_index * 2 : 0.0
float minGapAbs = fvgMinAtr > 0 and not na(atr14) ? atr14 * fvgMinAtr : 0.0

bool rawBullFvg = low > high[2] and close[1] > high[2] and barDelta > fvgThr and (low - high[2]) >= minGapAbs
bool rawBearFvg = high < low[2] and close[1] < low[2] and -barDelta > fvgThr and (low[2] - high) >= minGapAbs

var array<fvgZone> fvgs = array.new<fvgZone>()

if barstate.isconfirmed and (rawBullFvg or rawBearFvg)
    float zTop = rawBullFvg ? low : low[2]
    float zBot = rawBullFvg ? high[2] : high
    box   zBx  = na
    line  zCe  = na
    if showFvg
        zBx := box.new(bar_index - 2, zTop, bar_index + 1, zBot, xloc = xloc.bar_index, border_color = color.new(rawBullFvg ? fvgBullCol : fvgBearCol, 60), bgcolor = rawBullFvg ? fvgBullCol : fvgBearCol)
        if showFvgEntry
            float entryLvl = f_fvgEntry(zTop, zBot, rawBullFvg, fvgEntryPct)
            zCe := line.new(bar_index - 2, entryLvl, bar_index + 1, entryLvl, xloc = xloc.bar_index, color = color.new(rawBullFvg ? fvgBullCol : fvgBearCol, 30), style = line.style_dotted)
    fvgs.unshift(fvgZone.new(zTop, zBot, rawBullFvg ? 1 : -1, bar_index, false, zBx, zCe))

if fvgs.size() > 0
    for i = 0 to fvgs.size() - 1
        fvgZone z = fvgs.get(i)
        if not z.mitigated
            bool filled = barstate.isconfirmed and (z.dir == 1 ? low <= z.bot : high >= z.top)
            if filled
                z.mitigated := true
                if not na(z.bx)
                    z.bx.set_right(bar_index)
                    z.bx.set_bgcolor(color.new(z.dir == 1 ? fvgBullCol : fvgBearCol, 94))
                    z.bx.set_border_color(color.new(z.dir == 1 ? fvgBullCol : fvgBearCol, 94))
                if not na(z.ceLine)
                    z.ceLine.set_x2(bar_index)
                    z.ceLine.set_color(color.new(color.gray, 80))
            else
                if not na(z.bx)
                    z.bx.set_right(bar_index + 1)
                if not na(z.ceLine)
                    z.ceLine.set_x2(bar_index + 1)

while fvgs.size() > maxFvgKeep
    fvgZone old = fvgs.pop()
    if not na(old.bx)
        old.bx.delet

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