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

Titpaud SMC All TFs

indicator titpaud smc all tfs for tradingview.pine

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

indicator crt with smc levels for tradingview.pineTradingView · 1 общих теговgold_session_liquidity_free_mt5 (1).mq5MQL5 / MetaTrader 5 · 1 общих теговconfluenceforge_pro.mq5TradingView · 1 общих теговidentical candles.mq5MQL5 / MetaTrader 5 · 1 общих теговbattleplan_ciclo_3_tempi.mq4MQL4 / MetaTrader 4 · 1 общих теговvolatility_gold_master.mq5MQL5 / MetaTrader 5 · 1 общих тегов
Вы автор или правообладатель?

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

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

О программе

Titpaud SMC All TFs — индикатор для TradingView, который поверх графика отображает ордер-блоки (OB) и фейр-вэлю гэпы (FVG) сразу со множества таймфреймов: от 1 минуты до 1 месяца. Логика расчёта OB и FVG основана на скрипте BigBeluga «Price Action Smart Money Concepts» и дополнена автором Titpaud многофрейменной сеткой, оценкой силы зон и фильтрами перекрытий. Расчёт выполняется средствами Pine Script, данные других таймфреймов получают через request.security(), отображение — линии, коробки и графические метки на графике.

Каждый таймфрейм учитывается только после закрытия свечи, что исключает перерисовку. Для ордер-блоков реализована оценка силы по пяти критериям (объём, импульс, отскок, FVG, ликвидность), расчёт веса по объёму, фильтры перекрытий зон и режимы отображения меток. FVG могут оцениваться по аналогичной шкале звёзд и дополняться опциями фильтрации размера, средней свечи, незаполненной части и близости к OB.

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

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

