Almazov Trade: MTF Structure & BOS Entries

9 953
Almazov Trade: MTF Structure & BOS Entries

Where could you enter on a structural breakout — and which higher-timeframe level would be the target? This indicator brings two market structures onto one chart and connects lower-timeframe BOS entries with higher-timeframe targets, predefined stop levels and a minimum risk-to-reward filter. Follow the structural context, the setup and its modeled outcome in one view.

Two structures, one chart

The indicator calculates two separate structural states for the current chart symbol. The lower timeframe (LTF) is the chart timeframe. The higher timeframe (HTF) defaults to four times the chart timeframe and can be set manually in minutes.

For example, a 15-minute chart uses a 60-minute higher structure by default. To use 75 minutes instead, enable Set higher timeframe manually and enter 75. The custom HTF must be greater than the chart timeframe, an exact integer multiple of it and no more than 100 times larger. The two structures have separate bullish/bearish colors; HTF segments are thicker.

HTF candles are assembled from chart candles inside the script. The indicator uses the current symbol only: it does not compare coins or rank external instruments. Standard minute and hourly charts are supported; seconds, daily and non-standard chart types are rejected.

Key implemented features

  • Independent LTF and HTF structures. Separate candle histories, confirmed swings, structural reference levels and direction states are maintained for each timeframe.
  • BOS-based trade setups. Eligible lower-timeframe continuation levels are linked to an active higher-timeframe target in the same direction.
  • Predefined entry, SL and TP. Levels are calculated before a modeled entry, with a configurable minimum RR requirement.
  • Integrated chart and table. Structural legs, BOS/CHoCH annotations, active levels, modeled entries/exits and signed distances share one chart.
  • Optional sweep observations and event alerts. These add context without introducing another trade filter.


How the structure is built

Swing High and Swing Low are local extremes confirmed within a window of 2 × d + 1 candles of the corresponding structural timeframe. High and Low widths are configured separately, from 1 to 60 candles on each side; both default to 2. Equal neighboring extremes are allowed.

The algorithm first finds a valid pair of confirmed High/Low references. Their order determines the initial structural leg. As new extremes are confirmed, a suitable intermediate swing can produce a corrective leg followed by an impulsive leg. When no suitable intermediate correction exists, the current leg is extended instead.

A swing becomes known only after its required right-side candles have closed. Lines are anchored to the earlier extreme, and the endpoint of the latest structural leg can be extended or repositioned as the structure develops. Historical swing anchors do not mean those points were available in real time on the extreme's candle.

BOS and CHoCH

BOS — Break of Structure: a continuation break of the active reference High in a bullish structure or reference Low in a bearish structure. BOS detection uses strict movement beyond the level and an OHLC-based path check against the opposite reference. Closing beyond the level is not required.

CHoCH — Change of Character: a break against the existing structural direction: below the reference Low in an uptrend or above the reference High in a downtrend. A wick beyond the level on a completed structural candle is sufficient; an exact touch is not a CHoCH. Direction can change before the first complete leg in the new direction has formed.

The entry rule does not require an additional newly confirmed opposite swing between the selected reference swing and its breakout. An existing structural reference can remain eligible while the current leg is being extended.

From lower-timeframe entry to higher-timeframe target

  1. Select the direction. A setup requires established local structure and matching LTF/HTF direction states. A fully rebuilt HTF leg is not an additional requirement if a usable retained target exists.
  2. Prepare the entry. Long setups use the active, unbroken LTF reference High; short setups use the active, unbroken LTF reference Low. Price must still be on the pre-breakout side of the entry, or exactly at it, when the setup is prepared.
  3. Define the stop. The SL is one minimum price tick beyond the opposite LTF reference: below the Low for a long, above the High for a short, rounded to the instrument's tick size.
  4. Define the target. Long setups use the active HTF reference High; short setups use the active HTF reference Low. The target must be unbroken and lie beyond the entry in the trade direction.
  5. Apply the RR filter. A setup is prepared only when its planned reward-to-risk ratio meets the selected minimum. The default minimum is 1.0.


Pine Script®


A pending setup can be updated or removed at a later candle close as the structural conditions change. Once an entry is modeled, its SL and TP remain fixed for that trade. Only one modeled position is tracked at a time; the position ends at SL or TP, not merely because the displayed direction changes.

The RR × marker identifies a detected local BOS that fails the target/direction/RR checks while no trade occupies that bar. Hover over it for the explanation. An unavailable HTF target can also cause this marker; it does not always mean that a numerical RR was simply below the threshold.

Entries, exits and OHLC modeling

This is an indicator with its own price-based execution model. It does not place orders and does not provide a native Strategy Tester report.

