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

Strong SFP MSS

indicator strong sfp mss for tradingview.pine
Вы автор или правообладатель?

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

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

О программе

Strong SFP MSS — это индикатор для TradingView (Pine Script v6), отображаемый поверх графика. Он строит уровни ликвидности на основе пивотов (свинг-хаи и свинг-лоу) и классифицирует события пробоя этих уровней: SWEEP (вик-рейд), SFP (реклайм) и MSS (сдвиг структуры). Каждому событию присваивается сила от 0 до 10, и только события выше заданного порога становятся отслеживаемыми сигналами с целевым и стоп-уровнем.

Индикатор отображает ключевые уровни ликвидности (PDH, PDL, PWH, PWL) из последнего закрытого дня и недели, окрашивает уровни по сессиям (Азия, Лондон, Нью-Йорк) и рисует линии событий разного стиля. Все уровни и события сопровождаются текстовыми метками с информацией о силе, возрасте и сессии происхождения.

Встроен пятипанельный дашборд: состояние ликвидности, карта уровней, аналитика сетапов, сессионная аналитика и статистика спреев. Панели показывают количество активных пулов, процент побед сигналов, среднее MFE/MAE в R, распределение событий по сессиям и калибровку системы.

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

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

НастройкаОписание
prdInput Период пивота. Определяет силу свинга: пивот-хай требует столько же более низких хаев с обеих сторон. Уровни подтверждаются через указанное количество баров после пивота.
maxActInput Максимальное количество активных уровней ликвидности на каждую сторону. При превышении oldest unswept уровень удаляется.
maxAgeInput Максимальный возраст уровня в барах. 0 означает без ограничения. Уровни старше этого порога удаляются.
eqMergeInput При включении новые пивоты в пределах допуска от активного уровня на той же стороне объединяются в пул (количество касаний +1, сила увеличивается) вместо рисования дополнительной линии.
eqTolInput Допуск для объединения равных уровней, выраженный в кратных ATR.
atrLenInput Период ATR, используемый как единица масштабирования для различных параметров индикатора.
tzInput Часовой пояс для определения торговых сессий. Доступны: America/New_York, UTC-4, UTC-5, UTC, Europe/London, Asia/Bangkok, Asia/Tokyo.
asiaSess Окно торговой сессии Азии в формате TradingView.
asiaColInput Цвет сессионной линии Азии.
lonSess Окно торговой сессии Лондона в формате TradingView.
lonColInput Цвет сессионной линии Лондона.
nyAmSess Окно торговой сессии Нью-Йорк AM в формате TradingView.
nyAmColInput Цвет сессионной линии Нью-Йорк AM.
nyPmSess Окно торговой сессии Нью-Йорк PM в формате TradingView.
nyPmColInput Цвет сессионной линии Нью-Йорк PM.
otherColInput Цвет линий за пределами определённых торговых сессий.
showXInput Включает или отключает отображение и отслеживание событий SWEEP (вик-рейд).
showSfpInput Включает или отключает отображение и отслеживание событий SFP (реклайм).
showMssInput Включает или отключает отображение и отслеживание событий MSS (сдвиг структуры).
mssDispInput Фильтр смещения MSS в единицах ATR. При значении больше 0, для MSS закрытие должно находиться как минимум на таком расстоянии за уровнем. Иначе уровень остаётся в состоянии PIERCED.
patienceInput Терпение в барах. Уровень, оставшийся пробитым без реклайма на протяжении этого количества баров, записывается как MSS по принятию, даже без подтверждения более низкого минимума / более высокого максимума.
proxInput Окно приближения цены к уровню ликвидности в единицах ATR. Используется для оповещений о приближении.
minStrInput Минимальная сила сигнала (0–10). Все классификации рисуются, но только события с силой на или выше этого порога становятся отслеживаемыми сигналами с целевыми и стоп-уровнями.
stopModeInput Модель расчёта стопа: Structural (структурный — расстояние до экстремума спрея + буфер) или ATR (расстояние = инвалидация × ATR).
bufInput Структурный буфер в единицах ATR, добавляемый к расстоянию до уровня при расчёте стопа в структурной модели.
minRiskInput Минимальный риск в единицах ATR. Все рассчитанные значения риска ограничиваются снизу этим значением.
tgtRInput Цель в кратных R. Цель = это количество R от цены входа. При 1.5R / 1R вероятность выигрыша составляет примерно 40%.
invUInput Инвалидация в единицах ATR, используемая в ATR-модели стопа. Определяет расстояние стопа как кратное ATR от цены входа.
maxHoldInput Максимальное количество баров для отслеживания результата сигнала. Если в течение этого количества баров ни цель, ни инвалидация не достигнуты, результат записывается как таймаут.
showOutInput Включает или отключает отображение меток результатов сигналов (цель, инвалидация, таймаут).
showTgtInput Включает или отключает отображение линий цели и инвалидации для отслеживаемых сигналов.
paletteInput Цветовая палитра индикатора: Neon Violet / Green, Neon Magenta / Cyan, Neon Amber / Ice или Custom.
bearCustom Пользовательский цвет медвежьей (медвежьей стороны) палитры.
bullCustom Пользовательский цвет бычьей (бычьей стороны) палитры.
colXInput Цвет линий и меток событий SWEEP (вик-рейд).
colSfpInput Цвет линий и меток событий SFP (реклайм).
colMssInput Цвет линий и меток событий MSS (сдвиг структуры).
styXInput Стиль линий событий SWEEP (Solid, Dashed, Dotted).
stySfpInput Стиль линий событий SFP (Solid, Dashed, Dotted).
styMssInput Стиль линий событий MSS (Solid, Dashed, Dotted).
widthInput Толщина активных линий уровней и событий (1–4).
glowInput Включает неоновое свечение линий уровней.
extInput Продление линий уровней и событий вправо от текущего бара в количестве баров.
kindSizeInput Размер текста меток событий (Tiny, Small, Normal, Large, Huge).
offAtrInput Расстояние текстовых меток от уровня в единицах ATR.
flipInput Переворачивает положение текстовых меток событий относительно уровня.
showPriceInput Включает или отключает ценовые метки (теги) на активных уровнях.
showSigLblInput Включает или отключает теги сигналов с указанием силы (звёзды).
showSweepBox Включает или отключает отображение прямоугольников зон спрея для событий SWEEP и SFP.
tagSizeInput Размер тегов (Tiny, Small, Normal).
maxHistInput Визуальный лимит сохраняемой истории событий. Статистика не ограничивается этим значением.
dashOn Включает или отключает отображение дашборда на графике.
dashPos Позиция дашборда на графике (верхний правый, средний правый, нижний правый, верхний левый, средний левый, нижний левый).
dashSizeS Размер текста в дашборде.
showP1 Включает или отключает панель I дашборда (состояние ликвидности).
showP2 Включает или отключает панель II дашборда (карта ликвидности).
showP3 Включает или отключает панель III дашборда (аналитика сетапов).
showP4 Включает или отключает панель IV дашборда (сессионная аналитика).
showP5 Включает или отключает панель V дашборда (статистика спреев).
panelTr Прозрачность панелей дашборда (0–90).
sepH Высота разделителя между строками дашборда в процентах от высоты.
monoFont Включает моноширинный шрифт для чисел в дашборде.

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