НастройкаОписание
obShow Главный переключатель ордер-блоков: снятие показывает все OB (коробки и метки) и оставляет только FVG. OB всё ещё рассчитываются.
tfList Список таймфреймов, для которых рассчитываются OB и FVG. Один запрос на каждый ТФ (Pine позволяет 40). Варианты: Wide 1m→1M (22 ТФ), Fine 1m→3M (36 ТФ), Custom list (16 слотов).
obLoR Нижняя граница диапазона таймфреймов для отображения OB: только ТФ между пределами показывают свои OB. Пример: график 1ч, ÷64 и ×1000 → все ТФ от 1м до 1М.
obHiR Верхняя граница диапазона таймфреймов для отображения OB: только ТФ между пределами показывают свои OB. Пример: график 1ч, ÷64 и ×1000 → все ТФ от 1м до 1М. ÷1 = нет ТФ ниже графика.
fvLoR Нижняя граница диапазона таймфреймов для отображения FVG: только таймфреймы между установленными пределами показывают свои FVG. Пример: график 1ч, ÷4 и ×4 → FVG от 15м до 4ч.
fvHiR Верхняя граница диапазона таймфреймов для отображения FVG: только таймфреймы между установленными пределами показывают свои FVG. Для FVG других ТФ. FVG графика настраиваются отдельно.
incChart Всегда включает таймфрейм графика в расчёт OB и FVG, даже если он не входит в выбранный список.
nChart Количество ордер-блоков с каждой стороны (бычьи и медвежьи) для таймфрейма графика. ТФ графика всегда рассчитывается.
nTF Количество ордер-блоков с каждой стороны для каждого ТФ из списка. % вес рассчитывается на этих OB. При 22 ТФ × 2 стороны × 4 OB = максимум 176 коробок до фильтра перекрытий.
win Количество свечей таймфрейма графика, используемых для расчёта (аналог Window в оригинальном SMC).
winTF Количество свечей каждого другого таймфрейма, используемых для расчёта. На графике 1ч, 1500 свечей 1м ≈ 25 часов. Уменьшите, если скрипт работает медленно.
cTf1 Таймфрейм первого слота пользовательского списка.
cOn1 Включает или отключает первый слот пользовательского списка таймфреймов.
cTf2 Таймфрейм второго слота пользовательского списка.
cOn2 Включает или отключает второй слот пользовательского списка таймфреймов.
cTf3 Таймфрейм третьего слота пользовательского списка.
cOn3 Включает или отключает третий слот пользовательского списка таймфреймов.
cTf4 Таймфрейм четвёртого слота пользовательского списка.
cOn4 Включает или отключает четвёртый слот пользовательского списка таймфреймов.
cTf5 Таймфрейм пятого слота пользовательского списка.
cOn5 Включает или отключает пятый слот пользовательского списка таймфреймов.
cTf6 Таймфрейм шестого слота пользовательского списка.
cOn6 Включает или отключает шестой слот пользовательского списка таймфреймов.
cTf7 Таймфрейм седьмого слота пользовательского списка.
cOn7 Включает или отключает седьмой слот пользовательского списка таймфреймов.
cTf8 Таймфрейм восьмого слота пользовательского списка.
cOn8 Включает или отключает восьмой слот пользовательского списка таймфреймов.
cTf9 Таймфрейм девятого слота пользовательского списка.
cOn9 Включает или отключает девятый слот пользовательского списка таймфреймов.
cTf10 Таймфрейм десятого слота пользовательского списка.
cOn10 Включает или отключает десятый слот пользовательского списка таймфреймов.
cTf11 Таймфрейм одиннадцатого слота пользовательского списка.
cOn11 Включает или отключает одиннадцатый слот пользовательского списка таймфреймов.
cTf12 Таймфрейм двенадцатого слота пользовательского списка.
cOn12 Включает или отключает двенадцатый слот пользовательского списка таймфреймов.
cTf13 Таймфрейм тринадцатого слота пользовательского списка.
cOn13 Включает или отключает тринадцатый слот пользовательского списка таймфреймов.
cTf14 Таймфрейм четырнадцатого слота пользовательского списка.
cOn14 Включает или отключает четырнадцатый слот пользовательского списка таймфреймов.
cTf15 Таймфрейм пятнадцатого слота пользовательского списка.
cOn15 Включает или отключает пятнадцатый слот пользовательского списка таймфреймов.
cTf16 Таймфрейм шестнадцатого слота пользовательского списка. Один таймфрейм, указанный дважды или совпадающий с графиком, рассчитывается только один раз.
cOn16 Включает или отключает шестнадцатый слот пользовательского списка таймфреймов.
cUp Цвет заполнения бычьих ордер-блоков всех таймфреймов.
cDn Цвет заполнения медвежьих ордер-блоков всех таймфреймов. Перекрывающиеся OB нескольких ТФ выглядят темнее за счёт наложения коробок.
bs1 Стиль границы ордер-блоков таймфреймов класса 1 (ниже 15 минут): Нет, Сплошная, Пунктирная, Штрихпунктирная.
bs2 Стиль границы ордер-блоков таймфреймов класса 2 (от 15 минут до 1 часа): Нет, Сплошная, Пунктирная, Штрихпунктирная.
bs3 Стиль границы ордер-блоков таймфреймов класса 3 (от 1 часа до 4 часов): Нет, Сплошная, Пунктирная, Штрихпунктирная.
bs4 Стиль границы ордер-блоков таймфреймов класса 4 (от 4 часов до 1 дня): Нет, Сплошная, Пунктирная, Штрихпунктирная.
bs5 Стиль границы ордер-блоков таймфреймов класса 5 (от 1 дня и выше): Нет, Сплошная, Пунктирная, Штрихпунктирная.
msmode Логика структуры: Extreme Points или Adjusted Points (аналог Algorithmic Logic в оригинальном SMC).
mslen Длина пивота для логики структуры (эквивалент Algorithmic Logic в оригинальном SMC).
buildsweep Включает смещение структурных уровней при проскальзывании: если свеча закрывается за уровнем без пробоя, уровень сдвигается.
obmode Режим построения OB: [Length] — высота OB ограничена ATR(200) × число / 5; [Full] — целая свеча.
len Длина для расчёта высоты OB в режиме Construction = Length. OB высота ограничена ATR(200) × число / 5.
obmiti Условие инвалидации OB: [Close] — тело свечи ТФ OB закрывается за ним; [Wick] — фитиль выходит за него; [Avg] — фитиль достигает середины OB.
showmetric Показывает объём и вес (%) в метках OB и легенде.
showline Показывает пунктирную среднюю линию через центр OB.
showLeg Показывает легенду с диапазоном рассчитанных ТФ для OB и FVG.
legPos Позиция легенды, показывающей диапазон рассчитанных ТФ для OB и FVG.
obtxt Размер текста меток OB.
txtCol Цвет текста меток (OB и FVG) и легенды.
labOff Смещение меток OB по горизонтали (в свечах) от цены.
labMode Режим меток OB: [One label per overlap zone] — OB всех ТФ в одной зоне перекрытия делят одну метку; [One label per OB] — отдельная метка на каждый OB; [No OB labels] — только коробки.
labRange Добавляет нижнюю и верхнюю цены группы перекрывающихся OB к метке.
labStep Горизонтальное смещение меток правее цены и расстояние между метками классов ТФ (ниже 15м, 15м–1ч, 1ч–4ч, 4ч–1Д, 1Д и выше), чтобы они не перекрывались.
obBWidth Толщина границы OB для классов ТФ, у которых граница не None.
obBOpac Непрозрачность границ OB (%) для классов ТФ, у которых граница не None. 100 = полностью непрозрачно.
maxDist Скрывает OB и FVG дальше текущей цены, чем указанный процент. 0 = без ограничений.
fvg_enable Главный переключатель: показывает или скрывает все FVG на всех таймфреймах. ТФ для FVG задаются в разделе «TIMEFRAMES».
fvg_num Количество FVG для отображения с каждой стороны на таймфрейме графика.
fvg_upcss Цвет бычьего FVG. По умолчанию используется чуть более тёмный оттенок зелёного OB.
fvg_dncss Цвет медвежьего FVG. По умолчанию используется чуть более тёмный оттенок красного OB, чтобы FVG и OB можно было различить.
fvg_src Триггер митигации FVG: [Close] — закрытие тела свечи, [Wick] — экстремальная точка, [Avg] — средняя между телом и экстремумом.
fvgthresh Фильтр: отбрасывает незначительные FVG, задаёт минимальный порог в ATR(14).
fvgoverlap Скрывает перекрывающиеся FVG одного направления.
fvgChart Включает отображение FVG на таймфрейме графика.
fvgMtfN Количество FVG с каждой стороны для каждого таймфрейма из списка. Для FVG графика используется параметр Show Last.
fvgOvStep Добавляемая непрозрачность FVG (%) за каждый дополнительный перекрывающий таймфрейм.
fvgOvCap Максимальное уменьшение прозрачности FVG (%) за каждый дополнительный перекрывающий TF. 0 = без эффекта.
fvgMtfLab Показывает метку таймфрейма на FVG других таймфреймов.
fvgMtfOut Рисует тонкий пунктирный контур вокруг FVG других таймфреймов, чтобы они выделялись на фоне FVG графика. Снимается: контура нет.
obOnlyOv Показывает только OB, перекрывающиеся с OB других таймфреймов.
obMinOv OB остаётся видимым только если он перекрывается (хотя бы частично) с OB одного направления как минимум этого числа других таймфреймов. 1 = достаточно одного другого ТФ.
obKeepLast При включённом фильтре перекрытий самый последний OB (все ТФ, оба направления) остаётся видимым, даже если не перекрывается ни с чем.
obKeepCh При включённом фильтре перекрытий все OB таймфрейма графика остаются видимыми, перекрываются они или нет.
fvgOnlyOv Показывает только те FVG, которые перекрываются с FVG другого таймфрейма.
showOvN Добавляет «+N TF» к метке OB: количество других таймфреймов, OB которых перекрывают данный OB.
minTr Нижний предел непрозрачности для любого OB, независимо от звёзд, перекрытий и веса. Зоны перекрытия всё равно темнее за счёт наложения коробок нескольких ТФ.
showStr Оценка силы OB звёздами (★ до ★★★★★): 1 звезда за каждый из 5 критериев (V, I, R, F, S). Больше звёзд = более непрозрачная зона.
showDetV Показывает значение V в метке OB: объём свечи OB относительно среднего.
showDetI Показывает значение I в метке OB: сила начального импульса.
showDetR Показывает значения R в метке OB: количество отскоков и лучший отскок.
showDetF Показывает маркер F в метке OB: импульс, покинувший OB, оставил FVG.
showDetS Показывает маркер S в метке OB: OB проскользнул ликвидность.
thrV Порог для оценки объёма OB: ≥ указанного кратного среднему объёму считается сильным.
thrI Порог для оценки силы импульса: ≥ указанного значения в ATR считается сильным.
thrR Порог для оценки отскока: ≥ указанного значения в ATR считается сильным.
swBars Звезда S: свеча OB выходила за последний подтверждённый свинг до неё, и закрытие вернулось на другую сторону этого уровня в пределах этого числа свечей. 0 = свеча OB сама должна вернуться.
opStep Добавляемая непрозрачность (%) за каждую звезду силы OB.

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

indicator("Titpaud SMC All TFs", "Titpaud SMC All TFs", overlay = true, max_bars_back = 5000, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)

G_TF  = "TIMEFRAMES"
G_CUS = "CUSTOM LIST (used when List = Custom list)"
G_COL = "COLOURS AND BORDERS"
G_OB  = "ORDER BLOCKS (same settings as the original SMC)"
G_AFF = "DISPLAY"
G_IMB = "NESTED OB"