A setup represents a stop-entry level, not an immediate market entry at the setup candle's close. It cannot fill on the same candle that created it. Subsequent candles can fill the entry on a touch or a gap through the level. Gap entries and gap exits are priced at the candle open.

The model assumes open → high → low → close when the open is closer to the high, and open → low → high → close otherwise. Equal distances use the low-first path. It can model an entry and exit inside the same candle. These are assumptions about intrabar order, not observed tick data. BOS annotations use strict crossings, while modeled stop entries can fill on an exact touch, so their events are not necessarily identical on boundary cases.

Entry and exit events are confirmed at the chart candle's close. The model excludes commissions, slippage, position sizing and Bar Magnifier. It does not establish identical trades or financial results to a separate TradingView strategy. Displayed RR is the planned setup ratio; a gap-adjusted entry can change the effective ratio.


Chart annotations and table

  • Structural legs: separate colors for bullish/bearish LTF and HTF structure.
  • Active levels: solid reference lines. Broken BOS/CHoCH annotations use dashed lines and timeframe labels.
  • Trade drawings: LONG/SHORT entry labels, entry/SL/TP lines and optional risk/reward zones. Trade lines and zones extend five chart bars to the right. Active entry/SL/TP price tags also sit to the right; exit labels show TP or SL.
  • History: 40 modeled trades are retained for chart drawings by default; the setting allows 1–60. This controls drawings, not the start of calculation.
  • Top-right table: LTF/HTF periods, direction, reference High/Low, signed percentage distances and the current pending or active trade's entry, SL, TP and planned RR.


The table shows WAITING, SETUP or ENTRY CONFIRMED. A dash means a value is unavailable. Reference prices marked broken have already been registered as broken by the script. Distances use the current close and can change during an open candle without confirming a new structural event:

Pine Script®


Positive values indicate a level above price; negative values indicate a level below price. Font size is adjustable from 8 to 18, default 12; column widths follow their contents.

Sweep observations

Sweep H means the chart candle traded above an existing reference High but closed below it. Sweep L means it traded below a reference Low but closed above it. A reference already registered as broken is excluded. The label includes the reference timeframe, and the observation is confirmed at the chart candle's close.

These are price-pattern observations. They do not verify actual stop executions, exchange order flow or liquidity transactions, and they do not filter entries.

Language, settings and alerts

  • Language / Язык: English by default; choose Русский for Russian chart labels, table text and runtime messages. Static settings and plot titles are bilingual because Pine requires constant strings for these interface items.
  • Timeframes: automatic ×4 HTF or a custom HTF in minutes.
  • Structure: separate Swing High/Low widths and BOS/CHoCH annotation visibility.
  • Trades: minimum RR, drawing history and risk/reward zones.
  • Appearance / Analysis: structural colors, table visibility/font size, active levels, broken levels, sweeps and trade drawings. Drawing switches do not disable the underlying calculations.


Alerts cover LONG entry, SHORT entry, TP, SL, a new or revised eligible setup, RR rejection, and separate LTF/HTF BOS, CHoCH, Sweep High and Sweep Low events. A setup alert describes a pending entry, not a filled position.

Each event has an EN and RU alert condition. Select the condition matching the indicator's language; the other language's conditions are inactive. Use Once Per Bar Close. Existing alerts retain the script and settings captured when created; recreate them after changing language or updating the script when you want the new configuration applied.

Open-source design and limitations

The script combines two independently maintained structural states with a specific BOS-to-HTF-target workflow, tick-adjusted stop placement, an RR filter and one integrated chart/table display. Unlike a single-timeframe structure overlay, it connects local continuation levels to a separate higher-timeframe objective. This public open-source publication requires no individual access approval; users can inspect its implementation.

Results depend on available history, swing settings, chart timeframe and the selected HTF. Internally aggregated HTF candles can differ from native exchange candles, especially with session boundaries or missing chart bars. History is compacted at 80,000 stored candles per structural timeframe; references that fall outside retained history can trigger rebuilding. Drawing and execution limits apply. The indicator models structural scenarios; it does not guarantee that a target will be reached or a trade will be profitable.

РУССКАЯ ВЕРСИЯ

Almazov Trade: MTF Structure & BOS Entries

Где войти на пробое структуры — и какой уровень старшего таймфрейма станет целью? Индикатор объединяет две рыночные структуры на одном графике и связывает входы по BOS младшего таймфрейма с целями старшего, заранее рассчитанным стопом и фильтром минимального RR. Структурный контекст, сетап и результат его моделирования — в одном окне.

Две структуры на одном графике

Для текущего инструмента отдельно рассчитываются две структуры. Младший таймфрейм (LTF) совпадает с таймфреймом графика. Старший (HTF) по умолчанию в четыре раза больше; его можно задать вручную в минутах.

