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

Trend Trader

trend trader m1.pine
Вы автор или правообладатель?

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

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

О программе

«Trend Trader» — индикатор для TradingView, написанный на Pine Script v6. Отображает сигналы покупки и продажи непосредственно на графике цены.

Индикатор рассчитывает несколько скользящих средних, индикатор Supertrend, определяет точки разворота и текущие тренды (бычий, медвежий, нейтральный) на двух уровнях — основном и промежуточном. На основании этих данных формируются визуальные сигналы в виде треугольников BUY и SELL.

Встроенная информационная панель показывает последний сигнал, точку входа, стоп-лосс и пять уровней тейк-профита на основе коэффициентов Фибоначчи. Поддерживаются пользовательские оповещения TradingView для событий BUY и SELL. Набор настраиваемых параметров позволяет гибко адаптировать логику под нужды трейдера.

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

НастройкаОписание
alpha_param Alpha Parameter — Задаёт направление торговли: только длинные, только короткие или оба направления.
beta_switch Beta Switch — Включает альтернативный режим формирования сигналов.
gamma_timing Gamma Timing — Определяет тип входа: на подтверждённом тренде или на продолжении тренда.
delta_sync Delta Sync — Определяет, требуется ли совпадение основного тренда для генерации сигналов.
epsilon_l Epsilon L — Задаёт условие выхода из длинной позиции.
epsilon_s Epsilon S — Задаёт условие выхода из короткой позиции.
zeta_time Zeta Time — Время ежедневного закрытия позиции в формате ЧЧММ.
eta_mode Eta Mode — Выбирает режим входа: мгновенный или отложенный.
theta_type Theta Type — Выбирает тип скользящей средней (SMA, EMA, WMA, RMA, HMA, VWMA, SWMA, ALMA, LSMA).
iota_src Iota Source — Выбирает источниковую цену для расчёта скользящих средних.
kappa_mode Kappa Mode — Задаёт режим сброса скользящих средних: непрерывный или ежедневный.
lambda_1 Lambda 1 — Длина первой скользящей средней.
lambda_2 Lambda 2 — Длина второй скользящей средней.
lambda_3 Lambda 3 — Длина третьей скользящей средней.
mu_span Mu Span — Период для индикатора Supertrend.
mu_mult Mu Mult — Множитель для индикатора Supertrend.
nu_mode Nu Mode — Задаёт режим сброса Supertrend: непрерывный или ежедневный.
xi_mode Xi Mode — Задаёт общий режим сброса: непрерывный или ежедневный.
omicron_logic Omicron Logic — Выбирает метод обнаружения точек разворота.
pi_lookback Pi Lookback — Глубина поиска точек разворота (pivot).
rho_floor Rho Floor — Множитель адаптивного порога для метода разворота.
sigma_min Sigma Min — Минимальная длина разворота в единицах ATR.
tau_mode Tau Mode — Задаёт режим сброса цвета свечей: непрерывный или ежедневный.
upsilon_bars Upsilon Bars — Минимальное количество баров для расчёта сессионного ATR.
phi_span Phi Span — Период для расчёта непрерывного ATR.
chi_mult Chi Mult — Множитель для расчёта порога на основе ATR при проверке скользящих средних.
Получить полный код

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

indicator('Trend Trader', shorttitle='Trend Trader', overlay=true, max_labels_count=500)

alpha_param = input.string("Omni", "Alpha Parameter", options=["Zenith", "Nadir", "Omni"], tooltip="Directional Bias")
tradeDirection = alpha_param == "Zenith" ? "Long Only" : alpha_param == "Nadir" ? "Short Only" : "Both"

beta_switch = input.bool(false, "Beta Switch", tooltip="Alternative Execution Logic")
enableOptionBuying = beta_switch

gamma_timing = input.string("Phase 1", "Gamma Timing", options=["Phase 1", "Phase 2"])
entryTiming = gamma_timing == "Phase 1" ? "Confirmed Trend" : "Trend Continuation"

delta_sync = input.bool(true, "Delta Sync")
requireMajorAlignment = delta_sync

epsilon_l = input.string("State A", "Epsilon L", options=["State A", "State B"])
exitLongCondition = epsilon_l == "State A" ? "Neutral OR Downtrend" : "Downtrend Only"

