Indicator · Pine Script v5 · On the chart

Smart Money M1 - Clean & Precise

by ifreddyman2014-tech· code credited to Claude

This overlay indicator marks smart-money structure on the price chart.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code280
Settings10inputs
LicenceNone statedfile: MPL-2.0
Last update8 months ago14 Feb 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

280 lines of Pine Script v5 from Clean_Smart_Money_M1_Indicator.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Clean_Smart_Money_M1_Indicator.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Claude AI - Clean Smart Money M1 Indicator with Precise Visualization

//@version=5
indicator("Smart Money M1 - Clean & Precise", overlay=true, max_boxes_count=100, max_labels_count=100)

// ═══════════════════════════════════════════════════════════════════════════════
// НАСТРОЙКИ / SETTINGS
// ═══════════════════════════════════════════════════════════════════════════════

// Свинги (Swing Detection)
pivotLength = input.int(5, "Pivot Length", minval=2, maxval=20,
     tooltip="Количество свечей слева/справа для подтверждения локального экстремума")

// Displacement (Импульс)
displacementFactor = input.float(1.5, "Displacement Factor", minval=1.0, maxval=5.0, step=0.1,
     tooltip="Тело свечи пробоя должно быть больше среднего × этот коэффициент")
avgBodyLength = input.int(10, "Период для среднего тела", minval=5, maxval=50)

// Визуализация
showBOSLabels = input.bool(true, "Показать BOS метки", group="Визуализация")
showOrderBlocks = input.bool(true, "Показать Order Blocks", group="Визуализация")
bullOBColor = input.color(color.new(color.green, 85), "Цвет Bullish OB", group="Визуализация")
bearOBColor = input.color(color.new(color.red, 85), "Цвет Bearish OB", group="Визуализация")

// Mitigation (Отработка OB)
enableMitigation = input.bool(true, "Удалять отработанные OB", group="Mitigation",
     tooltip="Удалять OB, когда цена полностью пробивает их в обратную сторону")

// ═══════════════════════════════════════════════════════════════════════════════
// ВСПОМОГАТЕЛЬНЫЕ РАСЧЁТЫ
// ═══════════════════════════════════════════════════════════════════════════════

// Тело свечи (абсолютное значение)
candleBody = math.abs(close - open)

// Среднее тело за последние N свечей
avgBody = ta.sma(candleBody, avgBodyLength)

// Проверка на импульсную свечу (Displacement)
isImpulseCandle = candleBody > (avgBody * displacementFactor)

// Направление свечи
isBullish = close > open
isBearish = close < open

// ═══════════════════════════════════════════════════════════════════════════════
// ОПРЕДЕЛЕНИЕ СВИНГОВ (PIVOTS)
// ═══════════════════════════════════════════════════════════════════════════════

// Подтверждённые пивоты (появляются с задержкой)
pivotHigh = ta.pivothigh(high, pivotLength, pivotLength)
pivotLow = ta.pivotlow(low, pivotLength, pivotLength)

// Переменные для хранения последних подтверждённых уровней
var float lastPivotHigh = na
var float lastPivotLow = na

// Обновление при появлении нового пивота
if not na(pivotHigh)
    lastPivotHigh := pivotHigh

if not na(pivotLow)
    lastPivotLow := pivotLow

// ═══════════════════════════════════════════════════════════════════════════════
// СТРОГАЯ ЛОГИКА BOS (Break of Structure)
// ═══════════════════════════════════════════════════════════════════════════════

// BUY BOS: Close пробивает Pivot High + импульс + бычья свеча
buyBOS = not na(lastPivotHigh) and
     close > lastPivotHigh and
     isImpulseCandle and
     isBullish

// SELL BOS: Close пробивает Pivot Low + импульс + медвежья свеча
sellBOS = not na(lastPivotLow) and
     close < lastPivotLow and
     isImpulseCandle and
     isBearish

// ═══════════════════════════════════════════════════════════════════════════════
// ПОИСК ORDER BLOCK (OB) СВЕЧИ
// ═══════════════════════════════════════════════════════════════════════════════

// Функция поиска последней противоположной свечи перед импульсом
findLastOppositeCandle(lookback, searchBearish) =>
    var int foundBar = na
    var float foundTop = na
    var float foundBottom = na

    for i = 1 to lookback
        // Для BUY BOS ищем медвежью свечу
        if searchBearish and close[i] < open[i]
            foundBar := bar_index - i
            foundTop := open[i]      // верх тела медвежьей свечи
            foundBottom := close[i]  // низ тела медвежьей свечи
            break
        // Для SELL BOS ищем бычью свечу
        if not searchBearish and close[i] > open[i]
            foundBar := bar_index - i
            foundTop := close[i]     // верх тела бычьей свечи
            foundBottom := open[i]   // низ тела бычьей свечи
            break

    [foundBar, foundTop, foundBottom]

// ═══════════════════════════════════════════════════════════════════════════════
// ХРАНИЛИЩЕ АКТИВНЫХ ORDER BLOCKS
// ═══════════════════════════════════════════════════════════════════════════════

