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

Trend Reversal Targets

indicator trend reversal targets for tradingview.pine
Вы автор или правообладатель?

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

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

О программе

Индикатор «Trend Reversal Targets» предназначен для анализа трендов и выявления потенциальных разворотов на графике в TradingView. Он построен на модели двойных принятых значений цены с адаптивной скоростью сглаживания, где быстрая и медленная линии формируют трендовый центр и ленту. Лента отображается залитой областью с прозрачностью, зависящей от качества тренда.

Индикатор включает модуль обнаружения экстремумов (exhaustion), который отслеживает крайние точки цены с учётом растяжения в ATR, краткости закрытия и относительного объёма. При достижении условий экстремума запускается механизм подтверждения разворота, проверяющий пробой структуры, размер тела свечи и объём в заданном окне.

При подтверждении разворота индикатор выводит метки LONG или SHORT, а при включённой опции — инструменты позиции с уровнями стоп-лосса и трёх тейк-профитов (в кратности R). Вспомогательные линии и прямоугольники автоматически обновляются или убираются при достижении целевых уровней, стопа или истечения срока. Также доступны условные оповещения TradingView для бычьих и медвежьих сигналов.

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

НастройкаОписание
trendLen Глубина просмотра для оценки принятой цены и краткости направления тренда.
atrLen Количество баров для расчёта среднего истинного диапазона (ATR), используемого в буфере тренда, ширине ленты, измерении растяжения и буфере стопа.
fastResponseMin Минимальная скорость адаптации быстрой принятой линии. При падении качества тренда линия движется к этому значению.
fastResponseMax Максимальная скорость адаптации быстрой принятой линии. Чем выше качество тренда, тем быстрее линия движется к этому значению.
slowResponseMin Минимальная скорость адаптации медленной принятой линии. Быстрая и медленная линии совместно формируют внутреннюю модель тренда.
slowResponseMax Максимальная скорость адаптации медленной принятой линии. Быстрая и медленная линии совместно формируют внутреннюю модель тренда.
trendBuffer Расстояние в ATR, на котором цена должна закрыться за трендовым центром при правильной стороне быстрой линии относительно медленной, прежде чем состояние тренда изменится.
ribbonMinATR Минимальная половина ширины ленты в ATR. Лента всегда поддерживается не ниже этого предела.
ribbonMaxATR Максимальная половина ширины ленты в ATR. Лента всегда ограничивается этим значением сверху.
ribbonSpread Множитель, применяемый к расстоянию между быстрой и медленной линиями для определения ширины ленты до применения пределов ATR.
exhaustLen Глубина просмотра для обнаружения нового экстремума и измерения краткости направления на этом экстремуме.
minStretchATR Минимальное расстояние от принятого значения в ATR, которое должно быть преодолено, прежде чем экстремум может быть признан исчерпанным.
maxExhaustEff Максимальная краткость направления, допустимая на экстремуме истощения. Позволяет определить, насколько «плоским» должен быть импульс для признания его исчерпанным.
volLen Количество баров для расчёта среднего объёма, используемого для определения относительного объёма.
climaxVolume Относительный объём, при котором свеча с слабым закрытием на экстремуме классифицируется как кульминация и может подтвердить истощение даже при высокой краткости.
weakClose Максимальная позиция закрытия в диапазоне свечи для кульминационной свечи на высоком экстремуме, измеренная от минимума и зеркально отражённая на минимумах. Меньшие значения требуют более слабого закрытия.
minTrendEfficiency Минимальная краткость направления за длину тренда, требуемая перед обнаружением экстремума истощения.
confirmWindow Максимальное количество баров между моментом истощения и подтверждённым разворотом.
breakBars Количество предыдущих баров, чей минимальный минимум или максимальный максимум должен быть пробит свечой подтверждения.
confirmBody Минимальный размер тела свечи подтверждения как кратное среднего тела за последние 12 баров.
confirmVolume Минимальный относительный объём, требуемый на свече подтверждения разворота.
confirmClose Насколько близко свеча подтверждения должна закрыться к экстремуму. Значение 0.70 означает закрытие в верхних 30% диапазона для лонгов и нижних 30% для шортов.
signalCooldown Минимальное количество баров после сигнала, прежде чем новый экстремум может быть подготовлен.
showPositions Отображает инструмент позиции на каждом сигнале с входом по закрытию сигнала, стоп-лоссом за экстремумом истощения и тремя целями в кратности R.
initialWidth Количество баров, на которые инструмент позиции изначально распространяется вправо от сигнала.
maximumWidth Максимальное количество баров вправо, до которого неразрешённые позиции продолжают расширяться вместе с ценой.
maxPositions Количество инструментов позиции, отображаемых на графике одновременно. Самый старый удаляется первым.
stopBufferATR Расстояние в ATR, на котором стоп-лосс размещается за экстремумом истощения.
tp1R Расстояние первой цели (TP1) в кратности риска (R).
tp2R Расстояние второй цели (TP2) в кратности риска (R). TP2 поддерживается минимум на 0.5R дальше TP1.
tp3R Расстояние третьей цели (TP3) в кратности риска (R). TP3 поддерживается минимум на 0.5R дальше TP2.
showRibbon Включает или отключает отображение трендовой ленты принятых значений.
paintBars Включает или отключает раскраску свечей на основе текущего состояния тренда.
showSignals Включает или отключает метки LONG и SHORT на подтверждённых сигналах разворота.
bullCol Цвет для бычьих элементов: элементы восходящего тренда, сигналы LONG и цели LONG.
bearCol Цвет для медвежьих элементов: элементы нисходящего тренда, сигналы SHORT и цели SHORT.

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