obShow  = input.bool(true, "Show order blocks", group = G_TF, tooltip = "Master switch of the order blocks: untick it to hide every OB (boxes and labels) and keep only the FVGs. The OBs are still computed, so the FVG option « Only FVGs touching an OB » keeps working.")
tfList  = input.string("Wide 1m → 1M (22 TFs)", "List", options = ["Wide 1m → 1M (22 TFs)", "Fine 1m → 3M (36 TFs)", "Custom list"], group = G_TF, tooltip = "Timeframes whose OBs and FVGs are computed. One request per TF (Pine allows 40).\nWide 1m → 1M: 1m, 3m, 5m, 10m, 15m, 30m, 45m, 1h, 1h30, 2h, 3h, 4h, 6h, 8h, 12h, 1D, 2D, 3D, 1W, 2W, 3W, 1M.\nFine 1m → 3M: 1m, 2m, 3m, 4m, 5m, 6m, 8m, 10m, 12m, 15m, 20m, 25m, 30m, 40m, 45m, 1h, 1h15, 1h30, 1h45, 2h, 2h30, 3h, 4h, 6h, 8h, 12h, 1D, 2D, 3D, 4D, 5D, 1W, 2W, 3W, 1M, 3M. Much heavier: lower the history per TF if the script is too slow.\nCustom list: the 16 slots of the « CUSTOM LIST » group.")
obLoR   = input.int(64, "OB TFs from chart TF ÷", minval = 1, maxval = 10000, inline = "obr", group = G_TF)
obHiR   = input.int(1000, "to chart TF ×", minval = 1, maxval = 10000, inline = "obr", group = G_TF, tooltip = "Only the TFs of the list between these two limits show their OBs. Example: 1h chart, ÷64 and ×1000 → every TF from 1m to 1M. ÷1 → no TF lower than the chart.")
fvLoR   = input.int(4, "FVG TFs from chart TF ÷", minval = 1, maxval = 10000, inline = "fvr", group = G_TF)
fvHiR   = input.int(4, "to chart TF ×", minval = 1, maxval = 10000, inline = "fvr", group = G_TF, tooltip = "Same for the FVGs of the other TFs. Example: 1h chart, ÷4 and ×4 → FVGs from 15m to 4h. The chart-TF FVGs are set in « FAIR VALUE GAP ».")
incChart = input.bool(true, "Always include the chart TF", inline = "ch", group = G_TF)
nChart  = input.int(4, "OBs per side", minval = 0, maxval = 10, inline = "ch", group = G_TF, tooltip = "The chart TF is always computed, even if it is not in the list, with its own number of OBs per side (bullish and bearish).")
nTF     = input.int(4, "OBs per side, other TFs", minval = 0, maxval = 10, group = G_TF, tooltip = "Number of OBs per side (bullish and bearish) for each TF of the list. The % weight is computed on these OBs. 22 TFs × 2 sides × 4 OBs = 176 boxes at most, before the overlap filter.")
win     = input.int(5000, "History: chart TF (bars)", minval = 500, maxval = 20000, inline = "win", group = G_TF)
winTF   = input.int(1500, "other TFs (bars)", minval = 300, maxval = 5000, inline = "win", group = G_TF, tooltip = "Like « Window » in the original SMC: number of candles of each timeframe used for the calculation. On a 1h chart, 1500 candles of 1m = about 25 hours: older 1m OBs are not found. Lower it if the script is slow or shows a memory error.")

cTf1  = input.timeframe("1",   "", inline = "cu1", group = G_CUS)
cOn1  = input.bool(true, "", inline = "cu1", group = G_CUS)
cTf2  = input.timeframe("3",   "", inline = "cu1", group = G_CUS)
cOn2  = input.bool(true, "", inline = "cu1", group = G_CUS)
cTf3  = input.timeframe("5",   "", inline = "cu2", group = G_CUS)
cOn3  = input.bool(true, "", inline = "cu2", group = G_CUS)
cTf4  = input.timeframe("15",  "", inline = "cu2", group = G_CUS)
cOn4  = input.bool(true, "", inline = "cu2", group = G_CUS)
cTf5  = input.timeframe("30",  "", inline = "cu3", group = G_CUS)
cOn5  = input.bool(true, "", inline = "cu3", group = G_CUS)
cTf6  = input.timeframe("60",  "", inline = "cu3", group = G_CUS)
cOn6  = input.bool(true, "", inline = "cu3", group = G_CUS)
cTf7  = input.timeframe("120", "", inline = "cu4", group = G_CUS)
cOn7  = input.bool(true, "", inline = "cu4", group = G_CUS)
cTf8  = input.timeframe("240", "", inline = "cu4", group = G_CUS)
cOn8  = input.bool(true, "", inline = "cu4", group = G_CUS)
cTf9  = input.timeframe("480", "", inline = "cu5", group = G_CUS)
cOn9  = input.bool(true, "", inline = "cu5", group = G_CUS)
cTf10 = input.timeframe("720", "", inline = "cu5", group = G_CUS)
cOn10 = input.bool(true, "", inline = "cu5", group = G_CUS)
cTf11 = input.timeframe("D",   "", inline = "cu6", group = G_CUS)
cOn11 = input.bool(true, "", inline = "cu6", group = G_CUS)
cTf12 = input.timeframe("3D",  "", inline = "cu6", group = G_CUS)
cOn12 = input.bool(true, "", inline = "cu6", group = G_CUS)
cTf13 = input.timeframe("W",   "", inline = "cu7", group = G_CUS)
cOn13 = input.bool(true, "", inline = "cu7", group = G_CUS)
cTf14 = input.timeframe("M",   "", inline = "cu7", group = G_CUS)
cOn14 = input.bool(true, "", inline = "cu7", group = G_CUS)
cTf15 = input.timeframe("2",   "", inline = "cu8", group = G_CUS)
cOn15 = input.bool(false, "", inline = "cu8", group = G_CUS)
cTf16 = input.timeframe("10",  "", inline = "cu8", group = G_CUS, tooltip = "16 slots: pick a TF and tick it to use it. A TF listed twice, or equal to the chart TF when « Always include the chart TF » is ticked, is only computed once.")
cOn16 = input.bool(false, "", inline = "cu8", group = G_CUS)