indicator("Strong SFP MSS", shorttitle="Strong SFP MSS", overlay=true,
     max_lines_count=500, max_labels_count=500, max_boxes_count=500, max_bars_back=500)

string G_LVL = "━━ Liquidity Levels ━━"
string G_SES = "━━ Sessions (level origin) ━━"
string G_KEY = "━━ Key Liquidity (PDH · PDL · PWH · PWL) ━━"
string G_EVT = "━━ Sweep Classification ━━"
string G_SIG = "━━ Signals · Honest Outcomes ━━"
string G_VIS = "━━ Neon Visuals ━━"
string G_DSH = "━━ Dashboard ━━"

int    prdInput      = input.int(10, "Pivot Period", minval=2, maxval=100, group=G_LVL,
     tooltip="Swing strength. A pivot high needs this many lower highs on both sides. Levels are confirmed this many bars after the pivot and only if price has not already broken them.")
int    maxActInput   = input.int(5, "Max Active Levels Per Side", minval=1, maxval=10, group=G_LVL,
     tooltip="Oldest unswept level is retired when the cap is hit.")
int    maxAgeInput   = input.int(0, "Max Level Age (bars · 0 = unlimited)", minval=0, maxval=5000, group=G_LVL)
bool   eqMergeInput  = input.bool(true, "Merge Equal Highs / Lows Into Pools", group=G_LVL,
     tooltip="A new pivot within the tolerance of an active level on the same side is merged into it (touches +1, strength up) instead of drawing a second line.")
float  eqTolInput    = input.float(0.25, "Equal-Level Tolerance (×ATR)", minval=0.05, maxval=2.0, step=0.05, group=G_LVL)
int    atrLenInput   = input.int(14, "ATR Length (scaling unit)", minval=2, maxval=200, group=G_LVL)

string tzInput       = input.string("America/New_York", "Timezone", options=["America/New_York", "UTC-4", "UTC-5", "UTC", "Europe/London", "Asia/Bangkok", "Asia/Tokyo"], group=G_SES)
string asiaSess      = input.session("2000-0000", "Asia", group=G_SES, inline="s1")
color  asiaColInput  = input.color(color.rgb(255, 230, 0), "", group=G_SES, inline="s1")
string lonSess       = input.session("0200-0500", "London", group=G_SES, inline="s2")
color  lonColInput   = input.color(color.rgb(0, 220, 255), "", group=G_SES, inline="s2")
string nyAmSess      = input.session("0830-1100", "NY AM", group=G_SES, inline="s3")
color  nyAmColInput  = input.color(color.rgb(255, 140, 0), "", group=G_SES, inline="s3")
string nyPmSess      = input.session("1330-1600", "NY PM", group=G_SES, inline="s4")
color  nyPmColInput  = input.color(color.rgb(255, 0, 200), "", group=G_SES, inline="s4")
color  otherColInput = input.color(color.rgb(150, 160, 190), "Outside Sessions", group=G_SES)

bool   showKeyInput  = input.bool(true, "Show Key Liquidity Lines", group=G_KEY,
     tooltip="Prior-day and prior-week high/low from the last CLOSED day/week (non-repainting). Drawn as neon targets and listed in the Liquidity Map.")
bool   keyDayInput   = input.bool(true, "Prior Day High / Low", group=G_KEY, inline="k1")
bool   keyWeekInput  = input.bool(true, "Prior Week High / Low", group=G_KEY, inline="k1")
int    keyLenInput   = input.int(60, "Key Line Length (bars)", minval=10, maxval=500, group=G_KEY)

