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

ICT Market Maker Model MMXM, SMR, Liquidity & Targets

indicator ict market maker model mmxm, smr, liquidity & targets for tradingview.pine
Вы автор или правообладатель?

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

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

О программе

Индикатор отслеживает модель Market Maker (MMXM) через четыре стадии: исходная консолидация, инженерная кривая ликвидности, разворот «умных денег» (SMR) и кривая возврата к началу. Все изменения стадий, достижения целей и провалы модели определяются только по закрытым свечам, без перерисовки. Индикатор строит кривые, отмечает шаги ликвидности (SSL/BSL), выводит три целевые цены (T1, T2, T3) и линию инвалидации.

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

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

НастройкаОписание
consLen Количество баров, определяющих исходную консолидацию, в пределах которой весь диапазон цены должен помещаться в заданную максимальную ширину.
consMult Максимальная ширина исходной консолидации, выраженная в кратных среднему истинному диапазону (ATR). При превышении этой ширины модель сбрасывается.
pivLen Количество баров с каждой стороны, необходимых для подтверждения свинг-хай или свинг-лоу при определении разворотов.
minSteps Минимальное количество последовательных более низких минимумов (бычья модель) или более высоких максимумов (продажная модель), которое должна пройти инженерная кривая, чтобы разворот считался подтверждённым.
legMin Минимальное расстояние, на которое цена должна отойти от консолидации, чтобы разворот «умных денег» был учтён как подтверждённый.
maxLeg Максимальное количество баров с момента формирования модели, после которого модель считается истёкшей и завершается.
showCurve Включает отображение кривых инженерной ликвидности и возврата на графике.
curveSty Определяет стиль отрисовки кривой: сглаженная (Smooth) — плавная между пройденными свингами, или прямая (Straight) — соединяющая свинги отрезками через каждый свинг.
showSteps Включает отображение меток шагов ликвидности на графике: SSL (серия более низких минимумов для бычьей модели) и BSL (серия более высоких максимумов для медвежьей модели).
showTgt Включает отображение линий трёх целевых цен (T1, T2, T3) и линии инвалидации модели на графике.
keepN Количество завершённых моделей, отображаемых на графике. Модели старше указанного количества баров удаляются, но статистика их достижения целей сохраняется полностью.
lblSize Размер текстовых меток на графике: малый (Small), нормальный (Normal) или большой (Large).
showTbl Включает отображение информационной панели с текущим состоянием модели и историей достижения целей.
tblPos Расположение информационной панели на графике: верхний правый, нижний правый, верхний левый или нижний левый угол.
tblSize Размер текста в информационной панели: малый (Small), нормальный (Normal) или большой (Large).
alForm Включает оповещение, которое срабатывает при пробое исходной консолидации и начале формирования модели (бычьей или медвежьей).
alSmr Включает оповещение, которое срабатывает при подтверждении разворота «умных денег» (SMR) и переходе модели в стадию возврата.
alTgt Включает оповещения при достижении одной из целей модели, завершении модели (возврат к началу) или её провале (выход за пределы разворота).
candOn_ Включает отображение неоновых свечей с полупрозрачным цветным телом на графике.
candGlw Включает эффект подсветки свечей: тело рисуется в четырёх полосах с нарастающей яркостью к закрытию, что позволяет определить направление движения. При выключении свечи отображаются плоскими полупрозрачными телами.

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

indicator("ICT Market Maker Model MMXM, SMR, Liquidity & Targets", "MMXM",
     overlay = true, max_lines_count = 300, max_labels_count = 300, max_boxes_count = 60, max_polylines_count = 60)

gM = "Model"
consLen  = input.int(20, "Consolidation length (bars)", minval = 8, maxval = 100, group = gM,
     tooltip = "The original consolidation is a stretch of this many bars whose whole range fits inside the width below.")
consMult = input.float(2.5, "Consolidation max width (× ATR)", minval = 1.0, maxval = 8.0, step = 0.1, group = gM)
pivLen   = input.int(3, "Swing strength", minval = 2, maxval = 10, group = gM, tooltip = "Bars on each side that confirm a swing high or low.")
minSteps = input.int(2, "Min. liquidity steps", minval = 1, maxval = 6, group = gM,
     tooltip = "How many successive lower lows (buy model) or higher highs (sell model) the engineering curve must make before a reversal counts.")
