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

Wisely Wealth ; M-W Pattern Scorer & Breakout Engine

indicator wisely wealth ; m-w pattern scorer & breakout engine for tradingview.pine

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

ea12sd.mq4MQL4 / MetaTrader 4 · 1 общих теговindicator market map for tradingview.pineTradingView · 1 общих теговconfluenceforge_pro.mq5TradingView · 1 общих теговvolatility_gold_master.mq5MQL5 / MetaTrader 5 · 1 общих теговhamster scalping v 21.0.mq5MQL5 / MetaTrader 5 · 1 общих теговqqe of rsi(oma)(on chart).mq5MQL5 / MetaTrader 5 · 1 общих тегов
Вы автор или правообладатель?

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

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

О программе

Индикатор «Wisely Wealth ; M-W Pattern Scorer & Breakout Engine» предназначен для автоматического обнаружения на графике TradingView паттернов «двойная вершина» (Double Top) и «двойное дно» (Double Bottom). Для каждого найденного паттерна рассчитывается оценка качества от 0 до 100, основанная на четырёх факторах: соответствии цен пиков, RSI-дивергенции, объёмной дивергенции и высоте паттерна. Паттерны, набравшие оценку ниже заданного порога, не отображаются.

При формировании паттерна индикатор рисует линии вершин и линию шеи, а также отображает метку с оценкой и её детализацией. После пробоя шеи в сторону тренда автоматически строятся проекции Stop Loss, Take Profit 1 и Take Profit 2, которые динамически обновляются до момента достижения одной из целевых отметок или срабатывания стоп-лосса.

Встроенный фильтр тренда на основе EMA (по умолчанию 200 периодов) позволяет пропускать пробои, не совпадающие с макро-трендом. Доступны отдельные оповещения: формирование паттерна, пробой шеи, достижение TP1, достижение TP2 и срабатывание SL. Все визуальные элементы настраиваются по цвету и отображению.

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

НастройкаОписание
leftBars Количество баров слева от текущей свечи, необходимых для подтверждения свинг-пивота.
rightBars Количество баров справа от текущей свечи, необходимых для валидации свинг-пивота. Определение паттерна происходит после закрытия этого количества баров.
atrLength Период расчёта индикатора Average True Range (ATR), используемого для допусков по цене, минимальной высоты паттерна и буфера стоп-лосса.
peakTolAtrMult Максимально допустимая разница цен между двумя пиками или впадинами в единицах ATR. Чем меньше значение, тем строже требование совпадения уровней.
minBarsBetween Минимальное количество баров между двумя пиками или впадинами, предотвращающее распознавание микроструктур.
maxBarsBetween Максимально допустимое количество баров между двумя пиками или впадинами паттерна; более широкие структуры отфильтровываются.
minHeightAtrMult Минимальная высота паттерна (от пика до линии шеи) в кратных значениях ATR. Обеспечивает значимость обнаруженной структуры.
minScoreThresh Минимальная оценка качества паттерна от 0 до 100. Паттерны с оценкой ниже порога не отображаются и не генерируют сигналы.
rsiLength Период расчёта индекса относительной силы (RSI), используемого для определения дивергенции между двумя пиками паттерна.
showScoreDetails Включает отображение детализированной разбивки оценки (Price Match, RSI Div, Volume Div, Height) во всплывающей подсказке метки паттерна.
useTrendFilter Включает фильтр направления тренда на основе EMA. При активном фильтре длинные пробои срабатывают только выше EMA, а короткие — только ниже EMA.
emaFilterLength Период экспоненциальной скользящей средней (EMA), используемой в качестве фильтра макро-тренда.
slAtrBuffer Дополнительный буфер в единицах ATR, добавляемый за пределы экстремальной вершины или впадины для размещения Stop Loss за пределами обычного шума.
maxWaitBreakout Максимальное количество баров после формирования паттерна, в течение которых ожидается пробой шеи. Если пробой не произошёл, паттерн считается просроченным.
showTargets Включает или отключает отображение линий и меток Stop Loss, Take Profit 1 и Take Profit 2 после пробоя паттерна.
targetLineLength Начальная горизонтальная длина (в барах) линий проекции Stop Loss и Take Profit при отрисовке на графике.
colorTop Цвет линий, маркеров и меток паттерна «двойная вершина» (Double Top).
colorBottom Цвет линий, маркеров и меток паттерна «двойное дно» (Double Bottom).
colorNeckline Цвет пунктирной линии шеи, соединяющей точку разворота с зоной пробоя.
colorTP1 Цвет линии и метки первой цели Take Profit (1.0x высоты паттерна).
colorTP2 Цвет линии и метки второй цели Take Profit (1.618x высоты паттерна).
colorSL Цвет линии и метки уровня Stop Loss после пробоя паттерна.

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