bool   showXInput    = input.bool(true, "Show SWEEP · Wick Raid",    group=G_EVT, inline="e1")
bool   showSfpInput  = input.bool(true, "SFP · Reclaim",          group=G_EVT, inline="e1")
bool   showMssInput  = input.bool(true, "MSS · Shift",            group=G_EVT, inline="e1")
float  mssDispInput  = input.float(0.0, "MSS Displacement Filter (×ATR · 0 = off)", minval=0.0, maxval=3.0, step=0.1, group=G_EVT,
     tooltip="When > 0, an MSS needs the close to be at least this far beyond the level. Until then the level stays in the PIERCED state (waiting for reclaim or acceptance).")
int    patienceInput = input.int(6, "Pierce Patience (bars)", minval=1, maxval=100, group=G_EVT,
     tooltip="A level that stays closed-through for this many bars without a reclaim is booked as MSS by acceptance, even without a lower-low / higher-high close.")
float  proxInput     = input.float(0.5, "Proximity Alert (×ATR)", minval=0.1, maxval=5.0, step=0.1, group=G_EVT)

float  minStrInput   = input.float(3.0, "Min Signal Strength (0-10)", minval=0.0, maxval=10.0, step=0.5, group=G_SIG,
     tooltip="Every classification is drawn. Only classifications at or above this strength become tracked signals (target / invalidation lines, outcome labels, statistics, alerts).")
string stopModeInput = input.string("Structural", "Stop Model", options=["Structural", "ATR"], group=G_SIG,
     tooltip="Structural: X / SFP risk = distance to the sweep extreme + buffer; MSS risk = distance back to the level + buffer. ATR: risk = Invalidation × ATR for every setup. Risk is floored at Min Risk.")
float  bufInput      = input.float(0.15, "Structural Buffer (×ATR)", minval=0.0, maxval=2.0, step=0.05, group=G_SIG, inline="r1")
float  minRiskInput  = input.float(0.5, "Min Risk (×ATR)", minval=0.1, maxval=5.0, step=0.1, group=G_SIG, inline="r1")
float  tgtRInput     = input.float(1.5, "Target (R)", minval=0.25, maxval=10.0, step=0.25, group=G_SIG, inline="r2",
     tooltip="Target = this many R from the entry close. Invalidation (ATR stop model only) = this many ATR against. A coin flip at 1.5R / 1R scores 40% — WIN% above that is edge.")
float  invUInput     = input.float(1.0, "Invalidation (×ATR · ATR model)", minval=0.25, maxval=5.0, step=0.25, group=G_SIG, inline="r2")
int    maxHoldInput  = input.int(60, "Outcome Max Hold (bars)", minval=5, maxval=1000, group=G_SIG,
     tooltip="A signal that hits neither level within this many bars is booked as TIMEOUT (marked to market, counted as a non-win).")
bool   showOutInput  = input.bool(true, "Mark Signal Outcomes", group=G_SIG, inline="o1")
bool   showTgtInput  = input.bool(true, "Target / Invalidation Lines", group=G_SIG, inline="o1")

string paletteInput  = input.string("Neon Violet / Green", "Palette",
     options=["Neon Violet / Green", "Neon Magenta / Cyan", "Neon Amber / Ice", "Custom"], group=G_VIS)