cUp = input.color(color.new(#089981, 97), "OB colours: bullish", inline = "k0", group = G_COL)
cDn = input.color(color.new(#f23645, 97), "bearish", inline = "k0", group = G_COL, tooltip = "Fill colours of the OBs of every TF. Overlapping OBs of several TFs look darker because their boxes stack up.")
T_CL = "Border of the OBs of this class of timeframes. The border is also used for the FVGs of these TFs."
bs1 = input.string("None", "Border: below 15m", options = ["None", "Solid", "Dashed", "Dotted"], group = G_COL, tooltip = T_CL)
bs2 = input.string("None", "Border: 15m to 1h", options = ["None", "Solid", "Dashed", "Dotted"], group = G_COL)
bs3 = input.string("None", "Border: 1h to 4h", options = ["None", "Solid", "Dashed", "Dotted"], group = G_COL)
bs4 = input.string("None", "Border: 4h to 1D", options = ["None", "Solid", "Dashed", "Dotted"], group = G_COL)
bs5 = input.string("None", "Border: 1D and above", options = ["None", "Solid", "Dashed", "Dotted"], group = G_COL)

msmode      = input.string("Adjusted Points", "Structure logic", options = ["Extreme Points", "Adjusted Points"], inline = "node", group = G_OB, tooltip = "Same as « Algorithmic Logic » in the original SMC. The number = pivot length.")
mslen       = input.int(5, "", minval = 2, inline = "node", group = G_OB)
buildsweep  = input.bool(true, "Sweeps (x)", group = G_OB, tooltip = "Same as « Build Sweep (x) »: a wick beyond a structure level without a close beyond it moves that level.")
obmode      = input.string("Length", "Construction", options = ["Length", "Full"], inline = "atr", group = G_OB, tooltip = "[Length] OB height limited to ATR(200) × number / 5\n[Full] whole candle")
len         = input.int(5, "", minval = 1, inline = "atr", group = G_OB)
obmiti      = input.string("Close", "Invalidation", options = ["Close", "Wick", "Avg"], group = G_OB, tooltip = "[Close] the body of a candle of the OB's timeframe closes beyond it\n[Wick] the wick goes beyond it\n[Avg] the wick reaches the middle of the OB")

showmetric = input.bool(true, "Volume and weight (%)", group = G_AFF)
showline   = input.bool(false, "Mid-line", group = G_AFF)
showLeg    = input.bool(true, "Legend", inline = "leg", group = G_AFF)
legPos     = input.string("Bottom left", "", options = ["Bottom left", "Bottom right", "Top right", "Top left"], inline = "leg", group = G_AFF, tooltip = "Legend: range of TFs computed for the OBs and the FVGs. Bottom left by default so it stays clear of the TradingView buttons and of the OB labels on the right.")
obtxt      = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal", "Large", "Huge", "Auto"], inline = "txt", group = G_AFF)
txtCol     = input.color(color.new(color.white, 50), "Color", inline = "txt", group = G_AFF, tooltip = "Text color of the labels (OB and FVG) and of the legend.")
labOff     = input.int(0, "Labels: offset", minval = 0, maxval = 200, inline = "lab", group = G_AFF)
labMode    = input.string("One label per overlap zone", "Labels", options = ["One label per overlap zone", "One label per OB", "No OB labels"], group = G_AFF, tooltip = "[One label per overlap zone] the OBs of all TFs that overlap (same direction) share one label: TF list, number of TFs, best stars. Volume and V/I/R details are not shown.\n[One label per OB] one label per OB with all the details, shifted per TF class (can pile up).\n[No OB labels] boxes only.")
labRange   = input.bool(false, "Price range in the overlap-zone labels", group = G_AFF, tooltip = "Adds the bottom and top prices of the whole group of overlapping OBs to its label. The label itself sits on the band where the most OBs of the group overlap.")
labStep    = input.int(11, "spacing between TF classes", minval = 0, maxval = 100, inline = "lab", group = G_AFF, tooltip = "Horizontal offset (in bars) of the labels to the right of price, and spacing between the labels of each TF class (below 15m, 15m-1h, 1h-4h, 4h-1D, 1D and above) so they don't overlap.")
obBWidth   = input.int(1, "OB border: width", minval = 1, maxval = 5, inline = "obb", group = G_AFF)
obBOpac    = input.int(70, "opacity (%)", minval = 0, maxval = 100, inline = "obb", group = G_AFF, tooltip = "Width and opacity of the OB borders, for TF classes whose border is not None. 100 = fully opaque.")
maxDist    = input.float(0.0, "Max distance from price (%)", minval = 0, step = 0.5, group = G_AFF, tooltip = "Hides the OBs and FVGs farther from the current price than this percentage. 0 = no limit.")

fvg_enable   = input.bool(true, "", inline="1", group="FAIR VALUE GAP", tooltip="Master switch: shows or hides ALL fair value gaps, on every timeframe. The TFs of the list showing FVGs are set in « TIMEFRAMES ».")
fvg_num      = input.int(4, "Show Last", inline="1a", group="FAIR VALUE GAP", tooltip="Number of fvg to show", minval=0)
fvg_upcss    = input.color(color.new(#067a67, 96), "", inline="1", group="FAIR VALUE GAP", tooltip="Bullish / bearish FVG colours: by default a slightly darker shade of the OB green and red, so FVGs and OBs can be told apart.")
fvg_dncss    = input.color(color.new(#c12b37, 95), "", inline="1", group="FAIR VALUE GAP")
fvg_src      = input.string("Close", "Mitigation",
 inline="3",
 group="FAIR VALUE GAP",
 tooltip="[Close] Use the close of the body as trigger\n\n[Wick] Use the extreme point of the body as trigger",
 options=["Close", "Wick", "Avg"])
fvgthresh    = input.float(0, "Threshold", tooltip="Filter out non significative FVG", group="FAIR VALUE GAP",
 inline="asd", minval=0, maxval=2, step=0.1)
fvgoverlap   = input.bool(true, "Hide Overlap", "Hide overlapping FVG", group="FAIR VALUE GAP")
fvgChart     = input.bool(false, "FVGs of the chart TF", group="FAIR VALUE GAP")
fvgMtfN      = input.int(4, "FVGs per side, other TFs", minval = 1, maxval = 10, group="FAIR VALUE GAP", tooltip = "Number of FVGs shown per side for each TF of the list. The chart TF uses « Show Last » above.")
fvgOvStep    = input.int(5, "Overlapping FVGs: opacity added per overlapping TF (%)", minval = 0, maxval = 10, inline = "fvo", group="FAIR VALUE GAP")
fvgOvCap     = input.int(5, "max (%)", minval = 0, maxval = 50, inline = "fvo", group="FAIR VALUE GAP", tooltip = "An FVG gets this many % less transparent for each other TF with a same-direction FVG overlapping it, up to the max. 0 = no effect.")
fvgMtfLab    = input.bool(false, "TF label on other-TF FVGs", group="FAIR VALUE GAP")
fvgMtfOut    = input.bool(false, "Dashed outline on other-TF FVGs", group="FAIR VALUE GAP", tooltip = "When the TF class border is None, draws a thin dashed outline around the FVGs of the other timeframes so they stand out from the chart-TF FVGs. Untick: no outline at all.")

G_SUP = "OVERLAP FILTER"
obOnlyOv   = input.bool(true, "Only show OBs overlapping OBs of other TFs", inline = "oo", group = G_SUP)
obMinOv    = input.int(2, "minimum number of TFs", minval = 1, maxval = 35, inline = "oo", group = G_SUP, tooltip = "An OB stays visible only if it overlaps (at least partly) same-direction OBs of at least this number of OTHER timeframes. 1 = one other TF is enough. Raise it to keep only the strongest confluences.")
obKeepLast = input.bool(true, "   … except the most recent OB", group = G_SUP, tooltip = "When the filter above is on, the most recent OB (all timeframes and both directions) stays visible even if it overlaps nothing.")
obKeepCh   = input.bool(true, "   … except the OBs of the chart TF", group = G_SUP, tooltip = "When the filter above is on, all OBs of the chart TF stay visible, overlapping or not. The other timeframes are still filtered.")
fvgOnlyOv  = input.bool(true, "Only show FVGs overlapping an FVG of another TF", group = G_SUP, tooltip = "An FVG stays visible only if it overlaps (at least partly) a same-direction FVG of another timeframe.")
showOvN    = input.bool(true, "Show the number of overlapping TFs in the OB label", group = G_SUP, tooltip = "Adds « +N TF » to the label: number of other timeframes whose same-direction OBs overlap this OB.")
minTr      = input.int(93, "Minimum transparency of one OB (%)", minval = 0, maxval = 100, group = G_SUP, tooltip = "No single OB is drawn more opaque than this, whatever its stars, ◆ or overlaps. The confluence zones still look darker because the boxes of several TFs stack up. 100 = invisible, 90 = quite visible.")

G_FOR = "OB STRENGTH"
showStr = input.bool(true, "Rate OB strength (★ to ★★★★★)", group = G_FOR, tooltip = "1 star per criterion met (5 at most): V volume of the OB candle, I strength of the initial impulse, R best bounce on retests, F the impulse left a fair value gap, S the OB swept liquidity (took out the previous swing high / low, then price closed back inside). More stars = more opaque zone.")
showDetV = input.bool(true, "Details:  V", inline = "det", group = G_FOR)
showDetI = input.bool(false, "I", inline = "det", group = G_FOR)
showDetR = input.bool(false, "R", inline = "det", group = G_FOR)
showDetF = input.bool(false, "F", inline = "det", group = G_FOR)
showDetS = input.bool(false, "S", inline = "det", group = G_FOR, tooltip = "Tick each detail to show it in the OB label (« One label per OB » mode):\nV = volume of the OB candle / 20-period average\nI = impulse: distance between the OB and the close that broke structure, in ATR(14)\nR = number of retests / best bounce in ATR(14)\nF = shown when the impulse leaving the OB left a fair value gap\nS = shown when the OB swept liquidity")
thrV    = input.float(1.5, "Strong volume if ≥ × average", minval = 0.1, step = 0.1, group = G_FOR)
thrI    = input.float(3.0, "Strong impulse if ≥ (ATR)", minval = 0.1, step = 0.5, group = G_FOR)
thrR    = input.float(2.0, "Strong bounce if ≥ (ATR)", minval = 0.1, step = 0.5, group = G_FOR)
swBars  = input.int(3, "Sweep: close back within (candles)", minval = 0, maxval = 20, group = G_FOR, tooltip = "Star S: the OB candle went beyond the last swing low (bullish OB) or swing high (bearish OB) confirmed before it, and a close came back on the other side of that level within this many candles. 0 = the OB candle itself must close back.")
opStep  = input.int(1, "Opacity added per star", minval = 0, maxval = 40, group = G_FOR)
wOn     = input.bool(true, "Heavy OBs: solid border", group = G_FOR, tooltip = "Weight = volume of the OB / average volume of the last OBs of the same TF and same side. From the threshold below, the OB keeps its normal fill but gets a solid border in its own colour, so heavy OBs stand out without darkening the chart. The labels show its volume multiple and rank (vol ×2.4 top 3%).")
wMin    = input.float(2.0, "Heavy from (× average)", minval = 1.0, step = 0.5, group = G_FOR)
volHist = input.int(50, "Volume reference: last N OBs of the TF", minval = 5, maxval = 200, group = G_FOR, tooltip = "The volume of each OB is compared with the average volume of the last N OBs of the same TF and same side, formed before it. ×3 = three times the usual OB volume on that TF.")
vxMin   = input.float(1.5, "Show the volume multiple from (× average)", minval = 0.0, step = 0.5, group = G_FOR, tooltip = "The labels show « vol ×3.2 » (the heaviest OB of an overlap zone, or each OB in « One label per OB » mode) only for OBs at least this many times the average volume. 0 = every OB.")
vxRank  = input.bool(true, "Add the rank (top N %)", group = G_FOR, tooltip = "Adds the rank of the OB volume among the last N OBs of the same TF and side: « top 5 % » = only 5 % of them had a higher volume. More reliable than the multiple when a few huge OBs inflate the average.")

markNest = input.bool(true, "Mark ◆ OBs contained in a higher-TF OB", group = G_IMB, tooltip = "An OB is marked ◆ if it lies within a same-direction, still active OB of a higher timeframe.")
nestMode = input.string("Inside", "Condition", options = ["Inside", "Overlap"], group = G_IMB, tooltip = "[Inside] the OB is fully contained in the higher-TF OB\n[Overlap] the two zones overlap at least partly")
nestBStyle = input.string("Same as TF", "Nested OB border", options = ["Same as TF", "Solid", "Dashed", "Dotted", "None"], inline = "nb", group = G_IMB, tooltip = "Border of OBs marked ◆.\n[Same as TF] same border as the other OBs of that TF class\n[Solid / Dashed / Dotted] custom border, with the width and opacity set here\n[None] no border; the ◆ stays in the label")
nestBWidth = input.int(2, "width", minval = 1, maxval = 5, inline = "nb", group = G_IMB)
nestBOpac  = input.int(100, "Nested OB border opacity (%)", minval = 0, maxval = 100, group = G_IMB, tooltip = "Opacity of the custom border of nested OBs. 100 = fully opaque, 0 = invisible.")
nestFill   = input.int(1, "Extra fill opacity for nested OBs (%)", minval = 0, maxval = 50, group = G_IMB, tooltip = "Opacity added to the fill of OBs marked ◆, on top of their colour and their stars, so nested OBs stand out. 0 = same fill as the other OBs.")

G_END     = "END OF ZONES"
endOn     = input.bool(true, "End OBs and FVGs when a chart-TF candle closes through them", group = G_END, tooltip = "An OB of a higher TF normally stays active until a candle of ITS OWN TF closes through it, so its band can cross many chart candles. With this option, the zone stops at the first chart-TF candle that closes through it (same rule as « Invalidation » for the OBs and « Mitigation » for the FVGs). Display only: the OB is still computed in its own TF.")
endMode   = input.string("Stop the box at the break", "Broken zones", options = ["Stop the box at the break", "Hide broken zones"], group = G_END, tooltip = "[Stop the box at the break] the zone is drawn from its start to the candle that broke it, without label\n[Hide broken zones] the zone disappears completely")

G_FVO     = "FVG FILTERS AND LOOK (optional)"
fv1       = input.bool(false, "1. Minimum size", inline = "fv1", group = G_FVO)
fv1Atr    = input.float(0.5, "(× ATR14 of its TF)", minval = 0.0, step = 0.1, inline = "fv1", group = G_FVO, tooltip = "Keeps only the FVGs at least this many ATR(14) high, ATR of their own TF at the time they formed. Removes the tiny gaps.")
fv2       = input.bool(false, "2. Strong middle candle", inline = "fv2", group = G_FVO)
fv2Min    = input.float(1.5, "(body or volume ≥ × average)", minval = 0.0, step = 0.1, inline = "fv2", group = G_FVO, tooltip = "Keeps only the FVGs whose middle candle has a body OR a volume at least this many times its 20-candle average: gaps created by a real displacement.")
fv3       = input.bool(true, "3. Show only the unfilled part", group = G_FVO, tooltip = "When price enters an FVG, the box shrinks to the part still unfilled (wicks included). A half-filled FVG only shows its remaining half.")
fv4       = input.bool(false, "4. Only the nearest FVGs", inline = "fv4", group = G_FVO)
fv4N      = input.int(2, "(per side of price)", minval = 1, maxval = 20, inline = "fv4", group = G_FVO, tooltip = "Keeps only the N FVGs closest to price above it and the N closest below it, all TFs together. FVGs containing the price are always kept.")
fv5       = input.bool(false, "5. Only FVGs touching an OB", group = G_FVO, tooltip = "Keeps only the FVGs overlapping a same-direction OB kept by the OB filters (even if the OBs are hidden).")
fv6       = input.bool(false, "6. Outline only, with a 50 % line", group = G_FVO, tooltip = "No fill: a thin dotted outline and a dotted line at the middle of the FVG (50 %, « consequent encroachment »). The OBs stay filled bands, the FVGs become frames.")
fv7       = input.bool(false, "7. Short boxes", inline = "fv7", group = G_FVO)
fv7Bars   = input.int(20, "(chart candles after the FVG)", minval = 3, maxval = 500, inline = "fv7", group = G_FVO, tooltip = "The FVG box stops this many chart candles after its start instead of extending to the right edge.")
fv8       = input.bool(true, "8. Own colours", inline = "fv8", group = G_FVO)
fv8Up     = input.color(color.new(#3949ab, 90), "", inline = "fv8", group = G_FVO)
fv8Dn     = input.color(color.new(#7b1fa2, 90), "", inline = "fv8", group = G_FVO, tooltip = "Bullish / bearish FVG colours used instead of the green / red ones, so FVGs cannot be confused with OBs.")

G_FST   = "FVG STRENGTH (optional)"
fsOn    = input.bool(false, "Rate FVG strength (★ to ★★★★★)", group = G_FST, tooltip = "1 star per criterion met (5 at most), measured in the FVG's own TF:\nV = volume of the middle candle vs its 20-candle average\nD = share of the middle candle volume in the FVG direction (buy share for a bullish FVG, sell share for a bearish one), estimated from where the candle closed in its range\nT = size of the gap vs the largest gap of the last 1000 candles (filter of Volumatic Fair Value Gaps [BigBeluga])\nO = the FVG touches a same-direction OB kept by the OB filters\nI = the FVG is still mostly intact (filled less than the % below)\nMore stars = more opaque FVG.")
fsV     = input.float(1.5, "V: volume ≥ × average", minval = 0.1, step = 0.1, group = G_FST)
fsD     = input.float(65, "D: volume in the FVG direction ≥ (%)", minval = 50, maxval = 100, step = 5, group = G_FST)
fsT     = input.float(10, "T: size ≥ % of the largest FVG (1000 candles)", minval = 0, maxval = 100, step = 5, group = G_FST)
fsI     = input.float(50, "I: filled less than (%)", minval = 1, maxval = 100, step = 5, group = G_FST)
fsStep  = input.int(1, "Opacity added per star (%)", minval = 0, maxval = 20, group = G_FST)
fsMin   = input.int(0, "Hide FVGs below (stars)", minval = 0, maxval = 5, group = G_FST, tooltip = "0 = all FVGs are shown. 3 = only the FVGs with at least 3 stars.")
fsLab   = input.bool(true, "Show the stars on each FVG", group = G_FST, tooltip = "Small ★ text at the start of each active FVG (nothing when it has no star).")

bool fsh1 = fvg_enable and fvgChart

bool fvUseReq = incChart

bool obshowbb = false   // breakers not shown (default of the original SMC): an invalidated OB disappears

plot(na, "", display = display.none, editable = false)   // mandatory output (like the plot(na) of the original SMC)

type FVG
    float top     = na
    float btm     = na
    int   loc     = na
    bool  isbb    = false
    int   bbloc   = na
    bool  israid  = false
    float raidy   = na
    int   raidloc = na
    int   raidx2  = na
    bool  active  = false
    color raidcs  = na
    float ftop    = na
    float fbtm    = na
    float sz      = na
    float imp     = na
    float vr      = na
    float dom     = na
    float rel     = na

type store
    line    [] ln
    label   [] lb
    box     [] bx
    linefill[] lf

type structure
    int    zn
    float  zz
    float  bos
    float  choch
    int    loc
    int    temp
    int    trend
    int    start
    float  main
    int    xloc
    bool   upsweep
    bool   dnsweep
    string txt = na

type ob
    bool  bull
    float top
    float btm
    float avg
    int   loc
    color css
    float vol
    int   dir
    int   move
    int   blPOS
    int   brPOS
    int   xlocbl
    int   xlocbr
    bool  isbb   = false
    int   bbloc
    float vr      = na
    float disp    = na
    int   nret    = 0
    float retX    = na
    float bestRet = 0.0
    float wr      = na
    float rk      = na
    int   fg      = 0
    int   sw      = 0

method txSz(string s) =>
    out = switch s
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        "Huge"   => size.huge
        "Auto"   => size.auto
    out

method find(structure ms, bool use_max, bool sweep, bool useob) =>
    min = 99999999.0
    max = 0.0
    idx = 0
    if not sweep
        if ((bar_index - ms.loc) - 1) > 0
            if use_max
                for i = 0 to (bar_index - ms.loc) - 1
                    max := math.max(high[i], max)
                    min := max ==   high[i] ? low[i] : min
                    idx := max ==   high[i] ?      i : idx

                if useob
                    if high[idx + 1] > high[idx]
                        max := high[idx + 1]
                        min := low [idx + 1]
                        idx :=      idx + 1

            else
                for i = 0 to (bar_index - ms.loc) - 1
                    min := math.min(low[i], min)
                    max := min ==   low[i] ? high[i] : max
                    idx := min ==   low[i] ?       i : idx

                if useob
                    if low[idx + 1] < low[idx]
                        max := high[idx + 1]
                        min := low [idx + 1]
                        idx :=      idx + 1

        else
            if use_max
                for i = 0 to (bar_index - ms.loc)
                    max := math.max(high[i], max)
                    min := max ==   high[i] ? low[i] : min
                    idx := max ==   high[i] ?      i : idx

                if useob
                    if high[idx + 1] > high[idx]
                        max := high[idx + 1]
                        min := low [idx + 1]
                        idx :=      idx + 1

            else
                for i = 0 to (bar_index - ms.loc)
                    min := math.min(low[i], min)
                    max := min ==   low[i] ? high[i] : max
                    idx := min ==   low[i] ?       i : idx

                if useob
                    if low[idx + 1] < low[idx]
                        max := high[idx + 1]
                        min := low [idx + 1]
                        idx :=      idx + 1

    else
        if ((bar_index - ms.xloc) - 1) > 0
            if use_max
                for i = 0 to (bar_index - ms.xloc) - 1
                    max := math.max(high[i], max)
                    min := max ==   high[i] ? low[i] : min
                    idx := max ==   high[i] ?      i : idx

                if useob
                    if high[idx + 1] > high[idx]
                        max := high[idx + 1]
                        min := low [idx + 1]
                        idx :=      idx + 1

            else
                for i = 0 to (bar_index - ms.xloc) - 1
                    min := math.min(low[i], min)
                    max := min ==   low[i] ? high[i] : max
                    idx := min ==   low[i] ?       i : idx

                if useob
                    if low[idx + 1] < low[idx]
                        max := high[idx + 1]
                        min := low [idx + 1]
                        idx :=      idx + 1

        else
            if use_max
                for i = 0 to (bar_index - ms.xloc)
                    max := math.max(high[i], max)
                    min := max ==   high[i] ? low[i] : min
                    idx := max ==   high[i] ?      i : idx

                if useob
                    if high[idx + 1] > high[idx]
                        max := high[idx + 1]
                        min := low [idx + 1]
                        idx :=      idx + 1

            else
                for i = 0 to (bar_index - ms.xloc)
                    min := math.min(low[i], min)
                    max := min ==   low[i] ? high[i] : max
                    idx := min ==   low[i] ?       i : idx

                if useob
                    if low[idx + 1] < low[idx]
                        max := high[idx + 1]
                        min := low [idx + 1]
                        idx :=      idx + 1

    idx

method fnOB(ob[] block, bool bull, float cords, int idx) =>
    switch bull
        true =>
            block.unshift(ob.new(true, cords, low[idx], math.avg(cords, low[idx]), time[idx], color.teal, volume[idx], close[idx] > open[idx] ? 1 : -1, 1, 1, 1, time[idx]))
        false =>
            block.unshift(ob.new(false, high[idx], cords, math.avg(cords, high[idx]), time[idx], color.red, volume[idx], close[idx] > open[idx] ? 1 : -1, 1, 1, 1, time[idx]))

method mitigated(ob[] block) =>
    if barstate.isconfirmed
        for [i, stuff] in block
            if not stuff.isbb
                switch stuff.bull
                    true =>
                        if obmiti == "Close" ? math.min(close, open) < stuff.btm : obmiti == "Wick" ? low  < stuff.btm : obmiti == "Avg" ? low  < stuff.avg : false
                            stuff.isbb          := true
                            stuff.bbloc         := time
                            if not obshowbb
                                block.remove(i)

                    false =>
                        if obmiti == "Close" ? math.max(close, open) > stuff.top : obmiti == "Wick" ? high > stuff.top : obmiti == "Avg" ? high > stuff.avg : false
                            stuff.isbb          := true
                            stuff.bbloc         := time
                            if not obshowbb
                                block.remove(i)

            else
                switch stuff.bull
                    true =>
                        if obmiti == "Close" ? math.max(close, open) > stuff.top : obmiti == "Wick" ? high > stuff.top : obmiti == "Avg" ? high > stuff.avg : false
                            block.remove(i)

                    false =>
                        if obmiti == "Close" ? math.min(close, open) < stuff.btm : obmiti == "Wick" ? low  < stuff.btm : obmiti == "Avg" ? low  < stuff.avg : false
                            block.remove(i)

f_volRank(float[] h, float v) =>
    float ratio = na
    float rank  = na
    int   n     = h.size()
    if n > 0 and not na(v)
        float avg = h.avg()
        ratio := avg > 0 ? v / avg : na
        int below = 0
        for x in h
            if x < v
                below += 1
        rank := below * 100.0 / n
    h.unshift(nz(v))
    if h.size() > volHist
        h.pop()
    [ratio, rank]

f_impFvg(bool bull, int idx) =>
    int res = 0
    int lim = math.min(idx, 300)
    if lim >= 2
        for k = 0 to lim - 2
            if bull ? low[k] > high[k + 2] : high[k] < low[k + 2]
                res := 1
                break
    res

f_sweep(bool bull, int idx, float[] pP, int[] pB) =>
    int res = 0
    float lvl = na
    if pP.size() > 0
        for j = 0 to pP.size() - 1
            if pB.get(j) < bar_index - idx
                lvl := pP.get(j)
                break
    if not na(lvl) and idx <= 4900
        bool beyond = bull ? low[idx] < lvl : high[idx] > lvl
        if beyond
            int kMin = math.max(0, idx - swBars)
            for k = idx to kMin
                if bull ? close[k] > lvl : close[k] < lvl
                    res := 1
                    break
    res

f_obState(bool act, int nShow) =>
    var structure ms    = structure.new(start = 0)
    var ob[]      blob  = array.new<ob>()
    var ob[]      brob  = array.new<ob>()
    var float     up    = na
    var float     dn    = na
    var int[]     phn   = array.new<int>(1, na)
    var int[]     pln   = array.new<int>(1, na)
    var float[]   php   = array.new<float>(1, na)
    var float[]   plp   = array.new<float>(1, na)
    var string    cache = ""
    var int       sigB  = -1
    var int       sigR  = -1
    var int       locB  = -1
    var int       locR  = -1
    float atrL    = ta.atr(200) / (5.0 / len)
    float ph      = ta.pivothigh(high, mslen, mslen)
    float pl      = ta.pivotlow (low , mslen, mslen)
    float vma     = ta.sma(volume, 20)
    float a14     = ta.atr(14)
    var float lastChk = -1.0
    var float[] hvB = array.new<float>()
    var float[] hvR = array.new<float>()
    var float[] swHP = array.new<float>()
    var int[]   swHB = array.new<int>()
    var float[] swLP = array.new<float>()
    var int[]   swLB = array.new<int>()
    bool  crossup = false
    bool  crossdn = false

    if act and not na(atrL)
        int nb0 = blob.size()
        int nr0 = brob.size()
        idbull = na(ms.loc) ? 0 : ms.find(false, false, true)
        idbear = na(ms.loc) ? 0 : ms.find(true , false, true)
        btmP   = obmode == "Length" ? (high[idbear] - 1 * atrL[idbear]) < low [idbear] ? low [idbear] : (high[idbear] - 1 * atrL[idbear]) : low [idbear]
        topP   = obmode == "Length" ? (low [idbull] + 1 * atrL[idbull]) > high[idbull] ? high[idbull] : (low [idbull] + 1 * atrL[idbull]) : high[idbull]

        if not na(ph)
            phn.unshift(bar_index[mslen])
            php.unshift(high[mslen])
            swHP.unshift(high[mslen]), swHB.unshift(bar_index)
            if swHP.size() > 30
                swHP.pop(), swHB.pop()

        if not na(pl)
            pln.unshift(bar_index[mslen])
            plp.unshift(low[mslen])
            swLP.unshift(low[mslen]), swLB.unshift(bar_index)
            if swLP.size() > 30
                swLP.pop(), swLB.pop()

        if php.size() > 0
            if high > php.get(0)
                php.clear()
                phn.clear()

        if plp.size() > 0
            if low < plp.get(0)
                plp.clear()
                pln.clear()

        if na(up)
            up := high

        if na(dn)
            dn := low

        if high > up
            up      := high
            dn      := low
            crossup := true

        if low < dn
            up      := high
            dn      := low
            crossdn := true

        if ms.start == 0
            ms := structure.new(bar_index, na, high, low, bar_index, bar_index, 0, 1, na, bar_index)

        ms.upsweep := false
        ms.dnsweep := false

        if ms.start == 1
            switch
                low <= ms.choch and close >= ms.choch and buildsweep =>
                    ms.dnsweep := true
                    ms.choch   := low
                    ms.xloc    := bar_index

                high >= ms.bos and close <= ms.bos and buildsweep =>
                    ms.upsweep := true
                    ms.bos     := high
                    ms.xloc    := bar_index

                close <= ms.choch =>
                    ms.txt   := "choch"
                    blob.fnOB(true, topP, idbull)
                    ms.trend := -1
                    ms.choch := ms.bos
                    ms.bos   := na
                    ms.start := 2
                    ms.loc   := bar_index
                    ms.main  := low
                    ms.temp  := ms.loc
                    ms.xloc  := bar_index

                close >= ms.bos =>
                    ms.txt   := "choch"
                    brob.fnOB(false, btmP, idbear)
                    ms.trend := 1
                    ms.choch := ms.choch
                    ms.bos   := na
                    ms.start := 2
                    ms.loc   := bar_index
                    ms.main  := high
                    ms.temp  := ms.loc
                    ms.xloc  := bar_index

        if ms.start == 2
            switch ms.trend
                -1 =>
                    if low <= ms.main
                        ms.main := low
                        ms.temp := bar_index

                    if bar_index % mslen * 2 == 0
                        if not na(ms.bos) and msmode == "Adjusted Points" and php.size() > 0
                            if php.get(0) < ms.choch
                                ms.choch := php.get(0)
                                ms.loc   := phn.get(0)
                                ms.xloc  := phn.get(0)
                                ms.temp  := phn.get(0)

                    if na(ms.bos)
                        if crossup and close > open and close[1] > open[1]
                            ms.bos  := ms.main
                            ms.loc  := ms.temp
                            ms.xloc := ms.loc

                    switch
                        low <= ms.bos and close >= ms.bos and not na(ms.bos) and buildsweep =>
                            ms.dnsweep := true
                            ms.bos     := low
                            ms.xloc    := bar_index

                        close <= ms.bos and not na(ms.bos) =>
                            ms.txt   := "bos"
                            ms.zz    := ms.bos
                            ms.zn    := bar_index
                            brob.fnOB(false, btmP, idbear)
                            id = ms.find(true, false, false)
                            ms.xloc  := bar_index
                            ms.bos   := na
                            ms.choch := high[id]
                            ms.loc   := bar_index[id]

                    switch
                        high >= ms.choch and close <= ms.choch and buildsweep =>
                            ms.upsweep := true
                            ms.choch   := high
                            ms.xloc    := bar_index

                        close >= ms.choch =>
                            ms.txt   := "choch"
                            ms.zz    := ms.choch
                            ms.zn    := bar_index
                            blob.fnOB(true, topP, idbull)
                            id = ms.find(false, false, false)
                            switch
                                na(ms.bos) =>
                                    ms.choch := low[id]
                                =>
                                    ms.choch := ms.bos
                            ms.bos   := na
                            ms.main  := high
                            ms.trend := 1
                            ms.loc   := bar_index
                            ms.xloc  := bar_index
                            ms.temp  := ms.loc
                            ms.xloc  := bar_index

                1 =>
                    if high >= ms.main
                        ms.main := high
                        ms.temp := bar_index

                    if na(ms.bos)
                        if crossdn and close < open and close[1] < open[1]
                            ms.bos  := ms.main
                            ms.loc  := ms.temp
                            ms.xloc := ms.loc

                    if bar_index % mslen * 2 == 0
                        if not na(ms.bos) and msmode == "Adjusted Points" and plp.size() > 0
                            if plp.get(0) > ms.choch
                                ms.choch := plp.get(0)
                                ms.loc   := pln.get(0)
                                ms.xloc  := pln.get(0)
                                ms.temp  := pln.get(0)

                    switch
                        high >= ms.bos and close <= ms.bos and not na(ms.bos) and buildsweep =>
                            ms.upsweep := true
                            ms.bos     := high
                            ms.xloc    := bar_index

                        close >= ms.bos and not na(ms.bos) =>
                            ms.txt   := "bos"
                            ms.zz    := ms.bos
                            ms.zn    := bar_index
                            blob.fnOB(true, topP, idbull)
                            id = ms.find(false, false, false)
                            ms.xloc  := bar_index
                            ms.bos   := na
                            ms.

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