indicator("Trend Reversal Targets", shorttitle="Reversal Targets", overlay=true,
     max_lines_count=500, max_boxes_count=500, max_labels_count=300, max_bars_back=2000)

const string g1 = "Trend Engine"
const string g2 = "Exhaustion"
const string g3 = "Reversal Confirmation"
const string g4 = "Position Tool"
const string g5 = "Display"

const color BULL = #00FF66
const color BEAR = #FF0066

const string tt_trendLen = "Lookback used to estimate accepted price and directional efficiency."
const string tt_atrLen = "Number of bars used to calculate the Average True Range for the trend buffer, ribbon width, stretch measurement, and stop buffer."
const string tt_fastResponse = "Range of adaptation speed for the fast accepted-value path. The path moves toward Max as trend efficiency rises and toward Min as it falls."
const string tt_response = "Fast and slow accepted-value paths drive the internal trend model."
const string tt_trendBuffer = "ATR distance price must close beyond the trend center, with the fast path on the correct side of the slow path, before the trend state changes."
const string tt_ribbonWidth = "Minimum and maximum ribbon half-width measured in ATR. The ribbon is always kept within these limits."
const string tt_ribbonSpread = "Multiplier applied to the distance between the fast and slow paths to size the ribbon before the ATR limits are applied."
const string tt_exhaustLen = "Lookback used to detect a new extreme and to measure short-term directional efficiency at that extreme."
const string tt_stretch = "Minimum ATR distance from accepted value required before an extreme can qualify as exhausted."
const string tt_exhaust = "Maximum short-term directional efficiency allowed at an exhaustion extreme."
const string tt_volLen = "Number of bars used to calculate average volume for relative volume readings."
const string tt_climax = "Relative volume at which a weak-closing extreme bar qualifies as a climax, allowing exhaustion even when short-term efficiency is still high."
const string tt_weakClose = "Maximum close position within the bar's range for a climax bar at a high, measured from the low and mirrored at lows. Lower values require a weaker close."
const string tt_trendQuality = "Minimum directional efficiency over the Trend Length required before an exhaustion extreme can be detected."
const string tt_window = "Maximum bars allowed between exhaustion and confirmed reversal."
const string tt_breakBars = "Number of prior bars whose lowest low or highest high the confirmation candle must close beyond."
const string tt_body = "Minimum confirmation candle body size as a multiple of the average body over the last 12 bars."
const string tt_confirmVol = "Minimum relative volume required on the confirmation candle."
const string tt_closeStrength = "How close to its extreme the confirmation candle must close. 0.70 means within the top 30% of the range for longs and the bottom 30% for shorts."
const string tt_cooldown = "Minimum number of bars after a signal before a new exhaustion can be armed."
const string tt_showPositions = "Draws a position tool on each signal, with entry at the signal close, stop beyond the exhaustion extreme, and three R-multiple targets."
const string tt_initialWidth = "Number of bars the position tool initially extends. Active positions continue extending with price up to the maximum width."
const string tt_maximum = "Unresolved positions continue until TP3, SL, the next reversal signal or this maximum width."
const string tt_maxPositions = "Number of position tools kept on the chart. The oldest is removed first."
const string tt_stopBuffer = "ATR distance the stop is placed beyond the exhaustion extreme."
const string tt_targets = "Take profit distances as multiples of risk (R). TP2 and TP3 are kept at least 0.5R beyond the previous target."
const string tt_showRibbon = "Toggles the accepted-value trend ribbon."
const string tt_paintBars = "Colors candles based on the current trend state."
const string tt_showSignals = "Toggles the LONG and SHORT labels on confirmed reversal signals."
const string tt_colors = "Bullish colors uptrend elements, long signals, and long targets. Bearish colors downtrend elements, short signals, and short targets."

int trendLen = input.int(34, "Trend Length", minval=10, maxval=150, group=g1, tooltip=tt_trendLen)
int atrLen = input.int(14, "ATR Length", minval=5, maxval=100, group=g1, tooltip=tt_atrLen)

float fastResponseMin = input.float(0.10, "Fast Response Min", minval=0.02, maxval=0.40, step=0.01, inline="FR", group=g1, tooltip=tt_fastResponse)
float fastResponseMax = input.float(0.38, "Max", minval=0.10, maxval=0.80, step=0.01, inline="FR", group=g1, tooltip=tt_fastResponse)

float slowResponseMin = input.float(0.025, "Slow Response Min", minval=0.005, maxval=0.20, step=0.005, inline="SR", group=g1, tooltip=tt_response)
float slowResponseMax = input.float(0.12, "Max", minval=0.03, maxval=0.40, step=0.01, inline="SR", group=g1, tooltip=tt_response)

float trendBuffer = input.float(0.18, "Trend Buffer ATR", minval=0.0, maxval=1.0, step=0.02, group=g1, tooltip=tt_trendBuffer)

float ribbonMinATR = input.float(0.05, "Minimum Ribbon ATR", minval=0.01, maxval=0.30, step=0.01, inline="RW", group=g1, tooltip=tt_ribbonWidth)
float ribbonMaxATR = input.float(0.22, "Maximum", minval=0.08, maxval=0.80, step=0.01, inline="RW", group=g1, tooltip=tt_ribbonWidth)
float ribbonSpread = input.float(0.50, "Accepted Spread", minval=0.10, maxval=2.0, step=0.05, group=g1, tooltip=tt_ribbonSpread)

int exhaustLen = input.int(8, "Exhaustion Lookback", minval=3, maxval=30, group=g2, tooltip=tt_exhaustLen)

float minStretchATR = input.float(1.40, "Minimum Stretch ATR", minval=0.50, maxval=5.0, step=0.05, group=g2, tooltip=tt_stretch)
float maxExhaustEff = input.float(0.46, "Maximum Extreme Efficiency", minval=0.10, maxval=0.90, step=0.02, group=g2, tooltip=tt_exhaust)

int volLen = input.int(24, "Volume Baseline", minval=5, maxval=100, group=g2, tooltip=tt_volLen)
float climaxVolume = input.float(1.35, "Climax Relative Volume", minval=0.75, maxval=4.0, step=0.05, group=g2, tooltip=tt_climax)

float weakClose = input.float(0.58, "Extreme Close Weakness", minval=0.50, maxval=0.90, step=0.02, group=g2, tooltip=tt_weakClose)
float minTrendEfficiency = input.float(0.28, "Minimum Trend Quality", minval=0.05, maxval=0.80, step=0.01, group=g2, tooltip=tt_trendQuality)

int confirmWindow = input.int(12, "Confirmation Window", minval=3, maxval=30, group=g3, tooltip=tt_window)
int breakBars = input.int(2, "Structure Break Bars", minval=1, maxval=6, group=g3, tooltip=tt_breakBars)

float confirmBody = input.float(1.20, "Displacement Body", minval=0.60, maxval=3.0, step=0.05, group=g3, tooltip=tt_body)
float confirmVolume = input.float(0.90, "Minimum Relative Volume", minval=0.30, maxval=3.0, step=0.05, group=g3, tooltip=tt_confirmVol)
float confirmClose = input.float(0.70, "Close Strength", minval=0.55, maxval=0.95, step=0.01, group=g3, tooltip=tt_closeStrength)

int signalCooldown = input.int(12, "Signal Cooldown", minval=0, maxval=100, group=g3, tooltip=tt_cooldown)

bool showPositions = input.bool(true, "Show Position Tools", group=g4, tooltip=tt_showPositions)

int initialWidth = input.int(30, "Initial Width", minval=10, maxval=70, group=g4, tooltip=tt_initialWidth)
int maximumWidth = input.int(120, "Maximum Width", minval=40, maxval=250, group=g4, tooltip=tt_maximum)
int maxPositions = input.int(4, "Historical Positions", minval=1, maxval=8, group=g4, tooltip=tt_maxPositions)

float stopBufferATR = input.float(0.16, "Stop Buffer ATR", minval=0.0, maxval=1.0, step=0.02, group=g4, tooltip=tt_stopBuffer)

float tp1R = input.float(1.0, "TP1", minval=0.5, maxval=5.0, step=0.25, inline="TP", group=g4, tooltip=tt_targets)
float tp2R = input.float(2.0, "TP2", minval=1.0, maxval=8.0, step=0.25, inline="TP", group=g4, tooltip=tt_targets)
float tp3R = input.float(3.0, "TP3", minval=1.5, maxval=12.0, step=0.25, inline="TP", group=g4, tooltip=tt_targets)

bool showRibbon = input.bool(true, "Show Trend Ribbon", group=g5, tooltip=tt_showRibbon)
bool paintBars = input.bool(true, "Color Candles", group=g5, tooltip=tt_paintBars)
bool showSignals = input.bool(true, "Show Reversal Signals", group=g5, tooltip=tt_showSignals)

color bullCol = input.color(BULL, "Bullish", inline="C", group=g5, tooltip=tt_colors)
color bearCol = input.color(BEAR, "Bearish", inline="C", group=g5, tooltip=tt_colors)

type TradeDraw
    box reward1
    box reward2
    box reward3
    box riskBox

    line entryLine
    line stopLine
    line tp1Line
    line tp2Line
    line tp3Line

    label entryTag
    label stopTag
    label tp1Tag
    label tp2Tag
    label tp3Tag

    int direction
    int startBar
    int initialRight
    int maximumRight

    float stopPrice
    float tp3Price

    bool active

var float fastValue = na
var float slowValue = na
var int trendState = 0

var int pendingDir = 0
var int pendingStart = na
var float pendingExtreme = na

var int lastSignalBar = na

var array<TradeDraw> trades = array.new<TradeDraw>()

float atr = ta.atr(atrLen)

float acceptedHigh = ta.highest(high, trendLen)
float acceptedLow = ta.lowest(low, trendLen)
float acceptedCenter = (acceptedHigh + acceptedLow) * 0.5

float longTravel = math.sum(math.abs(close - close[1]), trendLen)
float longMove = math.abs(close - close[trendLen])

float trendEfficiency =
     longTravel > 0
     ? longMove / longTravel
     : 0.0

float fastResponse =
     fastResponseMin +
     (fastResponseMax - fastResponseMin) * trendEfficiency

float slowResponse =
     slowResponseMin +
     (slowResponseMax - slowResponseMin) * trendEfficiency

fastValue :=
     na(fastValue[1])
     ? acceptedCenter
     : fastValue[1] + fastResponse * (acceptedCenter - fastValue[1])

slowValue :=
     na(slowValue[1])
     ? acceptedCenter
     : slowValue[1] + slowResponse * (acceptedCenter - slowValue[1])

float trendCenter = (fastValue + slowValue) * 0.5
float acceptedSpread = math.abs(fastValue - slowValue)

float rawRibbonHalf = acceptedSpread * ribbonSpread

float ribbonHalf =
     math.max(
          atr * ribbonMinATR,
          math.min(
               rawRibbonHalf,
               atr * ribbonMaxATR))

float ribbonUpper = trendCenter + ribbonHalf
float ribbonLower = trendCenter - ribbonHalf

float innerHalf = ribbonHalf * 0.48

float ribbonInnerUpper = trendCenter + innerHalf
float ribbonInnerLower = trendCenter - innerHalf

float volBase = ta.sma(volume, volLen)

float relVol =
     volBase > 0
     ? volume / volBase
     : 1.0

float body = math.abs(close - open)
float avgBody = ta.sma(body, 12)

float candleSpan = math.max(high - low, syminfo.mintick)

float closeLocation =
     math.max(
          0.0,
          math.min(
               1.0,
               (close - low) / candleSpan))

float stateBuffer = atr * trendBuffer

bool acceptBull =
     fastValue > slowValue and
     close > trendCenter + stateBuffer

bool acceptBear =
     fastValue < slowValue and
     close < trendCenter - stateBuffer

if acceptBull
    trendState := 1

else if acceptBear
    trendState := -1

color trendCol =
     trendState == 1
     ? bullCol
     : trendState == -1
     ? bearCol
     : chart.fg_color

float ribbonStrength =
     math.min(
          1.0,
          trendEfficiency * 1.5 +
          ribbonHalf / math.max(atr, syminfo.mintick))

int outerAlpha =
     int(
          math.max(
               92,
               97 - ribbonStrength * 4))

int innerAlpha =
     int(
          math.max(
               80,
               89 - ribbonStrength * 8))

pOuterUpper = plot(
     showRibbon ? ribbonUpper : na,
     "Outer Upper",
     color=color.new(trendCol, 100),
     linewidth=1)

pOuterLower = plot(
     showRibbon ? ribbonLower : na,
     "Outer Lower",
     color=color.new(trendCol, 100),
     linewidth=1)

pInnerUpper = plot(
     showRibbon ? ribbonInnerUpper : na,
     "Inner Upper",
     color=color.new(trendCol, 100),
     linewidth=1)

pInnerLower = plot(
     showRibbon ? ribbonInnerLower : na,
     "Inner Lower",
     color=color.new(trendCol, 100),
     linewidth=1)

fill(
     pOuterUpper,
     pOuterLower,
     color=showRibbon
          ? color.new(trendCol, outerAlpha)
          : na)

fill(
     pInnerUpper,
     pInnerLower,
     color=showRibbon
          ? color.new(trendCol, innerAlpha)
          : na)

float shortTravel = math.sum(math.abs(close - close[1]), exhaustLen)
float shortMove = math.abs(close - close[exhaustLen])

float shortEfficiency =
     shortTravel > 0
     ? shortMove / shortTravel
     : 0.0

bool newTrendHigh =
     high >= ta.highest(high, exhaustLen)

bool newTrendLow =
     low <= ta.lowest(low, exhaustLen)

float upperStretch =
     atr > 0
     ? (high - trendCenter) / atr
     : 0.0

float lowerStretch =
     atr > 0
     ? (trendCenter - low) / atr
     : 0.0

bool upperClimax =
     relVol >= climaxVolume and
     closeLocation <= weakClose

bool lowerClimax =
     relVol >= climaxVolume and
     closeLocation >= 1.0 - weakClose

bool shortExhaustion =
     trendState == 1 and
     trendEfficiency >= minTrendEfficiency and
     newTrendHigh and
     upperStretch >= minStretchATR and
     (shortEfficiency <= maxExhaustEff or upperClimax)

bool longExhaustion =
     trendState == -1 and
     trendEfficiency >= minTrendEfficiency and
     newTrendLow and
     lowerStretch >= minStretchATR and
     (shortEfficiency <= maxExhaustEff or lowerClimax)

bool cooldownReady =
     na(lastSignalBar) or
     bar_index - lastSignalBar >= signalCooldown

if cooldownReady
    if shortExhaustion and pendingDir != -1
        pendingDir := -1
        pendingStart := bar_index
        pendingExtreme := high

    else if longExhaustion and pendingDir != 1
        pendingDir := 1
        pendingStart := bar_index
        pendingExtreme := low

if pendingDir == -1
    pendingExtreme :=
         math.max(
              nz(pendingExtreme, high),
              high)

if pendingDir == 1
    pendingExtreme :=
         math.min(
              nz(pendingExtreme, low),
              low)

float priorBreakLow =
     ta.lowest(low, breakBars)[1]

float priorBreakHigh =
     ta.highest(high, breakBars)[1]

bool strongBear =
     close < open and
     avgBody > 0 and
     body >= avgBody * confirmBody and
     closeLocation <= 1.0 - confirmClose and
     relVol >= confirmVolume

bool strongBull =
     close > open and
     avgBody > 0 and
     body >= avgBody * confirmBody and
     closeLocation >= confirmClose and
     relVol >= confi

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