indicator("Wisely Wealth ; M-W Pattern Scorer & Breakout Engine", shorttitle="M-W Scorer", overlay=true, max_lines_count=500, max_labels_count=500)

leftBars         = input.int(5, "Pivot Left Bars", minval=1, group="Pivot Detection Settings", tooltip="Number of bars to the left required to confirm a swing pivot. Higher values capture larger swings, while lower values detect faster, minor pivots.")
rightBars        = input.int(5, "Pivot Right Bars", minval=1, group="Pivot Detection Settings", tooltip="Number of bars to the right needed to validate a pivot. Detection occurs after this number of bars closes, ensuring price confirmation.")

atrLength        = input.int(14, "ATR Length", minval=1, group="ATR & Tolerance Settings", tooltip="Lookback period for Average True Range (ATR). Measures market volatility for peak tolerance, pattern height thresholds, and stop loss buffers.")
peakTolAtrMult   = input.float(0.5, "Peak Matching Tolerance (ATR Mult)", minval=0.05, step=0.05, group="ATR & Tolerance Settings", tooltip="Maximum allowable price difference between the two peaks or valleys in ATR units. Closer peaks receive a higher quality score.")

minBarsBetween   = input.int(5, "Min Bars Between Peaks", minval=2, group="Pattern Distance & Dimensions", tooltip="Minimum bar distance between Peak 1 and Peak 2. Prevents identifying micro-structures or adjacent duplicate candles.")
maxBarsBetween   = input.int(60, "Max Bars Between Peaks", minval=3, group="Pattern Distance & Dimensions", tooltip="Maximum allowable bar span between the two peaks or valleys. Filters out overly wide or detached patterns.")
minHeightAtrMult = input.float(1.0, "Min Pattern Height (ATR Mult)", minval=0.1, step=0.1, group="Pattern Distance & Dimensions", tooltip="Minimum vertical distance from peak to neckline in ATR multiples. Ensures the pattern is large enough to represent a significant reversal.")

minScoreThresh   = input.float(60.0, "Minimum Score Threshold", minval=0.0, maxval=100.0, step=5.0, group="Quality Scoring System (0 - 100)", tooltip="Minimum quality score (0-100) required to validate a pattern. Considers price matching, RSI divergence, volume divergence, and height.")
rsiLength        = input.int(14, "RSI Length for Divergence", minval=1, group="Quality Scoring System (0 - 100)", tooltip="Lookback period for Relative Strength Index (RSI). Used to detect momentum divergence between Peak 1 and Peak 2.")
showScoreDetails = input.bool(true, "Show Score Breakdown in Tooltip", group="Quality Scoring System (0 - 100)", tooltip="Displays the detailed 4-factor scoring breakdown (Price Match, RSI Div, Volume Div, and Height) inside the pattern label tooltip on hover.")

useTrendFilter   = input.bool(false, "Enable 200 EMA Trend Filter", group="Trend Filter", tooltip="Enables trend direction filtering. When active, Long breakouts only trigger above the EMA, and Short breakouts only trigger below the EMA.")
emaFilterLength  = input.int(200, "EMA Filter Length", minval=1, group="Trend Filter", tooltip="Period for the Exponential Moving Average (EMA) macro trend filter. Typically set to 200 to align entries with broader market trends.")

slAtrBuffer      = input.float(0.5, "Stop Loss ATR Buffer", minval=0.0, step=0.1, group="Risk & Targets", tooltip="ATR buffer added beyond the extreme peak or valley to place the Stop Loss safely outside normal market noise.")
maxWaitBreakout  = input.int(50, "Max Bars Waiting for Breakout", minval=5, group="Risk & Targets", tooltip="Maximum bars allowed after pattern formation for price to break through the neckline before the pattern expires.")
showTargets      = input.bool(true, "Show TP1, TP2 & SL Projections", group="Risk & Targets", tooltip="Toggles visualization of Stop Loss (SL), Take Profit 1 (TP1), and Take Profit 2 (TP2) projection lines and labels upon breakout.")
targetLineLength = input.int(15, "Target Projections Default Span", minval=3, group="Risk & Targets", tooltip="Initial horizontal bar length for plotting Stop Loss and Take Profit target lines on the chart.")