legMin   = input.float(3.0, "Min. curve depth (× ATR)", minval = 1.0, maxval = 20.0, step = 0.5, group = gM,
     tooltip = "How far price must travel away from the consolidation before a smart money reversal counts.")
maxLeg   = input.int(400, "Model expiry (bars)", minval = 50, maxval = 2000, group = gM)

gD = "Drawing"
showCurve = input.bool(true, "Draw the curves", group = gD)
curveSty  = input.string("Smooth", "Curve style", options = ["Smooth", "Straight"], group = gD,
     tooltip = "Smooth rounds the curve between the swings it passes through. Straight joins them with straight segments, exactly through each swing.")
showSteps = input.bool(true, "Mark liquidity steps (SSL / BSL)", group = gD)
showTgt   = input.bool(true, "Targets and invalidation", group = gD)
keepN     = input.int(3, "Models drawn", minval = 1, maxval = 20, group = gD, tooltip = "Finished models older than this are removed from the chart. The track record keeps all of them.")
lblSize   = input.string("Normal", "Label size", options = ["Small", "Normal", "Large"], group = gD)

gP = "Panel"
showTbl  = input.bool(true, "Show panel", group = gP)
tblPos   = input.string("Top Right", "Position", options = ["Top Right", "Bottom Right", "Top Left", "Bottom Left"], group = gP)
tblSize  = input.string("Normal", "Text size", options = ["Small", "Normal", "Large"], group = gP)

gA = "Alerts"
alForm   = input.bool(true, "Alert: model forming (consolidation broken)", group = gA)
alSmr    = input.bool(true, "Alert: smart money reversal", group = gA)
alTgt    = input.bool(true, "Alert: target hit / model complete / failed", group = gA)

candOn_  = input.bool(true, "Neon candles", group = "Visuals")
candGlw  = input.bool(true, "Glow candles", group = "Visuals", tooltip = "Each body is drawn in four bands that brighten towards the close, so the candle reads in the direction it moved. Off = flat translucent bodies.")

bgLum   = 0.2126 * color.r(chart.bg_color) + 0.7152 * color.g(chart.bg_color) + 0.0722 * color.b(chart.bg_color)
isLight = bgLum > 128
UP      = isLight ? #00A896 : #00F5D4   // turquoise: buy models, rising candles
DN      = isLight ? #E0115F : #FF2E88   // pink: sell models, falling candles
TGT     = isLight ? #7B1FD6 : #B026FF   // neon violet: consolidation and target lines
TGTX    = isLight ? #6A1BB8 : #D7A6FF   // light violet for text, readable on a dark chart
VIOLET  = isLight ? #7B1FD6 : #B026FF
GREY    = isLight ? #8A8F9C : #6B7080
TXT     = isLight ? #1A1D24 : #E8EAF0
MUTE    = isLight ? #5E6472 : #9AA0AE
PANEL   = isLight ? #FFFFFF : #0B0E14
ROW     = isLight ? #F1F3F7 : #141823
INK     = #0B0E14
NONE    = color.new(color.black, 100)

lSize = lblSize == "Small" ? size.small : lblSize == "Large" ? size.large : size.normal
tSize = tblSize == "Small" ? size.small : tblSize == "Large" ? size.large : size.normal

px(float v) =>
    str.tostring(v, format.mintick)

pct(int a, int b) =>
    b > 0 ? str.tostring(a * 100.0 / b, "0") + "%" : "—"

atr  = ta.atr(50)
hh   = ta.highest(high, consLen)
ll   = ta.lowest(low, consLen)
compress = not na(atr) and hh - ll <= consMult * atr
ph   = ta.pivothigh(high, pivLen, pivLen)
pl   = ta.pivotlow(low, pivLen, pivLen)
pBar = bar_index - pivLen

var int   stage   = 0
var int   dir     = 0
var float ocTop   = na
var float ocBot   = na
var int   ocL     = na
var int   ocR     = na
var float legExt  = na
var int   legExtBar = na
var int   legStart  = na
var float prevPiv = na
var int   steps   = 0
var float lastSw  = na     // the swing the reversal must break (formed before the extreme)
var int   lastSwBar = na
var float recentSw = na    // the latest confirmed opposite swing
var int   recentSwBar = na
var float t1 = na
var float t2 = na
var float t3 = na
var float inv = na
var int   smrBar  = na
var int   hitMax  = 0