epsilon_s = input.string("State A", "Epsilon S", options=["State A", "State B"])
exitShortCondition = epsilon_s == "State A" ? "Neutral OR Uptrend" : "Uptrend Only"

zeta_time = input.string("1500", "Zeta Time")
dailyCloseTime = zeta_time

eta_mode = input.string("Type X", "Eta Mode", options=["Type X", "Type Y"])
entryMode = eta_mode == "Type X" ? "Delayed Entry" : "Immediate Entry"

theta_type = input.string("Form 2", "Theta Type", options=["Form 1","Form 2","Form 3","Form 4","Form 5","Form 6","Form 7","Form 8","Form 9"])
maType = theta_type == "Form 1" ? "SMA" : theta_type == "Form 2" ? "EMA" : theta_type == "Form 3" ? "WMA" : theta_type == "Form 4" ? "RMA" : theta_type == "Form 5" ? "HMA" : theta_type == "Form 6" ? "VWMA" : theta_type == "Form 7" ? "SWMA" : theta_type == "Form 8" ? "ALMA" : "LSMA"

iota_src = input.string("Origin 1", "Iota Source", options=["Origin 1", "Origin 2", "Origin 3", "Origin 4", "Origin 5", "Origin 6", "Origin 7"])
maSource = iota_src == "Origin 1" ? "Close" : iota_src == "Origin 2" ? "Open" : iota_src == "Origin 3" ? "High" : iota_src == "Origin 4" ? "Low" : iota_src == "Origin 5" ? "HL2" : iota_src == "Origin 6" ? "HLC3" : "OHLC4"

kappa_mode = input.string("Cycle A", "Kappa Mode", options=["Cycle A", "Cycle B"])
maResetMode = kappa_mode == "Cycle A" ? "Continuous" : "Daily Reset"

lambda_1 = input.int(21, "Lambda 1")
ma1Length = lambda_1
lambda_2 = input.int(55, "Lambda 2")
ma2Length = lambda_2
lambda_3 = input.int(89, "Lambda 3")
ma3Length = lambda_3

mu_span = input.int(10, "Mu Span")
superPeriod = mu_span
mu_mult = input.float(3.0, "Mu Mult")
factor = mu_mult

nu_mode = input.string("Cycle A", "Nu Mode", options=["Cycle A", "Cycle B"])
stResetMode = nu_mode == "Cycle A" ? "Continuous" : "Daily Reset"

xi_mode = input.string("Cycle A", "Xi Mode", options=["Cycle A", "Cycle B"])
resetMode = xi_mode == "Cycle A" ? "Continuous" : "Daily Reset"

omicron_logic = input.string("Logic 1", "Omicron Logic", options=["Logic 1", "Logic 2", "Logic 3", "Logic 4"])
swingMethod = omicron_logic == "Logic 1" ? "Two-Rejection" : omicron_logic == "Logic 2" ? "Standard Pivot" : omicron_logic == "Logic 3" ? "One-Rejection ATR" : "Adaptive Session"

pi_lookback = input.int(2, "Pi Lookback")
pivotLookback = pi_lookback

rho_floor = input.float(0.3, "Rho Floor")
adaptiveFloorMult = rho_floor

sigma_min = input.float(1.0, "Sigma Min")
minSwingLengthATR = sigma_min

tau_mode = input.string("Cycle A", "Tau Mode", options=["Cycle A", "Cycle B"])
candleColorMode = tau_mode == "Cycle A" ? "Continuous" : "Daily Reset"

upsilon_bars = input.int(2, "Upsilon Bars")
minBars = upsilon_bars

phi_span = input.int(14, "Phi Span")
continuousATRPeriod = phi_span

chi_mult = input.float(0.5, "Chi Mult")
atrMultiplier = chi_mult

isDailyReset = resetMode == "Daily Reset"
isCandleColorDailyReset = candleColorMode == "Daily Reset" and timeframe.multiplier <= 5 and not timeframe.isdaily and not timeframe.isweekly and not timeframe.ismonthly
isNewDay = ta.change(time("D")) != 0
continuousATR = ta.atr(continuousATRPeriod)
atrForLabels = ta.atr(14)