colorTop         = input.color(#ef5350, "Double Top (Bearish) Color", group="Visual Styling", tooltip="Color used to draw Double Top lines, markers, and labels.")
colorBottom      = input.color(#26a69a, "Double Bottom (Bullish) Color", group="Visual Styling", tooltip="Color used to draw Double Bottom lines, markers, and labels.")
colorNeckline    = input.color(#ff9800, "Neckline Color", group="Visual Styling", tooltip="Color of the horizontal neckline connecting the pattern valley or peak to the breakout.")
colorTP1         = input.color(#00bcd4, "Take Profit 1 Color", group="Visual Styling", tooltip="Color for the Take Profit 1 (1.0x pattern height) target line and label.")
colorTP2         = input.color(#4caf50, "Take Profit 2 Color", group="Visual Styling", tooltip="Color for the Take Profit 2 (1.618x pattern height) target line and label.")
colorSL          = input.color(#e91e63, "Stop Loss Color", group="Visual Styling", tooltip="Color for the Stop Loss level line and label.")

atrVal  = ta.atr(atrLength)
rsiVal  = ta.rsi(close, rsiLength)
trendMa = ta.ema(close, emaFilterLength)

plot(useTrendFilter ? trendMa : na, "200 EMA Trend Filter", color=color.new(color.orange, 20), linewidth=2)

type PivotPoint
    int   bar
    float price
    float rsi
    float vol
    float atr

type Pattern
    bool  isTop             // true = Double Top (Bearish), false = Double Bottom (Bullish)
    int   p1_bar
    float p1_price
    int   neck_bar
    float neck_price
    int   p2_bar
    float p2_price
    float height
    float score
    float scoreMatch
    float scoreRsi
    float scoreVol
    float scoreHeight
    float sl
    float tp1
    float tp2
    bool  brokenOut
    bool  tp1Hit
    bool  slHit
    bool  completed
    int   breakout_bar
    line  l1
    line  l2
    line  lNeck
    line  lBreak
    line  lSL
    line  lTP1
    line  lTP2
    label lblScore
    label lblSL
    label lblTP1
    label lblTP2

f_newPattern(bool isTop, int p1_bar, float p1_price, int neck_bar, float neck_price, int p2_bar, float p2_price, float height, float score, float sMatch, float sRsi, float sVol, float sHeight, line l1, line l2, line lNeck, label lblScore) =>
    Pattern.new(isTop, p1_bar, p1_price, neck_bar, neck_price, p2_bar, p2_price, height, score, sMatch, sRsi, sVol, sHeight, na, na, na, false, false, false, false, na, l1, l2, lNeck, na, na, na, na, lblScore, na, na, na)

var pivotHighs     = array.new<PivotPoint>()
var pivotLows      = array.new<PivotPoint>()
var activePatterns = array.new<Pattern>()

f_calcScore(bool isTop, float p1_price, float p2_price, float p1_rsi, float p2_rsi, float p1_vol, float p2_vol, float height, float atr, float maxTolerance) =>

    float priceDiff  = math.abs(p1_price - p2_price)
    float matchRatio = math.max(0.0, 1.0 - (priceDiff / math.max(maxTolerance, 1e-6)))
    float scoreMatch = matchRatio * 25.0

    float scoreRsi = 0.0
    if isTop

        if p2_rsi < p1_rsi
            float rsiDelta = p1_rsi - p2_rsi
            scoreRsi := math.min(25.0, 10.0 + (rsiDelta / 15.0) * 15.0)
    else

        if p2_rsi > p1_rsi
            float rsiDelta = p2_rsi - p1_rsi
            scoreRsi := math.min(25.0, 10.0 + (rsiDelta / 15.0) * 15.0)

    float scoreVol = 0.0
    if p2_vol < p1_vol
        float volDropRatio = (p1_vol - p2_vol) / math.max(p1_vol, 1.0)
        scoreVol := math.min(25.0, 10.0 + math.min(volDropRatio, 1.0) * 15.0)

    float scoreHeight = 0.0
    float heightInAtr = height / math.max(atr, 1e-6)
    if heightInAtr >= minHeightAtrMult
        float excessRatio = (heightInAtr - minHeightAtrMult) / (minHeightAtrMult * 2.0)
        scoreHeight := math.min(25.0, 10.0 + math.min(math.max(0.0, excessRatio), 1.0) * 15.0)

    float totalScore = math.round(scoreMatch + scoreRsi + scoreVol + scoreHeight, 1)
    [totalScore, scoreMatch, scoreRsi, scoreVol, scoreHeight]

ph = ta.pivothigh(high, leftBars, rightBars)
pl = ta.pivotlow(low, leftBars, rightBars)

bool patternFormedAlert = false
bool longBreakout       = false
bool shortBreakout      = false
bool tp1HitAlert        = false
bool slHitAlert         = false

if not na(ph)
    int   p2_bar   = bar_index - rightBars
    float p2_price = ph
    float p2_rsi   = rsiVal[rightBars]
    float p2_vol   = volume[rightBars]
    float p2_atr   = atrVal[rightBars]

    int numPivots = array.size(pivotHighs)
    if numPivots > 0
        for i = numPivots - 1 to 0
            PivotPoint p1 = array.get(pivotHighs, i)
            int barsBetween = p2_bar - p1.bar

            if barsBetween < minBarsBetween
                continue
            if barsBetween > maxBarsBetween
                break

            float maxAllowedDiff = p2_atr * peakTolAtrMult
            float priceDiff = math.abs(p1.price - p2_price)

            if priceDiff <= maxAllowedDiff

                int offset2 = bar_index - p2_bar
                int offset1 = bar_index - p1.bar

                float neckPrice = 1e10
                int neckBar = na
                bool peakViolated = false
                float highestAllowed = math.max(p1.price, p2_price) + (maxAllowedDiff * 0.5)

                for b = offset2 + 1 to offset1 - 1
                    if low[b] < neckPrice
                        neckPrice := low[b]
                        neckBar := bar_index - b
                    if high[b] > highestAllowed
                        peakViolated := true

                if not peakViolated and neckPrice < math.min(p1.price, p2_price) and not na(neckBar)
                    float patternHeight = math.max(p1.price, p2_price) - neckPrice
                    if patternHeight >= (p2_atr * minHeightAtrMult)

                        [totalScore, sMatch, sRsi, sVol, sHeight] = f_calcScore(true, p1.price, p2_price, p1.rsi, p2_rsi, p1.vol, p2_vol, patternHeight, p2_atr, maxAllowedDiff)

                        if totalScore >= minScoreThresh
                            patternFormedAlert := true

                            line l1 = line.new(p1.bar, p1.price, neckBar, neckPrice, color=colorTop, width=2)
                            line l2 = line.new(neckBar, neckPrice, p2_bar, p2_price, color=colorTop, width=2)
                            line lNeck = line.new(neckBar, neckPrice, bar_index, neckPrice, color=colorNeckline, style=line.style_dashed, width=1)

                            string tooltipText = showScoreDetails ? "Score Breakdown (Score: " + str.tostring(totalScore, "#.#") + "/100)\n" +
                                                 "• Price Match: " + str.tostring(sMatch, "#.#") + "/25\n" +
                                                 "• RSI Divergence: " + str.tostring(sRsi, "#.#") + "/25\n" +
                                                 "• Volume Divergence: " + str.tostring(sVol, "#.#") + "/25\n" +
                                                 "• Pattern Height: " + str.tostring(sHeight, "#.#") + "/25" : ""

                            label lblScore = label.new(p2_bar, p2_price, text="Double Top\n" + str.tostring(totalScore, "#") + " pts",
                                                       style=label.style_label_down, color=color.new(colorTop, 20), textcolor=color.white,
                                                       size=size.small, tooltip=tooltipText)

                            Pattern newPat = f_newPattern(true, p1.bar, p1.price, neckBar, neckPrice, p2_bar, p2_price, patternHeight, totalScore, sMatch, sRsi, sVol, sHeight, l1, l2, lNeck, lblScore)
                            array.push(activePatterns, newPat)
                            break // Formed pattern with closest valid peak

    array.push(pivotHighs, PivotPoint.new(p2_bar, p2_price, p2_rsi, p2_vol, p2_atr))
    if array.size(pivotHighs) > 40
        array.shift(pivotHighs)

if not na(pl)
    int   p2_bar   = bar_index - rightBars
    float p2_price = pl
    float p2_rsi   = rsiVal[rightBars]
    float p2_vol   = volume[rightBars]
    float p2_atr   = atrVal[rightBars]

    int numPivots = array.size(pivotLows)
    if numPivots > 0
        for i = numPivots - 1 to 0
            PivotPoint p1 = array.get(pivotLows, i)
            int barsBetween = p2_bar - p1.bar

            if barsBetween < minBarsBetween
                continue
            if barsBetween > maxBarsBetween
                break

            float maxAllowedDiff = p2_atr * pea

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