// Типы для хранения OB
type OrderBlock
    box boxObj          // объект коробки
    float top           // верхняя граница
    float bottom        // нижняя граница
    bool isBullish      // тип OB

// Массивы для хранения активных OB
var array<OrderBlock> activeOBs = array.new<OrderBlock>()

// ═══════════════════════════════════════════════════════════════════════════════
// СОЗДАНИЕ ORDER BLOCKS ПРИ BOS
// ═══════════════════════════════════════════════════════════════════════════════

// При BUY BOS создаём Bullish OB
if buyBOS and showOrderBlocks
    [obBar, obTop, obBottom] = findLastOppositeCandle(20, true)

    if not na(obBar)
        // Создаём коробку СТРОГО от той свечи, которая сформировала OB
        newBox = box.new(
             left=obBar,           // ТОЧНАЯ привязка к OB-свече
             top=obTop,
             right=bar_index + 50, // продлеваем в будущее
             bottom=obBottom,
             border_color=color.new(color.green, 50),
             bgcolor=bullOBColor,
             border_width=1,
             extend=extend.right,
             text="OB",
             text_color=color.green,
             text_size=size.tiny
         )

        // Сохраняем в массив активных OB
        array.push(activeOBs, OrderBlock.new(newBox, obTop, obBottom, true))

// При SELL BOS создаём Bearish OB
if sellBOS and showOrderBlocks
    [obBar, obTop, obBottom] = findLastOppositeCandle(20, false)

    if not na(obBar)
        // Создаём коробку СТРОГО от той свечи, которая сформировала OB
        newBox = box.new(
             left=obBar,           // ТОЧНАЯ привязка к OB-свече
             top=obTop,
             right=bar_index + 50,
             bottom=obBottom,
             border_color=color.new(color.red, 50),
             bgcolor=bearOBColor,
             border_width=1,
             extend=extend.right,
             text="OB",
             text_color=color.red,
             text_size=size.tiny
         )

        // Сохраняем в массив активных OB
        array.push(activeOBs, OrderBlock.new(newBox, obTop, obBottom, false))

// ═══════════════════════════════════════════════════════════════════════════════
// MITIGATION: УДАЛЕНИЕ ОТРАБОТАННЫХ ORDER BLOCKS
// ═══════════════════════════════════════════════════════════════════════════════

if enableMitigation and array.size(activeOBs) > 0
    // Проходим по всем активным OB в обратном порядке
    for i = array.size(activeOBs) - 1 to 0
        ob = array.get(activeOBs, i)

        // Условия полного пробития (Mitigation):
        // Для Bullish OB: цена закрывается ниже нижней границы
        // Для Bearish OB: цена закрывается выше верхней границы
        isMitigated = false

        if ob.isBullish
            // Bullish OB пробит, если close ниже bottom
            if close < ob.bottom
                isMitigated := true
        else
            // Bearish OB пробит, если close выше top
            if close > ob.top
                isMitigated := true

        // Удаляем отработанный OB
        if isMitigated
            box.delete(ob.boxObj)
            array.remove(activeOBs, i)

// ═══════════════════════════════════════════════════════════════════════════════
// ВИЗУАЛИЗАЦИЯ BOS МЕТОК (СТРОГАЯ ПРИВЯЗКА К СВЕЧАМ)
// ═══════════════════════════════════════════════════════════════════════════════

if showBOSLabels and buyBOS
    // Метка СТРОГО над свечой пробоя
    label.new(
         bar_index,
         high,  // привязка к high свечи
         "BOS",
         color=color.new(color.green, 0),
         style=label.style_label_down,
         textcolor=color.white,
         size=size.tiny,
         yloc=yloc.abovebar  // над баром
     )

if showBOSLabels and sellBOS
    // Метка СТРОГО под свечой пробоя
    label.new(
         bar_index,
         low,  // привязка к low свечи
         "BOS",
         color=color.new(color.red, 0),
         style=label.style_label_up,
         textcolor=color.white,
         size=size.tiny,
         yloc=yloc.belowbar  // под баром
     )

// ═══════════════════════════════════════════════════════════════════════════════
// ОПЦИОНАЛЬНАЯ ВИЗУАЛИЗАЦИЯ ПИВОТОВ (ДЛЯ ОТЛАДКИ)
// ═══════════════════════════════════════════════════════════════════════════════

showPivots = input.bool(false, "Показать Pivot High/Low", group="Debug")

plotshape(
     showPivots and not na(pivotHigh) ? pivotHigh : na,
     title="Pivot High",
     style=shape.diamond,
     location=location.abovebar,
     color=color.new(color.red, 0),
     size=size.tiny
 )

plotshape(
     showPivots and not na(pivotLow) ? pivotLow : na,
     title="Pivot Low",
     style=shape.diamond,
     location=location.belowbar,
     color=color.new(color.green, 0),
     size=size.tiny
 )