var array<chart.point> pts    = array.new<chart.point>()
var array<chart.point> retPts = array.new<chart.point>()
var array<label>       stepLbs = array.new<label>()

var box      ocBox  = na
var polyline legPl  = na
var polyline retPl  = na
var line     t1Ln = na
var line     t2Ln = na
var line     t3Ln = na
var line     invLn = na
var label    t1Lb = na
var label    t2Lb = na
var label    t3Lb = na
var label    invLb = na
var label    smrLb = na

var array<int> rN    = array.new_int(2, 0)
var array<int> rT1   = array.new_int(2, 0)
var array<int> rT2   = array.new_int(2, 0)
var array<int> rT3   = array.new_int(2, 0)
var array<int> rFail = array.new_int(2, 0)
var array<int> rBars = array.new_int(2, 0)

evForm = false
evSmr  = false
evHit  = 0
evFrom = 0
evDone = false
evFail = false
evEnd  = false

bump(array<int> a, int i, int add) =>
    array.set(a, i, array.get(a, i) + add)

var int mid = 0
var array<line>     gLn  = array.new<line>()
var array<int>      gLnI = array.new_int()
var array<label>    gLb  = array.new<label>()
var array<int>      gLbI = array.new_int()
var array<box>      gBx  = array.new<box>()
var array<int>      gBxI = array.new_int()
var array<polyline> gPl  = array.new<polyline>()
var array<int>      gPlI = array.new_int()

regLn(line o) =>
    array.push(gLn, o)
    array.push(gLnI, mid)
regLb(label o) =>
    array.push(gLb, o)
    array.push(gLbI, mid)
regBx(box o) =>
    array.push(gBx, o)
    array.push(gBxI, mid)
regPl(polyline o) =>
    array.push(gPl, o)
    array.push(gPlI, mid)

prune(int upTo) =>
    while array.size(gLnI) > 0 and array.get(gLnI, 0) <= upTo
        line.delete(array.shift(gLn))
        array.shift(gLnI)
    while array.size(gLbI) > 0 and array.get(gLbI, 0) <= upTo
        label.delete(array.shift(gLb))
        array.shift(gLbI)
    while array.size(gBxI) > 0 and array.get(gBxI, 0) <= upTo
        box.delete(array.shift(gBx))
        array.shift(gBxI)
    while array.size(gPlI) > 0 and array.get(gPlI, 0) <= upTo
        polyline.delete(array.shift(gPl))
        array.shift(gPlI)
var table wm = table.new(position.bottom_right, 1, 1)
if barstate.isfirst
    table.cell(wm, 0, 0, "Telegram @SimpleForexTools", text_color = color.new(color.gray, 70), text_size = size.large)