parseTime(timeStr) =>
    timeInt = str.tonumber(timeStr)
    [math.floor(timeInt / 100), timeInt % 100]
[closeHour, closeMinute] = parseTime(dailyCloseTime)

getSource(sourceType) =>
    switch sourceType
        "Close" => close
        "Open" => open
        "High" => high
        "Low" => low
        "HL2" => hl2
        "HLC3" => hlc3
        "OHLC4" => ohlc4
        => close
maSourceValue = getSource(maSource)

getMA(length, type, src) =>
    if maResetMode == "Daily Reset" and timeframe.isintraday
        sessionBars = ta.barssince(isNewDay) + 1
        if type == "SMA"
            var float sessionSum = 0.0
            var int sessionCount = 0
            if isNewDay
                sessionSum := src, sessionCount := 1
            else
                sessionSum += src, sessionCount += 1
            sessionCount <= length ? sessionSum / sessionCount : ta.sma(src, length)
        else if type == "EMA"
            var float sessionEMA = na
            alpha = 2.0 / (math.min(length, sessionBars) + 1.0)
            sessionEMA := isNewDay ? src : na(sessionEMA) ? src : alpha * src + (1 - alpha) * sessionEMA
            sessionEMA
        else
            math.sum(src, math.min(length, sessionBars)) / math.min(length, sessionBars)
    else
        switch type
            "SMA" => ta.sma(src, length)
            "EMA" => ta.ema(src, length)
            "WMA" => ta.wma(src, length)
            "RMA" => ta.rma(src, length)
            "HMA" => ta.hma(src, length)
            "VWMA" => ta.vwma(src, length)
            "SWMA" => ta.swma(src)
            "ALMA" => ta.alma(src, length, 0.85, 6)
            "LSMA" => ta.linreg(src, length, 0)
            => ta.sma(src, length)

ma1Value = getMA(ma1Length, maType, maSourceValue)
ma2Value = getMA(ma2Length, maType, maSourceValue)
ma3Value = getMA(ma3Length, maType, maSourceValue)

stUseDailyReset = stResetMode == "Daily Reset" and timeframe.isintraday
[stBuiltin, stDirectionBuiltin] = ta.supertrend(factor, superPeriod)
var float st_atr_sum = 0.0
var int st_atr_count = 0
var float st_prev_close = na
var float st_upper_band = na
var float st_lower_band = na
var float st_supertrend = na
var int st_direction = 1

if isNewDay and stUseDailyReset
    st_atr_sum := 0.0, st_atr_count := 0, st_prev_close := na, st_upper_band := na, st_lower_band := na, st_supertrend := na, st_direction := 1
if stUseDailyReset
    st_tr = na(st_prev_close) ? high - low : math.max(high - low, math.max(math.abs(high - st_prev_close), math.abs(low - st_prev_close)))
    st_atr_sum += st_tr, st_atr_count += 1
    if st_atr_count >= superPeriod
        st_atr = st_atr_sum / st_atr_count
        basic_upper = hl2 + factor * st_atr
        basic_lower = hl2 - factor * st_atr
        prev_upper = na(st_upper_band) ? basic_upper : st_upper_band
        prev_lower = na(st_lower_band) ? basic_lower : st_lower_band
        st_upper_band := basic_upper < prev_upper or close[1] > prev_upper ? basic_upper : prev_upper
        st_lower_band := basic_lower > prev_lower or close[1] < prev_lower ? basic_lower : prev_lower
        st_direction := na(st_supertrend) ? (close > st_upper_band ? -1 : 1) : (st_supertrend == prev_upper ? (close > st_upper_band ? -1 : 1) : (close < st_lower_band ? 1 : -1))
        st_supertrend := st_direction == -1 ? st_lower_band : st_upper_band
    st_prev_close := close
resolvedST = stUseDailyReset ? st_supertrend : stBuiltin
resolvedDirection = stUseDailyReset ? float(st_direction) : float(stDirectionBuiltin)

var float sessionTRsum = 0.0
var int sessionTRcount = 0
var int barsInSession = 0
var bool closedAtTimeToday = false
if isNewDay
    sessionTRsum := 0.0, sessionTRcount := 0, barsInSession := 0, closedAtTimeToday := false
else
    barsInSession += 1
sessionTRsum += math.max(high - low, math.max(math.abs(high - close[1]), math.abs(low - close[1])))
sessionTRcount += 1
sessionATR = isCandleColorDailyReset and sessionTRcount >= minBars ? sessionTRsum / sessionTRcount : na

pivotHigh_global = ta.pivothigh(high, pivotLookback, pivotLookback)
pivotLow_global = ta.pivotlow(low, pivotLookback, pivotLookback)

var string trendState = "neutral"
var string minorTrendState = "neutral"
var string latestMinorHighType = na
var string latestMinorLowType = na
var float recentMajorHigh = na
var float recentMajorLow = na
var float lastHH_or_H = na
var float lastLL_or_L = na
var float lastLH = na
var float lastHL = na
var int lastHH_or_H_Bar = na
var int lastLL_or_L_Bar = na
var int lastLH_Bar = na
var int lastHL_Bar = na
var string lastPivot = na
var float hh = na
var int hhBar = na
var float ll = na
var int llBar = na
var float prevHigh = na
var float prevLow = na
var bool firstHighRejection = false
var float rejectionReferenceHigh = na
var float firstHighRejectionLow = na
var bool firstLowRejection = false
var float rejectionReferenceLow = na
var float firstLowRejectionHigh = na
var int completedBullLegs = 0
var int completedBearLegs = 0
var bool forcedSwingProcessed = false
var array<float> bullLegPointMoves = array.new<float>()
var array<float> bearLegPointMoves = array.new<float>()
var string lastMajorPivot = na
var float latestMinorHigh = na
var float latestMinorLow = na
var float highestSinceMajorLow = na
var float lowestSinceMajorHigh = na
var bool bullishSetupActive = false
var bool bearishSetupActive = false
var bool validSwingHighExists = false
var bool validSwingLowExists = false
var bool sufficientRetracementForHigh = false
var bool sufficientRetracementForLow = false

if isNewDay and isDailyReset and timeframe.in_seconds() <= 300
    lastPivot := na, hh := na, hhBar := na, ll := na, llBar := na, prevHigh := na, prevLow := na, firstHighRejection := false, firstLowRejection := false
    minorTrendState := "neutral", latestMinorHighType := na, latestMinorLowType := na, lastHH_or_H := na, lastLL_or_L := na, lastLH := na, lastHL := na
    lastHH_or_H_Bar := na, lastLL_or_L_Bar := na, lastLH_Bar := na, lastHL_Bar := na, lastMajorPivot := na, latestMinorHigh := na, latestMinorLow := na
    highestSinceMajorLow := na, lowestSinceMajorHigh := na, trendState := "neutral", recentMajorHigh := na, recentMajorLow := na, completedBullLegs := 0, completedBearLegs := 0
    forcedSwingProcessed := false, sufficientRetracementForHigh := false, sufficientRetracementForLow := false
    bullishSetupActive := false, bearishSetupActive := false, validSwingHighExists := false, validSwingLowExists := false
    array.clear(bullLegPointMoves), array.clear(bearLegPointMoves)

bool inHighLeg = lastPivot == 'low' or na(lastPivot)
bool inLowLeg = lastPivot == 'high' or na(lastPivot)
if inHighLeg and (na(hh) or high > hh)
    hh := high, hhBar := bar_index
if inLowLeg and (na(ll) or low < ll)
    ll := low, llBar := bar_index
if (lastMajorPivot == 'low' or na(lastMajorPivot)) and (na(highestSinceMajorLow) or high > highestSinceMajorLow)
    highestSinceMajorLow := high
if (lastMajorPivot == 'high' or na(lastMajorPivot)) and (na(lowestSinceMajorHigh) or low < lowestSinceMajorHigh)
    lowestSinceMajorHigh := low
int hhOffset = na(hhBar) ? na : bar_index - hhBar
int llOffset = na(llBar) ? na : bar_index - llBar

bool isSwingHigh = false
bool isSwingLow = false
if swingMethod == "Two-Rejection"
    if not na(hhOffset) and hhOffset >= 0 and lastPivot != 'high' and (not isDailyReset or barsInSession > 0)
        if close < low[1] and not firstHighRejection
            firstHighRejection := true, firstHighRejectionLow := low, rejectionReferenceHigh := hh
        else if firstHighRejection and close < low[1] and close < firstHighRejectionLow
            if high <= rejectionReferenceHigh
                isSwingHigh := true, firstHighRejection := false
            else
                firstHighRejection := true, firstHighRejectionLow := low, rejectionReferenceHigh := hh
    if not na(llOffset) and llOffset >= 0 and lastPivot != 'low' and (not isDailyReset or barsInSession > 0)
        if close > high[1] and not firstLowRejection
            firstLowRejection := true, firstLowRejectionHigh := high, rejectionReferenceLow := ll
        else if firstLowRejection and close > high[1] and close > firstLowRejectionHigh
            if low >= rejectionReferenceLow
                isSwingLow := true, firstLowRejection := false
            else
                firstLowRejection := true, firstLowRejectionHigh := high, rejectionReferenceLow := ll
    if firstHighRejection and not na(rejectionReferenceHigh) and high > rejectionReferenceHigh
        firstHighRejection := false
    if firstLowRejection and not na(rejectionReferenceLow) and low < rejectionReferenceLow
        firstLowRejection := false
else if swingMethod == "Standard Pivot"
    if not isDailyReset or barsInSession > pivotLookback
        if not na(pivotHigh_global) and lastPivot != 'high'
            isSwingHigh := true, hh := pivotHigh_global, hhBar := bar_index - pivotLookback
        if not na(pivotLow_global) and lastPivot != 'low'
            isSwingLow := true, ll := pivotLow_global, llBar := bar_index - pivotLookback
else if swingMethod == "One-Rejection ATR" or swingMethod == "Adaptive Session"
    swingFilterATR = not na(sessionATR) ? math.max(sessionATR, continuousATR) : continuousATR
    if (not isDailyReset or barsInSession > 0) and not na(swingFilterATR)
        requiredATR = swingFilterATR * minSwingLengthATR
        float requiredAvgSwing = na
        if swingMethod == "Adaptive Session" and (completedBullLegs + completedBearLegs) >= 5
            avgBull = array.size(bullLegPointMoves) > 0 ? array.avg(bullLegPointMoves) : na
            avgBear = array.size(bearLegPointMoves) > 0 ? array.avg(bearLegPointMoves) : na
            avgSwingPts = not na(avgBull) and not na(avgBear) ? (avgBull + avgBear) / 2 : not na(avgBull) ? avgBull : avgBear
            requiredAvgSwing := not na(avgSwingPts) ? avgSwingPts * adaptiveFloorMult : na
        if not na(hhOffset) and hhOffset > 0 and lastPivot != 'high'
            retH = hh - low
            sufficientRetracementForHigh := retH >= requiredATR and (na(requiredAvgSwing) ? true : retH >= requiredAvgSwing)
            if sufficientRetracementForHigh and close < low[1] and high <= hh
                isSwingHigh := true, sufficientRetracementForHigh := false
        if not na(llOffset) and llOffset > 0 and lastPivot != 'low'
            retL = high - ll
            sufficientRetracementForLow := retL >= requiredATR and (na(requiredAvgSwing) ? true : retL >= requiredAvgSwing)
            if sufficientRetracementForLow and close > high[1] and low >= ll
                isSwingLow := true, sufficientRetracementForLow := false

if lastPivot == 'low' and not na(latestMinorLow) and close < latestMinorLow
    firstHighRejection := false, sufficientRetracementForHigh := false, isSwingHigh := false
    array.push(bullLegPointMoves, math.abs(hh - latestMinorLow)), completedBullLegs += 1
    lastHH_or_H := hh, lastHH_or_H_Bar := hhBar, latestMinorHighType := na(prevHigh) ? 'h' : hh > prevHigh ? 'hh' : 'lh', prevHigh := hh
    lastPivot := 'high', latestMinorHigh := hh, forcedSwingProcessed := true
if lastPivot == 'high' and not na(latestMinorHigh) and close > latestMinorHigh
    firstLowRejection := false, sufficientR

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

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

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

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

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

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

Стоимость полного кода
2 472₽ ≈ $30.22