Например, на графике 15 минут старшая структура по умолчанию рассчитывается за 60 минут. Чтобы выбрать 75 минут, включите «Задать старший таймфрейм вручную» и введите 75. Старший ТФ должен быть больше текущего, кратен ему и превышать его не более чем в 100 раз. Для каждой структуры отдельно задаются восходящий и нисходящий цвета; старшие ветки толще.

Старшие свечи собираются внутри скрипта из свечей графика. Анализируется только открытый инструмент: сравнения монет и рейтинга внешних тикеров здесь нет. Поддерживаются стандартные минутные и часовые графики; секундные, дневные и нестандартные типы отклоняются.

Ключевые возможности

  • Независимые младшая и старшая структуры: отдельные истории свечей, подтверждённые свинги, опорные уровни и состояния направления.
  • Сетапы на пробой BOS: подходящий уровень продолжения младшей структуры связывается с активной старшей целью в том же направлении.
  • Заранее рассчитанные вход, SL и TP: сетап проходит настраиваемый фильтр минимального RR.
  • Общий график и таблица: ветки структуры, BOS/CHoCH, активные уровни, моделируемые входы/выходы и расстояния до опор.
  • Дополнительные Sweep и алерты: наблюдение за событиями без дополнительного фильтра сделок.


Как строится структура

Swing High / Swing Low — локальный экстремум, подтверждённый в окне из 2 × d + 1 свечей соответствующего структурного таймфрейма. Ширина High и Low задаётся отдельно: 1–60 свечей с каждой стороны, по умолчанию по 2. Равные соседние экстремумы допускаются.

Алгоритм находит актуальную пару подтверждённых High/Low. Порядок опор определяет первую ветку. При подтверждении следующего экстремума пригодный промежуточный свинг позволяет добавить коррекционную и импульсную ветки. Если подходящей коррекции нет, последняя ветка продлевается.

Свинг становится известен только после закрытия нужного числа свечей справа. Линия привязывается к более раннему экстремуму, а конец последней ветки может продлеваться или переноситься при развитии структуры. Наличие линии на исторической свече не означает, что эта точка была известна в момент её формирования.

BOS и CHoCH

BOS — Break of Structure: пробой по направлению структуры: действующего High при восходящей или Low при нисходящей. Для отметки BOS требуется строгое движение за уровень; учитывается предполагаемый OHLC-путь относительно противоположной опоры. Закрытие за уровнем не обязательно.

CHoCH — Change of Character: пробой против текущей структуры: ниже опорного Low при росте или выше опорного High при снижении. Достаточно тени завершённой структурной свечи; точное касание не считается CHoCH. Направление может переключиться до формирования первой полноценной ветки нового тренда.

Для входа не требуется отдельный новый подтверждённый противоположный свинг между выбранной опорой и её пробоем. Уровень существующего структурного свинга может использоваться и при продлении текущей ветки.

От младшего входа к старшей цели

  1. Направление. Нужны сформированная исходная локальная структура и совпадение состояний направления LTF/HTF. Полностью перестроенная новая старшая ветка не является отдельным требованием, если пригодная сохранённая цель уже существует.
  2. Вход. Для long используется активный непробитый High младшего ТФ, для short — Low. При подготовке сетапа текущая цена должна оставаться до уровня входа или точно на нём.
  3. Стоп. Один минимальный шаг цены за противоположной младшей опорой: ниже Low для long, выше High для short, с округлением до шага инструмента.
  4. Цель. Активный High старшего ТФ для long или Low для short. Цель должна быть непробитой и находиться впереди входа по направлению сделки.
  5. RR. Плановое отношение расстояния до цели к расстоянию до стопа должно быть не меньше выбранного минимума. По умолчанию минимум равен 1,0.


Pine Script®


До входа ожидающий сетап может обновляться или отменяться на закрытии свечи при изменении структуры. После моделируемого входа SL и TP фиксированы для этой сделки. Одновременно учитывается только одна позиция; она завершается по SL или TP, а не просто при изменении отображаемого направления.

Метка RR × появляется при обнаруженном младшем BOS, не прошедшем проверки цели, направления или RR, если этот бар не занят сделкой. Причина доступна при наведении. Метка возможна и при отсутствии пригодной старшей цели: это не всегда просто числовое значение RR ниже минимума.

Моделирование входов и выходов

Это индикатор с собственной ценовой моделью исполнения. Он не выставляет реальные заявки и не формирует встроенный отчёт Strategy Tester.

Сетап — подготовленный уровень стоп-входа, а не немедленный вход по рынку на закрытии свечи. На создавшей его свече он не исполняется. На последующих свечах вход может произойти при касании или гэпе через уровень. При гэпе цена входа или выхода принимается равной открытию свечи.

Если открытие ближе к High, предполагается путь open → high → low → close; иначе open → low → high → close. При равных расстояниях первым считается Low. Возможны вход и выход на одной свече. Это допущение о последовательности движения внутри бара, а не восстановленные тики. Для отметки BOS нужен строгий пробой, а моделируемый стоп-вход может исполниться при точном касании, поэтому в граничных случаях события не обязаны совпадать.

События входа и выхода подтверждаются на закрытии свечи графика. Модель не учитывает комиссии, проскальзывание, объём позиции и Bar Magnifier. Совпадение сделок и финансового результата с отдельной стратегией TradingView не установлено. Отображаемый RR относится к подготовленному сетапу; вход по цене гэпа может изменить фактическое соотношение.


Разметка и таблица

  • Ветки структуры: отдельные цвета восходящего/нисходящего состояния младшего и старшего ТФ.
  • Уровни: активные опоры показаны сплошными линиями; снятые BOS/CHoCH — пунктиром с подписью таймфрейма.
  • Сделки: метки LONG/SHORT, уровни входа/SL/TP и опциональные зоны риска/прибыли. Линии и зоны продлеваются на пять баров вправо; там же расположены ценовые подписи активной сделки. Выход отмечается TP или SL.
  • История: по умолчанию сохраняется разметка 40 моделируемых сделок, диапазон 1–60. Настройка ограничивает рисунки, а не начало расчётов.
  • Таблица справа сверху: таймфреймы, направления, опорные High/Low, процентные расстояния со знаком, а также вход, SL, TP и плановый RR текущего ожидающего или активного сетапа.


Состояния таблицы: «ОЖИДАНИЕ», «СЕТАП», «ВХОД ПОДТВЕРЖДЁН». Прочерк означает отсутствие значения, а пометка «снят» — зарегистрированный скриптом пробой опоры. Расстояния рассчитываются от текущего close и могут меняться на открытой свече без подтверждения нового структурного события:

Pine Script®


Плюс означает уровень выше цены, минус — ниже. Размер шрифта: 8–18, по умолчанию 12. Ширина столбцов определяется содержимым.

Дополнительные Sweep

Sweep H: свеча графика вышла выше существующего опорного High, но закрылась ниже. Sweep L: вышла ниже Low, но закрылась выше. Опоры, уже зарегистрированные как пробитые, исключаются. Указан таймфрейм уровня; событие подтверждается на закрытии свечи графика.

Это наблюдение за ценовым паттерном. Код не проверяет реальные исполнения стопов, биржевой поток заявок или фактические операции с ликвидностью. Sweep не влияет на отбор входов.

Язык, настройки и алерты

  • Language / Язык: по умолчанию English. Выбор Русский переключает подписи графика, таблицу и сообщения об ошибках. Постоянные названия настроек и графиков двуязычные из-за требований Pine к строковым константам.
  • Timeframes / Таймфреймы: автоматический старший ТФ ×4 или ручной ввод минут.
  • Structure / Структура: ширина свингов High/Low и отображение BOS/CHoCH.
  • Trades / Сделки: минимальный RR, история разметки, зоны риска/прибыли.
  • Appearance / Оформление, Analysis / Анализ: цвета, таблица и её шрифт, активные/снятые уровни, Sweep, разметка сделок. Переключатели отображения не отключают соответствующие расчёты.


Доступны алерты LONG, SHORT, TP, SL, нового или изменённого подходящего сетапа, отказа RR, а также отдельных BOS, CHoCH, Sweep High и Sweep Low младшего и старшего ТФ. Алерт сетапа означает подготовленный вход, а не исполненную позицию.

У каждого события есть условия EN и RU. Выбирайте вариант, соответствующий языку индикатора: другая языковая группа неактивна. Частота — «Один раз при закрытии бара». Уже созданный алерт использует сохранённую на момент создания версию скрипта и настройки. После смены языка или обновления кода пересоздайте алерт, чтобы применить новую конфигурацию.

Открытый код и ограничения

Скрипт связывает две независимо рассчитываемые структуры с конкретной логикой BOS → старшая цель, стопом с поправкой на шаг цены, фильтром RR и общей разметкой/таблицей. В отличие от однотаймфреймовой структуры, он использует локальный уровень продолжения вместе с отдельной старшей целью. Публикация публичная, исходный код открыт; индивидуальное разрешение на доступ не требуется.

Расчёты зависят от доступной истории, ширины свингов и таймфреймов. Собранные внутри скрипта старшие свечи могут отличаться от биржевых, особенно при разрывах сессий и пропусках баров. При достижении 80 000 сохранённых свечей каждого структурного ТФ история сокращается; выход опор за сохранённый участок может привести к перестроению. Действуют ограничения Pine на выполнение и рисунки. Индикатор моделирует структурные сценарии и не гарантирует достижение цели или прибыльность сделки.

Haftungsausschluss

Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.