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

Trend Target Ribbon

indicator trend target ribbon for tradingview.pine

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

#__slope direction line.mq5MQL5 / MetaTrader 5 · 1 общих теговrange breakout @meowforex1.pineTradingView · 1 общих тегов#1.mtf_collider_h4_close_13_v18bar.mq4MQL4 / MetaTrader 4 · 1 общих тегов!mth_fasttmaline_edit3.mq4MQL4 / MetaTrader 4 · 1 общих тегов!mth_fasttmaline_edit2.mq4MQL4 / MetaTrader 4 · 1 общих тегов!mth_fasttmaline_edit.mq4MQL4 / MetaTrader 4 · 1 общих тегов
Вы автор или правообладатель?

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

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

О программе

Индикатор «Trend Target Ribbon» отображает трендовую аналитику на графике цены с помощью скользящей средней ALMA, окружённой полосами стандартного отклонения. Он определяет направление тренда и визуализирует его в виде градиентной ленты, а также раскрашивает свечи в зависимости от силы текущего тренда.

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

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

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

НастройкаОписание
src Источник цены, используемый для расчёта тренда ALMA.
almaLen Количество баров, используемых для расчёта скользящей средней ALMA. Большие значения дают более сглаженную и медленную линию тренда.
almaOffset Управляет балансом между отзывчивостью и сглаженностью. Более высокие значения смещают вес в сторону недавнего движения цены.
almaSigma Управляет сглаженностью кривой ALMA. Более высокие значения дают более гладкую линию с меньшим шумом.
devLen Количество баров для расчёта полос стандартного отклонения вокруг ALMA для подтверждения тренда.
devMult Множитель, применяемый к полосам отклонения. Более высокие значения требуют большего удаления цены от ALMA для подтверждения тренда.
slopeLen Количество баров назад, используемых для измерения наклона ALMA для подтверждения тренда.
slopeMin Минимальная сила наклона относительно ATR, необходимая для подтверждения направления тренда.
atrLen Количество баров для расчёта среднего истинного диапазона (ATR), используемого для нормализации наклона и расстояния стопа.
stopLookback Количество баров назад для определения структуры свингей при размещении стоп-лосса.
minStopAtr Минимально допустимое расстояние стоп-лосса, выраженное в кратных ATR.
maxStopAtr Максимально допустимое расстояние стоп-лосса, выраженное в кратных ATR.
targetCount Количество уровней прибыльных целей, отображаемых для каждой позиции, от 2 до 4.
zonePct Размер затенённой зоны вокруг каждой цели по прибыли как процент от расстояния риска.
approachR Расстояние в кратных риска, на котором уровень цели начинает визуально подсвечиваться при приближении к нему цены.
extendBars Количество баров, на которое линии входа, стопа и целей проецируются вперёд от текущего бара.
keepPositions Количество прошлых позиций, оставляемых видимыми на графике, прежде чем самая старая будет удалена.
showRibbon Включает или отключает видимость градиентной ленты тренда.
showLabels Включает или отключает отображение подписей позиций, стопа и целей.
paintBars Включает или отключает градиентную раскраску свечей на основе силы тренда.
labelInput Размер подписей для позиций и целей.
buyCol Цвет, используемый для бычьих элементов тренда.
sellCol Цвет, используемый для медвежьих элементов тренда.
tpCol Цвет, используемый для элементов целей по прибыли.
slCol Цвет, используемый для элементов стоп-лосса.
whiteCol Цвет, используемый для основной линии ALMA и маркеров входа.
neutralCol Цвет, используемый при отсутствии активного тренда.
Получить полный код

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

indicator("Trend Target Ribbon", overlay = true,
     max_lines_count = 100, max_boxes_count = 100, max_labels_count = 100)

const string g1 = "Trend"
const string g2 = "Position"
const string g3 = "Display"

float src          = input.source(close, "Source", group = g1,
     tooltip = "Price source used for the ALMA trend calculation.")
int almaLen        = input.int(34, "ALMA Length", minval = 5, group = g1,
     tooltip = "Number of bars used to calculate the ALMA moving average. Higher values produce a smoother, slower trend line.")