// ═══════════════════════════════════════════════════════════════════════════════
// DEBUG ИНФОРМАЦИЯ
// ═══════════════════════════════════════════════════════════════════════════════

showDebugTable = input.bool(false, "Показать Debug таблицу", group="Debug")

if showDebugTable
    var table debugTable = table.new(position.top_right, 2, 4, border_width=1)

    if barstate.islast
        table.cell(debugTable, 0, 0, "Активных OB:", text_color=color.white, bgcolor=color.new(color.gray, 70))
        table.cell(debugTable, 1, 0, str.tostring(array.size(activeOBs)), text_color=color.yellow, bgcolor=color.new(color.gray, 70))

        table.cell(debugTable, 0, 1, "Текущее тело:", text_color=color.white, bgcolor=color.new(color.gray, 70))
        table.cell(debugTable, 1, 1, str.tostring(candleBody, "#.#####"), text_color=color.white, bgcolor=color.new(color.gray, 70))

        table.cell(debugTable, 0, 2, "Среднее тело:", text_color=color.white, bgcolor=color.new(color.gray, 70))
        table.cell(debugTable, 1, 2, str.tostring(avgBody, "#.#####"), text_color=color.white, bgcolor=color.new(color.gray, 70))

        table.cell(debugTable, 0, 3, "Displacement:", text_color=color.white, bgcolor=color.new(color.gray, 70))
        table.cell(debugTable, 1, 3, isImpulseCandle ? "✓ ДА" : "✗ НЕТ",
             text_color=isImpulseCandle ? color.lime : color.gray,
             bgcolor=color.new(color.gray, 70))

// ═══════════════════════════════════════════════════════════════════════════════
// КОНЕЦ СКРИПТА
// ═══════════════════════════════════════════════════════════════════════════════

Overview

Smart Money M1 - Clean & Precise finds swing pivots, flags displacement candles whose body exceeds a multiple of the average body, and can label breaks of structure. It draws bullish and bearish order-block boxes and can remove a block after price fully trades through it. Pivot length, displacement factor, and average-body lookback change how swings and impulses are detected. Optional pivot marks and a debug table are off by default. It is an indicator with no entry or exit rules.

Details

Published by

ifreddyman2014-tech on GitHub

Code credit

Claude, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

SMC / ICT / price action, Support & resistance

Markets

Forex

Timeframes

M1-M5

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Pivot Lengthint5pivotLength
Displacement Factorfloat1.5displacementFactor
Период для среднего телаint10avgBodyLength
Показать BOS меткиbooltrueshowBOSLabels
Показать Order BlocksbooltrueshowOrderBlocks
Цвет Bullish OBcolorcolor.new(color.green, 85)bullOBColor
Цвет Bearish OBcolorcolor.new(color.red, 85)bearOBColor
Удалять отработанные OBbooltrueenableMitigation
Показать Pivot High/LowboolfalseshowPivots
Показать Debug таблицуboolfalseshowDebugTable
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

ICT Equal Highs and Lows

by ArunKBhaskar
575 stars

This overlay indicator finds pivot highs and lows on the price chart and compares the last two highs and the last two lows. When the percentage difference between a pair is below the Equal HL threshold, it treats them as equal levels and draws a box. Left and

Indicator v5 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows

DE-tracker

by Allen1212
303 stars

This indicator plots labels on the TradingView price chart to mark ARK Invest's buy and sell trades for the DE stock. Buy transactions appear in green with X1 or X2 multipliers showing the number of ARK ETFs involved on the same day; sells appear in red. The m

Indicator v4 Support & resistanceSMC / ICT / price action
Updated 2 years ago · None stated GitHub repository of DE-tracker

This Pine Script indicator plots a ZigZag on the price chart. It identifies reversal points when price moves more than a set percentage from the last pivot. The script calculates forecasts using zigzag data and labels detected geometric patterns including harm

Indicator v4 TrendSupport & resistance

Golden Bullet Strategy

by TradersPost
218 stars

The Golden Bullet Strategy is an overlay signal indicator based on Smart Money Concepts and time-based liquidity models. It identifies liquidity sweeps of a designated reference session range during a specified hunt window. It then confirms Market Structure Sh

Indicator v6 SMC / ICT / price actionSessions & time
Updated 3 months ago · None stated GitHub repository of Golden Bullet Strategy

Open Source Fractal

by cantolab
183 stars

This indicator implements the Fractal Model concept to plot market structure shifts, liquidity sweeps, and Change in State of Delivery (CISD) levels. It overlays custom higher-timeframe candle previews, open prices, and time markers directly on the price chart

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 2 months ago · MIT GitHub repository of Open Source Fractal

Swing Failure Signals

by Ganador1
154 stars

This indicator calculates pivot highs and pivot lows to detect liquidity sweeps and Swing Failure Patterns. It identifies when price breaks past recent key swing highs or lows within a configurable historical window, then looks for a quick reversal or change i

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 2 months ago · Apache-2.0 GitHub repository of Swing Failure Signals

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers