SuperTrend Finder Lines S&R WaveTrend
Похожие материалы по тегам
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «mr_mt4_indicator_supertrend_finder_lines_s&r_wavetrend_for_tradingview.pine» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Этот индикатор TradingView на Pine Script v6 объединяет несколько аналитических модулей на одном графике. Первая модуль строит линии трендов, уровни поддержки и сопротивления на основе точек разворота цены, отслеживает их нарушение и отправляет оповещения TradingView. Второй модуль — адаптивный канал на основе логарифмической регрессии, который автоматически выбирает период с наибольшей корреляцией цены и тренда, отображает канал со средней линией, заливку и информационную таблицу с оценкой силы тренда и годовым доходом. Третья часть реализует осциллятор WaveTrend с зонами перекупленности и перепроданности. Четвёртая часть — классический Supertrend на основе ATR, показывающий направление тренда, сигналы покупки и продажи, а также подсветку зон.
Индикатор отображается на графике как оверлей и в отдельном окне, поддерживает настраиваемые цвета, стили линий, прозрачность и толщину. Все компоненты имеют собственные группы настроек и независимые параметры оповещений. Таблица с метриками тренда может быть размещена в нескольких позициях на графике.
Настройки программы
| Настройка | Описание |
|---|---|
| pvtLength | Длина пивота — Количество баров для определения точек разворота (пивотов) при построении линий трендов и уровней поддержки/сопротивления. |
| pvtMarkPivots | Отмечать пивоты — Включает отображение маркеров точек разворота (высоких и низких) на графике. |
| pvtAlertsEnabled | Оповещения о пивотах включены — Включает отправку оповещений при обнаружении новых точек разворота. |
| pvtAlertrequency | Частота оповещений о пивотах — Задаёт частоту срабатывания оповещений о новых пивотах: однажды на бар, на закрытие бара или на каждом тике. |
| tlEnabled | Линии трендов включены — Включает построение линий трендов по парам точек разворота. |
| tlPointsToCheck | Точек для проверки линий трендов — Количество последних точек разворота, используемых для построения и проверки линий трендов. |
| tlMaxViolation | Максимальное нарушение линий трендов — Допустимое количество баров, в течение которых цена может нарушать линию тренда, прежде чем она будет помечена как нарушенная. |
| tlExceptBars | Исключаемые последние бары — Количество последних баров, которые не учитываются при проверке нарушений линий трендов. |
| tlShowViolated | Показывать нарушенные линии трендов — Включает отображение линий трендов, нарушенных ценой, в виде пунктирных линий. |
| tlExtension | Продление линий трендов — Направление продления линий трендов: никуда, влево, вправо или в обе стороны. |
| tlShowLabels | Показывать метки линий трендов — Включает отображение ценовых меток рядом с линиями трендов. |
| tlAlertsEnabled | Оповещения о линиях трендов включены — Включает отправку оповещений при нарушении линий трендов ценой. |
| tlAlertrequency | Частота оповещений о линиях трендов — Задаёт частоту срабатывания оповещений о нарушении линий трендов. |
| srEnabled | Уровни поддержки и сопротивления включены — Включает автоматическое построение уровней поддержки и сопротивления на основе точек разворота. |
| srPointsToCheck | Точек для проверки уровней — Количество последних точек разворота, используемых для построения уровней поддержки и сопротивления. |
| srMaxViolation | Максимальное нарушение уровней — Допустимое количество нарушений уровня поддержки или сопротивления перед тем, как он перестанет отображаться. |
| srExceptBars | Исключаемые последние бары для уровней — Количество последних баров, исключаемых из проверки нарушений уровней поддержки и сопротивления. |
| srShowLabels | Показывать метки уровней — Включает отображение текстовых меток «Support» и «Resistance» рядом с соответствующими уровнями. |
| srAlertsEnabled | Оповещения об уровнях включены — Включает отправку оповещений при нарушении уровней поддержки или сопротивления ценой. |
| srAlertrequency | Частота оповещений об уровнях — Задаёт частоту срабатывания оповещений о нарушении уровней поддержки и сопротивления. |
| stlHighColor | Цвет высоких значений — Цвет, используемый для маркировки высоких точек разворота и линий восходящего тренда. |
| stlLowColor | Цвет низких значений — Цвет, используемый для маркировки низких точек разворота и линий нисходящего тренда. |
| lineWidth | Толщина линий — Толщина линий трендов, уровней поддержки и сопротивления на графике. |
| sourceInput | Источник данных — Исходный ценовой ряд (например, close), используемый для расчётов адаптивного канала тренда. |
| periodMode | Использовать долгосрочный канал — Переключает между набором периодов для краткосрочного и долгосрочного канала адаптивной регрессии. |
| devMultiplier | Множитель отклонения — Множитель стандартного отклонения, определяющий ширину канала относительно средней линии. |
| colorInput | Цвет канала — Цвет линий и заливки канала адаптивного тренда. |
| lineStyle1 | Стиль линий канала — Стиль отображения линий канала: сплошной, пунктирный или точечный. |
| extendStyle | Стиль продления канала — Направление продления линий канала: вправо, в обе стороны, никуда или влево. |
| fillTransparency | Прозрачность заливки — Уровень прозрачности заливки между линиями канала и средней линией. |
| channelTransparency | Прозрачность линий канала — Уровень прозрачности линий канала адаптивного тренда. |
| colorInputMidline | Цвет средней линии — Цвет средней линии (базовой линии) канала тренда. |
| transpInput | Прозрачность средней линии — Уровень прозрачности средней линии канала. |
| lineWidths | Толщина средней линии — Толщина средней линии канала тренда. |
| midLineStyle | Стиль средней линии — Стиль отображения средней линии канала: сплошной, пунктирный или точечный. |
| showAutoSelectedPeriod | Показывать автоматически выбранный период — Включает отображение в таблице длины периода, автоматически выбранного индикатором. |
| showTrendStrength | Показывать силу тренда — Включает отображение оценки силы тренда в информационной таблице. |
| showPearsonInput | Показывать Pearson's R — Включает отображение коэффициента корреляции Пирсона вместо оценки силы тренда в таблице. |
| showTrendAnnualizedReturn | Показывать годовой доход тренда — Включает отображение годовой доходности тренда (CAGR) в таблице, доступно на дневных и недельных таймфреймах. |
| tablePositionInput | Положение таблицы — Позиция информационной таблицы на графике: справа снизу, слева снизу, по центру снизу и другие. |
| textSizeInput | Размер текста таблицы — Размер текста в информационной таблице: нормальный, крупный или мелкий. |
| trend_sourceInput | Источник тренда — Исходный ценовой ряд для расчётов второго экземпляра адаптивного канала тренда. |
| trend_periodMode | Использовать долгосрочный канал тренда — Переключает второй экземпляр канала между краткосрочным и долгосрочным набором периодов. |
| trend_devMultiplier | Множитель отклонения тренда — Множитель отклонения для второго экземпляра адаптивного канала тренда. |
| trend_colorInput | Цвет канала тренда — Цвет линий и заливки второго экземпляра канала тренда. |
| trend_lineStyle1 | Стиль линий канала тренда — Стиль отображения линий второго экземпляра канала: сплошной, пунктирный или точечный. |
| trend_extendStyle | Стиль продления канала тренда — Направление продления линий второго экземпляра канала. |
| trend_fillTransparency | Прозрачность заливки тренда — Уровень прозрачности заливки второго экземпляра канала. |
| trend_channelTransparency | Прозрачность линий канала тренда — Уровень прозрачности линий второго экземпляра канала тренда. |
| trend_colorInputMidline | Цвет средней линии тренда — Цвет средней линии второго экземпляра канала тренда. |
| trend_transpInput | Прозрачность средней линии тренда — Уровень прозрачности средней линии второго экземпляра канала. |
| trend_lineWidths | Толщина средней линии тренда — Толщина средней линии второго экземпляра канала тренда. |
| trend_midLineStyle | Стиль средней линии тренда — Стиль отображения средней линии второго экземпляра канала. |
| trend_showAutoSelectedPeriod | Показывать автоматически выбранный период тренда — Включает отображение автоматически выбранного периода в таблице второго экземпляра канала. |
| trend_showTrendStrength | Показывать силу тренда второго экземпляра — Включает отображение оценки силы тренда в таблице второго экземпляра канала. |
| trend_showPearsonInput | Показывать Pearson's R второго экземпляра — Включает отображение коэффициента корреляции Пирсона вместо оценки силы тренда в таблице второго канала. |
| trend_showTrendAnnualizedReturn | Показывать годовой доход тренда второго экземпляра — Включает отображение годовой доходности тренда в таблице второго экземпляра канала. |
| trend_tablePositionInput | Положение таблицы тренда — Позиция информационной таблицы второго экземпляра канала на графике. |
| trend_textSizeInput | Размер текста таблицы тренда — Размер текста в информационной таблице второго экземпляра канала. |
| n1 | Длина канала WaveTrend — Период сглаживания для расчёта канала WaveTrend осциллятора. |
| n2 | Период усреднения WaveTrend — Период экспоненциального сглаживания для расчёта сигнальной линии WaveTrend. |
| obLevel1 | Уровень перекупленности 1 WaveTrend — Первая линия зоны перекупленности осциллятора WaveTrend. |
| obLevel2 | Уровень перекупленности 2 WaveTrend — Вторая линия зоны перекупленности осциллятора WaveTrend (отображается крестиком). |
| osLevel1 | Уровень перепроданности 1 WaveTrend — Первая линия зоны перепроданности осциллятора WaveTrend. |
| osLevel2 | Уровень перепроданности 2 WaveTrend — Вторая линия зоны перепроданности осциллятора WaveTrend (отображается крестиком). |
| PeriodsS | Период ATR — Период расчёта среднего истинного диапазона (ATR) для индикатора Supertrend. |
| src | Источник Supertrend — Исходный ценовой ряд, используемый для расчёта линий Supertrend. |
| Multiplier | Множитель ATR — Множитель ATR, определяющий расстояние линий Supertrend от цены. |
| changeATR | Изменить метод расчёта ATR — Переключает между стандартным ATR и простым скользящим средним истинного диапазона для расчёта Supertrend. |
| showsignals | Показывать сигналы покупки и продажи — Включает отображение меток «Buy» и «Sell» при смене направления тренда Supertrend. |
| highlighting | Подсветка включена — Включает цветовую заливку области между ценой и линиями Supertrend, соответствующую текущему направлению тренда. |
Поиск по коду файла
indicator('SuperTrend Finder Lines S&R WaveTrend', shorttitle = 'SuperTrend Finder Lines S&R WaveTrend', overlay = false, max_bars_back = 5000, format = format.price, precision = 2, explicit_plot_zorder = true)
grpPivotPoints = 'Trend Lines, Supports and Resistances'
pvtLength = input.int(20, title = 'Pivot Length', minval = 1, group = grpPivotPoints)
pvtMarkPivots = input.bool(false, title = 'Mark Pivots', group = grpPivotPoints)
pvtAlertsEnabled = input.bool(true, title = 'Alerts Enabled', inline = 'tlAlerts', group = grpPivotPoints)
pvtAlertrequency = input.string('Once Per Bar', title = ' ・ Frequency', options = ['Once Per Bar', 'Once Per Bar Close', 'All'], inline = 'tlAlerts', group = grpPivotPoints, display = display.none)
grpTrendLines = 'Trend Lines'
tlEnabled = input.bool(true, title = 'Enabled', group = grpTrendLines)
tlPointsToCheck = input.int(3, title = 'Points to Check', minval = 2, group = grpTrendLines)
tlMaxViolation = input.int(0, title = 'Maximum Violation', minval = 0, group = grpTrendLines)
tlExceptBars = input.int(3, title = 'Excepted Last Bars', minval = 0, group = grpTrendLines)
tlShowViolated = input.bool(false, title = 'Show Violated Trend Lines', group = grpTrendLines)
tlExtension = input.string('Right', title = 'Line Extension', options = ['None', 'Left', 'Right', 'Both'], group = grpTrendLines)
tlShowLabels = input.bool(true, title = 'Show Labels', group = grpTrendLines)
tlAlertsEnabled = input.bool(true, title = 'Alerts Enabled', inline = 'tlAlerts', group = grpTrendLines)
tlAlertrequency = input.string('Once Per Bar', title = ' ・ Frequency', options = ['Once Per Bar', 'Once Per Bar Close', 'All'], inline = 'tlAlerts', group = grpTrendLines, display = display.none)
grpSupportResistance = 'Supports & Resistances'
srEnabled = input.bool(true, title = 'Enabled', group = grpSupportResistance)
srPointsToCheck = input.int(3, title = 'Points to Check', minval = 2, group = grpSupportResistance)
srMaxViolation = input.int(0, title = 'Maximum Violation Allowed', minval = 0, group = grpSupportResistance)
srExceptBars = input.int(3, title = 'Excepted Last Bars', minval = 0, group = grpSupportResistance)
srShowLabels = input.bool(true, title = 'Show Labels', group = grpSupportResistance)
srAlertsEnabled = input.bool(true, title = 'Alerts Enabled', inline = 'srAlerts', group = grpSupportResistance)
srAlertrequency = input.string('Once Per Bar', title = ' ・ Frequency', options = ['Once Per Bar', 'Once Per Bar Close', 'All'], inline = 'srAlerts', group = grpSupportResistance, display = display.none)
grpVisual = 'Style'
stlHighColor = input.color(color.blue, title = 'High Color', inline = 'colors', group = grpVisual)
stlLowColor = input.color(color.red, title = 'Low Color', inline = 'colors', group = grpVisual)
lineWidth = input.int(1, title = 'Line Width', minval = 1, group = grpVisual)
type pointPair
chart.point firstPoint
chart.point secondPoint
type trendLine
line mainLine
line extensionLine = na
label priceLabel = na
bool isViolated = false
type srLevel
box levelBox
float price
label priceLabel = na
tlExtendMode = str.lower(array.get(str.split(tlExtension, ''), 0))
tlAlertrequencyMode = switch tlAlertrequency
'Once Per Bar' => alert.freq_once_per_bar
'Once Per Bar Close' => alert.freq_once_per_bar_close
'All' => alert.freq_all
=> alert.freq_once_per_bar
srAlertrequencyMode = switch srAlertrequency
'Once Per Bar' => alert.freq_once_per_bar
'Once Per Bar Close' => alert.freq_once_per_bar_close
'All' => alert.freq_all
=> alert.freq_once_per_bar
pvtAlertrequencyMode = switch pvtAlertrequency
'Once Per Bar' => alert.freq_once_per_bar
'Once Per Bar Close' => alert.freq_once_per_bar_close
'All' => alert.freq_all
=> alert.freq_once_per_bar
var array<chart.point> highPivots = array.new<chart.point>()
var array<chart.point> lowPivots = array.new<chart.point>()
var array<trendLine> uptrends = array.new<trendLine>()
var array<trendLine> downtrends = array.new<trendLine>()
var array<srLevel> supports = array.new<srLevel>()
var array<srLevel> resistances = array.new<srLevel>()
method reversed(array<chart.point> id) =>
array<chart.point> reversedArray = array.new<chart.point>()
for [i, v] in id
reversedArray.unshift(v)
reversedArray
method getHighsAbovePrice(trendLine id, int exceptBars) =>
historyReference = bar_index - id.mainLine.get_x1()
count = 0
if exceptBars < historyReference
for i = historyReference to exceptBars by 1
if high[i] > line.get_price(id.mainLine, bar_index - i)
count := count + 1
count
count
method getLowsBelowPrice(trendLine id, int exceptBars) =>
historyReference = bar_index - id.mainLine.get_x1()
count = 0
if exceptBars < historyReference
for i = historyReference to exceptBars by 1
if low[i] < line.get_price(id.mainLine, bar_index - i)
count := count + 1
count
count
method setViolated(trendLine id, color trendColor) =>
id.isViolated := true
line.delete(id.extensionLine)
label.delete(id.priceLabel)
line.set_style(id.mainLine, line.style_dotted)
line.set_extend(id.mainLine, extend = tlExtendMode)
line.set_color(id.mainLine, tlShowViolated ? color.new(trendColor, 50) : na)
f_isHigher(chart.point firstPoint, chart.point secondPoint) =>
firstPoint.price > secondPoint.price
f_isLower(chart.point firstPoint, chart.point secondPoint) =>
firstPoint.price < secondPoint.price
f_checkSupportViolation(chart.point point, int exceptBars) =>
historyReference = bar_index - point.index
violationCount = 0
if exceptBars < historyReference
for i = historyReference to exceptBars by 1
if low[i] < point.price
violationCount := violationCount + 1
violationCount
violationCount
f_checkResistanceViolation(chart.point point, int exceptBars) =>
historyReference = bar_index - point.index
violationCount = 0
if exceptBars < historyReference
for i = historyReference to exceptBars by 1
if high[i] > point.price
violationCount := violationCount + 1
violationCount
violationCount
f_drawSupport(int index) =>
historyReference = bar_index - index
lowValue = low[historyReference]
boxColor = color.new(stlHighColor, 70)
textColor = color.new(stlHighColor, 50)
supportBox = box.new(left = index, top = math.min(open[historyReference], close[historyReference]), right = bar_index, bottom = lowValue, bgcolor = boxColor, border_color = boxColor, force_overlay = true)
supportLabel = srShowLabels ? label.new(x = bar_index - int(historyReference / 2), y = lowValue, text = 'Support : ' + str.tostring(lowValue, format.mintick), style = label.style_label_up, color = color.new(boxColor, 100), textcolor = textColor, force_overlay = true) : na
supports.push(srLevel.new(levelBox = supportBox, price = lowValue, priceLabel = supportLabel))
f_drawResistance(int index) =>
historyReference = bar_index - index
highValue = high[historyReference]
boxColor = color.new(stlLowColor, 70)
textColor = color.new(stlLowColor, 50)
resistanceBox = box.new(left = index, top = highValue, right = bar_index, bottom = math.max(open[historyReference], close[historyReference]), bgcolor = boxColor, border_color = boxColor, force_overlay = true)
resistanceLabel = srShowLabels ? label.new(x = bar_index - int(historyReference / 2), y = highValue, text = 'Resistance : ' + str.tostring(highValue, format.mintick), style = label.style_label_down, color = color.new(boxColor, 100), textcolor = textColor, force_overlay = true) : na
resistances.push(srLevel.new(levelBox = resistanceBox, price = highValue, priceLabel = resistanceLabel))
f_getAllPairCombinations(array<chart.point> srcArray) =>
int inputLength = array.size(srcArray)
array<pointPair> pairs = array.new<pointPair>()
for i = 0 to inputLength - 2 by 1
for j = i + 1 to inputLength - 1 by 1
pairs.push(pointPair.new(firstPoint = srcArray.get(i), secondPoint = srcArray.get(j)))
pairs
f_drawUptrend(chart.point start, chart.point end) =>
uExtension = tlExtendMode == 'n' ? na : line.new(start, end, color = color.new(stlHighColor, 50), extend = tlExtendMode, style = line.style_dashed, width = lineWidth, force_overlay = true)
uMain = line.new(start, end, color = stlHighColor, style = line.style_arrow_both, width = lineWidth, force_overlay = true)
uPrice = line.get_price(uMain, bar_index)
uLabel = tlShowLabels ? label.new(x = bar_index, y = uPrice, text = 'Uptrend : ' + str.tostring(uPrice, format.mintick), style = label.style_label_left, color = color.new(stlHighColor, 80), textcolor = stlHighColor, force_overlay = true) : na
uptrends.push(trendLine.new(mainLine = uMain, extensionLine = uExtension, priceLabel = uLabel))
f_drawDowntrend(chart.point start, chart.point end) =>
uExtension = tlExtendMode == 'n' ? na : line.new(start, end, color = color.new(stlLowColor, 50), extend = tlExtendMode, style = line.style_dashed, width = lineWidth, force_overlay = true)
uMain = line.new(start, end, color = stlLowColor, style = line.style_arrow_both, width = lineWidth, force_overlay = true)
uPrice = line.get_price(uMain, bar_index)
uLabel = tlShowLabels ? label.new(x = bar_index, y = uPrice, text = 'Downtrend : ' + str.tostring(uPrice, format.mintick), style = label.style_label_left, color = color.new(stlLowColor, 80), textcolor = stlLowColor, force_overlay = true) : na
downtrends.push(trendLine.new(mainLine = uMain, extensionLine = uExtension, priceLabel = uLabel))
f_clearAll() =>
for [i, v] in line.all
line.delete(v)
for [i, v] in box.all
box.delete(v)
for [i, v] in label.all
label.delete(v)
supports.clear()
resistances.clear()
uptrends.clear()
downtrends.clear()
phE = ta.pivothigh(pvtLength, pvtLength)
plE = ta.pivotlow(pvtLength, pvtLength)
if not na(phE)
highPivots.unshift(chart.point.from_index(bar_index[pvtLength], phE))
if pvtAlertsEnabled
alert(str.format('New possible resistance (high pivot) detected at {0} now.', str.tostring(phE, format.mintick)), pvtAlertrequencyMode)
if not na(plE)
lowPivots.unshift(chart.point.from_index(bar_index[pvtLength], plE))
if pvtAlertsEnabled
alert(str.format('New possible support (low pivot) detected at {0} now.', str.tostring(plE, format.mintick)), pvtAlertrequencyMode)
if barstate.islast
f_clearAll()
if tlEnabled
for [i, v] in f_getAllPairCombinations(lowPivots.slice(0, tlPointsToCheck).reversed())
if f_isLower(v.firstPoint, v.secondPoint)
f_drawUptrend(v.firstPoint, v.secondPoint)
for [i, v] in uptrends
if v.getLowsBelowPrice(exceptBars = tlExceptBars) > tlMaxViolation
v.setViolated(trendColor = stlHighColor)
for [i, v] in uptrends
trendPrice = line.get_price(v.mainLine, bar_index)
if not v.isViolated and low <= trendPrice and tlAlertsEnabled
alert(str.format('Uptrend at {0} broken with a new low price at {1} now.', str.tostring(trendPrice, format.mintick), str.tostring(low, format.mintick)), tlAlertrequencyMode)
for [i, v] in f_getAllPairCombinations(highPivots.slice(0, tlPointsToCheck).reversed())
if f_isHigher(v.firstPoint, v.secondPoint)
f_drawDowntrend(v.firstPoint, v.secondPoint)
for [i, v] in downtrends
if v.getHighsAbovePrice(exceptBars = tlExceptBars) > tlMaxViolation
v.setViolated(trendColor = stlLowColor)
for [i, v] in downtrends
trendPrice = line.get_price(v.mainLine, bar_index)
if not v.isViolated and high >= trendPrice and tlAlertsEnabled
alert(str.format('Downtrend at {0} broken with a new high price at {1} now.', str.tostring(trendPrice, format.mintick), str.tostring(high, format.mintick)), tlAlertrequencyMode)
if srEnabled
sCount = 0
lIndex = 0
rCount = 0
hIndex = 0
while sCount < srPointsToCheck
if f_isLower(lowPivots.get(lIndex), lowPivots.get(lIndex + 1))
if f_checkSupportViolation(lowPivots.get(lIndex), exceptBars = srExceptBars) <= srMaxViolation
f_drawSupport(lowPivots.get(lIndex).index)
sCount := sCount + 1
sCount
lIndex := lIndex + 1
lIndex
while rCount < srPointsToCheck
if f_isHigher(highPivots.get(hIndex), highPivots.get(hIndex + 1))
if f_checkResistanceViolation(highPivots.get(hIndex), exceptBars = srExceptBars) <= srMaxViolation
f_drawResistance(highPivots.get(hIndex).index)
rCount := rCount + 1
rCount
hIndex := hIndex + 1
hIndex
for [i, v] in supports
if low <= v.price and srAlertsEnabled
alert(str.format('Support at {0} broken by new low price at {1} now.', str.tostring(v.price, format.mintick), str.tostring(low, format.mintick)), srAlertrequencyMode)
for [i, v] in resistances
if high >= v.price and srAlertsEnabled
alert(str.format('Resistance at {0} broken by new high price at {1} now.', str.tostring(v.price, format.mintick), str.tostring(high, format.mintick)), srAlertrequencyMode)
plotshape(not na(phE) and pvtMarkPivots ? phE : na, title = 'High Pivots', style = shape.triangleup, color = stlHighColor, location = location.abovebar, size = size.tiny, offset = -pvtLength, force_overlay = true)
plotshape(not na(plE) and pvtMarkPivots ? plE : na, title = 'Low Pivots', style = shape.triangledown, color = stlLowColor, location = location.belowbar, size = size.tiny, offset = -pvtLength, force_overlay = true)
confidence(pearsonR) =>
switch
pearsonR < 0.2 => 'Extremely Weak'
pearsonR < 0.3 => 'Very Weak'
pearsonR < 0.4 => 'Weak'
pearsonR < 0.5 => 'Mostly Weak'
pearsonR < 0.6 => 'Somewhat Weak'
pearsonR < 0.7 => 'Moderately Weak'
pearsonR < 0.8 => 'Moderate'
pearsonR < 0.9 => 'Moderately Strong'
pearsonR < 0.92 => 'Mostly Strong'
pearsonR < 0.94 => 'Strong'
pearsonR < 0.96 => 'Very Strong'
pearsonR < 0.98 => 'Exceptionally Strong'
=> 'Ultra Strong'
getTablePosition(string pos) =>
switch pos
'Bottom Right' => position.bottom_right
'Bottom Center' => position.bottom_center
'Bottom Left' => position.bottom_left
'Top Right' => position.top_right
'Top Left' => position.top_left
'Top Center' => position.top_center
'Middle Right' => position.middle_right
=> position.middle_left // "Middle Left" - default
calcDev(float source, int length) =>
float logSource = math.log(source)
var int period_1 = length - 1
if barstate.islast
float sumX = 0.0
float sumXX = 0.0
float sumYX = 0.0
float sumY = 0.0
for int i = 1 to length by 1
float lSrc = logSource[i - 1]
sumX := sumX + i
sumXX := sumXX + i * i
sumYX := sumYX + i * lSrc
sumY := sumY + lSrc
sumY
float slope = nz((length * sumYX - sumX * sumY) / (length * sumXX - sumX * sumX))
float average = sumY / length
float intercept = average - slope * sumX / length + slope
float sumDev = 0.0
float sumDxx = 0.0
float sumDyy = 0.0
float sumDyx = 0.0
float regres = intercept + slope * period_1 * 0.5
float sumSlp = intercept
for int i = 0 to period_1 by 1
float lSrc = logSource[i]
float dxt = lSrc - average
float dyt = sumSlp - regres
lSrc := lSrc - sumSlp
sumSlp := sumSlp + slope
sumDxx := sumDxx + dxt * dxt
sumDyy := sumDyy + dyt * dyt
sumDyx := sumDyx + dxt * dyt
sumDev := sumDev + lSrc * lSrc
sumDev
float unStdDev = math.sqrt(sumDev / period_1) // unbiased
float divisor = sumDxx * sumDyy
float pearsonR = nz(sumDyx / math.sqrt(divisor))
[unStdDev, pearsonR, slope, intercept]
else
[na, na, na, na]
string t1 = 'In Long-Term Channel mode, if the channel is not visible, scroll back on the chart for additional historical data. To view both Short-Term and Long-Term channels simultaneously, load this indicator twice on your chart.'
string t2 = 'Displays the length of the period automatically selected by the indicator that shows the strongest trend. This period is determined by identifying the highest correlation between price movements and trend direction.'
string t3 = 'Pearson\'s R is a statistical measure that evaluates the linear relationship between price movements and trend projection. A value closer to 1 indicates a strong positive correlation, increasing confidence in the trend direction based on historical data.'
string t4 = 'Displays the annualized return (CAGR) of the trend over the auto-selected period. This feature is available only for daily (D) and weekly (W) timeframes, providing insight into the expected yearly growth rate if the trend continues.'
sourceInput = input.source(close, title = 'Source', group = ' Adaptive Trend Finder I')
string group0 = 'CHANNEL SETTINGS'
bool periodMode = input.bool(true, 'Use Long-Term Channel', group = group0, tooltip = t1)
float devMultiplier = input.float(2.0, 'Deviation Multiplier:', group = group0, step = 0.1)
color colorInput = input.color(color.gray, '', group = group0, inline = group0)
string lineStyle1 = input.string('Solid', '', group = group0, inline = group0, options = ['Solid', 'Dotted', 'Dashed'])
string extendStyle = input.string('Extend Right', '', group = group0, inline = group0, options = ['Extend Right', 'Extend Both', 'Extend None', 'Extend Left'])
int fillTransparency = input.int(93, 'Fill Transp:', group = group0, inline = 'mid', minval = 0, maxval = 100, step = 1)
int channelTransparency = input.int(40, 'Line Transp:', group = group0, inline = 'mid', minval = 0, maxval = 100, step = 1)
string group1 = 'MIDLINE SETTINGS'
color colorInputMidline = input.color(color.blue, '', group = group1, inline = group1)
int transpInput = input.int(100, 'Transp:', group = group1, inline = group1, minval = 0, maxval = 100, step = 10)
int lineWidths = input.int(1, 'Line Width:', group = group1, inline = group1)
string midLineStyle = input.string('Dashed', '', group = group1, inline = group1, options = ['Dotted', 'Solid', 'Dashed'])
string group2 = 'TABLE SETTINGS'
bool showAutoSelectedPeriod = input(true, 'Show Auto-Selected Period', group = group2, tooltip = t2)
bool showTrendStrength = input(true, 'Show Trend Strength', group = group2, inline = 'secondLine')
bool showPearsonInput = input.bool(false, 'Show Pearson\'s R', group = group2, inline = 'secondLine', tooltip = t3)
bool showTrendAnnualizedReturn = input(true, 'Show Trend Annualized Return', group = group2, tooltip = t4)
string tablePositionInput = input.string('Bottom Right', 'Table Position', options = ['Bottom Right', 'Bottom Left', 'Middle Right', 'Middle Left', 'Top Right', 'Top Left', 'Top Center', 'Bottom Center'], group = group2, inline = 'fourthLine')
string textSizeInput = input.string('Normal', 'Text Size', options = ['Normal', 'Large', 'Small'], group = group2, inline = 'fourthLine')
get_tf_multiplier() =>
var float multiplier = 1.0
if syminfo.type == 'crypto'
if timeframe.isdaily
multiplier := 365 // ~365 trading days per year
multiplier
else if timeframe.isweekly
multiplier := 52 // 52 weeks per year
multiplier
multiplier
else // Default for stocks and other asset types
if timeframe.isdaily
multiplier := 252 // ~252 trading days per year
multiplier
else if timeframe.isweekly
multiplier := 52 // 52 weeks per year
multiplier
multiplier
is_valid_timeframe() =>
timeframe.isdaily or timeframe.isweekly
var string EXTEND_STYLE = switch extendStyle
'Extend Right' => extend.right
'Extend Both' => extend.both
'Extend None' => extend.none
=> extend.left
var array<int> Periods = periodMode ? array.from(na, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1050, 1100, 1150, 1200) : array.from(na, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200)
[stdDev01, pearsonR01, slope01, intercept01] = calcDev(sourceInput, Periods.get(1))
[stdDev02, pearsonR02, slope02, intercept02] = calcDev(sourceInput, Periods.get(2))
[stdDev03, pearsonR03, slope03, intercept03] = calcDev(sourceInput, Periods.get(3))
[stdDev04, pearsonR04, slope04, intercept04] = calcDev(sourceInput, Periods.get(4))
[stdDev05, pearsonR05, slope05, intercept05] = calcDev(sourceInput, Periods.get(5))
[stdDev06, pearsonR06, slope06, intercept06] = calcDev(sourceInput, Periods.get(6))
[stdDev07, pearsonR07, slope07, intercept07] = calcDev(sourceInput, Periods.get(7))
[stdDev08, pearsonR08, slope08, intercept08] = calcDev(sourceInput, Periods.get(8))
[stdDev09, pearsonR09, slope09, intercept09] = calcDev(sourceInput, Periods.get(9))
[stdDev10, pearsonR10, slope10, intercept10] = calcDev(sourceInput, Periods.get(10))
[stdDev11, pearsonR11, slope11, intercept11] = calcDev(sourceInput, Periods.get(11))
[stdDev12, pearsonR12, slope12, intercept12] = calcDev(sourceInput, Periods.get(12))
[stdDev13, pearsonR13, slope13, intercept13] = calcDev(sourceInput, Periods.get(13))
[stdDev14, pearsonR14, slope14, intercept14] = calcDev(sourceInput, Periods.get(14))
[stdDev15, pearsonR15, slope15, intercept15] = calcDev(sourceInput, Periods.get(15))
[stdDev16, pearsonR16, slope16, intercept16] = calcDev(sourceInput, Periods.get(16))
[stdDev17, pearsonR17, slope17, intercept17] = calcDev(sourceInput, Periods.get(17))
[stdDev18, pearsonR18, slope18, intercept18] = calcDev(sourceInput, Periods.get(18))
[stdDev19, pearsonR19, slope19, intercept19] = calcDev(sourceInput, Periods.get(19))
if barstate.islast
float highestPearsonR = math.max(pearsonR01, pearsonR02, pearsonR03, pearsonR04, pearsonR05, pearsonR06, pearsonR07, pearsonR08, pearsonR09, pearsonR10, pearsonR11, pearsonR12, pearsonR13, pearsonR14, pearsonR15, pearsonR16, pearsonR17, pearsonR18, pearsonR19)
int detectedPeriod = na
float detectedSlope = na
float detectedIntrcpt = na
float detectedStdDev = na
switch highestPearsonR
pearsonR01 =>
detectedPeriod := Periods.get(1)
detectedSlope := slope01
detectedIntrcpt := intercept01
detectedStdDev := stdDev01
detectedStdDev
pearsonR02 =>
detectedPeriod := Periods.get(2)
detectedSlope := slope02
detectedIntrcpt := intercept02
detectedStdDev := stdDev02
detectedStdDev
pearsonR03 =>
detectedPeriod := Periods.get(3)
detectedSlope := slope03
detectedIntrcpt := intercept03
detectedStdDev := stdDev03
detectedStdDev
pearsonR04 =>
detectedPeriod := Periods.get(4)
detectedSlope := slope04
detectedIntrcpt := intercept04
detectedStdDev := stdDev04
detectedStdDev
pearsonR05 =>
detectedPeriod := Periods.get(5)
detectedSlope := slope05
detectedIntrcpt := intercept05
detectedStdDev := stdDev05
detectedStdDev
pearsonR06 =>
detectedPeriod := Periods.get(6)
detectedSlope := slope06
detectedIntrcpt := intercept06
detectedStdDev := stdDev06
detectedStdDev
pearsonR07 =>
detectedPeriod := Periods.get(7)
detectedSlope := slope07
detectedIntrcpt := intercept07
detectedStdDev := stdDev07
detectedStdDev
pearsonR08 =>
detectedPeriod := Periods.get(8)
detectedSlope := slope08
detectedIntrcpt := intercept08
detectedStdDev := stdDev08
detectedStdDev
pearsonR09 =>
detectedPeriod := Periods.get(9)
detectedSlope := slope09
detectedIntrcpt := intercept09
detectedStdDev := stdDev09
detectedStdDev
pearsonR10 =>
detectedPeriod := Periods.get(10)
detectedSlope := slope10
detectedIntrcpt := intercept10
detectedStdDev := stdDev10
detectedStdDev
pearsonR11 =>
detectedPeriod := Periods.get(11)
detectedSlope := slope11
detectedIntrcpt := intercept11
detectedStdDev := stdDev11
detectedStdDev
pearsonR12 =>
detectedPeriod := Periods.get(12)
detectedSlope := slope12
detectedIntrcpt := intercept12
detectedStdDev := stdDev12
detectedStdDev
pearsonR13 =>
detectedPeriod := Periods.get(13)
detectedSlope := slope13
detectedIntrcpt := intercept13
detectedStdDev := stdDev13
detectedStdDev
pearsonR14 =>
detectedPeriod := Periods.get(14)
detectedSlope := slope14
detectedIntrcpt := intercept14
detectedStdDev := stdDev14
detectedStdDev
pearsonR15 =>
detectedPeriod := Periods.get(15)
detectedSlope := slope15
detectedIntrcpt := intercept15
detectedStdDev := stdDev15
detectedStdDev
pearsonR16 =>
detectedPeriod := Periods.get(16)
detectedSlope := slope16
detectedIntrcpt := intercept16
detectedStdDev := stdDev16
detectedStdDev
pearsonR17 =>
detectedPeriod := Periods.get(17)
detectedSlope := slope17
detectedIntrcpt := intercept17
detectedStdDev := stdDev17
detectedStdDev
pearsonR18 =>
detectedPeriod := Periods.get(18)
detectedSlope := slope18
detectedIntrcpt := intercept18
detectedStdDev := stdDev18
detectedStdDev
=> // pearsonR19
detectedPeriod := Periods.get(19)
detectedSlope := slope19
detectedIntrcpt := intercept19
detectedStdDev := stdDev19
detectedStdDev
var line upperLine = na
var linefill upperFill = na
var line baseLine = na
var line lowerLine = na
var linefill lowerFill = na
float startPrice = math.exp(detectedIntrcpt + detectedSlope * (detectedPeriod - 1))
float endPrice = math.exp(detectedIntrcpt)
int startAtBar = bar_index - detectedPeriod + 1
var color ChannelColor = color.new(colorInput, channelTransparency)
if na(baseLine)
baseLine := line.new(startAtBar, startPrice, bar_index, endPrice, width = lineWidths, extend = EXTEND_STYLE, color = color.new(colorInputMidline, transpInput), style = midLineStyle == 'Dotted' ? line.style_dotted : midLineStyle == 'Dashed' ? line.style_dashed : line.style_solid, force_overlay = true)
baseLine
else
line.set_xy1(baseLine, startAtBar, startPrice)
line.set_xy2(baseLine, bar_index, endPrice)
float upperStartPrice = startPrice * math.exp(devMultiplier * detectedStdDev)
float upperEndPrice = endPrice * math.exp(devMultiplier * detectedStdDev)
if na(upperLine)
upperLine := line.new(startAtBar, upperStartPrice, bar_index, upperEndPrice, width = 1, extend = EXTEND_STYLE, color = ChannelColor, style = lineStyle1 == 'Dotted' ? line.style_dotted : lineStyle1 == 'Dashed' ? line.style_dashed : line.style_solid, force_overlay = true)
upperLine
else
line.set_xy1(upperLine, startAtBar, upperStartPrice)
line.set_xy2(upperLine, bar_index, upperEndPrice)
Показано первые 50% кода (символов: 44594)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.