float almaOffset   = input.float(0.85, "ALMA Offset", minval = 0.0, maxval = 1.0, step = 0.05, group = g1,
     tooltip = "Controls the balance between responsiveness and smoothness. Higher values shift weighting toward recent price action.")
float almaSigma    = input.float(6.0, "ALMA Sigma", minval = 1.0, maxval = 15.0, step = 0.5, group = g1,
     tooltip = "Controls the smoothness of the ALMA curve. Higher values produce a smoother line with less noise.")
int devLen         = input.int(34, "Deviation Length", minval = 5, group = g1,
     tooltip = "Number of bars used to calculate the standard deviation bands around the ALMA for trend confirmation.")
float devMult      = input.float(0.65, "Trend Confirmation", minval = 0.1, maxval = 3.0, step = 0.05, group = g1,
     tooltip = "Multiplier applied to the deviation bands. Higher values require price to move further from the ALMA before confirming a trend.")
int slopeLen       = input.int(3, "Slope Length", minval = 1, maxval = 10, group = g1,
     tooltip = "Number of bars back used to measure the ALMA's slope for trend confirmation.")
float slopeMin     = input.float(0.08, "Minimum Slope", minval = 0.0, maxval = 1.0, step = 0.01, group = g1,
     tooltip = "Minimum slope strength, relative to ATR, required to confirm a trend direction.")
int atrLen         = input.int(14, "ATR Length", minval = 5, group = g1,
     tooltip = "Number of bars used to calculate the Average True Range, used for slope normalization and stop distance.")

int stopLookback   = input.int(12, "Stop Structure Lookback", minval = 3, maxval = 50, group = g2,
     tooltip = "Number of bars back used to locate swing structure for stop loss placement.")
float minStopAtr   = input.float(0.75, "Minimum Stop ATR", minval = 0.25, maxval = 3.0, step = 0.05, group = g2,
     tooltip = "Minimum stop distance allowed, expressed as a multiple of ATR.")
float maxStopAtr   = input.float(3.0, "Maximum Stop ATR", minval = 1.0, maxval = 8.0, step = 0.25, group = g2,
     tooltip = "Maximum stop distance allowed, expressed as a multiple of ATR.")
int targetCount    = input.int(4, "Profit Targets", minval = 2, maxval = 4, group = g2,
     tooltip = "Number of profit targets plotted for each position, from 2 to 4.")
float zonePct      = input.float(0.06, "Target Zone Size", minval = 0.01, maxval = 0.20, step = 0.01, group = g2,
     tooltip = "Size of the shaded zone drawn around each profit target, as a percentage of the risk distance.")
float approachR    = input.float(0.65, "Target Approach Range", minval = 0.1, maxval = 1.5, step = 0.05, group = g2,
     tooltip = "Distance, in risk multiples, within which a target begins visually highlighting as price approaches it.")
int extendBars     = input.int(30, "Projection Length", minval = 10, maxval = 100, group = g2,
     tooltip = "Number of bars the entry, stop, and target lines are projected forward from the current bar.")
int keepPositions  = input.int(4, "Positions On Chart", minval = 1, maxval = 5, group = g2,
     tooltip = "Number of past positions kept visible on the chart before the oldest is removed.")

bool showRibbon    = input.bool(true, "Show Trend Gradient", group = g3,
     tooltip = "Toggles visibility of the trend gradient ribbon.")
bool showLabels    = input.bool(true, "Show Position Labels", group = g3,
     tooltip = "Toggles visibility of position, stop, and target labels.")
bool paintBars     = input.bool(true, "Color Candles", group = g3,
     tooltip = "Toggles gradient coloring of candles based on trend conviction.")

string labelInput  = input.string("Normal", "Label Size",
     options = ["Tiny", "Small", "Normal", "Large", "Huge"],
     group = g3,
     tooltip = "Controls the size of position and target labels.")

color buyCol       = input.color(#00FF00, "Bull", inline = "c1", group = g3,
     tooltip = "Color used for bullish trend elements.")
color sellCol      = input.color(#FF0066, "Bear", inline = "c1", group = g3,
     tooltip = "Color used for bearish trend elements.")