if barstate.isconfirmed and not na(atr)

    if stage == 3
        evFrom := hitMax
        failNow = dir == 1 ? low < inv : high > inv
        if failNow
            evFail := true
        else
            for k = 1 to 3
                tk = k == 1 ? t1 : k == 2 ? t2 : t3
                if hitMax == k - 1 and (dir == 1 ? high >= tk : low <= tk)
                    hitMax := k
                    evHit := k

        if dir == 1 and not na(pl) and pBar > smrBar
            array.push(retPts, chart.point.from_index(pBar, pl))
        if dir == -1 and not na(ph) and pBar > smrBar
            array.push(retPts, chart.point.from_index(pBar, ph))
        expired = bar_index - smrBar > maxLeg
        if showCurve
            live = array.copy(retPts)
            array.push(live, chart.point.from_index(bar_index, close))
            polyline.delete(retPl)
            retPl := polyline.new(live, curved = curveSty == "Smooth", xloc = xloc.bar_index, line_color = color.new(dir == 1 ? UP : DN, 0), line_width = 3)
        if evFail or hitMax == 3 or expired
            d = dir == 1 ? 0 : 1
            bump(rN, d, 1)
            bump(rT1, d, hitMax >= 1 ? 1 : 0)
            bump(rT2, d, hitMax >= 2 ? 1 : 0)
            bump(rT3, d, hitMax >= 3 ? 1 : 0)
            bump(rFail, d, evFail ? 1 : 0)
            bump(rBars, d, hitMax == 3 ? bar_index - smrBar : 0)
            evDone := hitMax == 3
            evEnd := true
            resTxt = hitMax == 3 ? "✓ MODEL COMPLETE · " + str.tostring(bar_index - smrBar) + " bars" : evFail ? "✕ MODEL FAILED" + (hitMax > 0 ? " · T" + str.tostring(hitMax) + " reached" : "") : "EXPIRED" + (hitMax > 0 ? " · T" + str.tostring(hitMax) + " reached" : "")
            regLb(label.new(bar_index, dir == 1 ? high : low, resTxt, style = dir == 1 ? label.style_label_down : label.style_label_up,
                 color = hitMax == 3 ? TGT : color.new(GREY, 0), textcolor = hitMax == 3 ? color.white : INK, size = lSize))
            if not na(retPl)
                regPl(retPl)
            retPl := na   // the finished curve stays, filed under this model
            prune(mid - keepN)
            stage := 0
            dir := 0

    if stage == 2
        if dir == 1 ? low < legExt : high > legExt
            legExt := dir == 1 ? low : high
            legExtBar := bar_index
            if not na(recentSw) and recentSwBar > legStart
                lastSw := recentSw
                lastSwBar := recentSwBar
        if dir == 1 and not na(pl) and pBar > legStart and pl < prevPiv
            steps += 1
            prevPiv := pl
            array.push(pts, chart.point.from_index(pBar, pl))
            if showSteps
                array.push(stepLbs, label.new(pBar, pl, "SSL " + str.tostring(steps), style = label.style_label_up, color = NONE, textcolor = DN, size = size.small))
        if dir == -1 and not na(ph) and pBar > legStart and ph > prevPiv
            steps += 1
            prevPiv := ph
            array.push(pts, chart.point.from_index(pBar, ph))
            if showSteps
                array.push(stepLbs, label.new(pBar, ph, "BSL " + str.tostring(steps), style = label.style_label_down, color = NONE, textcolor = UP, size = size.small))

        oppSw = dir == 1 ? ph : pl
        if not na(oppSw) and pBar > legStart
            recentSw := oppSw
            recentSwBar := pBar
            if pBar < legExtBar
                lastSw := oppSw
                lastSwBar := pBar

        ocEdge = dir == 1 ? ocBot : ocTop
        depth  = dir == 1 ? ocBot - legExt : legExt - ocTop
        eq  = legExt + (ocEdge - legExt) * 0.5

        deep = not na(lastSw) and (dir == 1 ? lastSw < eq : lastSw > eq)
        smr = steps >= minSteps and depth >= legMin * atr and deep and lastSwBar < legExtBar and (dir == 1 ? close > lastSw : close < lastSw)
        broken = dir == 1 ? close > ocTop : close < ocBot
        expired = bar_index - ocR > maxLeg

        curve = array.new<chart.point>()
        array.push(curve, chart.point.from_index(ocR, ocEdge))
        for p in pts
            if p.index < legExtBar
                array.push(curve, p)
        array.push(curve, chart.point.from_index(legExtBar, legExt))
        if showCurve
            polyline.delete(legPl)
            legPl := polyline.new(curve, curved = curveSty == "Smooth", xloc = xloc.bar_index, line_color = color.new(dir == 1 ? DN : UP, smr ? 0 : 35), line_width = 3)

        if smr
            evSmr := true
            stage := 3
            mid += 1
            smrBar := bar_index
            hitMax := 0
            t1 := legExt + (ocEdge - legExt) * 0.5
            t2 := ocEdge
            t3 := dir == 1 ? ocTop : ocBot
            inv := legExt
            array.clear(retPts)
            array.push(retPts, chart.point.from_index(legExtBar, legExt))

            if dir == 1 ? close >= t1 : close <= t1
                hitMax := 1
            mc = dir == 1 ? UP : DN
            regBx(ocBox)
            if not na(legPl)
                regPl(legPl)
            for lb in stepLbs
                regLb(lb)
            regLn(line.new(lastSwBar, lastSw, bar_index, lastSw, color = mc, width = 2, style = line.style_dashed))
            regLb(label.new(bar_index, lastSw, "MSS", style = label.style_label_left, color = NONE, t

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