color  bearCustom    = input.color(color.rgb(170, 60, 255), "Custom Bearish", group=G_VIS, inline="cc")
color  bullCustom    = input.color(color.rgb(0, 255, 140),  "Bullish",        group=G_VIS, inline="cc")
color  colXInput     = input.color(color.rgb(236, 236, 255), "SWEEP",   group=G_VIS, inline="ek")
color  colSfpInput   = input.color(color.rgb(255, 47, 160),  "SFP", group=G_VIS, inline="ek")
color  colMssInput   = input.color(color.rgb(0, 229, 255),   "MSS", group=G_VIS, inline="ek")
string styXInput     = input.string("Dotted", "SWEEP Line",   options=["Solid", "Dashed", "Dotted"], group=G_VIS, inline="es")
string stySfpInput   = input.string("Dashed", "SFP Line", options=["Solid", "Dashed", "Dotted"], group=G_VIS, inline="es")
string styMssInput   = input.string("Solid",  "MSS Line", options=["Solid", "Dashed", "Dotted"], group=G_VIS, inline="es")
int    widthInput    = input.int(2, "Active Line Width", minval=1, maxval=4, group=G_VIS, inline="v0")
bool   glowInput     = input.bool(true, "Neon Glow", group=G_VIS, inline="v0")
int    extInput      = input.int(15, "Line Extension (bars)", minval=0, maxval=100, group=G_VIS)
string kindSizeInput = input.string("Large", "Event Text Size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=G_VIS, inline="t1")
float  offAtrInput   = input.float(0.6, "Text Distance (×ATR)", minval=0.0, maxval=5.0, step=0.1, group=G_VIS, inline="t1")
bool   flipInput     = input.bool(false, "Flip Text Position", group=G_VIS, inline="t2")
bool   showPriceInput = input.bool(true, "Price Tags (active levels)", group=G_VIS, inline="t2")
bool   showSigLblInput = input.bool(true, "Signal Tags (★ strength)", group=G_VIS, inline="t3")
bool   showSweepBox  = input.bool(true, "Sweep Boxes", group=G_VIS, inline="t3")
string tagSizeInput  = input.string("Small", "Tag Size", options=["Tiny", "Small", "Normal"], group=G_VIS)
int    maxHistInput  = input.int(80, "Event History Kept", minval=10, maxval=200, group=G_VIS,
     tooltip="Visual cap only. Statistics are cumulative over every bar and are never touched by recycling.")

bool   dashOn    = input.bool(true, "Show Dashboard", group=G_DSH)
string dashPos   = input.string("Top Right", "Position", options=["Top Right","Middle Right","Bottom Right","Top Left","Middle Left","Bottom Left"], group=G_DSH)
string dashSizeS = input.string("Small", "Text Size", options=["Tiny","Small","Normal","Large"], group=G_DSH)
bool   showP1    = input.bool(true, "Panel I · Liquidity State",     group=G_DSH)
bool   showP2    = input.bool(true, "Panel II · Liquidity Map",      group=G_DSH)
bool   showP3    = input.bool(true, "Panel III · Setup Analytics",   group=G_DSH)
bool   showP4    = input.bool(true, "Panel IV · Session Analytics",  group=G_DSH)
bool   showP5    = input.bool(true, "Panel V · Sweep Statistics",    group=G_DSH)
int    panelTr   = input.int(6, "Panel Transparency", minval=0, maxval=90, step=2, group=G_DSH)
float  sepH      = input.float(0.9, "Separator Gap (% height)", minval=0.1, maxval=4.0, step=0.1, group=G_DSH)
bool   monoFont  = input.bool(true, "Monospace Numbers", group=G_DSH)

color BEAR_T1 = switch paletteInput
    "Neon Violet / Green" => color.rgb(214, 160, 255)
    "Neon Magenta / Cyan" => color.rgb(255, 150, 220)
    "Neon Amber / Ice"    => color.rgb(255, 214, 140)
    =>                       color.new(bearCustom, 0)
color BEAR_T3 = switch paletteInput
    "Neon Violet / Green" => color.rgb(128, 32, 255)
    "Neon Magenta / Cyan" => color.rgb(255, 0, 150)
    "Neon Amber / Ice"    => color.rgb(255, 120, 0)
    =>                       color.new(bearCustom, 0)
color BULL_T1 = switch paletteInput
    "Neon Violet / Green" => color.rgb(170, 255, 196)
    "Neon Magenta / Cyan" => color.rgb(150, 245, 255)
    "Neon Amber / Ice"    => color.rgb(170, 225, 255)
    =>                       color.new(bullCustom, 0)
color BULL_T3 = switch paletteInput
    "Neon Violet / Green" => color.rgb(0, 230, 96)
    "Neon Magenta / Cyan" => color.rgb(0, 200, 255)
    "Neon Amber / Ice"    => color.rgb(0, 140, 255)
    =>                       color.new(bullCustom, 0)

f_tint(color _c, float _toWhite) =>
    float r = color.r(_c)
    float g = color.g(_c)
    float b = color.b(_c)
    color.rgb(r + (255.0 - r) * _toWhite, g + (255.0 - g) * _toWhite, b + (255.0 - b) * _toWhite)

color bearSoft   = paletteInput == "Custom" ? f_tint(bearCustom, 0.45) : BEAR_T1
color bullSoft   = paletteInput == "Custom" ? f_tint(bullCustom, 0.45) : BULL_T1
color bearAccent = paletteInput == "Custom" ? bearCustom : BEAR_T3
color bullAccent = paletteInput == "Custom" ? bullCustom : BULL_T3

const int GLOW_T  = 82
const int BOX_T   = 86
const int BOX_BRD = 55

color TXT     = #d9dce6
color MUTED   = #7d8597
color DIM     = #4a5163
color GOLD    = #f5b942
color WHITE   = #e8e6f0
color CLEAR   = color.new(#000000, 100)
color PANEL   = color.new(#0b0e15, panelTr)
color PANEL2  = color.new(#10141e, panelTr)
color HEAD    = color.new(#181e2c, panelTr)
color COLHD   = color.new(#131826, panelTr)
color PRICEBG = color.new(#1d2333, panelTr)

f_clamp(float _v, float _lo, float _hi) => math.max(_lo, math.min(_hi, _v))
f_px(float v)  => na(v) ? "—" : str.tostring(v, format.mintick)
f_sn(float v, string fmt) => (v > 0 ? "+" : "") + str.tostring(v, fmt)
f_pct(int n, int d) => d > 0 ? str.tostring(float(n) / d * 100.0, "#") + "%" : "—"
f_frac(int n, int d) => d > 0 ? float(n) / d : 0.0
f_stars(float sc) => sc >= 8 ? "★★★★" : sc >= 6.5 ? "★★★" : sc >= 5 ? "★★" : sc >= 3 ? "★" : "·"
f_tierWord(float _s) => _s >= 7.5 ? "EXTREME" : _s >= 5.0 ? "STRONG" : "MILD"
f_bucket(float _s) => _s >= 7.5 ? 2 : _s >= 5.0 ? 1 : 0

f_gauge(float frac, int n) =>
    int k = math.max(0, math.min(n, int(math.round(frac * n))))
    str.repeat("▰", k) + str.repeat("▱", n - k)

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

f_textOn(color _bg) =>
    float lum = 0.299 * color.r(_bg) + 0.587 * color.g(_bg) + 0.114 * color.b(_bg)
    lum >= 150.0 ? color.rgb(8, 8, 12) : color.rgb(226, 228, 238)

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

f_inSess(string _s) => not na(time(timeframe.period, _s + ":1234567", tzInput))

f_sessName(int s) => s == 1 ? "ASIA" : s == 2 ? "LONDON" : s == 3 ? "NY AM" : s == 4 ? "NY PM" : "OFF"
f_sessShort(int s) => s == 1 ? "AS" : s == 2 ? "LN" : s == 3 ? "NA" : s == 4 ? "NP" : "··"
f_sessCol(int s) => s == 1 ? asiaColInput : s == 2 ? lonColInput : s == 3 ? nyAmColInput : s == 4 ? nyPmColInput : otherColInput
f_sessW(int s) => s == 3 ? 1.5 : s == 2 ? 1.0 : s == 4 ? 1.0 : s == 1 ? 0.5 : 0.0

f_kindName(int k) => k == 0 ? "SWEEP" : k == 1 ? "SFP" : "MSS"
f_kindCol(int k) => k == 0 ? colXInput : k == 1 ? colSfpInput : colMssInput
f_kindStyle(int k) => k == 0 ? f_style(styXInput) : k == 1 ? f_style(stySfpInput) : f_style(styMssInput)
f_kindShow(int k) => k == 0 ? showXInput : k == 1 ? showSfpInput : showMssInput

f_nextTf(string _tf) =>
    _tf == "1" ? "5" : _tf == "5" ? "15" : _tf == "15" ? "30" : _tf == "30" ? "60" : _tf == "60" ? "240" : _tf == "240" ? "1D" : _tf == "1D" ? "1W" : _tf == "1W" ? "1M" : ""

f_prettyTf(string _tf) =>
    _tf == "1" ? "1m" : _tf == "5" ? "5m" : _tf == "15" ? "15m" : _tf == "30" ? "30m" : _tf == "60" ? "1H" : _tf == "120" ? "2H" : _tf == "240" ? "4H" : _tf == "1D" ? "1D" : _tf == "1W" ? "1W" : _tf == "1M" ? "1M" : _tf

float atrUnit   = ta.atr(atrLenInput)
float atrSafe   = na(atrUnit) or atrUnit <= 0.0 ? syminfo.mintick * 10.0 : atrUnit
float volAvg20  = ta.sma(volume, 20)
bool  hasVol    = not na(volume) and volAvg20 > 0.0
float volRatio  = hasVol ? nz(volume) / volAvg20 : 1.0
float rangeBar  = math.max(high - low, syminfo.mintick)
float wickUpR   = (high - math.max(open, close)) / rangeBar
float wickDnR   = (math.min(open, close) - low) / rangeBar
int   sessNow   = f_inSess(nyPmSess) ? 4 : f_inSess(nyAmSess) ? 3 : f_inSess(lonSess) ? 2 : f_inSess(asiaSess) ? 1 : 0

float ph = ta.pivothigh(high, prdInput, prdInput)
float pl = ta.pivotlow(low, prdInput, prdInput)

int   pivBar    = bar_index - prdInput
int   pivSess   = sessNow[prdInput]
float pivVol    = volRatio[prdInput]
float pivWickUp = wickUpR[prdInput]
float pivWickDn = wickDnR[prdInput]

float biasRaw = (close - ta.ema(close, 50)) / atrSafe
string tf1 = f_nextTf(timeframe.period)
string tf2 = f_nextTf(tf1)
string tf3 = f_nextTf(tf2)
string tf1Safe = tf1 == "" ? timeframe.period : tf1
string tf2Safe = tf2 == "" ? timeframe.period : tf2
string tf3Safe = tf3 == "" ? timeframe.period : tf3
float b1raw = request.security(syminfo.tickerid, tf1Safe, biasRaw[1], lookahead=barmerge.lookahead_on)
float b2raw = request.security(syminfo.tickerid, tf2Safe, biasRaw[1], lookahead=barmerge.lookahead_on)
float b3raw = request.security(syminfo.tickerid, tf3Safe, biasRaw[1], lookahead=barmerge.lookahead_on)
float b1 = tf1 == "" ? na : b1raw
float b2 = tf2 == "" ? na : b2raw
float b3 = tf3 == "" ? na : b3raw

bool keyDayOk  = timeframe.in_seconds(timeframe.period) < timeframe.in_seconds("D")
bool keyWeekOk = timeframe.in_seconds(timeframe.period) < timeframe.in_seconds("W")
[pdHraw, pdLraw] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead=barmerge.lookahead_on)
[pwHraw, pwLraw] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead=barmerge.lookahead_on)
float pdH = keyDayInput and keyDayOk ? pdHraw : na
float pdL = keyDayInput and keyDayOk ? pdLraw : na
float pwH = keyWeekInput and keyWeekOk ? pwHraw : na
float pwL = keyWeekInput and keyWeekOk ? pwLraw : na

var float dayHi = na
var float dayLo = na
var float wkHi  = na
var float wkLo  = na
if timeframe.change("D") or na(dayHi)
    dayHi := high
    dayLo := low
else
    dayHi := math.max(dayHi, high)
    dayLo := math.min(dayLo, low)
if timeframe.change("W") or na(wkHi)
    wkHi := high
    wkLo := low
else
    wkHi := math.max(wkHi, high)
    wkLo := math.min(wkLo, low)
bool pdhSwept = not na(pdH) and dayHi >= pdH
bool pdlSwept = not na(pdL) and dayLo <= pdL
bool pwhSwept = not na(pwH) and wkHi >= pwH
bool pwlSwept = not na(pwL) and wkLo <= pwL

type Lvl
    int   dir
    float price
    int   pbar
    int   sess
    int   touches
    float score
    bool  pierced
    int   pierceBar
    float extreme
    line  ln
    line  glow
    label tag

type Sig
    int   dir
    int   kind
    int   sess
    int   bucket
    float entry
    float target
    float invalid
    float risk
    int   ebar
    float mfe
    float mae
    line  lnT
    line  lnX

var array<Lvl>   lvls   = array.new<Lvl>()
var array<Sig>   sigs   = array.new<Sig>()
var array<line>  hLines = array.new<line>()
var array<label> hLbls  = array.new<label>()
var array<box>   hBoxes = array.new<box>()
var array<label> outLbls = array.new<label>()

var line  pdhLn = na
var line  pdlLn = na
var line  pwhLn = na
var line  pwlLn = na
var label pdhLb = na
var label pdlLb = na
var label pwhLb = na
var label pwlLb = na

var array<int>   evKind  = array.new<int>(3, 0)
var array<float> evDepth = array.new<float>(3, 0.0)
var array<float> evAge   = array.new<float>(3, 0.0)
var array<int>   sesLvl  = array.new<int>(5, 0)
var array<int>   sesEv   = array.new<int>(15, 0)
var array<int>   sesSigN = array.new<int>(5, 0)
var array<int>   sesSigW = array.new<int>(5, 0)
var int   nLvlCreated = 0
var int   nLvlExpired = 0
var int   nLvlMerged  = 0
var int   nEvBull     = 0
var int   nEvBear     = 0

var array<int>   kN   = array.new<int>(3, 0)
var array<int>   kW   = array.new<int>(3, 0)
var array<int>   kTO  = array.new<int>(3, 0)
var array<float> kBar = array.new<float>(3, 0.0)
var array<float> kMfe = array.new<float>(3, 0.0)
var array<float> kMae = array.new<float>(3, 0.0)
var array<int>   sN   = array.new<int>(2, 0)
var array<int>   sW   = array.new<int>(2, 0)
var array<int>   bN   = array.new<int>(3, 0)
var array<int>   bW   = array.new<int>(3, 0)
var int   totN  = 0
var int   totW  = 0
var int   totTO = 0
var float totR  = 0.0
var float sumWinR  = 0.0
var float sumLossR = 0.0
var float eqPeak = 0.0
var float maxDD  = 0.0
var int   streak = 0
var int   lastSigBar  = na
var int   lastSigDir  = 0
var int   lastSigKind = 0
var float lastSigSc   = na

bool evXBull = false
bool evXBear = false
bool evSfpBull = false
bool evSfpBear = false
bool evMssBull = false
bool evMssBear = false
bool sigNow = false
bool sigStrongNow = false
bool outTgtNow = false
bool outInvNow = false
bool newLvlBull = false
bool newLvlBear = false
float bestSigSc = 0.0

f_recycleHist() =>
    while hLines.size() > maxHistInput * 2
        line.delete(hLines.shift())
    while hLbls.size() > maxHistInput * 2
        label.delete(hLbls.shift())
    while hBoxes.size() > maxHistInput
        box.delete(hBoxes.shift())
    while outLbls.size() > maxHistInput * 2
        label.delete(outLbls.shift())

f_tagText(Lvl L) =>
    f_px(L.price) + " " + f_stars(L.score) + (L.touches > 1 ? " ×" + str.tostring(L.touches) : "") + " " + f_sessShort(L.sess)

f_tagTip(Lvl L) =>
    (L.dir == 1 ? "SELL-SIDE liquidity · stops above a swing high" : "BUY-SIDE liquidity · stops below a swing low") +
     "\nOrigin " + f_sessName(L.sess) + " session · " + str.tostring(L.touches) + " touch" + (L.touches > 1 ? "es (equal level pool)" : "") +
     "\nLevel strength " + str.tostring(L.score, "#.0") + "/10 " + f_stars(L.score) +
     "\nAge " + str.tostring(bar_index - L.pbar) + " bars" + (L.pierced ? "\n● PIERCED · waiting for reclaim (SFP) or acceptance (MSS)" : "")

f_refreshTag(Lvl L) =>
    if not na(L.tag)
        label.set_text(L.tag, f_tagText(L))
        label.set_tooltip(L.tag, f_tagTip(L))
        label.set_x(L.tag, bar_index + extInput)
        if L.pierced
            label.set_color(L.tag, color.new(f_sessCol(L.sess), 35))

f_levelScore(int _sess, int _touch, float _vr, float _wick) =>
    float s = 2.0 + f_sessW(_sess) + math.min(3.0, (_touch - 1) * 1.5) + f_clamp(_vr - 1.0, 0.0, 1.5) + f_clamp(_wick, 0.0, 1.0) * 2.0
    f_clamp(s, 0.0, 10.0)

f_createLevel(int _dir, float _price) =>
    int pbar = pivBar
    int ps   = pivSess
    float vr = pivVol
    float wk = _dir == 1 ? pivWickUp : pivWickDn
    color sc = f_sessCol(ps)
    line  gl = na
    if glowInput
        gl := line.new(pbar, _price, bar_index + extInput, _price, xloc=xloc.bar_index, color=color.new(sc, GLOW_T), style=line.style_solid, width=widthInput + 4)
    line  ln = line.new(pbar, _price, bar_index + extInput, _price, xloc=xloc.bar_index, color=sc, style=line.style_solid, width=widthInput)
    label tg = na
    int   noBar = na
    Lvl L = Lvl.new(_dir, _price, pbar, ps, 1, f_levelScore(ps, 1, vr, wk), false, noBar, _price, ln, gl, tg)
    if showPriceInput
        tg := label.new(bar_index + extInput, _price, "", xloc=xloc.bar_index, yloc=yloc.price, color=sc, style=label.style_label_left, textcolor=f_textOn(sc), size=f_size3(tagSizeInput))
        L.tag := tg
        f_refreshTag(L)
    L

f_countSide(int _dir) =>
    int c = 0
    if lvls.size() > 0
        for i = 0 to lvls.size() - 1
            if lvls.get(i).dir == _dir
                c += 1
    c

f_dropLevel(int i) =>
    Lvl L = lvls.get(i)
    line.delete(L.ln)
    if not na(L.glow)
        line.delete(L.glow)
    if not na(L.tag)
        label.delete(L.tag)
    lvls.remove(i)

f_expireOldest(int _dir) =>

    if lvls.size() > 0
        int idx = -1
        for i = 0 to lvls.size() - 1
            if idx < 0 and lvls.get(i).dir == _dir
                idx := i
        if idx >= 0
            f_dropLevel(idx)

f_tryMerge(int _dir, float _price) =>

    bool merged = false
    if eqMergeInput and lvls.size() > 0
        for i = 0 to lvls.size() - 1
            Lvl L = lvls.get(i)
            if not merged and L.dir == _dir and not L.pierced and math.abs(L.price - _price) <= eqTolInput * atrSafe
                L.touches += 1
                float vr = pivVol
                float wk = _dir == 1 ? pivWickUp : pivWickDn
                L.score := math.max(L.score, f_levelScore(L.sess, L.touches, vr, wk))

                if _dir == 1 and _price > L.price
                    L.price := _price
                else if _dir == -1 and _price < L.price
                    L.price := _price
                L.extreme := L.price
                line.set_y1(L.ln, L.price)
                line.set_y2(L.ln, L.price)
                if not na(L.glow)
                    line.set_y1(L.glow, L.price)
                    line.set_y2(L.glow, L.price)
                if not na(L.tag)
                    label.set_y(L.tag, L.price)
                f_refreshTag(L)
                merged := true
    merged

if not na(ph)
    bool broken = false
    for i = 0 to prdInput - 1
        if high[i] > ph
            broken := true
    if not broken
        if f_tryMerge(1, ph)
            nLvlMerged += 1
        else
            if f_countSide(1) >= maxActInput
                f_expireOldest(1)
                nLvlExpired += 1
            Lvl L = f_createLevel(1, ph)
            lvls.push(L)
            nLvlCreated += 1
            sesLvl.set(L.sess, sesLvl.get(L.sess) + 1)
            newLvlBear := true

if not na(pl)
    bool broken = false
    for i = 0 to prdInput - 1
        if low[i] < pl
            broken := true
    if not broken
        if f_tryMerge(-1, pl)
            nLvlMerged += 1
        else
            if f_countSide(-1) >= maxActInput
                f_expireOldest(-1)
                nLvlExpired += 1
            Lvl L = f_createLevel(-1, pl)
            lvls.push(L)
            nLvlCreated += 1
            sesLvl.set(L.sess, sesLvl.get(L.sess) + 1)
            newLvlBull := true

f_sigStrength(Lvl L, int kind, int thesis, float depthAtr) =>

    float base  = L.score * 0.4
    float depth = f_clamp(depthAtr, 0.0, 1.0) * 2.0
    float vol   = hasVol ? f_clamp(volRatio - 1.0, 0.0, 1.0) * 2.0 : 1.0
    float body  = kind == 2 ? f_clamp(math.abs(close - close[1]) / atrSafe, 0.0, 0.5) * 4.0 : f_clamp(math.abs(close - L.price) / atrSafe, 0.0, 0.5) * 4.0
    f_clamp(base + depth + vol + body, 0.0, 10.0)

f_fireEvent(Lvl L, int kind, int thesis, float depthAtr, float sc) =>
    color kc = f_kindCol(kind)
    color ac = thesis == 1 ? bullAccent : bearAccent
    string ks = f_kindName(kind)
    line.set_x2(L.ln, bar_index)
    line.set_color(L.ln, kc)
    line.set_style(L.ln, f_kindStyle(kind))
    line.set_width(L.ln, kind == 2 ? widthInput + 1 : widthInput)
    if not na(L.glow)
        line.set_x2(L.glow, bar_index)
        line.set_color(L.glow, color.new(kc, GLOW_T))
    if not na(L.tag)
        label.delete(L.tag)
    string tip = ks + " · " + (kind == 0 ? "liquidity sweep · wick through the pool, same-bar close back inside (stop raid, no acceptance)" : kind == 1 ? "closed through, then reclaimed (swing failure)" : "closed through and accepted (structure shift)") +
         "\nThesis " + (thesis == 1 ? "BULLISH ▲" : "BEARISH ▼") + " · " + f_tierWord(sc) + " " + str.tostring(sc, "#.0") + "/10 " + f_stars(sc) +
         "\nLevel " + f_px(L.price) + " · " + (L.dir == 1 ? "sell-side" : "buy-side") + " · origin " + f_sessName(L.sess) + " · " + str.tostring(L.touches) + " touch" +
         "\nSweep depth " + str.tostring(depthAtr, "#.00") + " ATR · level age " + str.tostring(bar_index - L.pbar) + " bars" +
         "\nVolume " + (hasVol ? str.tostring(volRatio, "#.00") + "× avg" : "n/a") + " · event session " + f_sessName(sessNow)
    if f_kindShow(kind)
        int   midX = math.round((L.pbar + bar_index) / 2.0)
        float mult = L.dir == 1 ? (flipInput ? -1.0 : 1.0) : (flipInput ? 1.0 : -1.0)
        label ml = label.new(midX, L.price + offAtrInput * atrSafe * mult, ks, xloc=xloc.bar_index, yloc=yloc.price,
             color=color.new(kc, 100), style=label.style_none, textcolor=kc, size=f_size5(kindSizeInput), tooltip=tip)
        hLbls.push(ml)
        if showSweepBox and kind != 2 and not na(L.extreme) and L.extreme != L.price
            int bx1 = L.pierced ? L.pierceBar : bar_index
            float top = L.dir == 1 ? L.extreme : L.price
            float bot = L.dir == 1 ? L.price : L.extreme
            box bx = box.new(bx1, top, bar_index, bot, border_color=color.new(ac, BOX_BRD), border_width=1, border_style=line.style_dotted,
                 xloc=xloc.bar_index, bgcolor=color.new(ac, BOX_T))
            hBoxes.push(bx)
    if showSigLblInput and sc >= minStrInput
        label sl = label.new(bar_index, thesis == 1 ? low : high, ks + " " + f_stars(sc) + " " + str.tostring(sc, "#.0"),
             xloc=xloc.bar_index, yloc=yloc.price, color=color.new(ac, sc >= 7.5 ? 0 : sc >= 5.0 ? 15 : 35),
             style=thesis == 1 ? label.style_label_up : label.style_label_down, textcolor=f_textOn(ac), size=f_size3(tagSizeInput), tooltip=tip)
        hLbls.push(sl)
    hLines.push(L.ln)
    if not na(L.glow)
        hLines.push(L.glow)
    f_recycleHist()

f_openSig(Lvl L, int kind, int thesis, float sc) =>
    float riskPx = invUInput * atrSafe
    if stopModeInput == "Structural"
        float structDist = kind == 2 ? math.abs(close - L.price) : math.abs(close - L.extreme)
        riskPx := structDist + bufInput * atrSafe
    riskPx := math.max(riskPx, minRiskInput * atrSafe)
    float tgt = close + thesis * tgtRInput * riskPx
    float inv = close - thesis * riskPx
    line noLn = na
    Sig s = Sig.new(thesis, kind, sessNow, f_bucket(sc), close, tgt, inv, riskPx, bar_index, 0.0, 0.0, noLn, noLn)
    if showTgtInput
        s.lnT := line.new(bar_index, tgt, bar_index + 1, tgt, xloc=xloc.bar_index, color=color.new(thesis == 1 ? bullAccent : bearAccent, 30), style=line.style_dotted, width=1)
        s.lnX := line.new(bar_index, inv, bar_index + 1, inv, xloc=xloc.bar_index, color=color.new(thesis == 1 ? bearAccent : bullAccent, 30), style=line.style_dotted, width=1)
    sigs.push(s)
    s

if barstate.isconfirmed and lvls.size() > 0
    for i = lvls.size() - 1 to 0
        Lvl L = lvls.get(i)
        int   d   = L.dir
        float lvl = L.price
        bool  beyond      = d == 1 ? high >= lvl : low <= lvl
        bool  closeBeyond = d == 1 ? close > lvl : close < lvl
        bool  closeInside = d == 1 ? close < lvl : close > lvl
        float wickExt     = d == 1 ? high : low
        int   kind = -1

        if maxAgeInput > 0 and bar_index - L.pbar > maxAgeInput
            f_dropLevel(i)
            nLvlExpired += 1
        else
            if L.pierced
                L.extreme := d == 1 ? math.max(L.extreme, wickExt) : math.min(L.extreme, wickExt)
                bool momentum = d == 1 ? close > close[1] : close < close[1]
                bool dispOk   = mssDispInput <= 0.0 or math.abs(close - lvl) >= mssDispInput * atrSafe
                if closeInside
                    kind := 1
                else if closeBeyond and momentum and dispOk
                    kind := 2
                else if bar_index - L.pierceBar >= patienceInput and closeBeyond
                    kind := 2
                if kind < 0
                    line.set_x2(L.ln, bar_index + extInput)
                    if not na(L.glow)
                        line.set_x2(L.glow, bar_index + extInput)
                    f_refreshTag(L)
            else
                if beyond and closeInside
                    L.extreme := wickExt
                    kind := 0
                else if closeBeyond
                    L.pierced := true
                    L.pierceBar := bar_index
                    L.extreme := wickExt
                    f_refreshTag(L)
                else

                    line.set_x2(L.ln, bar_index + extInput)
                    if not na(L.glow)
                        line.set_x2(L.glow, bar_index + extInput)
                    f_refreshTag(L)
            if kind >= 0
                int   thesis   = kind == 2 ? d : -d
                float depthAtr = math.abs(L.extreme - lvl) / atrSafe
                float sc       = f_sigStrength(L, kind, thesis, depthAtr)
                f_fireEvent(L, kind, thesis, depthAtr, sc)

                evKind.set(kind, evKind.get(kind) + 1)
                evDepth.set(kind, evDepth.get(kind) + depthAtr)
                evAge.set(kind, evAge.get(kind) + (bar_index - L.pbar))
                sesEv.set(L.sess * 3 + kind, sesEv.get(L.sess * 3 + kind) + 1)
                nEvBull += thesis == 1 ? 1 : 0
                nEvBear += thesis == -1 ? 1 : 0
                if kind == 0
                    evXBull := evXBull or thesis == 1
                    evXBear := evXBear or thesis == -1
                else if kind == 1
                    evSfpBull := evSfpBull or thesis == 1
                    evSfpBear := evSfpBear or thesis == -1
                else
                    evMssBull := evMssBull or thesis == 1
                    evMssBear := evMssBear or thesis == -1
                if sc >= minStrInput
                    f_openSig(L, kind, thesis, sc)
                    sigNow := true
                    sigStrongNow := sigStrongNow or sc >= 7.5
                    bestSigSc := math.max(bestSigSc, sc)
        

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