color tpCol        = input.color(#00FF00, "Take Profit", inline = "c2", group = g3,
     tooltip = "Color used for take-profit target elements.")
color slCol        = input.color(#FF0066, "Stop Loss", inline = "c2", group = g3,
     tooltip = "Color used for stop-loss elements.")

color whiteCol     = input.color(#FFFFFF, "Core", group = g3,
     tooltip = "Color used for the core ALMA line and entry markers.")
color neutralCol   = input.color(#555555, "Neutral", group = g3,
     tooltip = "Color used when no trend is active.")

f_label_size(string value) =>
    value == "Tiny" ? size.tiny :
     value == "Small" ? size.small :
     value == "Large" ? size.large :
     value == "Huge" ? size.huge :
     size.normal

string labelSize = f_label_size(labelInput)

float alma = ta.alma(src, almaLen, almaOffset, almaSigma)
float dev  = ta.stdev(src, devLen)
float atr  = ta.atr(atrLen)

float slopeScore = atr > 0 ? (alma - alma[slopeLen]) / atr : 0.0

float upperConfirm = alma + dev * devMult
float lowerConfirm = alma - dev * devMult

bool bullSetup = slopeScore > slopeMin and close > upperConfirm
bool bearSetup = slopeScore < -slopeMin and close < lowerConfirm

var int trend = 0

bool bullFlip = false
bool bearFlip = false

if trend != 1 and bullSetup
    trend := 1
    bullFlip := true
else if trend != -1 and bearSetup
    trend := -1
    bearFlip := true

bool bull = trend == 1
bool bear = trend == -1
bool flip = bullFlip or bearFlip

color trendCol = bull ? buyCol : bear ? sellCol : neutralCol

float distanceScore = atr > 0 ? math.abs(close - alma) / atr : 0.0

float conviction = math.max(0.0, math.min(1.0,
     math.abs(slopeScore) * 2.0 + distanceScore * 0.35))

float ribbonEdge = bull ?
     alma - dev * 0.55 :
     bear ? alma + dev * 0.55 :
     alma

float ribbonMid = (alma + ribbonEdge) * 0.5

float almaDraw = flip ? na : alma
float midDraw  = flip ? na : ribbonMid
float edgeDraw = flip ? na : ribbonEdge

int edgeT = int(math.round(82.0 - conviction * 16.0))
int coreT = int(math.round(50.0 - conviction * 35.0))

pEdgeGlow = plot(showRibbon ? edgeDraw : na, "Trend Glow",
     color = color.new(trendCol, 86),
     linewidth = 9,
     style = plot.style_linebr)

pEdge = plot(showRibbon ? edgeDraw : na, "Trend Edge",
     color = color.new(trendCol, edgeT),
     linewidth = 3,
     style = plot.style_linebr)

pMid = plot(showRibbon ? midDraw : na, "Trend Mid",
     color = color.new(trendCol, 100),
     linewidth = 1,
     style = plot.style_linebr)

pAlma = plot(showRibbon ? almaDraw : na, "ALMA",
     color = color.new(whiteCol, coreT),
     linewidth = 1,
     style = plot.style_linebr)

fill(pEdge, pMid,
     color = showRibbon ? color.new(trendCol, 84) : na)

fill(pMid, pAlma,
     color = showRibbon ? color.new(trendCol, 93) : na)

color weakCol = color.new(trendCol, 72)

color barCol = color.from_gradient(
     conviction,
     0.0,
     1.0,
     weakCol,
     trendCol)

barcolor(paintBars and trend != 0 ? barCol : na)

var float entryPrice = na
var float stopPrice  = na
var float riskDist   = na

var int entryBar     = na
var int positionDir  = 0

var bool positionEnded = true

var line entryGlow = na
var line entryCore = na
var line stopGlow  = na
var line stopCore  = na

var box riskBox = na

var label entryTag = na
var label stopTag  = na

var line[] targetGlow  = array.new<line>()
var line[] targetCore  = array.new<line>()
var box[] targetZone   = array.new<box>()
var box[] targetBand   = array.new<box>()
var label[] targetTags = array.new<label>()

var bool[] targetHit = array.new<bool>(4, false)

var line[] allPositionLines   = array.new<line>()
var box[] allPositionBoxes    = array.new<box>()
var label[] allPositionLabels = array.new<label>()

var int positionCount = 0

if flip and not na(entryPrice) and not positionEnded
    int endBar = bar_index
    color oldCol = positionDir == 1 ? buyCol : sellCol

    line.set_xy2(entryGlow, endBar, entryPrice)
    line.set_xy2(entryCore, endBar, entryPrice)
    line.set_xy2(stopGlow, endBar, stopPrice)
    line.set_xy2(stopCore, endBar, stopPrice)

    line.set_color(entryGlow, color.new(oldCol, 88))
    line.set_color(entryCore, color.new(whiteCol, 50))

    line.set_color(stopGlow, color.new(slCol, 88))
    line.set_color(stopCore, color.new(slCol, 48))

    box.set_right(riskBox, endBar)
    box.set_bgcolor(riskBox, color.new(slCol, 97))

    if showLabels
        label.set_xy(entryTag, endBar + 1, entryPrice)
        label.set_color(entryTag, color.new(oldCol, 58))

        label.set_xy(stopTag, endBar + 1, stopPrice)
        label.set_color(stopTag, color.new(slCol, 65))

    for i = 0 to targetGlow.size() - 1
        float targetPrice = entryPrice + positionDir * riskDist * (i + 1)

        line glow = targetGlow.get(i)
        line core = targetCore.get(i)
        box zone = targetZone.get(i)
        box band = targetBand.get(i)
        label tag = targetTags.get(i)

        bool hit = targetHit.get(i)

        line.set_xy2(glow, endBar, targetPrice)
        line.set_xy2(core, endBar, targetPrice)

        line.set_color(glow,
             color.new(tpCol, hit ? 80 : 94))

        line.set_color(core,
             hit ?
             color.new(whiteCol, 38) :
             color.new(tpCol, 72))

        box.set_right(zone, endBar)
        box.set_right(band, endBar)

        box.set_bgcolor(zone,
             color.new(tpCol, hit ? 93 : 98))

        box.set_bgcolor(band,
             color.new(tpCol, hit ? 95 : 99))

        if showLabels
            label.set_xy(tag, endBar + 1, targetPrice)

            label.set_color(tag,
                 color.new(tpCol, hit ? 52 : 76))

    positionEnded := true
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 flip
    int linesPerPosition  = 4 + targetCount * 2
    int boxesPerPosition  = 1 + targetCount * 2
    int labelsPerPosition = 2 + targetCount

    if positionCount >= keepPositions
        for i = 0 to linesPerPosition - 1
            line oldLine = array.shift(allPositionLines)
            line.delete(oldLine)

        for i = 0 to boxesPerPosition - 1
            box oldBox = array.shift(allPositionBoxes)
            box.delete(oldBox)

        for i = 0 to labelsPerPosition - 1
            label oldLabel = array.shift(allPositionLabels)
            label.delete(oldLabel)

        positionCount -= 1

    targetGlow.clear()
    targetCore.clear()
    targetZone.clear()
    targetBand.clear()
    targetTags.clear()

    for i = 0 to 3
        targetHit.set(i, false)

    entryPrice := close
    entryBar := bar_index
    positionDir := bull ? 1 : -1
    positionEnded := false

    float structureStop = positionDir == 1 ?
         ta.lowest(low, stopLookback)[1] :
         ta.highest(high, stopLookback)[1]

    float rawRisk = positionDir == 1 ?
         entryPrice - structureStop :
         structureStop - entryPrice

    float minimumRisk = atr * minStopAtr
    float maximumRisk = atr * maxStopAtr

    riskDist := math.min(
         math.max(nz(rawRisk, minimumRisk), minimumRisk),
         maximumRisk)

    stopPrice := entryPrice - positionDir * riskDist

    color activeCol = positionDir == 1 ? buyCol : sellCol

    entryGlow := line.new(
         entryBar,
         entryPri

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

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
1 603₽ ≈ $19.59