AD

User info

Welcome, Guest! Please login or register.


You are here » AD » WOW.that's literally me » #8 investing.com


#8 investing.com

Posts 91 to 120 of 124

91

//@version=3
study(title="Donchain Keltner Channels", shorttitle="DKC", overlay=true)
length = input(20, minval=1)
lower = lowest(length)
upper = highest(length)
basis = avg(upper, lower)
l = plot(lower, color=blue, title="Lower DC")
u = plot(upper, color=blue, title="Upper DC")
plot(basis, color=orange, title="Basis DC")
fill(u, l, color=blue)

useTrueRange = input(true)
length2 = input(20, minval=1)
mult = input(1.0)
src = input(close, title="Source")

ma = ema(src, length2)
range = useTrueRange ? tr : high - low
rangema = ema(range, length2)
upper2 = ma + rangema * mult
lower2 = ma - rangema * mult
c = blue
u2 = plot(upper2, color=c, title="Upper KC")
plot(ma, color=c, title="Basis KC")
l2 = plot(lower2, color=c, title="Lower KC")
fill(u2, l2, color=c)

0

92

Это индикатор для торговой платформы МТ4
https://forexsystemru.com/threads/arkhi … st-1994738

//+------------------------------------------------------------------+
//|                       RSI_Bands_MTF_Triple.mq4                   |
//+------------------------------------------------------------------+
#property copyright   "Based on LazyBear's RSI Bands"
#property description "Triple MTF RSI Bands by DemaN_FxMen"
#property version     "2.0"

#property indicator_chart_window
#property indicator_buffers 15
#property indicator_color1  clrRed
#property indicator_color2  clrGreen
#property indicator_color3  clrNavy
#property indicator_color4  clrGold
#property indicator_color5  clrGold
#property indicator_color6  clrRed
#property indicator_color7  clrGreen
#property indicator_color8  clrNavy
#property indicator_color9  clrGold
#property indicator_color10 clrGold
#property indicator_color11 clrRed
#property indicator_color12 clrGreen
#property indicator_color13 clrNavy
#property indicator_color14 clrGold
#property indicator_color15 clrGold
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  1
#property indicator_width4  1
#property indicator_width5  1
#property indicator_width6  2
#property indicator_width7  2
#property indicator_width8  1
#property indicator_width9  1
#property indicator_width10 1
#property indicator_width11 2
#property indicator_width12 2
#property indicator_width13 1
#property indicator_width14 1
#property indicator_width15 1
#property indicator_style4 DRAW_ARROW
#property indicator_style5 DRAW_ARROW
#property indicator_style9 DRAW_ARROW
#property indicator_style10 DRAW_ARROW
#property indicator_style14 DRAW_ARROW
#property indicator_style15 DRAW_ARROW
#property indicator_type4  DRAW_ARROW
#property indicator_type5  DRAW_ARROW
#property indicator_type9  DRAW_ARROW
#property indicator_type10 DRAW_ARROW
#property indicator_type14 DRAW_ARROW
#property indicator_type15 DRAW_ARROW

//--- входные параметры для индикатора 1
input string SECTION1 = "========= Индикатор 1 =========";
input ENUM_TIMEFRAMES TimeFrame1 = PERIOD_CURRENT;
input int  RSILength1 = 14;
input int  OB1 = 70;
input int  OS1 = 30;
input bool ShowIndicator1 = true;
input bool ShowArrows1    = true;

//--- входные параметры для индикатора 2
input string SECTION2 = "========= Индикатор 2 =========";
input ENUM_TIMEFRAMES TimeFrame2 = PERIOD_CURRENT;
input int  RSILength2 = 20;
input int  OB2 = 65;
input int  OS2 = 35;
input bool ShowIndicator2 = true;
input bool ShowArrows2    = true;

//--- входные параметры для индикатора 3
input string SECTION3 = "========= Индикатор 3 =========";
input ENUM_TIMEFRAMES TimeFrame3 = PERIOD_CURRENT;
input int  RSILength3 = 10;
input int  OB3 = 75;
input int  OS3 = 25;
input bool ShowIndicator3 = true;
input bool ShowArrows3    = true;

//--- буферы отображения для индикатора 1
double ubBuffer1[];
double lbBuffer1[];
double midBuffer1[];
double buyArrow1[];
double sellArrow1[];

//--- буферы отображения для индикатора 2
double ubBuffer2[];
double lbBuffer2[];
double midBuffer2[];
double buyArrow2[];
double sellArrow2[];

//--- буферы отображения для индикатора 3
double ubBuffer3[];
double lbBuffer3[];
double midBuffer3[];
double buyArrow3[];
double sellArrow3[];

//--- глобальные массивы для расчетов
double aucArray[], adcArray[], upArray[], downArray[];
double closeArray[];

//+------------------------------------------------------------------+
int OnInit()
{
   //--- инициализация буферов индикатора 1
   SetIndexBuffer(0, ubBuffer1);
   SetIndexLabel(0, "Resistance 1");
   SetIndexBuffer(1, lbBuffer1);
   SetIndexLabel(1, "Support 1");
   SetIndexBuffer(2, midBuffer1);
   SetIndexLabel(2, "Midline 1");
   SetIndexBuffer(3, buyArrow1);
   SetIndexLabel(3, "Buy Signal 1");
   SetIndexArrow(3, 233);
   SetIndexBuffer(4, sellArrow1);
   SetIndexLabel(4, "Sell Signal 1");
   SetIndexArrow(4, 234);
   
   //--- инициализация буферов индикатора 2
   SetIndexBuffer(5, ubBuffer2);
   SetIndexLabel(5, "Resistance 2");
   SetIndexBuffer(6, lbBuffer2);
   SetIndexLabel(6, "Support 2");
   SetIndexBuffer(7, midBuffer2);
   SetIndexLabel(7, "Midline 2");
   SetIndexBuffer(8, buyArrow2);
   SetIndexLabel(8, "Buy Signal 2");
   SetIndexArrow(8, 233);
   SetIndexBuffer(9, sellArrow2);
   SetIndexLabel(9, "Sell Signal 2");
   SetIndexArrow(9, 234);
   
   //--- инициализация буферов индикатора 3
   SetIndexBuffer(10, ubBuffer3);
   SetIndexLabel(10, "Resistance 3");
   SetIndexBuffer(11, lbBuffer3);
   SetIndexLabel(11, "Support 3");
   SetIndexBuffer(12, midBuffer3);
   SetIndexLabel(12, "Midline 3");
   SetIndexBuffer(13, buyArrow3);
   SetIndexLabel(13, "Buy Signal 3");
   SetIndexArrow(13, 233);
   SetIndexBuffer(14, sellArrow3);
   SetIndexLabel(14, "Sell Signal 3");
   SetIndexArrow(14, 234);
   
   //--- установка стилей отрисовки
   ArraySetAsSeries(ubBuffer1, true);
   ArraySetAsSeries(lbBuffer1, true);
   ArraySetAsSeries(midBuffer1, true);
   ArraySetAsSeries(buyArrow1, true);
   ArraySetAsSeries(sellArrow1, true);
   ArraySetAsSeries(ubBuffer2, true);
   ArraySetAsSeries(lbBuffer2, true);
   ArraySetAsSeries(midBuffer2, true);
   ArraySetAsSeries(buyArrow2, true);
   ArraySetAsSeries(sellArrow2, true);
   ArraySetAsSeries(ubBuffer3, true);
   ArraySetAsSeries(lbBuffer3, true);
   ArraySetAsSeries(midBuffer3, true);
   ArraySetAsSeries(buyArrow3, true);
   ArraySetAsSeries(sellArrow3, true);
   
   ArraySetAsSeries(aucArray, true);
   ArraySetAsSeries(adcArray, true);
   ArraySetAsSeries(upArray, true);
   ArraySetAsSeries(downArray, true);
   ArraySetAsSeries(closeArray, true);

   Comment("Triple MTF RSI Bands © 2025, DemaN_FxMen");
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Функция расчета полос RSI для конкретных параметров              |
//+------------------------------------------------------------------+
void CalculateRSIBands(int length, int ob, int os, ENUM_TIMEFRAMES tf,
                      double &ubBuffer[], double &lbBuffer[], double &midBuffer[],
                      double &buyArrow[], double &sellArrow[], bool showIndicator, bool showArrows)
{
   if(!showIndicator) return;
   
   int rates_total = Bars;
   if(rates_total < length + 10) return;
   
   int ep = 2 * length - 1;
   int start = rates_total - length - 10;
   if(start < 1) start = 1;
   
   //--- подготовка массивов для расчета
   ArrayResize(upArray, rates_total);
   ArrayResize(downArray, rates_total);
   ArrayResize(aucArray, rates_total);
   ArrayResize(adcArray, rates_total);
   ArrayResize(closeArray, rates_total);
   
   //--- копируем данные с нужного таймфрейма
   CopyClose(_Symbol, tf, 0, rates_total, closeArray);
   
   //--- Расчёт дельты
   for(int i = start; i >= 1; i--)
   {
      double change = closeArray[i] - closeArray[i + 1];
      upArray[i] = (change > 0) ? change : 0;
      downArray[i] = (change < 0) ? -change : 0;
   }
   
   //--- Основной цикл расчёта
   for(int j = rates_total - 2; j >= 1; j--)
   {
      aucArray[j] = iMAOnArray(upArray, rates_total, ep, 0, MODE_EMA, j);
      adcArray[j] = iMAOnArray(downArray, rates_total, ep, 0, MODE_EMA, j);
     
      double x1 = (length - 1) * (adcArray[j] * ob / (100.0 - ob) - aucArray[j]);
      double x2 = (length - 1) * (adcArray[j] * os / (100.0 - os) - aucArray[j]);
     
      double ub = (x1 >= 0) ? closeArray[j] + x1 : closeArray[j] + x1 * (100.0 - ob) / ob;
      double lb = (x2 >= 0) ? closeArray[j] + x2 : closeArray[j] + x2 * (100.0 - os) / os;
     
      ubBuffer[j] = ub;
      lbBuffer[j] = lb;
      midBuffer[j] = (ub + lb) / 2.0;
     
      //--- Расчет стрелок
      if(showArrows)
      {
         // BUY: предыдущая цена ниже lb, текущая выше lb
         if(closeArray[j + 1] < lbBuffer[j + 1] && closeArray[j] > lb)
            buyArrow[j] = Low[j] - (10 * Point);
         else
            buyArrow[j] = EMPTY_VALUE;

         // SELL: предыдущая цена выше ub, текущая ниже ub
         if(closeArray[j + 1] > ubBuffer[j + 1] && closeArray[j] < ub)
            sellArrow[j] = High[j] + (10 * Point);
         else
            sellArrow[j] = EMPTY_VALUE;
      }
      else
      {
         buyArrow[j] = EMPTY_VALUE;
         sellArrow[j] = EMPTY_VALUE;
      }
   }
}

//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
   //--- расчет первого индикатора
   CalculateRSIBands(RSILength1, OB1, OS1, TimeFrame1, ubBuffer1, lbBuffer1, midBuffer1, buyArrow1, sellArrow1, ShowIndicator1, ShowArrows1);
   
   //--- расчет второго индикатора
   CalculateRSIBands(RSILength2, OB2, OS2, TimeFrame2, ubBuffer2, lbBuffer2, midBuffer2, buyArrow2, sellArrow2, ShowIndicator2, ShowArrows2);
   
   //--- расчет третьего индикатора
   CalculateRSIBands(RSILength3, OB3, OS3, TimeFrame3, ubBuffer3, lbBuffer3, midBuffer3, buyArrow3, sellArrow3, ShowIndicator3, ShowArrows3);
   
   return rates_total;
}
//+------------------------------------------------------------------+

0

93

RSIBAND_LB

//
// @author LazyBear
// List of all my indicators: https://www.tradingview.com/v/4IneGo8h/
//
study("RSI Bands [LazyBear]", shorttitle="RSIBANDS_LB", overlay=true)
obLevel = input(70, title="RSI Overbought")
osLevel = input(30, title="RSI Oversold")
length = input(14, title="RSI Length")
src=close
ep = 2 * length - 1
auc = ema( max( src - src[1], 0 ), ep )
adc = ema( max( src[1] - src, 0 ), ep )
x1 = (length - 1) * ( adc * obLevel / (100-obLevel) - auc)
ub = iff( x1 >= 0, src + x1, src + x1 * (100-obLevel)/obLevel )
x2 = (length - 1) * ( adc * osLevel / (100-osLevel) - auc)
lb = iff( x2 >= 0, src + x2, src + x2 * (100-osLevel)/osLevel )

plot( ub, title="Resistance", color=red, linewidth=2)
plot( lb, title="Support", color=green, linewidth=2)
plot( avg(ub, lb), title="RSI Midline", color=gray, linewidth=1)

0

94

EMA 28 HL/2

//@version=6
indicator(title="Moving Average Exponential", shorttitle="EMA", overlay=true, timeframe="", timeframe_gaps=true)
len = input.int(9, minval=1, title="Length")
src = input(close, title="Source")
offset = input.int(title="Offset", defval=0, minval=-500, maxval=500, display = display.data_window)
out = ta.ema(src, len)
plot(out, title="EMA", color=color.blue, offset=offset)

// Smoothing MA inputs
GRP = "Smoothing"
TT_BB = "Only applies when 'SMA + Bollinger Bands' is selected. Determines the distance between the SMA and the bands."
maTypeInput = input.string("None", "Type", options = ["None", "SMA", "SMA + Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group = GRP, display = display.data_window)
maLengthInput = input.int(14, "Length", group = GRP, display = display.data_window)
bbMultInput = input.float(2.0, "BB StdDev", minval = 0.001, maxval = 50, step = 0.5, tooltip = TT_BB, group = GRP, display = display.data_window)
var enableMA = maTypeInput != "None"
var isBB = maTypeInput == "SMA + Bollinger Bands"

// Smoothing MA Calculation
ma(source, length, MAtype) =>
switch MAtype
    "SMA"                   => ta.sma(source, length)
    "SMA + Bollinger Bands" => ta.sma(source, length)
    "EMA"                   => ta.ema(source, length)
    "SMMA (RMA)"            => ta.rma(source, length)
    "WMA"                   => ta.wma(source, length)
    "VWMA"                  => ta.vwma(source, length)

// Smoothing MA plots
smoothingMA = enableMA ? ma(out, maLengthInput, maTypeInput) : na
smoothingStDev = isBB ? ta.stdev(out, maLengthInput) * bbMultInput : na
plot(smoothingMA, "EMA-based MA", color=color.yellow, display = enableMA ? display.all : display.none, editable = enableMA)
bbUpperBand = plot(smoothingMA + smoothingStDev, title = "Upper Bollinger Band", color=color.green, display = isBB ? display.all : display.none, editable = isBB)
bbLowerBand = plot(smoothingMA - smoothingStDev, title = "Lower Bollinger Band", color=color.green, display = isBB ? display.all : display.none, editable = isBB)
fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(color.green, 90) : na, title="Bollinger Bands Background Fill", display = isBB ? display.all : display.none, editable = isBB)

0

95

RSIBANDS 

HIGH
LOW

--------------

//
// @author LazyBear
// List of all my indicators: https://www.tradingview.com/v/4IneGo8h/
//
study("RSI Bands [LazyBear]", shorttitle="RSI_BANDS_HIGH", overlay=true)
obLevel = input(70, title="RSI Overbought")
osLevel = input(30, title="RSI Oversold")
length = input(14, title="RSI Length")
src=high
ep = 2 * length - 1
auc = ema( max( src - src[1], 0 ), ep )
adc = ema( max( src[1] - src, 0 ), ep )
x1 = (length - 1) * ( adc * obLevel / (100-obLevel) - auc)
ub = iff( x1 >= 0, src + x1, src + x1 * (100-obLevel)/obLevel )
x2 = (length - 1) * ( adc * osLevel / (100-osLevel) - auc)
lb = iff( x2 >= 0, src + x2, src + x2 * (100-osLevel)/osLevel )

plot( ub, title="Resistance", color=blue, linewidth=2)
plot( lb, title="Support", color=white, linewidth=2)
plot( avg(ub, lb), title="RSI Midline", color=orange, linewidth=1)



------------------------

//
// @author LazyBear
// List of all my indicators: https://www.tradingview.com/v/4IneGo8h/
//
study("RSI Bands [LazyBear]", shorttitle="RSI_BANDS_LOW", overlay=true)
obLevel = input(70, title="RSI Overbought")
osLevel = input(30, title="RSI Oversold")
length = input(14, title="RSI Length")
src=low
ep = 2 * length - 1
auc = ema( max( src - src[1], 0 ), ep )
adc = ema( max( src[1] - src, 0 ), ep )
x1 = (length - 1) * ( adc * obLevel / (100-obLevel) - auc)
ub = iff( x1 >= 0, src + x1, src + x1 * (100-obLevel)/obLevel )
x2 = (length - 1) * ( adc * osLevel / (100-osLevel) - auc)
lb = iff( x2 >= 0, src + x2, src + x2 * (100-osLevel)/osLevel )

plot( ub, title="Resistance", color=white, linewidth=2)
plot( lb, title="Support", color=blue, linewidth=2)
plot( avg(ub, lb), title="RSI Midline", color=orange, linewidth=1)

0

96

//@version=6

indicator('<[Расширенный двойной конверт HL MTF]>', '<[ADHL-Env-MTF]>', true)
// Настройки МТФ
mtf = input.timeframe('', 'Таймфрейм')

// ВЫБОР ТИПА МУВИНГА
ma_type = input.string('EMA', 'Тип мувинга', options = ['SMA', 'EMA', 'WMA', 'Hull MA', 'VWMA', 'TEMA', 'JMA', 'LSMA', 'ALMA', 'Vidya', 'ZLEMA', 'FRAMA'])

ma_length = input.int(9, 'Период мувинга')
ma_source = input.source(hl2, 'Источник для MA')

// Дополнительные параметры для некоторых MA
ma_offset = input.int(0, 'Смещение MA')
jma_power = input.float(2.0, 'JMA: Мощность', minval = 1, maxval = 10, step = 0.1)
alma_offset = input.float(0.85, 'ALMA: Смещение', minval = 0, maxval = 1, step = 0.01)
alma_sigma = input.float(6.0, 'ALMA: Сигма', minval = 1, maxval = 10, step = 0.1)

// Настройки конвертов
lookback1 = input.int(5, 'Период волатильности 1')
mult1 = input.float(1.0, 'Множитель 1', step = 0.1)
lookback2 = input.int(10, 'Период волатильности 2')
mult2 = input.float(1.0, 'Множитель 2', step = 0.1)

// Получаем данные с нужного ТФ
src = request.security(syminfo.tickerid, mtf, ma_source)
high_mtf = request.security(syminfo.tickerid, mtf, high)
low_mtf = request.security(syminfo.tickerid, mtf, low)

// ФУНКЦИИ РАСЧЕТА РАЗНЫХ MA
// Hull Moving Average
hma(_src, _length) =>
    _wma1 = ta.wma(_src, _length / 2)
    _wma2 = ta.wma(_src, _length)
    2 * _wma1 - _wma2

// Volume Weighted Moving Average
vwma(_src, _length) =>
    _sum = math.sum(_src * volume, _length)
    _vol = math.sum(volume, _length)
    _sum / _vol

// Triple Exponential Moving Average
tema(_src, _length) =>
    _ema1 = ta.ema(_src, _length)
    _ema2 = ta.ema(_ema1, _length)
    _ema3 = ta.ema(_ema2, _length)
    3 * _ema1 - 3 * _ema2 + _ema3

// Jurik Moving Average (упрощенная версия)
jma(_src, _length, _power) =>
    _beta = 0.45 * (_length - 1) / (0.45 * (_length - 1) + 2)
    _alpha = math.pow(_beta, _power)
    _jma = 0.0
    _jma := _alpha * _src + (1 - _alpha) * nz(_jma[1])
    _jma

// Least Squares Moving Average
lsma(_src, _length) =>
    _sum_x = _length * (_length - 1) / 2
    _sum_x2 = _length * (_length - 1) * (2 * _length - 1) / 6
    _sum_xy = 0.0
    _sum_y = 0.0
    for i = 0 to _length - 1 by 1
        _sum_xy := _sum_xy + i * _src[i]
        _sum_y := _sum_y + _src[i]
        _sum_y
    _slope = (_length * _sum_xy - _sum_x * _sum_y) / (_length * _sum_x2 - _sum_x * _sum_x)
    _intercept = (_sum_y - _slope * _sum_x) / _length
    _intercept + _slope * (_length - 1)

// Arnaud Legoux Moving Average
alma(_src, _length, _offset, _sigma) =>
    _m = math.floor(_offset * (_length - 1))
    _s = _length / _sigma
    _weights = array.new_float(0)
    _norm = 0.0
    for i = 0 to _length - 1 by 1
        _w = math.exp(-math.pow(i - _m, 2) / (2 * math.pow(_s, 2)))
        array.push(_weights, _w)
        _norm := _norm + _w
        _norm
    _sum = 0.0
    for i = 0 to _length - 1 by 1
        _sum := _sum + _src[i] * array.get(_weights, i)
        _sum
    _sum / _norm

// Variable Index Dynamic Average
vidya(_src, _length) =>
    _cmos = math.abs(ta.change(_src, 9)) / ta.atr(9)
    _alpha = 2.0 / (_length + 1)
    _vidya = 0.0
    _vidya := _alpha * _cmos * _src + (1 - _alpha * _cmos) * nz(_vidya[1])
    _vidya

// Zero-Lag EMA
zlema(_src, _length) =>
    _lag = math.round((_length - 1) / 2)
    _zlsrc = _src + _src - _src[_lag]
    ta.ema(_zlsrc, _length)

// Fractal Adaptive Moving Average
frama(_src, _length) =>
    float _n1 = math.max(ta.highest(_length), ta.lowest(_length))
    float _n2 = math.max(ta.highest(_length / 2), ta.lowest(_length / 2))
    float _n3 = math.max(ta.highest(_length / 2), ta.lowest(_length / 2))
    float _dimen = 1.0
    if _n1 > 0 and _n2 > 0 and _n3 > 0
        float _temp1 = math.log(_n1 + _n2)
        float _temp2 = math.log(_n3)
        _dimen := (_temp1 - _temp2) / math.log(2)
        _dimen
    float _alpha = math.exp(-4.6 * (_dimen - 1))
    _alpha := math.max(math.min(_alpha, 1), 0.01)
    float _frama = 0.0
    _frama := _alpha * _src + (1 - _alpha) * nz(_frama[1])
    _frama

// ВЫБОР ТИПА MA
get_ma() =>
    switch ma_type
        'SMA' => ta.sma(src, ma_length)
        'EMA' => ta.ema(src, ma_length)
        'WMA' => ta.wma(src, ma_length)
        'Hull MA' => hma(src, ma_length)
        'VWMA' => vwma(src, ma_length)
        'TEMA' => tema(src, ma_length)
        'JMA' => jma(src, ma_length, jma_power)
        'LSMA' => lsma(src, ma_length)
        'ALMA' => alma(src, ma_length, alma_offset, alma_sigma)
        'Vidya' => vidya(src, ma_length)
        'ZLEMA' => zlema(src, ma_length)
        'FRAMA' => frama(src, ma_length)

// Расчет центральной линии
center_line = get_ma()

// ПЕРВЫЙ конверт: Суммарная волатильность
total_hl_diff = 0.0
for i = 0 to lookback1 - 1 by 1
    total_hl_diff := total_hl_diff + high_mtf[i] - low_mtf[i]
    total_hl_diff

upper_band1 = center_line + total_hl_diff * mult1
lower_band1 = center_line - total_hl_diff * mult1

// ВТОРОЙ конверт: Общий диапазон
overall_high = ta.highest(high_mtf, lookback2)
overall_low = ta.lowest(low_mtf, lookback2)
hl_range = overall_high - overall_low

upper_band2 = center_line + hl_range * mult2
lower_band2 = center_line - hl_range * mult2

// Отрисовка
plot(center_line, 'Мувинг', #ff9800, 2)

// Конверт 1
u1 = plot(upper_band1, 'Верх Суммарный', #ff5252, 2)
l1 = plot(lower_band1, 'Низ Суммарный', #ff5252, 2)
fill(u1, l1, color.new(color.red, 90), 'Конверт 1')

// Конверт 2
u2 = plot(upper_band2, 'Верх Общий', #4caf50, 2)
l2 = plot(lower_band2, 'Низ Общий', #4caf50, 2)
fill(u2, l2, color.new(color.green, 90), 'Конверт 2')

// Общие High/Low
plot(overall_high, 'Общий High', #ff0057, 1, plot.style_circles)
plot(overall_low, 'Общий Low', #00ffff, 1, plot.style_circles)

var table logo = table.new(position.bottom_right, 1, 1)
table.cell(logo, 0, 0, 'DM', text_size = size.normal, text_color = #00897b)

//===========================================================================//

0

97

//@version=6

indicator('<[Расширенный двойной конверт HL MTF]>', '<[ADHL-Env-MTF]>', true)
// Настройки МТФ
mtf = input.timeframe('', 'Таймфрейм')

// ВЫБОР ТИПА МУВИНГА
ma_type = input.string('EMA', 'Тип мувинга', options = ['SMA', 'EMA', 'WMA', 'Hull MA', 'VWMA', 'TEMA', 'JMA', 'LSMA', 'ALMA', 'Vidya', 'ZLEMA', 'FRAMA'])

ma_length = input.int(9, 'Период мувинга')
ma_source = input.source(hl2, 'Источник для MA')

// Дополнительные параметры для некоторых MA
ma_offset = input.int(0, 'Смещение MA')
jma_power = input.float(2.0, 'JMA: Мощность', minval = 1, maxval = 10, step = 0.1)
alma_offset = input.float(0.85, 'ALMA: Смещение', minval = 0, maxval = 1, step = 0.01)
alma_sigma = input.float(6.0, 'ALMA: Сигма', minval = 1, maxval = 10, step = 0.1)

// Настройки конвертов
lookback1 = input.int(9, 'Период волатильности 1')
mult1 = input.float(1.0, 'Множитель 1', step = 0.1)
lookback2 = input.int(9, 'Период волатильности 2')
mult2 = input.float(1.0, 'Множитель 2', step = 0.1)

// Получаем данные с нужного ТФ
src = request.security(syminfo.tickerid, mtf, ma_source)
high_mtf = request.security(syminfo.tickerid, mtf, high)
low_mtf = request.security(syminfo.tickerid, mtf, low)

// ВЫБОР ТИПА MA
get_ma() =>
    switch ma_type
        'EMA' => ta.ema(src, ma_length)
     
// Расчет центральной линии
center_line = get_ma()

// ПЕРВЫЙ конверт: Суммарная волатильность
total_hl_diff = 0.0
for i = 0 to lookback1 - 1 by 1
    total_hl_diff := total_hl_diff + high_mtf[i] - low_mtf[i]
    total_hl_diff

upper_band1 = center_line + total_hl_diff * mult1
lower_band1 = center_line - total_hl_diff * mult1

// ВТОРОЙ конверт: Общий диапазон
overall_high = ta.highest(high_mtf, lookback2)
overall_low = ta.lowest(low_mtf, lookback2)
hl_range = overall_high - overall_low

upper_band2 = center_line + hl_range /3
lower_band2 = center_line - hl_range /3

// Отрисовка
plot(center_line, 'Мувинг', #ff9800, 2)

// Конверт 1
u1 = plot(upper_band1, 'Верх Суммарный', #ff5252, 2)
l1 = plot(lower_band1, 'Низ Суммарный', #ff5252, 2)
fill(u1, l1, color.new(color.red, 90), 'Конверт 1')

// Конверт 2
u2 = plot(upper_band2, 'Верх Общий', #4caf50, 2)
l2 = plot(lower_band2, 'Низ Общий', #4caf50, 2)
fill(u2, l2, color.new(color.green, 90), 'Конверт 2')

// Общие High/Low
plot(overall_high, 'Общий High', #ff0057, 1, plot.style_circles)
plot(overall_low, 'Общий Low', #00ffff, 1, plot.style_circles)

var table logo = table.new(position.bottom_right, 1, 1)
table.cell(logo, 0, 0, 'DM', text_size = size.normal, text_color = #00897b)

//===========================================================================//

0

98

//@version=6

indicator('<[Расширенный двойной конверт HL MTF]>', '<[ADHL-Env-MTF]>', true)
// Настройки МТФ
mtf = input.timeframe('', 'Таймфрейм')

// ВЫБОР ТИПА МУВИНГА
ma_type = input.string('EMA', 'Тип мувинга', options = ['EMA'])

ma_length = input.int(9, 'Период мувинга')
ma_source = input.source(hl2, 'Источник для MA')

// Дополнительные параметры для некоторых MA
ma_offset = input.int(0, 'Смещение MA')

// Настройки конвертов
lookback1 = input.int(9, 'Период волатильности 1')
mult1 = input.float(1.0, 'Множитель 1', step = 0.1)
lookback2 = input.int(9, 'Период волатильности 2')
mult2 = input.float(1.0, 'Множитель 2', step = 0.1)

// Получаем данные с нужного ТФ
src = request.security(syminfo.tickerid, mtf, ma_source)
high_mtf = request.security(syminfo.tickerid, mtf, high)
low_mtf = request.security(syminfo.tickerid, mtf, low)

// ВЫБОР ТИПА MA
get_ma() =>
    switch ma_type
        'EMA' => ta.ema(src, ma_length)
     
// Расчет центральной линии
center_line = get_ma()

// ПЕРВЫЙ конверт: Суммарная волатильность
total_hl_diff = 0.0
for i = 0 to lookback1 - 1 by 1
    total_hl_diff := total_hl_diff + high_mtf[i] - low_mtf[i]
    total_hl_diff

upper_band1 = center_line + total_hl_diff /3
lower_band1 = center_line - total_hl_diff /3

// ВТОРОЙ конверт: Общий диапазон
overall_high = ta.highest(high_mtf, lookback2)
overall_low = ta.lowest(low_mtf, lookback2)
hl_range = overall_high - overall_low

upper_band2 = center_line + hl_range /3
lower_band2 = center_line - hl_range /3

// Отрисовка
plot(center_line, 'Мувинг', #ff9800, 2)

// Конверт 1
u1 = plot(upper_band1, 'Верх Суммарный', #ff5252, 2)
l1 = plot(lower_band1, 'Низ Суммарный', #ff5252, 2)
fill(u1, l1, color.new(color.red, 90), 'Конверт 1')

// Конверт 2
u2 = plot(upper_band2, 'Верх Общий', #4caf50, 2)
l2 = plot(lower_band2, 'Низ Общий', #4caf50, 2)
fill(u2, l2, color.new(color.green, 90), 'Конверт 2')

// Общие High/Low
plot(overall_high, 'Общий High', color.rgb(206, 23, 223), 1, plot.style_circles)
plot(overall_low, 'Общий Low', #e017e0, 1, plot.style_circles)

var table logo = table.new(position.bottom_right, 1, 1)
table.cell(logo, 0, 0, 'DM', text_size = size.normal, text_color = #00897b)

//===========================================================================//

0

99

//@version=6

indicator('<[Расширенный двойной конверт HL MTF]>', '<[ADHL-Env-MTF]>', true)
// Настройки МТФ
mtf = input.timeframe('', 'Таймфрейм')

// ВЫБОР ТИПА МУВИНГА
ma_type = input.string('EMA', 'Тип мувинга', options = ['EMA'])

ma_length = input.int(9, 'Период мувинга')
ma_source = input.source(hl2, 'Источник для MA')

// Дополнительные параметры для некоторых MA
ma_offset = input.int(0, 'Смещение MA')

// Настройки конвертов
lookback1 = input.int(15, 'Период волатильности 1')
mult1 = input.float(1.0, 'Множитель 1', step = 0.1)
lookback2 = input.int(15, 'Период волатильности 2')
mult2 = input.float(1.0, 'Множитель 2', step = 0.1)

// Получаем данные с нужного ТФ
src = request.security(syminfo.tickerid, mtf, ma_source)
high_mtf = request.security(syminfo.tickerid, mtf, high)
low_mtf = request.security(syminfo.tickerid, mtf, low)

// ВЫБОР ТИПА MA
get_ma() =>
    switch ma_type
        'EMA' => ta.ema(src, ma_length)
     
// Расчет центральной линии
center_line = get_ma()

// ПЕРВЫЙ конверт: Суммарная волатильность
total_hl_diff = 0.0
for i = 0 to lookback1 - 1 by 1
    total_hl_diff := high_mtf[i] - low_mtf[i]
    total_hl_diff

upper_band1 = center_line + total_hl_diff /3
lower_band1 = center_line - total_hl_diff /3

// ВТОРОЙ конверт: Общий диапазон
overall_high = ta.highest(high_mtf, lookback2)
overall_low = ta.lowest(low_mtf, lookback2)
hl_range = overall_high - overall_low

upper_band2 = center_line + hl_range /3
lower_band2 = center_line - hl_range /3

// Отрисовка
plot(center_line, 'Мувинг', #ff9800, 2)

// Конверт 1
u1 = plot(upper_band1, 'Верх Суммарный', #ff5252, 2)
l1 = plot(lower_band1, 'Низ Суммарный', #ff5252, 2)
fill(u1, l1, color.new(color.red, 90), 'Конверт 1')

// Конверт 2
u2 = plot(upper_band2, 'Верх Общий', #4caf50, 2)
l2 = plot(lower_band2, 'Низ Общий', #4caf50, 2)
fill(u2, l2, color.new(color.green, 90), 'Конверт 2')

//===========================================================================//

//@version=6

indicator('<[Расширенный двойной конверт HL MTF]>', '<[ADHL-Env-MTF]>', true)
// Настройки МТФ
mtf = input.timeframe('', 'Таймфрейм')

// ВЫБОР ТИПА МУВИНГА
ma_type = input.string('EMA', 'Тип мувинга', options = ['EMA'])

ma_length = input.int(9, 'Период мувинга')
ma_source = input.source(hl2, 'Источник для MA')

// Дополнительные параметры для некоторых MA
ma_offset = input.int(0, 'Смещение MA')

// Настройки конвертов
lookback1 = input.int(18, 'Период волатильности 1')
mult1 = input.float(1.0, 'Множитель 1', step = 0.1)
lookback2 = input.int(18, 'Период волатильности 2')
mult2 = input.float(1.0, 'Множитель 2', step = 0.1)

// Получаем данные с нужного ТФ
src = request.security(syminfo.tickerid, mtf, ma_source)
high_mtf = request.security(syminfo.tickerid, mtf, high)
low_mtf = request.security(syminfo.tickerid, mtf, low)

// ВЫБОР ТИПА MA
get_ma() =>
    switch ma_type
        'EMA' => ta.ema(src, ma_length)
     
// Расчет центральной линии
center_line = get_ma()

// ПЕРВЫЙ конверт: Суммарная волатильность
total_hl_diff = 0.0
for i = 0 to lookback1 - 1 by 1
    total_hl_diff = high_mtf[i] - low_mtf[i]
    total_hl_diff

upper_band1 = center_line + total_hl_diff/3
lower_band1 = center_line - total_hl_diff/3

// ВТОРОЙ конверт: Общий диапазон
overall_high = ta.highest(high_mtf, lookback2)
overall_low = ta.lowest(low_mtf, lookback2)
hl_range = overall_high - overall_low

upper_band2 = center_line + hl_range/3
lower_band2 = center_line - hl_range/3

// Отрисовка
plot(center_line, 'Мувинг', #ff9800, 1)

// Конверт 1
u1 = plot(upper_band1, 'Верх Суммарный', #ff5252, 1)
l1 = plot(lower_band1, 'Низ Суммарный', #ff5252, 1)
fill(u1, l1, color.new(color.red, 90), 'Конверт 1')

// Конверт 2
u2 = plot(upper_band2, 'Верх Общий', #4caf50, 1)
l2 = plot(lower_band2, 'Низ Общий', #4caf50, 1)
fill(u2, l2, color.new(color.green, 90), 'Конверт 2')

//===================================================================

0

100

//@version=6

indicator('<[NINJA]>', '<[NINJA]>', true)
// Настройки МТФ
mtf = input.timeframe('', 'Таймфрейм')

// ВЫБОР ТИПА МУВИНГА
ma_type = input.string('EMA', 'Тип мувинга', options = ['SMA', 'EMA', 'WMA', 'Hull MA', 'VWMA', 'TEMA', 'JMA', 'LSMA', 'ALMA', 'Vidya', 'ZLEMA', 'FRAMA'])

ma_length = input.int(9, 'Период мувинга')
ma_source = input.source(hl2, 'Источник для MA')

// Дополнительные параметры для некоторых MA
ma_offset = input.int(0, 'Смещение MA')
jma_power = input.float(2.0, 'JMA: Мощность', minval = 1, maxval = 10, step = 0.1)
alma_offset = input.float(0.85, 'ALMA: Смещение', minval = 0, maxval = 1, step = 0.01)
alma_sigma = input.float(6.0, 'ALMA: Сигма', minval = 1, maxval = 10, step = 0.1)

// Настройки конвертов
lookback1 = input.int(18, 'Период волатильности 1')
mult1 = input.float(0.33, 'Множитель 1', step = 0.01)
lookback2 = input.int(18, 'Период волатильности 2')
mult2 = input.float(0.33, 'Множитель 2', step = 0.01)

// Получаем данные с нужного ТФ
src = request.security(syminfo.tickerid, mtf, ma_source)
high_mtf = request.security(syminfo.tickerid, mtf, high)
low_mtf = request.security(syminfo.tickerid, mtf, low)

// ФУНКЦИИ РАСЧЕТА РАЗНЫХ MA
// Hull Moving Average
hma(_src, _length) =>
    _wma1 = ta.wma(_src, _length / 2)
    _wma2 = ta.wma(_src, _length)
    2 * _wma1 - _wma2

// Volume Weighted Moving Average
vwma(_src, _length) =>
    _sum = math.sum(_src * volume, _length)
    _vol = math.sum(volume, _length)
    _sum / _vol

// Triple Exponential Moving Average
tema(_src, _length) =>
    _ema1 = ta.ema(_src, _length)
    _ema2 = ta.ema(_ema1, _length)
    _ema3 = ta.ema(_ema2, _length)
    3 * _ema1 - 3 * _ema2 + _ema3

// Jurik Moving Average (упрощенная версия)
jma(_src, _length, _power) =>
    _beta = 0.45 * (_length - 1) / (0.45 * (_length - 1) + 2)
    _alpha = math.pow(_beta, _power)
    _jma = 0.0
    _jma := _alpha * _src + (1 - _alpha) * nz(_jma[1])
    _jma

// Least Squares Moving Average
lsma(_src, _length) =>
    _sum_x = _length * (_length - 1) / 2
    _sum_x2 = _length * (_length - 1) * (2 * _length - 1) / 6
    _sum_xy = 0.0
    _sum_y = 0.0
    for i = 0 to _length - 1 by 1
        _sum_xy := _sum_xy + i * _src[i]
        _sum_y := _sum_y + _src[i]
        _sum_y
    _slope = (_length * _sum_xy - _sum_x * _sum_y) / (_length * _sum_x2 - _sum_x * _sum_x)
    _intercept = (_sum_y - _slope * _sum_x) / _length
    _intercept + _slope * (_length - 1)

// Arnaud Legoux Moving Average
alma(_src, _length, _offset, _sigma) =>
    _m = math.floor(_offset * (_length - 1))
    _s = _length / _sigma
    _weights = array.new_float(0)
    _norm = 0.0
    for i = 0 to _length - 1 by 1
        _w = math.exp(-math.pow(i - _m, 2) / (2 * math.pow(_s, 2)))
        array.push(_weights, _w)
        _norm := _norm + _w
        _norm
    _sum = 0.0
    for i = 0 to _length - 1 by 1
        _sum := _sum + _src[i] * array.get(_weights, i)
        _sum
    _sum / _norm

// Variable Index Dynamic Average
vidya(_src, _length) =>
    _cmos = math.abs(ta.change(_src, 9)) / ta.atr(9)
    _alpha = 2.0 / (_length + 1)
    _vidya = 0.0
    _vidya := _alpha * _cmos * _src + (1 - _alpha * _cmos) * nz(_vidya[1])
    _vidya

// Zero-Lag EMA
zlema(_src, _length) =>
    _lag = math.round((_length - 1) / 2)
    _zlsrc = _src + _src - _src[_lag]
    ta.ema(_zlsrc, _length)

// Fractal Adaptive Moving Average
frama(_src, _length) =>
    float _n1 = math.max(ta.highest(_length), ta.lowest(_length))
    float _n2 = math.max(ta.highest(_length / 2), ta.lowest(_length / 2))
    float _n3 = math.max(ta.highest(_length / 2), ta.lowest(_length / 2))
    float _dimen = 1.0
    if _n1 > 0 and _n2 > 0 and _n3 > 0
        float _temp1 = math.log(_n1 + _n2)
        float _temp2 = math.log(_n3)
        _dimen := (_temp1 - _temp2) / math.log(2)
        _dimen
    float _alpha = math.exp(-4.6 * (_dimen - 1))
    _alpha := math.max(math.min(_alpha, 1), 0.01)
    float _frama = 0.0
    _frama := _alpha * _src + (1 - _alpha) * nz(_frama[1])
    _frama

// ВЫБОР ТИПА MA
get_ma() =>
    switch ma_type
        'SMA' => ta.sma(src, ma_length)
        'EMA' => ta.ema(src, ma_length)
        'WMA' => ta.wma(src, ma_length)
        'Hull MA' => hma(src, ma_length)
        'VWMA' => vwma(src, ma_length)
        'TEMA' => tema(src, ma_length)
        'JMA' => jma(src, ma_length, jma_power)
        'LSMA' => lsma(src, ma_length)
        'ALMA' => alma(src, ma_length, alma_offset, alma_sigma)
        'Vidya' => vidya(src, ma_length)
        'ZLEMA' => zlema(src, ma_length)
        'FRAMA' => frama(src, ma_length)

// Расчет центральной линии
center_line = get_ma()

// ПЕРВЫЙ конверт: Суммарная волатильность
total_hl_diff = 0.0
for i = 0 to lookback1 - 1 by 1
    total_hl_diff := total_hl_diff + high_mtf[i] - low_mtf[i]
    total_hl_diff

upper_band1 = center_line + total_hl_diff * mult1
lower_band1 = center_line - total_hl_diff * mult1

// ВТОРОЙ конверт: Общий диапазон
overall_high = ta.highest(high_mtf, lookback2)
overall_low = ta.lowest(low_mtf, lookback2)
hl_range = overall_high - overall_low

upper_band2 = center_line + hl_range * mult1
lower_band2 = center_line - hl_range * mult2

// Отрисовка
plot(center_line, 'Мувинг', #ff9800, 2)

// Конверт 1
u1 = plot(upper_band1, 'Верх Суммарный', #ff5252, 2)
l1 = plot(lower_band1, 'Низ Суммарный', #ff5252, 2)
fill(u1, l1, color.new(color.red, 90), 'Конверт 1')

// Конверт 2
u2 = plot(upper_band2, 'Верх Общий', #4caf50, 2)
l2 = plot(lower_band2, 'Низ Общий', #4caf50, 2)
fill(u2, l2, color.new(color.green, 90), 'Конверт 2')

// Общие High/Low
plot(overall_high, 'Общий High', #ff0057, 1, plot.style_circles)
plot(overall_low, 'Общий Low', #00ffff, 1, plot.style_circles)

var table logo = table.new(position.bottom_right, 1, 1)
table.cell(logo, 0, 0, 'DM', text_size = size.normal, text_color = #00897b)

//===================================================================

0

101

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SamRecio
//

//@version=5
indicator("HTF Tool 2", shorttitle = "[HTF2]", overlay = true, max_boxes_count = 500, max_lines_count = 500)

//General Inputs
tf = input.timeframe("15", title = "Higher Timeframe", tooltip = "Timeframe must be...\n|Greater-than or Equal-to|\nthe Current Chart Timeframe.")
up_color = input.color(color.rgb(0,230,118,70), title = "        Up Color", inline = "2")
down_color = input.color(color.rgb(230,30,50,70), title = "        Down Color", inline = "2")

//HTF MA Inputs
ma_tog = input.bool(true, title = "", group = "HTF Moving Average", inline = "1" )
len = input.int(13, minval = 1, title  = "HTF MA ➡", group = "HTF Moving Average", inline = "1")
ma_type = input.string("EMA", title = "", options = ["EMA","SMA"], group = "HTF Moving Average", inline = "1")
ma_col = input.color(color.rgb(251,192,45), title = "", group = "HTF Moving Average", inline = "1" )

//Lvl 1 Inputs
lvl1_tog = input.bool(false, title = "Lvl 1    ➡ ", group = "measurments", inline = "1", tooltip = "How levels are drawn:\nGreen Candle = High(0.00) to Low(1.00)\nRed Candle = Low(0.00) to High(1.00)")
in_lvl_1 = input.float(0.382, step = 0.01, title = "", group = "measurments", inline = "1")
lvl1_style = input.string(". . .", title = "", options = ["___","- - -",". . ."], group = "measurments", inline = "1")
lvl1_color = input.color(color.white,title = "", group = "measurments", inline = "1")
//Lvl 2 Inputs
lvl2_tog = input.bool(true, title = "Lvl 2    ➡ ", group = "measurments", inline = "2")
in_lvl_2 = input.float(0.5, title = "", step = 0.01, group = "measurments", inline = "2")
lvl2_style = input.string("- - -", title = "", options = ["___","- - -",". . ."], group = "measurments", inline = "2")
lvl2_color = input.color(color.white,title = "", group = "measurments", inline = "2")
//Lvl 3 Inputs
lvl3_tog = input.bool(false, title = "Lvl 3    ➡ ", group = "measurments", inline = "3")
in_lvl_3 = input.float(0.618, title = "", step = 0.01, group = "measurments", inline = "3")
lvl3_style = input.string(". . .", title = "", options = ["___","- - -",". . ."], group = "measurments", inline = "3")
lvl3_color = input.color(color.white,title = "", group = "measurments", inline = "3")
//Lvl Settings
lvl_extend = input.int(10, title = "Extend Levels", tooltip = "# of bars to extend levels past the current bar.\nNote: Value can be negative.")
lb = input.int(30, maxval = 120, minval = 1, title = "Number of HTF Bars to Display:", tooltip = "MinVal = 1\nMaxVal = 120")

//Check for Same TF to make bars clear
tf_check = timeframe.period == tf
//Check for HTF
if timeframe.in_seconds(tf) < timeframe.in_seconds(timeframe.period)
    runtime.error("Please use a HIGHER Timeframe.")
//UD type to store candle box and line data, for easy access later
type candle
    box body
    line high_wick
    line low_wick

//red/green/gray coloring function
rg(_open,_close,_color1,_color2,_color3) =>
    _close > _open?_color1:
     _close < _open?_color2:
     _color3
///
//Candle Drawing Function
draw_candle(_o,_h,_l,_c,_left,_right,_rcolor,_gcolor,_ncolor) =>
    top = math.max(_o,_c)
    bot = math.min(_o,_c)
    mid = math.round(math.avg(_left,_right))
    rg_color = rg(_o,_c,_gcolor,_rcolor,_ncolor)
    candle.new(box.new(_left,top,_right,bot,bgcolor = tf_check?na:rg_color,border_color = tf_check?na:color.new(rg_color,0)),
         line.new(mid,top,mid,_h, color = tf_check?na:color.new(rg_color,0)),
         line.new(mid,bot,mid,_l, color = tf_check?na:color.new(rg_color,0)))

//Line style translation Function
linestyle(_input) =>
    _input == "___"?line.style_solid:
     _input == "- - -"?line.style_dashed:
     _input == ". . ."?line.style_dotted:
     na

///
//The ticking of the clock
new_tf = timeframe.change(tf)
//
//Necessary Candle Data
last_open = ta.valuewhen(new_tf,open,1)
last_left = ta.valuewhen(new_tf,bar_index,1)
current_open = ta.valuewhen(new_tf,open,0)
current_left = ta.valuewhen(new_tf,bar_index,0)

//HTF High/Low Tracking
//Is easier than using Highest/Lowest and it works flawlessly.
var float h = na
var float l = na
if new_tf
    h := high
    l := low
if low < l
    l := low
if high > h
    h := high
///////////////////////

//Lvl function for switching level placement depending on bar direction
lvl(_lvl) =>
    close>current_open?h-_lvl:l+_lvl 

//Lvl Calc
var lvls = array.new_line(na)
rng = h-l
lvl1 = lvl(in_lvl_1*rng)
lvl2 = lvl(in_lvl_2*rng)
lvl3 = lvl(in_lvl_3*rng)

//Draw Historic Candles on New TF
//and Lvls on historic bars
var candle_array = array.new<candle>(na)
var mid_array = array.new_int(na)
if new_tf
    array.push(candle_array,draw_candle(last_open,h[1],l[1],close[1],last_left,bar_index-1,down_color,up_color,color.new(color.gray,70)))
    array.push(mid_array,math.round(math.avg(last_left,bar_index-1)))
if new_tf and lvl1_tog   
    array.push(lvls,line.new(last_left,lvl1[1],bar_index-1,lvl1[1], style = linestyle(lvl1_style), color = lvl1_color))
if new_tf and lvl2_tog
    array.push(lvls,line.new(last_left,lvl2[1],bar_index-1,lvl2[1], style = linestyle(lvl2_style), color = lvl2_color))
if new_tf and lvl3_tog     
    array.push(lvls,line.new(last_left,lvl3[1],bar_index-1,lvl3[1], style = linestyle(lvl3_style), color = lvl3_color))

//Lvl Line Management (Dynamic deletion)
lb_bi = ta.valuewhen(new_tf,bar_index,lb-1) //lookback bar_index
if array.size(lvls) > 0
    for i = array.size(lvls) - 1 to 0
        lx = array.get(lvls,i)
        lx_left = line.get_x1(lx)
        lx_lvl = line.get_y1(lx)
        cross = (lx_lvl >= close[1] and lx_lvl < close) or (lx_lvl  <= close[1] and lx_lvl > close) or (lx_lvl < math.max(open,close) and lx_lvl > math.min(open,close))
        toofar = lx_left < lb_bi
        if cross or toofar
            line.delete(lx)
            array.remove(lvls,i)
        line.set_x2(lx,bar_index+lvl_extend)

//Drawing live candle
live_candle = draw_candle(current_open,h,l,close,current_left,bar_index,down_color,up_color,color.new(color.gray,70))
box.delete(live_candle.body[1])
line.delete(live_candle.high_wick[1])
line.delete(live_candle.low_wick[1])

//Deleting HTF bars past the lookback number
if array.size(candle_array) > lb-1
    box.delete(array.get(candle_array,0).body)
    line.delete(array.get(candle_array,0).high_wick)
    line.delete(array.get(candle_array,0).low_wick)
    array.remove(candle_array,0)

//Live Levels
var ll1 = line.new(na,na,na,na, style = linestyle(lvl1_style), color = lvl1_color)
var ll2 = line.new(na,na,na,na, style = linestyle(lvl2_style), color = lvl2_color)
var ll3 = line.new(na,na,na,na, style = linestyle(lvl3_style), color = lvl3_color)

//Setting Live LVL Values
if lvl1_tog
    line.set_xy1(ll1,current_left,lvl1)
    line.set_xy2(ll1,bar_index+lvl_extend,lvl1)
if lvl2_tog
    line.set_xy1(ll2,current_left,lvl2)
    line.set_xy2(ll2,bar_index+lvl_extend,lvl2)
if lvl3_tog
    line.set_xy1(ll3,current_left,lvl3)
    line.set_xy2(ll3,bar_index+lvl_extend,lvl3)

//MOVING AVERAGE STUFF
//close array(for SMA)
var close_array = array.new_float(na)
if new_tf
    array.push(close_array,close[1])
if new_tf and array.size(close_array) > len
    array.remove(close_array,0)
//Calculating Historic MA values to append to the historic MA
k = 2/(len + 1)
var float ma = na
if new_tf and ma_type == "EMA"
    ma := (close[1]*k) + (nz(ma[1])*(1-k))
if new_tf and ma_type == "SMA"
    ma := array.avg(close_array)
//Initiating variables fo draw the mas
var ma_array = array.new_line(na)
last_mid = array.size(mid_array)>1?array.get(mid_array,array.size(mid_array)-1):na
prev_last_mid = array.size(mid_array)>1?array.get(mid_array,array.size(mid_array)-2):na
//Adds a line to the MA every new bar
if new_tf and ma_tog
    array.push(ma_array,line.new(prev_last_mid,ma[1],last_mid,ma, width = 2, color = ma_col))
if array.size(ma_array) > lb-1
    line.delete(array.get(ma_array,0))
    array.remove(ma_array,0)
//Tip of the MA
//Calculating Averages
htf_sma = array.size(close_array) > 0?((array.sum(close_array) - array.get(close_array,0))+close)/len:na
htf_ema = (close*k) + (nz(ma[1])*(1-k))
htf_ma = ma_type == "EMA"?htf_ema:htf_sma
//Drawing the Tip
if ma_tog
    live_line = line.new(last_mid,ma,bar_index,htf_ma, width = 2, color = ma_col)
    line.delete(live_line[1])
//Plotting for values
plot(ma_tog?htf_ma:na,show_last = 1, title = "HTF_MA",editable = false, display = ma_tog?display.price_scale + display.status_line:display.none, color = ma_col)

0

102

// © Julien_Eche
// Indicator based on "Nadaraya-Watson Envelope [LuxAlgo]" by LuxAlgo
// and "Strongest Trendline" by Julien_Eche

//@version=5

indicator("Smart Trend Envelope", overlay=true, max_bars_back=1000, max_lines_count=500)

group1 = "Channel Settings"
h = input.float(8.0, title='Bandwidth', group=group1)
multnw = input.float(3.0, title='Multiplier')
log(x) => math.log(x) / math.log(math.e)
exp(x) => math.pow(math.e, x)
src = log(input(close, title='Source'))

up_col = input(color.teal, title='Upper Line Color')
dn_col = input(color.red, title='Lower Line Color')
line_widthnw = input.int(2, title='Line Width')

group2 = "Table Settings"
tablePositionInput = input.string("Top Center", "Table Position", options=["Bottom Right", "Bottom Left", "Middle Right", "Middle Left", "Top Right", "Top Left", "Top Center", "Bottom Center"], group=group2)
getTablePosition(pos) =>
    // Function to convert table position input string to the corresponding position value
    if pos == "Bottom Right"
        position.bottom_right
    else if pos == "Bottom Left"
        position.bottom_left
    else if pos == "Middle Right"
        position.middle_right
    else if pos == "Middle Left"
        position.middle_left
    else if pos == "Top Right"
        position.top_right
    else if pos == "Top Left"
        position.top_left
    else if pos == "Top Center"
        position.top_center
    else if pos == "Bottom Center"
        position.bottom_center       
    else
        position.bottom_right

tablePos = getTablePosition(tablePositionInput)

rightTableTextColorInput = input.color(color.silver, "Projection Confidence Text Color")

showPearsonInput = input.bool(false, "Show Pearson's R instead of Projection Confidence Level")

lengthInput1 = 50
lengthInput2 = 100
lengthInput3 = 150
lengthInput4 = 200
lengthInput5 = 250
lengthInput6 = 300
lengthInput7 = 350
lengthInput8 = 400
lengthInput9 = 450
lengthInput10 = 500

calcSlope(src, length) =>
    // Function to calculate slope, average, and intercept
    max_bars_back(src, 5000)
    if not barstate.islast or length <= 1
        [float(na), float(na), float(na)]
    else
        sumX = 0.0
        sumY = 0.0
        sumXSqr = 0.0
        sumXY = 0.0
        for i = 0 to length - 1 by 1
            val = math.log(src[i])
            per = i + 1.0
            sumX += per
            sumY += val
            sumXSqr += per * per
            sumXY += val * per
        slope = (length * sumXY - sumX * sumY) / (length * sumXSqr - sumX * sumX)
        average = sumY / length
        intercept = average - slope * sumX / length + slope
        [slope, average, intercept]

calcDev(src, length, slope, average, intercept) =>
    // Function to calculate standard deviation, Pearson's R, up deviation, and down deviation
    upDev = 0.0
    dnDev = 0.0
    stdDevAcc = 0.0
    dsxx = 0.0
    dsyy = 0.0
    dsxy = 0.0
    periods = length - 1
    daY = intercept + slope * periods / 2
    val = intercept
    for j = 0 to periods by 1
        price = math.log(high[j]) - val
        if price > upDev
            upDev := price
        price := val - math.log(low[j])
        if price > dnDev
            dnDev := price
        price := math.log(src[j])
        dxt = price - average
        dyt = val - daY
        price -= val
        stdDevAcc += price * price
        dsxx += dxt * dxt
        dsyy += dyt * dyt
        dsxy += dxt * dyt
        val += slope
    stdDev = math.sqrt(stdDevAcc / (periods == 0 ? 1 : periods))
    pearsonR = dsxx == 0 or dsyy == 0 ? 0 : dsxy / math.sqrt(dsxx * dsyy)
    [stdDev, pearsonR, upDev, dnDev]

// Calculate slope, average, and intercept for each length
[s1, a1, i1] = calcSlope(src, lengthInput1)
[s2, a2, i2] = calcSlope(src, lengthInput2)
[s3, a3, i3] = calcSlope(src, lengthInput3)
[s4, a4, i4] = calcSlope(src, lengthInput4)
[s5, a5, i5] = calcSlope(src, lengthInput5)
[s6, a6, i6] = calcSlope(src, lengthInput6)
[s7, a7, i7] = calcSlope(src, lengthInput7)
[s8, a8, i8] = calcSlope(src, lengthInput8)
[s9, a9, i9] = calcSlope(src, lengthInput9)
[s10, a10, i10] = calcSlope(src, lengthInput10)

// Calculate standard deviation, Pearson's R, up deviation, and down deviation for each length
[stdDev1, pearsonR1, upDev1, dnDev1] = calcDev(src, lengthInput1, s1, a1, i1)
[stdDev2, pearsonR2, upDev2, dnDev2] = calcDev(src, lengthInput2, s2, a2, i2)
[stdDev3, pearsonR3, upDev3, dnDev3] = calcDev(src, lengthInput3, s3, a3, i3)
[stdDev4, pearsonR4, upDev4, dnDev4] = calcDev(src, lengthInput4, s4, a4, i4)
[stdDev5, pearsonR5, upDev5, dnDev5] = calcDev(src, lengthInput5, s5, a5, i5)
[stdDev6, pearsonR6, upDev6, dnDev6] = calcDev(src, lengthInput6, s6, a6, i6)
[stdDev7, pearsonR7, upDev7, dnDev7] = calcDev(src, lengthInput7, s7, a7, i7)
[stdDev8, pearsonR8, upDev8, dnDev8] = calcDev(src, lengthInput8, s8, a8, i8)
[stdDev9, pearsonR9, upDev9, dnDev9] = calcDev(src, lengthInput9, s9, a9, i9)
[stdDev10, pearsonR10, upDev10, dnDev10] = calcDev(src, lengthInput10, s10, a10, i10)

// Find the highest Pearson's R among all lengths
highestPearsonR = math.max(pearsonR1, pearsonR2, pearsonR3, pearsonR4, pearsonR5, pearsonR6, pearsonR7, pearsonR8, pearsonR9, pearsonR10)

// Select the length, slope, intercept, and standard deviation based on the highest Pearson's R
selectedLength = highestPearsonR == pearsonR1 ? lengthInput1 : (highestPearsonR == pearsonR2 ? lengthInput2 : (highestPearsonR == pearsonR3 ? lengthInput3 : (highestPearsonR == pearsonR4 ? lengthInput4 : (highestPearsonR == pearsonR5 ? lengthInput5 : (highestPearsonR == pearsonR6 ? lengthInput6 : (highestPearsonR == pearsonR7 ? lengthInput7 : (highestPearsonR == pearsonR8 ? lengthInput8 : (highestPearsonR == pearsonR9 ? lengthInput9 : lengthInput10))))))))
selectedS = highestPearsonR == pearsonR1 ? s1 : (highestPearsonR == pearsonR2 ? s2 : (highestPearsonR == pearsonR3 ? s3 : (highestPearsonR == pearsonR4 ? s4 : (highestPearsonR == pearsonR5 ? s5 : (highestPearsonR == pearsonR6 ? s6 : (highestPearsonR == pearsonR7 ? s7 : (highestPearsonR == pearsonR8 ? s8 : (highestPearsonR == pearsonR9 ? s9 : s10))))))))
selectedI = highestPearsonR == pearsonR1 ? i1 : (highestPearsonR == pearsonR2 ? i2 : (highestPearsonR == pearsonR3 ? i3 : (highestPearsonR == pearsonR4 ? i4 : (highestPearsonR == pearsonR5 ? i5 : (highestPearsonR == pearsonR6 ? i6 : (highestPearsonR == pearsonR7 ? i7 : (highestPearsonR == pearsonR8 ? i8 : (highestPearsonR == pearsonR9 ? i9 : i10))))))))
selectedStdDev = highestPearsonR == pearsonR1 ? stdDev1 : (highestPearsonR == pearsonR2 ? stdDev2 : (highestPearsonR == pearsonR3 ? stdDev3 : (highestPearsonR == pearsonR4 ? stdDev4 : (highestPearsonR == pearsonR5 ? stdDev5 : (highestPearsonR == pearsonR6 ? stdDev6 : (highestPearsonR == pearsonR7 ? stdDev7 : (highestPearsonR == pearsonR8 ? stdDev8 : (highestPearsonR == pearsonR9 ? stdDev9 : stdDev10))))))))

startPrice = math.exp(selectedI + selectedS * (selectedLength - 1))
endPrice = math.exp(selectedI)

StartPrice = startPrice
EndPrice = endPrice

var string confidenceLevel = ""

var color lineColor = na

trendDirection = startPrice > endPrice ? -1 : 1

if trendDirection == 1
    lineColor := color.teal
else
    lineColor := color.red

if barstate.islast
    var table t = table.new(position = tablePos, columns = 2, rows = 2)
   
    text1 = ""
    if selectedLength == lengthInput1
        text1 := "Auto-Selected Length: 50"
    if selectedLength == lengthInput2
        text1 := "Auto-Selected Length: 100"
    if selectedLength == lengthInput3
        text1 := "Auto-Selected Length: 150"
    if selectedLength == lengthInput4
        text1 := "Auto-Selected Length: 200"
    if selectedLength == lengthInput5
        text1 := "Auto-Selected Length: 250"
    if selectedLength == lengthInput6
        text1 := "Auto-Selected Length: 300"
    if selectedLength == lengthInput7
        text1 := "Auto-Selected Length: 350"
    if selectedLength == lengthInput8
        text1 := "Auto-Selected Length: 400"
    if selectedLength == lengthInput9
        text1 := "Auto-Selected Length: 450"
    if selectedLength == lengthInput10
        text1 := "Auto-Selected Length: 500"
   
    confidenceLevel := ""
    if highestPearsonR < 0.3
        confidenceLevel := "Ultra Weak"
    else if highestPearsonR < 0.5
        confidenceLevel := "Very Weak"
    else if highestPearsonR < 0.6
        confidenceLevel := "Weak"
    else if highestPearsonR < 0.7
        confidenceLevel := "Moderately Weak"
    else if highestPearsonR < 0.8
        confidenceLevel := "Slightly Weak"
    else if highestPearsonR < 0.9
        confidenceLevel := "Moderate"
    else if highestPearsonR < 0.92
        confidenceLevel := "Slightly Strong"
    else if highestPearsonR < 0.94
        confidenceLevel := "Moderately Strong"
    else if highestPearsonR < 0.96
        confidenceLevel := "Strong"
    else if highestPearsonR < 0.98
        confidenceLevel := "Very Strong"
    else
        confidenceLevel := "Ultra Strong"
   
    table.cell(t, 0, 0, text1, text_color=lineColor)
    if showPearsonInput
        table.cell(t, 1, 0, "Pearson's R: " + str.tostring(highestPearsonR, "#.##"), text_color=rightTableTextColorInput)
    else
        table.cell(t, 1, 0, "Projection Confidence: " + confidenceLevel, text_color=rightTableTextColorInput)

lengthnw = selectedLength

n = bar_index
var k = 2
var uppernw = array.new_line(0)
var lowernw = array.new_line(0)

lset(l, x1, y1, x2, y2, col) =>
    line.set_xy1(l, x1, exp(y1))
    line.set_xy2(l, x2, exp(y2))
    line.set_color(l, col)
    line.set_width(l, line_widthnw)
    line.set_style(l, line.style_solid)

if barstate.isfirst
    for i = 0 to lengthnw/k-1
        array.push(uppernw, line.new(na, na, na, na, color=up_col, width=line_widthnw, style=line.style_solid))
        array.push(lowernw, line.new(na, na, na, na, color=dn_col, width=line_widthnw, style=line.style_solid))

line up = na
line dn = na

cross_up = 0.0
cross_dn = 0.0
if barstate.islast
    y = array.new_float(0)
   
    sum_e = 0.0
    for i = 0 to lengthnw-1
        sum = 0.0
        sumw = 0.0
       
        for j = 0 to lengthnw-1
            w = math.exp(-(math.pow(i-j, 2)/(h*h*2)))
            sum += src[j] * w
            sumw += w
       
        y2 = sum / sumw
        sum_e += math.abs(src[i] - y2)
        array.push(y, y2)

    mae = sum_e / lengthnw * multnw
   
    for i = 1 to lengthnw-1
        y2 = array.get(y, i)
        y1 = array.get(y, i-1)
       
        up := array.get(uppernw, i/k)
        dn := array.get(lowernw, i/k)
       
        lset(up, n-i+1, y1 + mae, n-i, y2 + mae, up_col)
        lset(dn, n-i+1, y1 - mae, n-i, y2 - mae, dn_col)

0

103

//@version=6

indicator('<[Расширенный двойной конверт HL MTF]>', '<[ADHL-Env-MTF]>', true)
// Настройки МТФ
mtf = input.timeframe('', 'Таймфрейм')

// ВЫБОР ТИПА МУВИНГА
ma_type = input.string('EMA', 'Тип мувинга', options = ['EMA'])

ma_length = input.int(28, 'Период мувинга')
ma_source = input.source(hl2, 'Источник для MA')

// Дополнительные параметры для некоторых MA
ma_offset = input.int(0, 'Смещение MA')

// Настройки конвертов
lookback1 = input.int(28, 'Период волатильности 1')
mult1 = input.float(1.0, 'Множитель 1', step = 0.1)
lookback2 = input.int(28, 'Период волатильности 2')
mult2 = input.float(1.0, 'Множитель 2', step = 0.1)

// Получаем данные с нужного ТФ
src = request.security(syminfo.tickerid, mtf, ma_source)
high_mtf = request.security(syminfo.tickerid, mtf, high)
low_mtf = request.security(syminfo.tickerid, mtf, low)

// ВЫБОР ТИПА MA
get_ma() =>
    switch ma_type
        'EMA' => ta.ema(src, ma_length)
     
// Расчет центральной линии
center_line = get_ma()

// ПЕРВЫЙ конверт: Суммарная волатильность
total_hl_diff = 0.0
for i = 0 to lookback1 - 1 by 1
    total_hl_diff := high_mtf[i] - low_mtf[i]
    total_hl_diff

upper_band1 = center_line + total_hl_diff /3
lower_band1 = center_line - total_hl_diff /3

// ВТОРОЙ конверт: Общий диапазон
overall_high = ta.highest(high_mtf, lookback2)
overall_low = ta.lowest(low_mtf, lookback2)
hl_range = overall_high - overall_low

upper_band2 = center_line + hl_range /3
lower_band2 = center_line - hl_range /3

// Отрисовка
plot(center_line, 'Мувинг', #ff9800, 2)

// Конверт 1
u1 = plot(upper_band1, 'Верх Суммарный', #ff5252, 2)
l1 = plot(lower_band1, 'Низ Суммарный', #ff5252, 2)
fill(u1, l1, color.new(color.red, 90), 'Конверт 1')

// Конверт 2
u2 = plot(upper_band2, 'Верх Общий', #4caf50, 2)
l2 = plot(lower_band2, 'Низ Общий', #4caf50, 2)
fill(u2, l2, color.new(color.green, 90), 'Конверт 2')

//===================================================================

0

104

//@version=6

indicator('<[NINJA]>', '<[NINJA]>', true)
// Настройки МТФ
mtf = input.timeframe('', 'Таймфрейм')

// ВЫБОР ТИПА МУВИНГА
ma_type = input.string('EMA', 'Тип мувинга', options = ['SMA', 'EMA', 'WMA', 'Hull MA', 'VWMA', 'TEMA', 'JMA', 'LSMA', 'ALMA', 'Vidya', 'ZLEMA', 'FRAMA'])

ma_length = input.int(28, 'Период мувинга')
ma_source = input.source(hl2, 'Источник для MA')

// Дополнительные параметры для некоторых MA
ma_offset = input.int(0, 'Смещение MA')
jma_power = input.float(2.0, 'JMA: Мощность', minval = 1, maxval = 10, step = 0.1)
alma_offset = input.float(0.85, 'ALMA: Смещение', minval = 0, maxval = 1, step = 0.01)
alma_sigma = input.float(6.0, 'ALMA: Сигма', minval = 1, maxval = 10, step = 0.1)

// Настройки конвертов
lookback1 = input.int(28, 'Период волатильности 1')
mult1 = input.float(0.33, 'Множитель 1', step = 0.01)
lookback2 = input.int(28, 'Период волатильности 2')
mult2 = input.float(0.33, 'Множитель 2', step = 0.01)

// Получаем данные с нужного ТФ
src = request.security(syminfo.tickerid, mtf, ma_source)
high_mtf = request.security(syminfo.tickerid, mtf, high)
low_mtf = request.security(syminfo.tickerid, mtf, low)

// ФУНКЦИИ РАСЧЕТА РАЗНЫХ MA
// Hull Moving Average
hma(_src, _length) =>
    _wma1 = ta.wma(_src, _length / 2)
    _wma2 = ta.wma(_src, _length)
    2 * _wma1 - _wma2

// Volume Weighted Moving Average
vwma(_src, _length) =>
    _sum = math.sum(_src * volume, _length)
    _vol = math.sum(volume, _length)
    _sum / _vol

// Triple Exponential Moving Average
tema(_src, _length) =>
    _ema1 = ta.ema(_src, _length)
    _ema2 = ta.ema(_ema1, _length)
    _ema3 = ta.ema(_ema2, _length)
    3 * _ema1 - 3 * _ema2 + _ema3

// Jurik Moving Average (упрощенная версия)
jma(_src, _length, _power) =>
    _beta = 0.45 * (_length - 1) / (0.45 * (_length - 1) + 2)
    _alpha = math.pow(_beta, _power)
    _jma = 0.0
    _jma := _alpha * _src + (1 - _alpha) * nz(_jma[1])
    _jma

// Least Squares Moving Average
lsma(_src, _length) =>
    _sum_x = _length * (_length - 1) / 2
    _sum_x2 = _length * (_length - 1) * (2 * _length - 1) / 6
    _sum_xy = 0.0
    _sum_y = 0.0
    for i = 0 to _length - 1 by 1
        _sum_xy := _sum_xy + i * _src[i]
        _sum_y := _sum_y + _src[i]
        _sum_y
    _slope = (_length * _sum_xy - _sum_x * _sum_y) / (_length * _sum_x2 - _sum_x * _sum_x)
    _intercept = (_sum_y - _slope * _sum_x) / _length
    _intercept + _slope * (_length - 1)

// Arnaud Legoux Moving Average
alma(_src, _length, _offset, _sigma) =>
    _m = math.floor(_offset * (_length - 1))
    _s = _length / _sigma
    _weights = array.new_float(0)
    _norm = 0.0
    for i = 0 to _length - 1 by 1
        _w = math.exp(-math.pow(i - _m, 2) / (2 * math.pow(_s, 2)))
        array.push(_weights, _w)
        _norm := _norm + _w
        _norm
    _sum = 0.0
    for i = 0 to _length - 1 by 1
        _sum := _sum + _src[i] * array.get(_weights, i)
        _sum
    _sum / _norm

// Variable Index Dynamic Average
vidya(_src, _length) =>
    _cmos = math.abs(ta.change(_src, 9)) / ta.atr(9)
    _alpha = 2.0 / (_length + 1)
    _vidya = 0.0
    _vidya := _alpha * _cmos * _src + (1 - _alpha * _cmos) * nz(_vidya[1])
    _vidya

// Zero-Lag EMA
zlema(_src, _length) =>
    _lag = math.round((_length - 1) / 2)
    _zlsrc = _src + _src - _src[_lag]
    ta.ema(_zlsrc, _length)

// Fractal Adaptive Moving Average
frama(_src, _length) =>
    float _n1 = math.max(ta.highest(_length), ta.lowest(_length))
    float _n2 = math.max(ta.highest(_length / 2), ta.lowest(_length / 2))
    float _n3 = math.max(ta.highest(_length / 2), ta.lowest(_length / 2))
    float _dimen = 1.0
    if _n1 > 0 and _n2 > 0 and _n3 > 0
        float _temp1 = math.log(_n1 + _n2)
        float _temp2 = math.log(_n3)
        _dimen := (_temp1 - _temp2) / math.log(2)
        _dimen
    float _alpha = math.exp(-4.6 * (_dimen - 1))
    _alpha := math.max(math.min(_alpha, 1), 0.01)
    float _frama = 0.0
    _frama := _alpha * _src + (1 - _alpha) * nz(_frama[1])
    _frama

// ВЫБОР ТИПА MA
get_ma() =>
    switch ma_type
        'SMA' => ta.sma(src, ma_length)
        'EMA' => ta.ema(src, ma_length)
        'WMA' => ta.wma(src, ma_length)
        'Hull MA' => hma(src, ma_length)
        'VWMA' => vwma(src, ma_length)
        'TEMA' => tema(src, ma_length)
        'JMA' => jma(src, ma_length, jma_power)
        'LSMA' => lsma(src, ma_length)
        'ALMA' => alma(src, ma_length, alma_offset, alma_sigma)
        'Vidya' => vidya(src, ma_length)
        'ZLEMA' => zlema(src, ma_length)
        'FRAMA' => frama(src, ma_length)

// Расчет центральной линии
center_line = get_ma()

// ПЕРВЫЙ конверт: Суммарная волатильность
total_hl_diff = 0.0
for i = 0 to lookback1 - 1 by 1
    total_hl_diff := total_hl_diff + high_mtf[i] - low_mtf[i]
    total_hl_diff

upper_band1 = center_line + total_hl_diff * mult1
lower_band1 = center_line - total_hl_diff * mult1

// ВТОРОЙ конверт: Общий диапазон
overall_high = ta.highest(high_mtf, lookback2)
overall_low = ta.lowest(low_mtf, lookback2)
hl_range = overall_high - overall_low

upper_band2 = center_line + hl_range * mult1
lower_band2 = center_line - hl_range * mult2

// Отрисовка
plot(center_line, 'Мувинг', #ff9800, 2)

// Конверт 1
u1 = plot(upper_band1, 'Верх Суммарный', #ff5252, 2)
l1 = plot(lower_band1, 'Низ Суммарный', #ff5252, 2)
fill(u1, l1, color.new(color.red, 90), 'Конверт 1')

// Конверт 2
u2 = plot(upper_band2, 'Верх Общий', #4caf50, 2)
l2 = plot(lower_band2, 'Низ Общий', #4caf50, 2)
fill(u2, l2, color.new(color.green, 90), 'Конверт 2')

// Общие High/Low
plot(overall_high, 'Общий High', #ff0057, 1, plot.style_circles)
plot(overall_low, 'Общий Low', #00ffff, 1, plot.style_circles)

var table logo = table.new(position.bottom_right, 1, 1)
table.cell(logo, 0, 0, 'DM', text_size = size.normal, text_color = #00897b)

//===================================================================

0

105

https://docsbot.ai/prompts/tags?tag=MQL4

https://www.tradingview.com/script/3g4T … -Strategy/

//This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//Reference Bourso Technique
//© RaphaelVigneault
//@version=6

// Make sure any custom timeframes are added to your layout for it to show properly and be selectable in the indicators
indicator('Standard Deviation Channel',  shorttitle='SDC', overlay=true,timeframe ="3D", format='price')

enum MAType
    NONE="NONE"
    SMA="SMA"
    EMA="EMA"
    RMA="RMA"
    WMA="WMA"
    VWMA="VWMA"

//IndicatorParameters
SOURCE=input.source(close, group="SOURCE", title='Target:')
DEF_DTE=input.int(28, minval=1,  title='Default DTE:', tooltip="Used when security selected has no expiration date.")
DTE=syminfo.expiration_date > 0 ? (syminfo.expiration_date - time) / (24 * 60 * 60 * 1000) : DEF_DTE

MA_TYPE=input.enum(MAType.NONE, group="DEVIATION", title="Smoothing:", options=[MAType.NONE, MAType.SMA, MAType.EMA, MAType.WMA, MAType.VWMA, MAType.RMA])
MA_LENGTH=input.int(32 , minval=1, title='Length:')

var float LOW=na
var float MID=na
var float TOP=na

float RSI= ta.rsi(SOURCE, MA_LENGTH)
float DEVIATION= ta.stdev(SOURCE,MA_LENGTH)
float RESULT = DEVIATION * math.sqrt(DTE / 365)

LOW := SOURCE + RESULT
TOP := SOURCE - RESULT
MID := LOW + ((TOP - LOW) / 2)
switch MA_TYPE
    MAType.SMA =>
        LOW := ta.sma(LOW,MA_LENGTH)
        MID := ta.sma(MID,MA_LENGTH)
        TOP := ta.sma(TOP,MA_LENGTH)
    MAType.EMA =>
        LOW := ta.ema(LOW,MA_LENGTH)
        MID := ta.ema(MID,MA_LENGTH)
        TOP := ta.ema(TOP,MA_LENGTH)
    MAType.RMA =>
        LOW := ta.rma(LOW,MA_LENGTH)
        MID := ta.rma(MID,MA_LENGTH)
        TOP := ta.rma(TOP,MA_LENGTH)
    MAType.VWMA =>
        LOW := ta.vwma(LOW,MA_LENGTH)
        MID := ta.vwma(MID,MA_LENGTH)
        TOP := ta.vwma(TOP,MA_LENGTH)
    MAType.WMA =>
        LOW := ta.wma(LOW,MA_LENGTH)
        MID := ta.wma(MID,MA_LENGTH)
        TOP := ta.wma(TOP,MA_LENGTH)
    => na

plot(LOW, title="top", style=plot.style_line, color=color.blue, linewidth=2)
plot(MID, title="mid", style=plot.style_line, color=color.white, linewidth=2)
plot(TOP, title="low", style=plot.style_line, color=color.orange, linewidth=2)

plotshape(DTE, location=location.bottom, title="All Cycles", text="P", style=shape.labelup, color=color.yellow, textcolor=color.black, size=size.tiny)
plotshape(DTE, location=location.bottom, title="Last Cycle", text="Current", style=shape.labeldown, show_last=1, color=color.yellow, textcolor=color.black, size=size.normal)

https://th.tradingview.com/script/CgjAg … n-Channel/

0

106

https://www.tradingview.com/script/AlUa … lopes-TAE/

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// The_Peaceful_Lizard

//@version=5
indicator("True Amplitude Envelopes (TAE)")

// { <FUNCTIONS>

// color {

method scale_alpha(float self, float alpha = 80)=>
    float invert = 100 - alpha
    self * invert / 100

method new_alpha(color self, float alpha = 80)=>
    color.new(self, alpha + color.t(self).scale_alpha(alpha))

// color }

// auto period {

auto_period(float source, simple float minimum, simple float maximum, simple bool extra_hpf = true)=>
    float period = 0
    float coef_1 = 0.0962
    float coef_2 = 0.5769
    float coef_3 = 0.075 * nz(period[1]) + 0.54
   
    float smooth = (4 * source + 3 * nz(source[1]) + 2 * nz(source[2]) + nz(source[3])) / 10.0
    float detrend = switch extra_hpf
        true => coef_3 * (coef_1 * smooth + coef_2 * nz(smooth[2]) - coef_2 * nz(smooth[4]) - coef_1 * nz(smooth[6]))
        => smooth

    float quad_1 = coef_3 * (coef_1 * detrend + coef_2 * nz(detrend[2]) - coef_2 * nz(detrend[4]) - coef_1 * nz(detrend[6]))
    float phase_1 = nz(detrend[3])

    float phase_advanced = coef_3 * (coef_1 * phase_1 + coef_2 * nz(phase_1[2]) - coef_2 * nz(phase_1[4]) - coef_1 * nz(phase_1[6]))
    float quad_advanced = coef_3 * (coef_1 * quad_1 + coef_2 * nz(quad_1[2]) - coef_2 * nz(quad_1[4]) - coef_1 * nz(quad_1[6]))

    float phase_2 = phase_1 - quad_advanced
    float quad_2 = quad_1 + phase_advanced

    phase_2 := 0.2 * phase_2 + 0.8 * nz(phase_2[1])
    quad_2 := 0.2 * quad_2 + 0.8 * nz(quad_2[1])

    float real_part = phase_2 * nz(phase_2[1]) + quad_2 * nz(quad_2[1])
    float imaginary_part = phase_2 * nz(quad_2[1]) - quad_2 * nz(phase_2[1])

    real_part := 0.2 * real_part + 0.8 * nz(real_part[1])
    imaginary_part := 0.2 * imaginary_part + 0.8 * nz(imaginary_part[1])

    period := (real_part != 0 and imaginary_part != 0) ? 2 * math.pi / math.atan(imaginary_part / real_part) : 0
    period := math.min(period, 1.5 * nz(period[1], period))
    period := math.max(period, (2.0 / 3.0) * nz(period[1], period))
    period := math.min(math.max(period, minimum), maximum)
    period := period * 0.2 + nz(period[1]) * 0.8
    period

// auto period }

// filter {

ema(float source = close, float length = 9)=>
    float alpha = 2.0 / (length + 1)
    var float smoothed = na
    smoothed := alpha * source + (1 - alpha) * nz(smoothed[1])
    smoothed

biquad_lpf(float source = close, float length = 10, float Q = 0.5, simple bool enable = true)=>
    if enable
        var float a1 = na
        var float a2 = na
        var float b0 = na
        var float b1 = na
        var float b2 = na

        if barstate.isfirst or length != length[1] or Q != Q[1]
            float fc = 1 / math.max(2, length)
            float omega = 2 * math.pi * fc
            float cos_omega = math.cos(omega)

            float alpha = math.sin(omega)/(2 * Q)
            float a0 = 1 / (1 + alpha)
            float b = 1 - cos_omega
           
            a1 := -2 * cos_omega * a0
            a2 := (1 - alpha) * a0

            b0 := b / 2 * a0
            b1 := b * a0
            b2 := b0

        var float biquad = nz(source)

        float x = nz(source)
        float x1 = nz(source[1], x)
        float x2 = nz(source[2], x1)

        float y1 = nz(biquad[1], biquad)
        float y2 = nz(biquad[2], y1)

        biquad := b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2
        biquad

    else
        source

biquad_hpf(float source = close, float length = 50, bool style)=>
    var float a1 = na
    var float a2 = na
    var float b0 = na
    var float b1 = na
    var float b2 = na

    if barstate.isfirst or length != length[1]
        float fc = 1 / math.max(2, length)
        float omega = 2 * math.pi * fc
        float cos_omega = math.cos(omega)

        float alpha = switch style
            true => math.sin(omega) / math.sqrt(2)
            false => math.sin(omega)

        float a0 = 1 / (1 + alpha)
        float b = 1 + cos_omega
       
        a1 := -2 * cos_omega * a0
        a2 := (1 - alpha) * a0

        b0 := b / 2 * a0
        b1 := -b * a0
        b2 := b0

    var float biquad = source

    float x = source
    float x1 = nz(source[1], x)
    float x2 = nz(source[2], x1)

    float y1 = nz(biquad[1], biquad)
    float y2 = nz(biquad[2], y1)

    biquad := b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2
    biquad

// filter }

// kde {

type coefficients
    float[] weights
    float sumw

sinc(series float source, series float bandwidth) =>
    float omega = math.pi * source / bandwidth
    source != 0.0 ? math.sin(omega) / omega : 1.0

gaussian(float source, float bandwidth) =>
    math.exp(-math.pow(source / bandwidth, 2) / 2) / math.sqrt(2 * math.pi)

epanechnikov(float source, float bandwidth) =>
    math.abs(source / bandwidth) <= 1 ? (3/4.) * (1 - math.pow(source / bandwidth, 2)) : 0.0

logistic(float source, float bandwidth) =>
    1 / (math.exp(source / bandwidth) + 2 + math.exp(-source / bandwidth))

triangular(float source, float bandwidth) =>
    math.abs(source / bandwidth) <= 1 ? 1 - math.abs(source / bandwidth) : 0.0

kernel(float source, float bandwidth, string style)=>
    switch str.lower(style)
        "sinc" => sinc(source, bandwidth)
        "gaussian" => gaussian(source, bandwidth)
        "epanechnikov" => epanechnikov(source, bandwidth)
        "logistic" => logistic(source, bandwidth)
        "triangular" => triangular(source, bandwidth)

precalculate(float bandwidth, int length, string style)=>
    var coefficients[] c = array.new<coefficients>()
    if barstate.isfirst
        for i = 0 to length
            coefficients w = coefficients.new(array.new<float>(), 0)
            float sumw = 0

            for j = 0 to length
                diff = i - j
                weight = kernel(diff, bandwidth, style)
                sumw += weight
                w.weights.push(weight)

            w.sumw := sumw
            c.push(w)
        c
    else
        c

method kde_static(series array<float> source, coefficients[] weights)=>
    int source_size = source.size()
    array<float> est  = array.new<float>(source_size)
    if source_size > 0
        for int i = 0 to source_size - 1
            float sum  = 0.0
            float[] weight = weights.get(i).weights
            float sumw = weights.get(i).sumw
            for int j = 0 to source_size - 1
                float w = weight.get(j)
                sum  += w * array.get(source, j)
            float current_price = sum / sumw
            est.set(i, current_price >= 0.0 ? current_price : 0.0)
        est
    else
        source

method kde_dynamic(series array<float> source, float bandwidth, string style)=>
    int source_size = source.size()
    array<float> est  = array.new<float>(source_size)
    if source_size > 0
        for int i = 0 to source_size - 1
            float sum  = 0.0
            float sumw = 0
            for int j = 0 to source_size - 1
                int diff = i - j
                weight = kernel(diff, bandwidth, style)
                sumw += weight
                sum  += weight * array.get(source, j)
            float current_price = sum / sumw
            est.set(i, current_price >= 0.0 ? current_price : 0.0)
        est

// kde }

// tae helpers {

get_data(float source, int length)=>
    var float[] data = array.new<float>(length, 0)
    data.unshift(source)
    data.pop()
    data

get_data_dynamic(float source, int length)=>
    float[] data = array.new<float>(length, 0)
    for i = 0 to length - 1
        data.set(i, nz(source[i]))
    data

method half_wave_rectify(float[] self)=>
    int size = self.size()
    float[] top = array.new<float>(size, 0)
    float[] bottom = array.new<float>(size, 0)

    for i = 0 to size - 1
        float val = self.get(i)
        if val > 0
            top.set(i, val)
        else
            bottom.set(i, math.abs(val))
    [top, bottom]

method full_wave_rectify(float[] self)=>
    int size = self.size()
    float[] rectify = array.new<float>(size, 0)
    for i = 0 to size - 1
        rectify.set(i, math.abs(self.get(i)))
    rectify

method array_max(float[] self, float[] a, float[] b)=>
    for i = 0 to self.size() - 1
        self.set(i, math.max(a.get(i), b.get(i)))

method tae_static(float[] source, int its, coefficients[] weights, bool extra_smooth)=>
    float[] a = source.copy()

    for i = 0 to its - 1
        float[] c = a.copy().kde_static(weights)
        a.array_max(source, c)

    if extra_smooth
        a.kde_static(weights).first()
    else
        a.first()

method tae_dynamic(float[] source, int its, float period, string style, bool extra_smooth)=>
    float[] a = source.copy()

    if its > 0
        for i = 0 to its - 1
            float[] c = a.copy().kde_dynamic(period, style)
            a.array_max(source, c)

    if extra_smooth
        a.kde_dynamic(period, style).first()
    else
        a.first()

// tae helpers }

// envelope {

tae_envelopes_static(  series float source
                     , simple bool filter_q
                     , simple float length
                     , simple int tae_its
                     , simple int tae_length
                     , simple float tae_smoothing
                     , simple string tae_filter_style
                     , simple bool symetric
                     , simple bool extra_smooth
                     , simple int history_length)=>
                       
    float hpf = biquad_hpf(source, length, filter_q)
    float carrier = source - hpf
    float[] hpf_series = get_data(hpf, tae_length)

    coefficients[] filter_coefs = precalculate(tae_smoothing, tae_length, tae_filter_style)

    bool calculate_flag = history_length > 0 ? bar_index >= (last_bar_index - history_length) : true

    if calculate_flag
        if symetric
            float[] signal = hpf_series.full_wave_rectify()
            float tae = signal.tae_static(tae_its, filter_coefs, extra_smooth)

            float top = carrier + tae
            float bottom = carrier - tae

            [carrier, top, bottom, hpf, tae, -tae]

        else
            [top_signal, bottom_signal] = hpf_series.half_wave_rectify()
            float top_tae = top_signal.tae_static(tae_its, filter_coefs, extra_smooth)
            float bottom_tae = bottom_signal.tae_static(tae_its, filter_coefs, extra_smooth)

            float top = carrier + top_tae
            float bottom = carrier - bottom_tae

            [carrier, top, bottom, hpf, top_tae, -bottom_tae]

tae_envelopes_dynamic( series float source
                     , simple bool filter_q
                     , simple int its
                     , simple float filter_period_multiplier
                     , simple float filter_min_period
                     , simple float filter_max_period
                     , simple float tae_period_multiplier
                     , simple float tae_min_period
                     , simple float tae_max_period
                     , simple string tae_filter_style
                     , simple bool symetric
                     , simple bool extra_smooth
                     , simple bool extra_hpf
                     , simple int history_length)=>

    float period = nz(auto_period(source, filter_min_period, filter_max_period), filter_min_period) * filter_period_multiplier

    float hpf = biquad_hpf(source, period, filter_q)
    float carrier = source - hpf

    float hpf_period = nz(auto_period(hpf, tae_min_period, tae_max_period, extra_hpf), tae_min_period) * tae_period_multiplier
    int int_period = math.max(1, int(hpf_period))
    float[] hpf_series = get_data_dynamic(hpf, int_period)

    bool calculate_flag = history_length > 0 ? bar_index >= (last_bar_index - history_length) : true

    if calculate_flag
        if symetric
            float[] signal = hpf_series.full_wave_rectify()

            float tae = signal.tae_dynamic(its, hpf_period, tae_filter_style, extra_smooth)

            float top = carrier + tae
            float bottom = carrier - tae

            [carrier, top, bottom, hpf, tae, -tae]

        else
            [top_signal, bottom_signal] = hpf_series.half_wave_rectify()

            float top_tae = top_signal.tae_dynamic(its, hpf_period * 0.5, tae_filter_style, extra_smooth)
            float bottom_tae = bottom_signal.tae_dynamic(its, hpf_period * 0.5, tae_filter_style, extra_smooth)

            float top = carrier + top_tae
            float bottom = carrier - bottom_tae

            [carrier, top, bottom, hpf, top_tae, -bottom_tae]

tae_envelopes( series float source
             , simple bool filter_q
             , simple float length
             , simple int tae_its
             , simple int tae_length
             , simple float tae_smoothing
             , simple float filter_period_multiplier
             , simple float filter_min_period
             , simple float filter_max_period
             , simple float tae_period_multiplier
             , simple float tae_min_period
             , simple float tae_max_period
             , simple string tae_filter_style
             , simple bool symetric
             , simple string envelope_style
             , simple bool extra_smooth
             , simple bool extra_hpf
             , simple int history_length)=>

    if envelope_style == "Static"
        [carrier, top, bottom, hpf, top_tae, bottom_tae] = tae_envelopes_static( source
                                                                               , filter_q
                                                                               , length
                                                                               , tae_its
                                                                               , tae_length
                                                                               , tae_smoothing
                                                                               , tae_filter_style
                                                                               , symetric
                                                                               , extra_smooth
                                                                               , history_length)
    else
        [carrier, top, bottom, hpf, top_tae, bottom_tae] = tae_envelopes_dynamic(source
                                                                               , filter_q
                                                                               , tae_its
                                                                               , filter_period_multiplier
                                                                               , filter_min_period
                                                                               , filter_max_period
                                                                               , tae_period_multiplier
                                                                               , tae_min_period
                                                                               , tae_max_period
                                                                               , tae_filter_style
                                                                               , symetric
                                                                               , extra_smooth
                                                                               , extra_hpf
                                                                               , history_length)

// envelope }

// } <FUNCTIONS>

// { <INPUTS>

// main settings {

const string main_settings = "Main Settings"
const string history_tip = "Pick how much historical data to show. When set to 0 it will display all."
const string iteration_tip = "Number of iterations used in the envelope algorithm."
const string kernel_tip = "Filter kernel used in the kernel density estimator for smoothing the envelope."
const string envelope_style_tip = "Dynamic utilizes automatic dominant period analysis. Static allows you to pick a static setting for the envelope."
const string symmetry_tip = "Allows you to have symmetric or asymmetric envelopes."
const string extra_smooth_tip = "Makes the envelop smoother but reduces responsiveness."
const string q_tip = "Has the effect of increasing the period of the filter."

float source = input.source(close, "Source", group = main_settings)
int history_length = input.int(2000, "History", minval = 0, tooltip = history_tip, group = main_settings)
int tae_its = input.int(10, "Iterations", minval = 1, tooltip = iteration_tip, group = main_settings)
string tae_filter_style = input.string("Epanechnikov", "Kernel Style", ["Sinc", "Gaussian", "Epanechnikov", "Logistic", "Triangular"], tooltip = kernel_tip, group = main_settings)
string envelope_style = input.string("Dynamic", "Envelope Style", ["Static", "Dynamic"], tooltip = envelope_style_tip, group = main_settings)
bool filter_q = input.bool(false, "High Q", tooltip = q_tip, group = main_settings)
bool symetric = input.bool(false, "Symetric", tooltip = symmetry_tip, group = main_settings)
bool extra_smooth = input.bool(true, "Smooth Envelopes", tooltip = extra_smooth_tip, group = main_settings)

// main settings }

// dynamic settings {

const string dynamic_group = "Dynamic Settings"
const string detrend_tip = "Enable when using a long filter period."
bool extra_hpf = input.bool(false, "Extra Detrend", tooltip = detrend_tip, group = dynamic_group)

float filter_period_multiplier = input.float(2, "Filter Period Multiplier", minval = 0.125, step = 0.125, group = dynamic_group)
float filter_min_period = input.float(9, "Filter Period | Min: ", minval = 0.125, step = 0.125, inline = "Filter Dynamic", group = dynamic_group)
float filter_max_period = input.float(128, "Max: ", minval = 0.125, step = 0.125, inline = "Filter Dynamic", group = dynamic_group)

float tae_period_multiplier = input.float(1, "Envelope Period Multiplier", minval = 0.125, step = 0.125, group = dynamic_group)
float tae_min_period = input.float(9, "Envelope Period | Min: ", minval = 0.125, step = 0.125, inline = "Envelope Dynamic", group = dynamic_group)
float tae_max_period = input.float(64, "Max: ", minval = 0.125, step = 0.125, inline = "Envelope Dynamic", group = dynamic_group)

// dynamic settings }

// static settings {

const string static_group = "Static Settings"
float length = input.float(100, "Filter Period", minval = 2, step = 0.5, group = static_group)
int tae_length = input.int(20, "Envelope Period", minval = 1, group = static_group)
float tae_smoothing = input.float(40, "TAE Smoothing", minval = 0, step = 0.125, group = static_group)

// static settings }

// oscillator settings {

const string osc_settings = "Oscillator Settings"
bool enable_osc_smoothing = input.bool(true, "Enable Smoothing", group = osc_settings)
float osc_period = input.float(10, "Oscillator Period", minval = 2, step = 0.5, group = osc_settings)
float osc_q = input.float(0.5, "Oscillator Q", minval = 0.125, step = 0.125, group = osc_settings)
float signal_period = input.float(10, "Signal Period", minval = 2, step = 0.5, group = osc_settings)

// oscillator settings }

// visual settings {

const string visual_group = "Visual Settings"
bool show_overlay = input.bool(true, "Show Overlay", group = visual_group)
color filter_color = input.color(#1C7FD0, "Center", group = visual_group)
color top_band_color = input.color(#17CC35, "Top Band", group = visual_group)
color bottom_band_color = input.color(#EF292C, "Bottom Band", group = visual_group)
color osc_signal_color = input.color(#F5BB00, "Oscillator Signal", group = visual_group)
int line_width = input.int(1, "Line Width", minval = 1, group = visual_group)
int fill_alpha = input.int(90, "Fill Alpha", minval = 0, maxval = 100, group = visual_group)

// visual settings }

// } <INPUTS>

// { <CALCULATIONS>

// tae {

[carrier, top, bottom, hpf, top_tae, bottom_tae] = tae_envelopes(source
                                                               , filter_q
                                                               , length
                                                               , tae_its
                                                               , tae_length
                                                               , tae_smoothing
                                                               , filter_period_multiplier
                                                               , filter_min_period
                                                               , filter_max_period
                                                               , tae_period_multiplier
                                                               , tae_min_period
                                                               , tae_max_period
                                                               , tae_filter_style
                                                               , symetric
                                                               , envelope_style
                                                               , extra_smooth
                                                               , extra_hpf
                                                               , history_length)

// tae }

// oscillator {

float hpf_signal = biquad_lpf(hpf, osc_period, osc_q, enable_osc_smoothing)
float osc_signal = ema(hpf_signal, signal_period)

// oscillator }

// } <CALCULATIONS>

// { <PLOT>

// overlay {

display_overlay_main = show_overlay ? display.all : display.none
display_overlay_glow = show_overlay ? display.pane : display.none

top_band = plot(top, "Envelope Top", top_band_color, line_width, display = display_overlay_main, force_overlay = true)
plot(top, "Envelope Top", top_band_color.new_alpha(80), line_width + 2, display = display_overlay_glow, force_overlay = true)
plot(top, "Envelope Top", top_band_color.new_alpha(80), line_width + 3, display = display_overlay_glow, force_overlay = true)
plot(top, "Envelope Top", top_band_color.new_alpha(90), line_width + 5, display = display_overlay_glow, force_overlay = true)

bottom_band = plot(bottom, "Envelope Bottom", bottom_band_color, line_width, display = display_overlay_main, force_overlay = true)
plot(bottom, "Envelope Bottom", bottom_band_color.new_alpha(80), line_width + 2, display = display_overlay_glow, force_overlay = true)
plot(bottom, "Envelope Bottom", bottom_band_color.new_alpha(80), line_width + 3, display = display_overlay_glow, force_overlay = true)
plot(bottom, "Envelope Bottom", bottom_band_color.new_alpha(90), line_width + 5, display = display_overlay_glow, force_overlay = true)

filter = plot(carrier, "Filter", filter_color, line_width, display = display_overlay_main, force_overlay = true)
plot(carrier, "Filter", filter_color.new_alpha(80), line_width + 2, display = display_overlay_glow, force_overlay = true)
plot(carrier, "Filter", filter_color.new_alpha(80), line_width + 3, display = display_overlay_glow, force_overlay = true)
plot(carrier, "Filter", filter_color.new_alpha(90), line_width + 5, display = display_overlay_glow, force_overlay = true)

fill(top_band, filter, top, carrier, top_band_color.new_alpha(fill_alpha), color.new(top_band_color, 100), "Top Fill", display_overlay_main)
fill(filter, bottom_band, carrier, bottom, color.new(bottom_band_color, 100), bottom_band_color.new_alpha(fill_alpha), "Bottom Fill", display_overlay_main)

// overlay }

// osc {

zero_line = plot(0, "Zero Line", color.silver)

upper_band = plot(top_tae, "Oscillator Envelope Top", top_band_color, line_width)
plot(top_tae, "Oscillator Envelope Top", top_band_color.new_alpha(80), line_width + 3, display = display.pane)
plot(top_tae, "Oscillator Envelope Top", top_band_color.new_alpha(90), line_width + 5, display = display.pane)

lower_band = plot(bottom_tae, "Oscillator Envelope Bottom", bottom_band_color, line_width)
plot(bottom_tae, "Oscillator Envelope Bottom", bottom_band_color.new_alpha(80), line_width + 3, display = display.pane)
plot(bottom_tae, "Oscillator Envelope Bottom", bottom_band_color.new_alpha(90), line_width + 5, display = display.pane)

plot(osc_signal, "Oscillator Signal", osc_signal_color, line_width)
plot(osc_signal, "Oscillator Signal", osc_signal_color.new_alpha(80), line_width + 3, display = display.pane)
plot(osc_signal, "Oscillator Signal", osc_signal_color.new_alpha(90), line_width + 5, display = display.pane)

plot(hpf_signal, "Oscillator", filter_color, line_width)
plot(hpf_signal, "Oscillator", filter_color.new_alpha(80), line_width + 3, display = display.pane)
plot(hpf_signal, "Oscillator", filter_color.new_alpha(90), line_width + 5, display = display.pane)

fill(upper_band, zero_line, top_tae, 0, top_band_color.new_alpha(fill_alpha), color.new(top_band_color, 100), "Top Fill")
fill(zero_line, lower_band, 0, bottom_tae, color.new(bottom_band_color, 100), bottom_band_color.new_alpha(fill_alpha), "Bottom Fill")

// osc }

// } <PLOT>

0

107

https://www.tradingview.com/script/AlUa … lopes-TAE/

Код для правки
-------------------------
--------------------

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// The_Peaceful_Lizard

//@version=5
indicator("True Amplitude Envelopes (TAE)")

// { <FUNCTIONS>

// color {

method scale_alpha(float self, float alpha = 80)=>
    float invert = 100 - alpha
    self * invert / 100

method new_alpha(color self, float alpha = 80)=>
    color.new(self, alpha + color.t(self).scale_alpha(alpha))

// color }

// auto period {

auto_period(float source, simple float minimum, simple float maximum, simple bool extra_hpf = true)=>
    float period = 0
    float coef_1 = 0.0962
    float coef_2 = 0.5769
    float coef_3 = 0.075 * nz(period[1]) + 0.54
   
    float smooth = (4 * source + 3 * nz(source[1]) + 2 * nz(source[2]) + nz(source[3])) / 10.0
    float detrend = switch extra_hpf
        true => coef_3 * (coef_1 * smooth + coef_2 * nz(smooth[2]) - coef_2 * nz(smooth[4]) - coef_1 * nz(smooth[6]))
        => smooth

    float quad_1 = coef_3 * (coef_1 * detrend + coef_2 * nz(detrend[2]) - coef_2 * nz(detrend[4]) - coef_1 * nz(detrend[6]))
    float phase_1 = nz(detrend[3])

    float phase_advanced = coef_3 * (coef_1 * phase_1 + coef_2 * nz(phase_1[2]) - coef_2 * nz(phase_1[4]) - coef_1 * nz(phase_1[6]))
    float quad_advanced = coef_3 * (coef_1 * quad_1 + coef_2 * nz(quad_1[2]) - coef_2 * nz(quad_1[4]) - coef_1 * nz(quad_1[6]))

    float phase_2 = phase_1 - quad_advanced
    float quad_2 = quad_1 + phase_advanced

    phase_2 := 0.2 * phase_2 + 0.8 * nz(phase_2[1])
    quad_2 := 0.2 * quad_2 + 0.8 * nz(quad_2[1])

    float real_part = phase_2 * nz(phase_2[1]) + quad_2 * nz(quad_2[1])
    float imaginary_part = phase_2 * nz(quad_2[1]) - quad_2 * nz(phase_2[1])

    real_part := 0.2 * real_part + 0.8 * nz(real_part[1])
    imaginary_part := 0.2 * imaginary_part + 0.8 * nz(imaginary_part[1])

    period := (real_part != 0 and imaginary_part != 0) ? 2 * math.pi / math.atan(imaginary_part / real_part) : 0
    period := math.min(period, 1.5 * nz(period[1], period))
    period := math.max(period, (2.0 / 3.0) * nz(period[1], period))
    period := math.min(math.max(period, minimum), maximum)
    period := period * 0.2 + nz(period[1]) * 0.8
    period

// auto period }

// filter {

ema(float source = close, float length = 9)=>
    float alpha = 2.0 / (length + 1)
    var float smoothed = na
    smoothed := alpha * source + (1 - alpha) * nz(smoothed[1])
    smoothed

biquad_lpf(float source = close, float length = 10, float Q = 0.5, simple bool enable = true)=>
    if enable
        var float a1 = na
        var float a2 = na
        var float b0 = na
        var float b1 = na
        var float b2 = na

        if barstate.isfirst or length != length[1] or Q != Q[1]
            float fc = 1 / math.max(2, length)
            float omega = 2 * math.pi * fc
            float cos_omega = math.cos(omega)

            float alpha = math.sin(omega)/(2 * Q)
            float a0 = 1 / (1 + alpha)
            float b = 1 - cos_omega
           
            a1 := -2 * cos_omega * a0
            a2 := (1 - alpha) * a0

            b0 := b / 2 * a0
            b1 := b * a0
            b2 := b0

        var float biquad = nz(source)

        float x = nz(source)
        float x1 = nz(source[1], x)
        float x2 = nz(source[2], x1)

        float y1 = nz(biquad[1], biquad)
        float y2 = nz(biquad[2], y1)

        biquad := b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2
        biquad

    else
        source

biquad_hpf(float source = close, float length = 50, bool style)=>
    var float a1 = na
    var float a2 = na
    var float b0 = na
    var float b1 = na
    var float b2 = na

    if barstate.isfirst or length != length[1]
        float fc = 1 / math.max(2, length)
        float omega = 2 * math.pi * fc
        float cos_omega = math.cos(omega)

        float alpha = switch style
            true => math.sin(omega) / math.sqrt(2)
            false => math.sin(omega)

        float a0 = 1 / (1 + alpha)
        float b = 1 + cos_omega
       
        a1 := -2 * cos_omega * a0
        a2 := (1 - alpha) * a0

        b0 := b / 2 * a0
        b1 := -b * a0
        b2 := b0

    var float biquad = source

    float x = source
    float x1 = nz(source[1], x)
    float x2 = nz(source[2], x1)

    float y1 = nz(biquad[1], biquad)
    float y2 = nz(biquad[2], y1)

    biquad := b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2
    biquad

// filter }

// kde {

type coefficients
    float[] weights
    float sumw

sinc(series float source, series float bandwidth) =>
    float omega = math.pi * source / bandwidth
    source != 0.0 ? math.sin(omega) / omega : 1.0

gaussian(float source, float bandwidth) =>
    math.exp(-math.pow(source / bandwidth, 2) / 2) / math.sqrt(2 * math.pi)

epanechnikov(float source, float bandwidth) =>
    math.abs(source / bandwidth) <= 1 ? (3/4.) * (1 - math.pow(source / bandwidth, 2)) : 0.0

logistic(float source, float bandwidth) =>
    1 / (math.exp(source / bandwidth) + 2 + math.exp(-source / bandwidth))

triangular(float source, float bandwidth) =>
    math.abs(source / bandwidth) <= 1 ? 1 - math.abs(source / bandwidth) : 0.0

kernel(float source, float bandwidth, string style)=>
    switch str.lower(style)
        "sinc" => sinc(source, bandwidth)
        "gaussian" => gaussian(source, bandwidth)
        "epanechnikov" => epanechnikov(source, bandwidth)
        "logistic" => logistic(source, bandwidth)
        "triangular" => triangular(source, bandwidth)

precalculate(float bandwidth, int length, string style)=>
    var coefficients[] c = array.new<coefficients>()
    if barstate.isfirst
        for i = 0 to length
            coefficients w = coefficients.new(array.new<float>(), 0)
            float sumw = 0

            for j = 0 to length
                diff = i - j
                weight = kernel(diff, bandwidth, style)
                sumw += weight
                w.weights.push(weight)

            w.sumw := sumw
            c.push(w)
        c
    else
        c

method kde_static(series array<float> source, coefficients[] weights)=>
    int source_size = source.size()
    array<float> est  = array.new<float>(source_size)
    if source_size > 0
        for int i = 0 to source_size - 1
            float sum  = 0.0
            float[] weight = weights.get(i).weights
            float sumw = weights.get(i).sumw
            for int j = 0 to source_size - 1
                float w = weight.get(j)
                sum  += w * array.get(source, j)
            float current_price = sum / sumw
            est.set(i, current_price >= 0.0 ? current_price : 0.0)
        est
    else
        source

method kde_dynamic(series array<float> source, float bandwidth, string style)=>
    int source_size = source.size()
    array<float> est  = array.new<float>(source_size)
    if source_size > 0
        for int i = 0 to source_size - 1
            float sum  = 0.0
            float sumw = 0
            for int j = 0 to source_size - 1
                int diff = i - j
                weight = kernel(diff, bandwidth, style)
                sumw += weight
                sum  += weight * array.get(source, j)
            float current_price = sum / sumw
            est.set(i, current_price >= 0.0 ? current_price : 0.0)
        est

// kde }

// tae helpers {

get_data(float source, int length)=>
    var float[] data = array.new<float>(length, 0)
    data.unshift(source)
    data.pop()
    data

get_data_dynamic(float source, int length)=>
    float[] data = array.new<float>(length, 0)
    for i = 0 to length - 1
        data.set(i, nz(source[i]))
    data

method half_wave_rectify(float[] self)=>
    int size = self.size()
    float[] top = array.new<float>(size, 0)
    float[] bottom = array.new<float>(size, 0)

    for i = 0 to size - 1
        float val = self.get(i)
        if val > 0
            top.set(i, val)
        else
            bottom.set(i, math.abs(val))
    [top, bottom]

method full_wave_rectify(float[] self)=>
    int size = self.size()
    float[] rectify = array.new<float>(size, 0)
    for i = 0 to size - 1
        rectify.set(i, math.abs(self.get(i)))
    rectify

method array_max(float[] self, float[] a, float[] b)=>
    for i = 0 to self.size() - 1
        self.set(i, math.max(a.get(i), b.get(i)))

method tae_static(float[] source, int its, coefficients[] weights, bool extra_smooth)=>
    float[] a = source.copy()

    for i = 0 to its - 1
        float[] c = a.copy().kde_static(weights)
        a.array_max(source, c)

    if extra_smooth
        a.kde_static(weights).first()
    else
        a.first()

method tae_dynamic(float[] source, int its, float period, string style, bool extra_smooth)=>
    float[] a = source.copy()

    if its > 0
        for i = 0 to its - 1
            float[] c = a.copy().kde_dynamic(period, style)
            a.array_max(source, c)

    if extra_smooth
        a.kde_dynamic(period, style).first()
    else
        a.first()

// tae helpers }

// envelope {

tae_envelopes_static(  series float source
                     , simple bool filter_q
                     , simple float length
                     , simple int tae_its
                     , simple int tae_length
                     , simple float tae_smoothing
                     , simple string tae_filter_style
                     , simple bool symetric
                     , simple bool extra_smooth
                     , simple int history_length)=>
                       
    float hpf = biquad_hpf(source, length, filter_q)
    float carrier = source - hpf
    float[] hpf_series = get_data(hpf, tae_length)

    coefficients[] filter_coefs = precalculate(tae_smoothing, tae_length, tae_filter_style)

    bool calculate_flag = history_length > 0 ? bar_index >= (last_bar_index - history_length) : true

    if calculate_flag
        if symetric
            float[] signal = hpf_series.full_wave_rectify()
            float tae = signal.tae_static(tae_its, filter_coefs, extra_smooth)

            float top = carrier + tae
            float bottom = carrier - tae

            [carrier, top, bottom, hpf, tae, -tae]

        else
            [top_signal, bottom_signal] = hpf_series.half_wave_rectify()
            float top_tae = top_signal.tae_static(tae_its, filter_coefs, extra_smooth)
            float bottom_tae = bottom_signal.tae_static(tae_its, filter_coefs, extra_smooth)

            float top = carrier + top_tae
            float bottom = carrier - bottom_tae

            [carrier, top, bottom, hpf, top_tae, -bottom_tae]

tae_envelopes_dynamic( series float source
                     , simple bool filter_q
                     , simple int its
                     , simple float filter_period_multiplier
                     , simple float filter_min_period
                     , simple float filter_max_period
                     , simple float tae_period_multiplier
                     , simple float tae_min_period
                     , simple float tae_max_period
                     , simple string tae_filter_style
                     , simple bool symetric
                     , simple bool extra_smooth
                     , simple bool extra_hpf
                     , simple int history_length)=>

    float period = nz(auto_period(source, filter_min_period, filter_max_period), filter_min_period) * filter_period_multiplier

    float hpf = biquad_hpf(source, period, filter_q)
    float carrier = source - hpf

    float hpf_period = nz(auto_period(hpf, tae_min_period, tae_max_period, extra_hpf), tae_min_period) * tae_period_multiplier
    int int_period = math.max(1, int(hpf_period))
    float[] hpf_series = get_data_dynamic(hpf, int_period)

    bool calculate_flag = history_length > 0 ? bar_index >= (last_bar_index - history_length) : true

    if calculate_flag
        if symetric
            float[] signal = hpf_series.full_wave_rectify()

            float tae = signal.tae_dynamic(its, hpf_period, tae_filter_style, extra_smooth)

            float top = carrier + tae
            float bottom = carrier - tae

            [carrier, top, bottom, hpf, tae, -tae]

        else
            [top_signal, bottom_signal] = hpf_series.half_wave_rectify()

            float top_tae = top_signal.tae_dynamic(its, hpf_period * 0.5, tae_filter_style, extra_smooth)
            float bottom_tae = bottom_signal.tae_dynamic(its, hpf_period * 0.5, tae_filter_style, extra_smooth)

            float top = carrier + top_tae
            float bottom = carrier - bottom_tae

            [carrier, top, bottom, hpf, top_tae, -bottom_tae]

tae_envelopes( series float source
             , simple bool filter_q
             , simple float length
             , simple int tae_its
             , simple int tae_length
             , simple float tae_smoothing
             , simple float filter_period_multiplier
             , simple float filter_min_period
             , simple float filter_max_period
             , simple float tae_period_multiplier
             , simple float tae_min_period
             , simple float tae_max_period
             , simple string tae_filter_style
             , simple bool symetric
             , simple string envelope_style
             , simple bool extra_smooth
             , simple bool extra_hpf
             , simple int history_length)=>

    if envelope_style == "Static"
        [carrier, top, bottom, hpf, top_tae, bottom_tae] = tae_envelopes_static( source
                                                                               , filter_q
                                                                               , length
                                                                               , tae_its
                                                                               , tae_length
                                                                               , tae_smoothing
                                                                               , tae_filter_style
                                                                               , symetric
                                                                               , extra_smooth
                                                                               , history_length)
    else
        [carrier, top, bottom, hpf, top_tae, bottom_tae] = tae_envelopes_dynamic(source
                                                                               , filter_q
                                                                               , tae_its
                                                                               , filter_period_multiplier
                                                                               , filter_min_period
                                                                               , filter_max_period
                                                                               , tae_period_multiplier
                                                                               , tae_min_period
                                                                               , tae_max_period
                                                                               , tae_filter_style
                                                                               , symetric
                                                                               , extra_smooth
                                                                               , extra_hpf
                                                                               , history_length)

// envelope }

// } <FUNCTIONS>

// { <INPUTS>

// main settings {

const string main_settings = "Main Settings"
const string history_tip = "Pick how much historical data to show. When set to 0 it will display all."
const string iteration_tip = "Number of iterations used in the envelope algorithm."
const string kernel_tip = "Filter kernel used in the kernel density estimator for smoothing the envelope."
const string envelope_style_tip = "Dynamic utilizes automatic dominant period analysis. Static allows you to pick a static setting for the envelope."
const string symmetry_tip = "Allows you to have symmetric or asymmetric envelopes."
const string extra_smooth_tip = "Makes the envelop smoother but reduces responsiveness."
const string q_tip = "Has the effect of increasing the period of the filter."

float source = input.source(close, "Source", group = main_settings)
int history_length = input.int(2000, "History", minval = 0, tooltip = history_tip, group = main_settings)
int tae_its = input.int(10, "Iterations", minval = 1, tooltip = iteration_tip, group = main_settings)
string tae_filter_style = input.string("Epanechnikov", "Kernel Style", ["Sinc", "Gaussian", "Epanechnikov", "Logistic", "Triangular"], tooltip = kernel_tip, group = main_settings)
string envelope_style = input.string("Dynamic", "Envelope Style", ["Static", "Dynamic"], tooltip = envelope_style_tip, group = main_settings)
bool filter_q = input.bool(false, "High Q", tooltip = q_tip, group = main_settings)
bool symetric = input.bool(false, "Symetric", tooltip = symmetry_tip, group = main_settings)
bool extra_smooth = input.bool(true, "Smooth Envelopes", tooltip = extra_smooth_tip, group = main_settings)

// main settings }

// dynamic settings {

const string dynamic_group = "Dynamic Settings"
const string detrend_tip = "Enable when using a long filter period."
bool extra_hpf = input.bool(false, "Extra Detrend", tooltip = detrend_tip, group = dynamic_group)

float filter_period_multiplier = input.float(2, "Filter Period Multiplier", minval = 0.125, step = 0.125, group = dynamic_group)
float filter_min_period = input.float(9, "Filter Period | Min: ", minval = 0.125, step = 0.125, inline = "Filter Dynamic", group = dynamic_group)
float filter_max_period = input.float(128, "Max: ", minval = 0.125, step = 0.125, inline = "Filter Dynamic", group = dynamic_group)

float tae_period_multiplier = input.float(1, "Envelope Period Multiplier", minval = 0.125, step = 0.125, group = dynamic_group)
float tae_min_period = input.float(9, "Envelope Period | Min: ", minval = 0.125, step = 0.125, inline = "Envelope Dynamic", group = dynamic_group)
float tae_max_period = input.float(64, "Max: ", minval = 0.125, step = 0.125, inline = "Envelope Dynamic", group = dynamic_group)

// dynamic settings }

// static settings {

const string static_group = "Static Settings"
float length = input.float(100, "Filter Period", minval = 2, step = 0.5, group = static_group)
int tae_length = input.int(20, "Envelope Period", minval = 1, group = static_group)
float tae_smoothing = input.float(40, "TAE Smoothing", minval = 0, step = 0.125, group = static_group)

// static settings }

// oscillator settings {

const string osc_settings = "Oscillator Settings"
bool enable_osc_smoothing = input.bool(true, "Enable Smoothing", group = osc_settings)
float osc_period = input.float(10, "Oscillator Period", minval = 2, step = 0.5, group = osc_settings)
float osc_q = input.float(0.5, "Oscillator Q", minval = 0.125, step = 0.125, group = osc_settings)
float signal_period = input.float(10, "Signal Period", minval = 2, step = 0.5, group = osc_settings)

// oscillator settings }

// visual settings {

const string visual_group = "Visual Settings"
bool show_overlay = input.bool(true, "Show Overlay", group = visual_group)
color filter_color = input.color(#1C7FD0, "Center", group = visual_group)
color top_band_color = input.color(#17CC35, "Top Band", group = visual_group)
color bottom_band_color = input.color(#EF292C, "Bottom Band", group = visual_group)
color osc_signal_color = input.color(#F5BB00, "Oscillator Signal", group = visual_group)
int line_width = input.int(1, "Line Width", minval = 1, group = visual_group)
int fill_alpha = input.int(90, "Fill Alpha", minval = 0, maxval = 100, group = visual_group)

// visual settings }

// } <INPUTS>

// { <CALCULATIONS>

// tae {

[carrier, top, bottom, hpf, top_tae, bottom_tae] = tae_envelopes(source
                                                               , filter_q
                                                               , length
                                                               , tae_its
                                                               , tae_length
                                                               , tae_smoothing
                                                               , filter_period_multiplier
                                                               , filter_min_period
                                                               , filter_max_period
                                                               , tae_period_multiplier
                                                               , tae_min_period
                                                               , tae_max_period
                                                               , tae_filter_style
                                                               , symetric
                                                               , envelope_style
                                                               , extra_smooth
                                                               , extra_hpf
                                                               , history_length)

// tae }

// oscillator {

float hpf_signal = biquad_lpf(hpf, osc_period, osc_q, enable_osc_smoothing)
float osc_signal = ema(hpf_signal, signal_period)

// oscillator }

// } <CALCULATIONS>

// { <PLOT>

// overlay {

display_overlay_main = show_overlay ? display.all : display.none
display_overlay_glow = show_overlay ? display.pane : display.none

top_band = plot(top, "Envelope Top", top_band_color, line_width, display = display_overlay_main, force_overlay = true)
plot(top, "Envelope Top", top_band_color.new_alpha(80), line_width + 2, display = display_overlay_glow, force_overlay = true)
plot(top, "Envelope Top", top_band_color.new_alpha(80), line_width + 3, display = display_overlay_glow, force_overlay = true)
plot(top, "Envelope Top", top_band_color.new_alpha(90), line_width + 5, display = display_overlay_glow, force_overlay = true)

bottom_band = plot(bottom, "Envelope Bottom", bottom_band_color, line_width, display = display_overlay_main, force_overlay = true)
plot(bottom, "Envelope Bottom", bottom_band_color.new_alpha(80), line_width + 2, display = display_overlay_glow, force_overlay = true)
plot(bottom, "Envelope Bottom", bottom_band_color.new_alpha(80), line_width + 3, display = display_overlay_glow, force_overlay = true)
plot(bottom, "Envelope Bottom", bottom_band_color.new_alpha(90), line_width + 5, display = display_overlay_glow, force_overlay = true)

filter = plot(carrier, "Filter", filter_color, line_width, display = display_overlay_main, force_overlay = true)
plot(carrier, "Filter", filter_color.new_alpha(80), line_width + 2, display = display_overlay_glow, force_overlay = true)
plot(carrier, "Filter", filter_color.new_alpha(80), line_width + 3, display = display_overlay_glow, force_overlay = true)
plot(carrier, "Filter", filter_color.new_alpha(90), line_width + 5, display = display_overlay_glow, force_overlay = true)

fill(top_band, filter, top, carrier, top_band_color.new_alpha(fill_alpha), color.new(top_band_color, 100), "Top Fill", display_overlay_main)
fill(filter, bottom_band, carrier, bottom, color.new(bottom_band_color, 100), bottom_band_color.new_alpha(fill_alpha), "Bottom Fill", display_overlay_main)

// overlay }

// osc {

zero_line = plot(0, "Zero Line", color.silver)

upper_band = plot(top_tae, "Oscillator Envelope Top", top_band_color, line_width)
plot(top_tae, "Oscillator Envelope Top", top_band_color.new_alpha(80), line_width + 3, display = display.pane)
plot(top_tae, "Oscillator Envelope Top", top_band_color.new_alpha(90), line_width + 5, display = display.pane)

lower_band = plot(bottom_tae, "Oscillator Envelope Bottom", bottom_band_color, line_width)
plot(bottom_tae, "Oscillator Envelope Bottom", bottom_band_color.new_alpha(80), line_width + 3, display = display.pane)
plot(bottom_tae, "Oscillator Envelope Bottom", bottom_band_color.new_alpha(90), line_width + 5, display = display.pane)

plot(osc_signal, "Oscillator Signal", osc_signal_color, line_width)
plot(osc_signal, "Oscillator Signal", osc_signal_color.new_alpha(80), line_width + 3, display = display.pane)
plot(osc_signal, "Oscillator Signal", osc_signal_color.new_alpha(90), line_width + 5, display = display.pane)

plot(hpf_signal, "Oscillator", filter_color, line_width)
plot(hpf_signal, "Oscillator", filter_color.new_alpha(80), line_width + 3, display = display.pane)
plot(hpf_signal, "Oscillator", filter_color.new_alpha(90), line_width + 5, display = display.pane)

fill(upper_band, zero_line, top_tae, 0, top_band_color.new_alpha(fill_alpha), color.new(top_band_color, 100), "Top Fill")
fill(zero_line, lower_band, 0, bottom_tae, color.new(bottom_band_color, 100), bottom_band_color.new_alpha(fill_alpha), "Bottom Fill")

// osc }

// } <PLOT>

0

108

https://www.extrica.com/article/16020

0

109

СУММАРНЫЙ

//@version=6

indicator('<NINJA5>', '<NINJA5>', true)
// Настройки МТФ
mtf = input.timeframe('', 'Таймфрейм')

// ВЫБОР ТИПА МУВИНГА
ma_type = input.string('EMA', 'Тип мувинга', options = ['SMA', 'EMA', 'WMA', 'Hull MA', 'VWMA', 'TEMA', 'JMA', 'LSMA', 'ALMA', 'Vidya', 'ZLEMA', 'FRAMA'])

ma_length = input.int(28, 'Период мувинга')
ma_source = input.source(hl2, 'Источник для MA')

// Дополнительные параметры для некоторых MA
ma_offset = input.int(0, 'Смещение MA')
jma_power = input.float(2.0, 'JMA: Мощность', minval = 1, maxval = 10, step = 0.1)
alma_offset = input.float(0.85, 'ALMA: Смещение', minval = 0, maxval = 1, step = 0.01)
alma_sigma = input.float(6.0, 'ALMA: Сигма', minval = 1, maxval = 10, step = 0.1)

// Настройки конвертов
lookback1 = input.int(28, 'Период волатильности 1')
mult1 = input.float(0.1, 'Множитель 1', step = 0.01)
lookback2 = input.int(28, 'Период волатильности 2')
mult2 = input.float(0.1, 'Множитель 2', step = 0.01)

// Получаем данные с нужного ТФ
src = request.security(syminfo.tickerid, mtf, ma_source)
high_mtf = request.security(syminfo.tickerid, mtf, high)
low_mtf = request.security(syminfo.tickerid, mtf, low)

// ФУНКЦИИ РАСЧЕТА РАЗНЫХ MA
// Hull Moving Average
hma(_src, _length) =>
    _wma1 = ta.wma(_src, _length / 2)
    _wma2 = ta.wma(_src, _length)
    2 * _wma1 - _wma2

// Volume Weighted Moving Average
vwma(_src, _length) =>
    _sum = math.sum(_src * volume, _length)
    _vol = math.sum(volume, _length)
    _sum / _vol

// Triple Exponential Moving Average
tema(_src, _length) =>
    _ema1 = ta.ema(_src, _length)
    _ema2 = ta.ema(_ema1, _length)
    _ema3 = ta.ema(_ema2, _length)
    3 * _ema1 - 3 * _ema2 + _ema3

// Jurik Moving Average (упрощенная версия)
jma(_src, _length, _power) =>
    _beta = 0.45 * (_length - 1) / (0.45 * (_length - 1) + 2)
    _alpha = math.pow(_beta, _power)
    _jma = 0.0
    _jma := _alpha * _src + (1 - _alpha) * nz(_jma[1])
    _jma

// Least Squares Moving Average
lsma(_src, _length) =>
    _sum_x = _length * (_length - 1) / 2
    _sum_x2 = _length * (_length - 1) * (2 * _length - 1) / 6
    _sum_xy = 0.0
    _sum_y = 0.0
    for i = 0 to _length - 1 by 1
        _sum_xy := _sum_xy + i * _src[i]
        _sum_y := _sum_y + _src[i]
        _sum_y
    _slope = (_length * _sum_xy - _sum_x * _sum_y) / (_length * _sum_x2 - _sum_x * _sum_x)
    _intercept = (_sum_y - _slope * _sum_x) / _length
    _intercept + _slope * (_length - 1)

// Arnaud Legoux Moving Average
alma(_src, _length, _offset, _sigma) =>
    _m = math.floor(_offset * (_length - 1))
    _s = _length / _sigma
    _weights = array.new_float(0)
    _norm = 0.0
    for i = 0 to _length - 1 by 1
        _w = math.exp(-math.pow(i - _m, 2) / (2 * math.pow(_s, 2)))
        array.push(_weights, _w)
        _norm := _norm + _w
        _norm
    _sum = 0.0
    for i = 0 to _length - 1 by 1
        _sum := _sum + _src[i] * array.get(_weights, i)
        _sum
    _sum / _norm

// Variable Index Dynamic Average
vidya(_src, _length) =>
    _cmos = math.abs(ta.change(_src, 9)) / ta.atr(9)
    _alpha = 2.0 / (_length + 1)
    _vidya = 0.0
    _vidya := _alpha * _cmos * _src + (1 - _alpha * _cmos) * nz(_vidya[1])
    _vidya

// Zero-Lag EMA
zlema(_src, _length) =>
    _lag = math.round((_length - 1) / 2)
    _zlsrc = _src + _src - _src[_lag]
    ta.ema(_zlsrc, _length)

// Fractal Adaptive Moving Average
frama(_src, _length) =>
    float _n1 = math.max(ta.highest(_length), ta.lowest(_length))
    float _n2 = math.max(ta.highest(_length / 2), ta.lowest(_length / 2))
    float _n3 = math.max(ta.highest(_length / 2), ta.lowest(_length / 2))
    float _dimen = 1.0
    if _n1 > 0 and _n2 > 0 and _n3 > 0
        float _temp1 = math.log(_n1 + _n2)
        float _temp2 = math.log(_n3)
        _dimen := (_temp1 - _temp2) / math.log(2)
        _dimen
    float _alpha = math.exp(-4.6 * (_dimen - 1))
    _alpha := math.max(math.min(_alpha, 1), 0.01)
    float _frama = 0.0
    _frama := _alpha * _src + (1 - _alpha) * nz(_frama[1])
    _frama

// ВЫБОР ТИПА MA
get_ma() =>
    switch ma_type
        'SMA' => ta.sma(src, ma_length)
        'EMA' => ta.ema(src, ma_length)
        'WMA' => ta.wma(src, ma_length)
        'Hull MA' => hma(src, ma_length)
        'VWMA' => vwma(src, ma_length)
        'TEMA' => tema(src, ma_length)
        'JMA' => jma(src, ma_length, jma_power)
        'LSMA' => lsma(src, ma_length)
        'ALMA' => alma(src, ma_length, alma_offset, alma_sigma)
        'Vidya' => vidya(src, ma_length)
        'ZLEMA' => zlema(src, ma_length)
        'FRAMA' => frama(src, ma_length)

// Расчет центральной линии
center_line = get_ma()

// ПЕРВЫЙ конверт: Суммарная волатильность
total_hl_diff = 0.0
for i = 0 to lookback1 - 1 by 1
    total_hl_diff := total_hl_diff + high_mtf[i] - low_mtf[i]
    total_hl_diff

upper_band1 = center_line + total_hl_diff * mult1
lower_band1 = center_line - total_hl_diff * mult1

// ВТОРОЙ конверт: Общий диапазон
overall_high = ta.highest(high_mtf, lookback2)
overall_low = ta.lowest(low_mtf, lookback2)
hl_range = overall_high - overall_low

upper_band2 = center_line + hl_range * mult1
lower_band2 = center_line - hl_range * mult2

// Отрисовка
plot(center_line, 'Мувинг', #ff9800, 2)

// Конверт 1
u1 = plot(upper_band1, 'Верх Суммарный', #ff5252, 2)
l1 = plot(lower_band1, 'Низ Суммарный', #ff5252, 2)
fill(u1, l1, color.new(color.red, 90), 'Конверт 1')

// Конверт 2
u2 = plot(upper_band2, 'Верх Общий', #4caf50, 2)
l2 = plot(lower_band2, 'Низ Общий', #4caf50, 2)
fill(u2, l2, color.new(color.green, 90), 'Конверт 2')

// Общие High/Low
plot(overall_high, 'Общий High', #ff0057, 1, plot.style_circles)
plot(overall_low, 'Общий Low', #00ffff, 1, plot.style_circles)

var table logo = table.new(position.bottom_right, 1, 1)
table.cell(logo, 0, 0, 'DM', text_size = size.normal, text_color = #00897b)

//===================================================================

Last edited by JEDY (2026-06-18 15:56:51)

0

110

ОБЩИЙ ДИАПАЗОН

//@version=6

indicator('<NINJA>', '<NINJA>', true)
// Настройки МТФ
mtf = input.timeframe('', 'Таймфрейм')

// ВЫБОР ТИПА МУВИНГА
ma_type = input.string('EMA', 'Тип мувинга', options = ['SMA', 'EMA', 'WMA', 'Hull MA', 'VWMA', 'TEMA', 'JMA', 'LSMA', 'ALMA', 'Vidya', 'ZLEMA', 'FRAMA'])

ma_length = input.int(9, 'Период мувинга')
ma_source = input.source(hl2, 'Источник для MA')

// Дополнительные параметры для некоторых MA
ma_offset = input.int(0, 'Смещение MA')
jma_power = input.float(2.0, 'JMA: Мощность', minval = 1, maxval = 10, step = 0.1)
alma_offset = input.float(0.85, 'ALMA: Смещение', minval = 0, maxval = 1, step = 0.01)
alma_sigma = input.float(6.0, 'ALMA: Сигма', minval = 1, maxval = 10, step = 0.1)

// Настройки конвертов
lookback1 = input.int(18, 'Период волатильности 1')
mult1 = input.float(0.33, 'Множитель 1', step = 0.01)
lookback2 = input.int(18, 'Период волатильности 2')
mult2 = input.float(0.33, 'Множитель 2', step = 0.01)

// Получаем данные с нужного ТФ
src = request.security(syminfo.tickerid, mtf, ma_source)
high_mtf = request.security(syminfo.tickerid, mtf, high)
low_mtf = request.security(syminfo.tickerid, mtf, low)

// ФУНКЦИИ РАСЧЕТА РАЗНЫХ MA
// Hull Moving Average
hma(_src, _length) =>
    _wma1 = ta.wma(_src, _length / 2)
    _wma2 = ta.wma(_src, _length)
    2 * _wma1 - _wma2

// Volume Weighted Moving Average
vwma(_src, _length) =>
    _sum = math.sum(_src * volume, _length)
    _vol = math.sum(volume, _length)
    _sum / _vol

// Triple Exponential Moving Average
tema(_src, _length) =>
    _ema1 = ta.ema(_src, _length)
    _ema2 = ta.ema(_ema1, _length)
    _ema3 = ta.ema(_ema2, _length)
    3 * _ema1 - 3 * _ema2 + _ema3

// Jurik Moving Average (упрощенная версия)
jma(_src, _length, _power) =>
    _beta = 0.45 * (_length - 1) / (0.45 * (_length - 1) + 2)
    _alpha = math.pow(_beta, _power)
    _jma = 0.0
    _jma := _alpha * _src + (1 - _alpha) * nz(_jma[1])
    _jma

// Least Squares Moving Average
lsma(_src, _length) =>
    _sum_x = _length * (_length - 1) / 2
    _sum_x2 = _length * (_length - 1) * (2 * _length - 1) / 6
    _sum_xy = 0.0
    _sum_y = 0.0
    for i = 0 to _length - 1 by 1
        _sum_xy := _sum_xy + i * _src[i]
        _sum_y := _sum_y + _src[i]
        _sum_y
    _slope = (_length * _sum_xy - _sum_x * _sum_y) / (_length * _sum_x2 - _sum_x * _sum_x)
    _intercept = (_sum_y - _slope * _sum_x) / _length
    _intercept + _slope * (_length - 1)

// Arnaud Legoux Moving Average
alma(_src, _length, _offset, _sigma) =>
    _m = math.floor(_offset * (_length - 1))
    _s = _length / _sigma
    _weights = array.new_float(0)
    _norm = 0.0
    for i = 0 to _length - 1 by 1
        _w = math.exp(-math.pow(i - _m, 2) / (2 * math.pow(_s, 2)))
        array.push(_weights, _w)
        _norm := _norm + _w
        _norm
    _sum = 0.0
    for i = 0 to _length - 1 by 1
        _sum := _sum + _src[i] * array.get(_weights, i)
        _sum
    _sum / _norm

// Variable Index Dynamic Average
vidya(_src, _length) =>
    _cmos = math.abs(ta.change(_src, 9)) / ta.atr(9)
    _alpha = 2.0 / (_length + 1)
    _vidya = 0.0
    _vidya := _alpha * _cmos * _src + (1 - _alpha * _cmos) * nz(_vidya[1])
    _vidya

// Zero-Lag EMA
zlema(_src, _length) =>
    _lag = math.round((_length - 1) / 2)
    _zlsrc = _src + _src - _src[_lag]
    ta.ema(_zlsrc, _length)

// Fractal Adaptive Moving Average
frama(_src, _length) =>
    float _n1 = math.max(ta.highest(_length), ta.lowest(_length))
    float _n2 = math.max(ta.highest(_length / 2), ta.lowest(_length / 2))
    float _n3 = math.max(ta.highest(_length / 2), ta.lowest(_length / 2))
    float _dimen = 1.0
    if _n1 > 0 and _n2 > 0 and _n3 > 0
        float _temp1 = math.log(_n1 + _n2)
        float _temp2 = math.log(_n3)
        _dimen := (_temp1 - _temp2) / math.log(2)
        _dimen
    float _alpha = math.exp(-4.6 * (_dimen - 1))
    _alpha := math.max(math.min(_alpha, 1), 0.01)
    float _frama = 0.0
    _frama := _alpha * _src + (1 - _alpha) * nz(_frama[1])
    _frama

// ВЫБОР ТИПА MA
get_ma() =>
    switch ma_type
        'SMA' => ta.sma(src, ma_length)
        'EMA' => ta.ema(src, ma_length)
        'WMA' => ta.wma(src, ma_length)
        'Hull MA' => hma(src, ma_length)
        'VWMA' => vwma(src, ma_length)
        'TEMA' => tema(src, ma_length)
        'JMA' => jma(src, ma_length, jma_power)
        'LSMA' => lsma(src, ma_length)
        'ALMA' => alma(src, ma_length, alma_offset, alma_sigma)
        'Vidya' => vidya(src, ma_length)
        'ZLEMA' => zlema(src, ma_length)
        'FRAMA' => frama(src, ma_length)

// Расчет центральной линии
center_line = get_ma()

// ПЕРВЫЙ конверт: Суммарная волатильность
total_hl_diff = 0.0
for i = 0 to lookback1 - 1 by 1
    total_hl_diff := total_hl_diff + high_mtf[i] - low_mtf[i]
    total_hl_diff

upper_band1 = center_line + total_hl_diff * mult1
lower_band1 = center_line - total_hl_diff * mult1

// ВТОРОЙ конверт: Общий диапазон
overall_high = ta.highest(high_mtf, lookback2)
overall_low = ta.lowest(low_mtf, lookback2)
hl_range = overall_high - overall_low

upper_band2 = center_line + hl_range * mult1
lower_band2 = center_line - hl_range * mult2

// Отрисовка
plot(center_line, 'Мувинг', #ff9800, 2)

// Конверт 1
u1 = plot(upper_band1, 'Верх Суммарный', #ff5252, 2)
l1 = plot(lower_band1, 'Низ Суммарный', #ff5252, 2)
fill(u1, l1, color.new(color.red, 90), 'Конверт 1')

// Конверт 2
u2 = plot(upper_band2, 'Верх Общий', #4caf50, 2)
l2 = plot(lower_band2, 'Низ Общий', #4caf50, 2)
fill(u2, l2, color.new(color.green, 90), 'Конверт 2')

// Общие High/Low
plot(overall_high, 'Общий High', #ff0057, 1, plot.style_circles)
plot(overall_low, 'Общий Low', #00ffff, 1, plot.style_circles)

var table logo = table.new(position.bottom_right, 1, 1)
table.cell(logo, 0, 0, 'DM', text_size = size.normal, text_color = #00897b)

//===================================================================

Last edited by JEDY (2026-06-18 15:57:33)

0

111

Для максимальной прибыли / настройки/
С 1:500 кредитного плеча
Дневная доходность в среднем 10,000%

Любой Свечи

Вход
Проверьте время, оставшееся до закрытия свечи Цена должна разбиться за пределами конверта /зеленый/
Перейти к безубыточности на центральной линии /желтый/
Закрытие позиции
На обратном ходе
МТФ
сигнал или на основе других систем

https://upforme.ru/uploads/001b/e9/c8/5/t993459.webp

//@version=6

индикатор('<NINJA>', '<NINJA>', правда)
// Найтрайл МТФ
mtf = вводимый-таймфрейм(', 'Тмйрарфм')

// ВЫБОРЬ ГИВИНГА
ma_type =ation.string('EMA', 'Tипвввинг', варианты = ['SMA', 'EMA', 'WMA', 'Hull MA', 'VWMA', 'TEMA', 'JMA', 'LSMA', 'ALMA', 'Vidya', 'ZLEMA', 'FRAMA'))

ma_length =contion.int(2, 'иеудвлюнинг')
ma_source = ввод.source(hl2, 'И йну МА')

//Леверп
ma_offset = ввод.int(0, 'ССМ МА')
jma_power = вводит.плавающий (2.0, 'JMA: Мощсяно', minval = 1, maxval = 10, шаг = 0.1)
alma_offset = ввод.float(0.85, 'ALMA: С)
alma_sigma = ввод.float(6.0, 'ALMA:Гима', minval = 1, maxval = 10, шаг = 0.1)

// Найрмайл ковей
lookback1 = ввод.in(Пер2, 'иествол 1')
mult1 = mass.float(0.1, 'Множ 1', шаг = 0,01)
lookback2 = ввод.int(Р2, 'иелл2')
mul2 =ration.float(0.1, 'Множ 2', шаг = 0.01)

// ОФ меда емк с фьо ТгоФ
src = запрос.security(syminfo.tickerid, mtf, ma_source)
high_mtf = запрос.security(syminfo.tickerid, mtf, высокий)
low_mtf = запрос.security(syminfo.tickerid, mtf, низкий)

// ФУНКЦИС РЦАЧАЕТИЗ РАЦЕЗАЗ
// Движущаяся средняя часть корпуса
hma(_src, _length) =>
_wma1 = ta.wma(_src, _length / 2)
_wma2 = ta.wma(_src, _length)
2 * _wma1 - _wma2

// Объем Взвешенный Движущийся Средний
vwma(_src, _length) =>
_sum = math.sum(_src * объем, _length)
_vol = math.sum (объем, _length)
_sum / _vol

// Тройной экспоненциальный скользящий средний
tema(_src, _length) =>
_ema1 = ta.ema(_src, _length)
_ema2 = ta.ema(_ema1, _length)
_ema3 = ta.ema(_ema2, _length)
3 _ema1 - 3 * _ema2 + _ema3

// Юрик Скользящая Средняя (унобъекаль стрелок)
jma(_src, _length, _power) =>
_beta = 0.45 * (_длина - 1) / (0.45 * (_длина - 1) +2)
_alpha = math.pow(_beta, _power)
_jma = 0,0
_jma := _alpha * _src + (1 - _alpha) * nz(_jma[1])
_jma

// Наименее Квадратные Движущиеся Средние
lsma(_src, _length) =>
_sum_x = _длина * (_длина - 1) / 2
_sum_x2 = _длина * (_длина - 1) * (2 * _длина - 1) / 6
_sum_xy = 0.0
_sum_y = 0.0
для i = 0 до _длины - 1 по 1
_sum_xy :=_sum_xy + i *_src[i]
_sum_y := _sum_y + _src[i]
_sum_y
_slope = (_length * _sum_x - _sum_x *sum_y) / (_длина * _sum_x2 - _sum_x * _sum_x)
_ перехват = (_sum_y - _slope * _sum_x) / _length
_передача + _slope * (_длина - 1)

// Арно Легу Перемещающийся Средний
alma(_src, _length, _offset, _sigma) =>
_m = math.floor(_offset * (_длина - 1))
_s = _length / _sigma
_весы = wave.new_float(0)
_норм = 0.0
для i = 0 до _длины - 1 по 1
_w = math.exp(-math.pow(i - _m, 2) / (2 * math.pow(s, 2))
wave.push(_weights, _w)
_норм := _норм + _w
_норм
_sum = 0.0
для i = 0 до _длины - 1 по 1
_sum := _sum + _src[i] * land.get(_weights, i)
_sum
_sum / _норм

// Динамический индекс переменный индекс
vidya(_src, _length) =>
_coms = math.abs(ta.change(_src, 9)) / ta.atr(9)
_alpha = 2.0 / (_длина + 1)
_vidya = 0.0
_vidya := _alpha * _cmos * _src + (1 - _alpha * _cmos) * nz(_vidya[1])
_vidya

// Нулево-лаг EMA
zlema(_src, _length) =>
_lag = math.round((_длина - 1) / 2)
_zlsrc = _src + _src - _src[_lag]
ta.ema(_zlsrc, _длин)

// Фрактальная адаптивная скользящая средняя
frama(_src, _length) =>
поплавок _n1 = math.max(ta.highest(_length), ta.lowst(_length))
поплавок _n2 = math.max(ta.highst(_length / 2), ta.lowst(_длина / 2))
float _n3 = math.max(ta.highest(_length / 2), ta.lowest(_длина / 2))
поплавок _dimen = 1.0
если _n1 > 0 и _n2 > 0 и _n3 > 0 и _n3 > 0
поплавок _temp1 = math.log(_n1 + _n2)
поплавок _temp2 = math.log(_n3)
_dimen := (_temp1 - _temp2) / math.log(2)
_dimen
поплавок _alpha = math.exp(-4.6 * (_димен - 1))
_alpha := math.max(math.min(_alpha, 1), 0.01)
поплавок _frama = 0.0
_frama := _alpha * _src + (1 - _alpha) * nz(_frama[1])
_frama

// ЫБОР ТИПА МА
получить_ma() =>
переключатель ma_type
'SMA' => ta.sma(src, ma_length)
'EMA' => ta.ema(src, ma_length)
'WMA' => ta.wma(src, ma_length)
'Hull MA' => hma(src, ma_length)
'VWMA' => vwma(src, ma_length)
'TEMA' => tema(src, ma_length)
'JMA' => jma(src, ma_length, jma_power)
'LSMA' => lsma(src, ma_length)
'ALMA' => alma(src, ma_length, alma_offset, alma_sigma)
'Видья' => vidya(src, ma_length)
'ZLEMA' => zlema(src, ma_length)
'FRAMA' => frama(src, ma_length)

// Расканы четвей
center_line = get_ma()

// ПЕРЫЙВВ Вентволю: Сумара Валаясла
total_hl_diff = 0.0
для i = 0 для оглядки 1 - 1 на 1
total_hl_diff := total_hl_diff + high_mtf[i] - low_mtf[i]
stat_hl_diff

upper_band1 = center_line + total_hl_diff * mult1
ниже_band1 = center_line - total_hl_diff * mult1

// ВВР ВОИТЛ: дикий
все_high = ta.highst(high_mtf, lookback2)
общий_low = ta.lowest(low_mtf, lookback2)
hl_range = gross_high - общий_low

upper_band2 = центр_line + hl_range * mult1
ниже_band2 = center_line - hl_range * mul2

// Ойц. Овева
сюжет(центр_line, 'УУвинг', #ff9800, 2)

// Конфенсация 1
u1 = сюжет(upper_band1, 'эрВх Суммарм, #ff5252, 2)
l1 = сюжет(lower_band1, 'Низ суизм натимар', #ff5252, 2)
наполните (u1, l1, color.new(color.red, 90), 'Коннус 1')

// Конфессия 2
u2 = сюжет(upper_band2, 'эрВх', #4caf50, 2)
l2 = сюжет(lower_band2, 'Низ', #4caf50, 2)
наполните(u2, l2, color.new(color.green, 90), 'Коннект 2')

// Об Щ/Высокий/Низкий
сюжет(moreal_high, 'Объкир, #ff0057, 1, plan.style_circles)
сюжет(moreall_low, 'Об Щит, #00ffff, 1, plan.style_circles)

Логотип var table = table.new(position.bottom_right, 1, 1)
table.cell(logo, 0, 0, 'DM', text_size = size.normal, text_color = #00897b)

//=========================================================================================================================================

https://upforme.ru/uploads/001b/e9/c8/5/t940262.webp

Last edited by JEDY (2026-06-28 00:01:26)

0

112

Holy Grail

https://www.forexfactory.com/thread/140 … -the-round

https://upforme.ru/uploads/001b/e9/c8/5/t532365.jpg

Last edited by JEDY (2026-07-11 22:48:11)

0

113

Обычные скользящие средние (Moving Average / MA) не предсказывают будущее, а всегда запаздывают, так как строятся по формуле средних значений за прошлые периоды. Если вы видите, что мувинг «дорисовывается» в пустое пространство графика, это происходит по одной из следующих причин:1. Специальные проекционные индикаторы (Forecasting/Projection)Некоторые продвинутые индикаторы созданы специально для визуализации математических сценариев. Они продолжают линию мувинга вправо с помощью пунктира или штриха, чтобы показать, где окажется средняя цена, если текущий тренд продолжится. Популярные примеры (доступны в каталогах на площадках вроде TradingView):Future EMA Projection (строит линии на основе допущений о цене).MA+ Projection (высчитывает будущую траекторию при выпадении старых данных).Projected Moving Averages (показывает, где закроется мувинг на следующей свече).

https://www.tradingview.com/script/so65 … g-Average/

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OmegaTools

//@version=5
indicator("Double Simple Moving Average", overlay = true)

lnt = input(21, "Length")
mult = input(2.00, "Band width")

a = ta.sma(high, lnt)
b = ta.sma(low, lnt)
c = ta.sma(close, lnt)
d = ta.vwma(close, lnt)
sp = a - b

tool = d - c
grad = color.from_gradient(tool, ta.lowest(tool, lnt*3), ta.highest(tool, lnt*3), #e91e63, #2962ff)

p1 = plot(a, "High average", #2962ff)
p2 = plot(b, "Low average", #e91e63)
p3 = plot(c, "Close average", color.gray, 1, display = display.none, editable = false)
fill(p1, p3, color.new(grad, 50))
fill(p2, p3, color.new(grad, 50))

p4 = plot(c + (sp * mult), "High band", color.gray, display = display.none)
p5 = plot(c - (sp * mult), "Low band", color.gray, display = display.none)
fill(p4, p5, color.new(color.gray, 85))

0

114

https://www.tradingview.com/script/L2Xo … rojection/

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Electrified

//@version=6
//@description This indicator helps forecast the future values of a moving average by considering the effect of historical data loss. It provides a practical view on how the moving average could change as older data points drop off over time. Notable features include optional deviation bands for a more comprehensive trend analysis and the ability to smooth the average using the last source value. This tool is designed for visualizing the possible future direction of moving averages, aiding in market analysis.
indicator("MA+ Projection", overlay = true) // thumb = 2
import Electrified/Time/11 as Time
import Electrified/MovingAverages/15 as MA
import Electrified/Averages/6 as Average

// Repainting note:
// This indicator is not meant for alters but for visualization.
// Repainting is unavoidable as each tick will cause the redrawing of the projection
// and should only calculate and render on the last bar.

// Constants
const string SMA = 'SMA'
const string EMA = 'EMA'
const string WMA = 'WMA'
const string VWMA = 'VWMA'
const string VAWMA = 'VAWMA'
const string BARS = 'Bars'
const string MINUTES = 'Minutes'
const string DAYS = 'Days'
const string SOURCE = 'Source'
const string LENGTH = 'Length'
const string PROJECT = 'Project %'
const string DEVIATION = "Deviation"
const string MOVINGAVERAGE = 'Moving Average'
const string PROJECTION = 'Projection'

//////////////////////////////
//// Configuration ///////////
//////////////////////////////

// Moving Avearage Configuration
src = input.source(close, SOURCE, "", SOURCE, MOVINGAVERAGE)
maType = input.string(SMA, "", [SMA, EMA, WMA, VWMA, VAWMA],
  "The source and type of moving average to calculate", SOURCE, MOVINGAVERAGE)

length = Time.spanToIntLen(
  input.int(200,LENGTH, 1, 5000, 5, "", LENGTH, MOVINGAVERAGE),
  input.string(BARS, "", [BARS, MINUTES, DAYS],
  "The length of the caclulcation.", LENGTH, MOVINGAVERAGE))

showDataStart = input.bool(false,
  "Highlight 'Start of Data'",
  "When true, highlights the previous bar before the data is being mesaured for the calculation.",
  group=MOVINGAVERAGE)
  and barstate.islast

// Projection Configuration
useLastBar = input.bool(true,
  "Use Last Source Value",
  "Replaces lost values with the last value of the source to smooth out the average",
  group=PROJECTION)

projectPercent = input.float(25, PROJECT, 1, 100, 5,
  "The amount of the measurement length to project forward.",
  PROJECT, PROJECTION)

const int MAX_HISTORY = 5000
projectLen = math.min(MAX_HISTORY, math.max(1, math.floor(length * projectPercent / 100)))
devLen = math.max(0, math.min(length * 10, MAX_HISTORY - projectLen))

deviationMultiple = input.float(2, DEVIATION, 0, 10, 0.5, "", DEVIATION, PROJECTION)
showDeviation = input.bool(true, "Show",
  "Controls the size (number of standard deviations) and visibility of the deviation 'cone'.",
  DEVIATION, PROJECTION)

// Theme
lineColor = input.color(color.orange, "Color", "", group="Theme")
//////////////////////////////

ma = MA.get(maType, length, src)
max_bars_back(ma, 5000)
plot(ma, "MA", lineColor, 2)

getAverage(float[] values, float[] vol) =>
    switch maType
        EMA => Average.exponential(values)
        WMA => Average.triangular(values),
        VWMA => Average.weighted(values, vol)
        VAWMA => Average.triangularWeighted(values, vol)
        => values.avg()

addProjection(chart.point[] points, color lc = na) =>
    polyline.new(points, true, line_color = na(lc) ? lineColor : lc, line_width = 2, line_style = line.style_dotted, xloc = xloc.bar_index)

var dataStartColor = color.new(lineColor, 50)
bgcolor(showDataStart ? dataStartColor : na, -length, title = "Start of Data")

// Populate the points array
if barstate.islast
    for p in polyline.all
        p.delete()

    currentPoint = chart.point.from_index(bar_index, ma)
    points = array.new<chart.point>(projectLen, currentPoint)
    pointsUpper = showDeviation ? array.new<chart.point>(projectLen, currentPoint) : na
    pointsLower = showDeviation ? array.new<chart.point>(projectLen, currentPoint) : na
    last = length - 1
    a = array.new_float(last, ma)
    vol = array.new_float(last, volume)

    for i = 1 to last - 1
        // Ensure the data is in order for use with different MAs.
        index = last - i
        a.set(index, src[i])
        vol.set(index, volume[i])

    for i = 1 to projectLen - 1
        if useLastBar
            a.push(src)
            vol.push(volume)
        value = getAverage(a, vol)
        a.shift()
        vol.shift()

        bar = bar_index + i
        points.set(i, chart.point.from_index(bar, value))
        if showDeviation

            da = array.new_float()
            for n = 0 to devLen
                da.push(math.abs(ma[n] - ma[n + i]))

            d = da.stdev() * deviationMultiple

            pointsUpper.set(i, chart.point.from_index(bar, value + d))
            pointsLower.set(i, chart.point.from_index(bar, value - d))

    if showDeviation
        addProjection(pointsUpper, color.gray)
        addProjection(pointsLower, color.gray)
    addProjection(points)

0

115

Linear Regression Trend Channel with Mr Tuan Doan trading view

linear regression trend channel with Entries & Alerts

Last edited by JEDY (2026-07-25 18:59:55)

0

116

// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Zeiierman {

//@version=6
indicator(title = 'Dynamic RSI Regression Bands (Zeiierman)', overlay = true, max_lines_count = 3, max_labels_count = 0, max_bars_back = 1005)
//~~}

//~~ Tooltips for Inputs {
var string t1 = "Defines how many bars the RSI uses to measure relative strength. Shorter values make it more reactive; longer values smooth out noise."
var string t2 = "Overbought level. When RSI crosses above this, it triggers a reset of the regression channel. Common levels: 70–90."
var string t3 = "Oversold level. When RSI crosses below this, it triggers a reset of the regression channel. Common levels: 10–30."
var string t4 = "Toggles the central regression line. This is the core trendline recalculated on every RSI reset."
var string t5 = "Toggles upper and lower standard deviation bands from the regression line, useful for spotting volatility zones."
var string t6 = "Maximum lookback for calculating regression after a reset. Actual length is limited by how many bars since last RSI trigger."
var string t7 = "Controls the width of the channel bands. Higher values make bands wider, capturing more price swings."
var string t8 = "Minimum number of bars required to start calculating a regression channel after an RSI reset. Helps filter out noise from immediate re-crosses."
var string t9 = "Displays triangle markers at RSI overbought (top) and oversold (bottom) resets."
var string t10 = "Marker colors for RSI resets — red for overbought, green for oversold."
var string t11 = "Shows dot markers when price rejects the upper or lower channel (e.g., wicks through, then closes back inside)."
var string t12 = "Marker colors for price rejection at upper or lower regression channel bands — red for upper, green for lower."
var string t13 = "Colors used for the upper and lower regression bands. Adjust transparency to blend or highlight."
var string t14 = "Adjusts thickness of the regression and channel lines."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Inputs {
rsiLen     = input.int(5, 'RSI Length', minval = 1, group="RSI", inline="RSI", tooltip=t1)
rsiObLevel = input.float(90.0, 'OB', minval = 0, maxval = 100, group="RSI", inline="RSI_", tooltip="")
rsiOsLevel = input.float(10.0, 'OS', minval = 0, maxval = 100, group="RSI", inline="RSI_", tooltip=t2 + t3)

showreg     = input.bool(true, title="Regression Channel", group="Regression Channel", inline="", tooltip=t4)
showregband = input.bool(true, title="Regression Bands", group="Regression Channel", inline="", tooltip=t5)
lrBaseLen   = input.int(1000, 'Base Regression Length (Max)', minval = 2, group="Regression Channel", inline="", tooltip=t6)
stdevMult   = input.float(2.0, 'StdDev Channel Multiplier', minval = 0.1, group="Regression Channel", inline="", tooltip=t7)

minChannelLen = input.int(2, 'Min Bars After Reset', minval = 1, group="", inline="", tooltip=t8)

plotColorUpper   = input.color(color.new(color.fuchsia, 60), '', group = 'Channel Style', inline="1", tooltip=t13)
plotColorLower   = input.color(color.new(color.aqua, 60), '', group = 'Channel Style', inline="1", tooltip=t13)
plotLineWidth    = input.int(1, 'Line Width', group = 'Channel Style', minval = 1, maxval = 5, inline="", tooltip=t14)

showResetMarker = input.bool(true, 'Show Reset Markers', group = 'RSI Reset Sign', inline="2", tooltip=t9)
markerObColor   = input.color(color.new(color.red, 0), '', group = 'RSI Reset Sign', inline="2", tooltip=t10)
markerOsColor   = input.color(color.new(color.green, 0), '', group = 'RSI Reset Sign', inline="2", tooltip=t10)

showRejection    = input.bool(true, 'Show Rejection Markers', group = 'Rejection Sign', inline="3", tooltip=t11)
rejectionObColor = input.color(color.new(color.red, 0), '', group = 'Rejection Sign', inline="3", tooltip=t12)
rejectionOsColor = input.color(color.new(color.green, 0), '', group = 'Rejection Sign', inline="3", tooltip=t12)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Var {
float lrVal_Current = na
float stdevVal      = na
float upperChannel_Plot = na
float lowerChannel_Plot = na
float slope = na
float intercept   = na
float lrVal_Start = na
float upperEnd    = na
float lowerEnd    = na
float upperStart  = na
float lowerStart  = na
var line lineMl   = na
var line lineUl   = na
var line lineLl   = na
var linefill lineFill = na
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

//~~ Regression Calculation {
regression(src, length) =>
    float sumX = 0.0
    float sumY = 0.0
    float sumXSqr = 0.0
    float sumXY = 0.0
    float _slope = na
    float _intercept = na

    if length > 1
        for i = 0 to length - 1 by 1
            val = src[i]
            per = i + 1.0
            sumX := sumX + per
            sumY := sumY + val
            sumXSqr := sumXSqr + per * per
            sumXY := sumXY + val * per
            sumXY

        denominator = length * sumXSqr - sumX * sumX
        if denominator != 0 // Avoid division by zero
            _slope := (length * sumXY - sumX * sumY) / denominator
            _intercept := (sumY - _slope * sumX) / length
            _intercept

    else if length == 1
        _slope := 0.0
        _intercept := src[0]
        _intercept
    [_slope, _intercept]
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ RSI {
rsi         = ta.rsi(close, rsiLen)
rsiOB_Cross = ta.crossover(rsi, rsiObLevel)
rsiOS_Cross = ta.crossunder(rsi, rsiOsLevel)
resetCondition = rsiOB_Cross or rsiOS_Cross 

var int barsSinceReset = 0
if resetCondition[1]
    barsSinceReset := 0
    barsSinceReset
else
    barsSinceReset := barsSinceReset + 1
    barsSinceReset

effectiveLen = math.min(lrBaseLen, barsSinceReset + 1)
effectiveLen := math.max(minChannelLen, effectiveLen)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Calc {
canCalculate = barsSinceReset >= minChannelLen - 1
if canCalculate
    [currentSlope, currentIntercept] = regression(close, effectiveLen)
    if not na(currentSlope) and not na(currentIntercept)
        slope := currentSlope
        intercept := currentIntercept
        lrVal_Current := intercept + slope * 1.0
        lrVal_Start := intercept + slope * float(effectiveLen)
        stdevVal := ta.stdev(close, effectiveLen)

        if not na(stdevVal)
            upperChannel_Plot := lrVal_Current + stdevMult * stdevVal
            lowerChannel_Plot := lrVal_Current - stdevMult * stdevVal
           
            upperEnd := lrVal_Current + stdevMult * stdevVal
            lowerEnd := lrVal_Current - stdevMult * stdevVal
            upperStart := lrVal_Start + stdevMult * stdevVal
            lowerStart := lrVal_Start - stdevMult * stdevVal
            lowerStart
        else
            upperChannel_Plot := lrVal_Current
            lowerChannel_Plot := lrVal_Current
            upperEnd := lrVal_Current
            lowerEnd := lrVal_Current
            upperStart := lrVal_Start
            lowerStart := lrVal_Start
            lowerStart
else
    slope := na
    slope
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Line plots {
int startBarIndex = bar_index - effectiveLen + 1
int endBarIndex = bar_index

currentLineColor = color.gray
if not na(slope)
    currentLineColor := slope > 0 ? plotColorUpper : plotColorLower
    currentLineColor

if (not canCalculate or na(slope) or resetCondition)
 
    line.delete(lineMl)
    line.delete(lineUl)
    line.delete(lineLl)
    linefill.delete(lineFill)
    lineMl := na
    lineUl := na
    lineLl := na
    lineFill := na
    lineFill
   
else
    if na(lineMl) and showreg
        lineMl := line.new(startBarIndex, lrVal_Start, endBarIndex, lrVal_Current, color = currentLineColor, style = line.style_solid, width = math.max(1, plotLineWidth))
        lineUl := line.new(startBarIndex, upperStart, endBarIndex, upperEnd, color = currentLineColor, style = line.style_dashed, width = math.max(1, plotLineWidth))
        lineLl := line.new(startBarIndex, lowerStart, endBarIndex, lowerEnd, color = currentLineColor, style = line.style_dashed, width = math.max(1, plotLineWidth))
        lineFill := linefill.new(lineUl, lineLl, color.new(currentLineColor,90))
        lineFill
    else
        line.set_xy1(lineMl, startBarIndex, lrVal_Start)
        line.set_xy2(lineMl, endBarIndex, lrVal_Current)
        line.set_xy1(lineUl, startBarIndex, upperStart)
        line.set_xy2(lineUl, endBarIndex, upperEnd)
        line.set_xy1(lineLl, startBarIndex, lowerStart)
        line.set_xy2(lineLl, endBarIndex, lowerEnd)

        line.set_color(lineMl, currentLineColor)
        line.set_color(lineUl, currentLineColor)
        line.set_color(lineLl, currentLineColor)
        linefill.set_color(lineFill, color.new(currentLineColor,90))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Get channel values {
midreg   = na(lrVal_Current) ? na : lrVal_Current
upperreg = na(upperChannel_Plot) ? na : upperChannel_Plot
lowerreg = na(lowerChannel_Plot) ? na : lowerChannel_Plot
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Rejection {
upperCross = ta.crossover(high, upperreg)
lowerCross = ta.crossunder(low, lowerreg)
upperReject = upperCross[1] and close < upperreg and close < open and showRejection
lowerReject = lowerCross[1] and close > lowerreg and close > open and showRejection
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Plots {
cond_Ob = rsiOB_Cross and showResetMarker
cond_Os = rsiOS_Cross and showResetMarker
atr_ = ta.ema(ta.atr(20), 100)
place_Ob = ta.highest(high, 10) + atr_
place_Os = ta.lowest(low, 10) - atr_
plotshape(cond_Ob ? place_Ob : na, title = 'RSI OB', location = location.absolute, color = markerObColor, style = shape.triangledown, size = size.tiny)
plotshape(cond_Os ? place_Os : na, title = 'RSI OS', location = location.absolute, color = markerOsColor, style = shape.triangleup, size = size.tiny)
p_ml = plot(showregband?midreg:na, title = 'Regression', color = currentLineColor, linewidth = 1, style = plot.style_linebr)
p_ul = plot(showregband?upperreg:na, title = 'Upper Channel', color = plotColorUpper, linewidth = 1, style = plot.style_linebr)
p_ll = plot(showregband?lowerreg:na, title = 'Lower Channel', color = plotColorLower, linewidth = 1, style = plot.style_linebr)

fill(p_ul, p_ml, upperreg, midreg, color.new(currentLineColor, 90), na)
fill(p_ll, p_ml, lowerreg, midreg, color.new(currentLineColor, 90), na)

plotshape(upperReject ? place_Ob : na, title = 'Upper Rejection', location = location.absolute, color = color.new(rejectionObColor, 0), style = shape.circle, size = size.tiny, offset = -1)
plotshape(lowerReject ? place_Os : na, title = 'Lower Rejection', location = location.absolute, color = color.new(rejectionOsColor, 0), style = shape.circle, size = size.tiny, offset = -1)

// For UI Only
plotshape(cond_Ob ? place_Ob : na, title = 'UI - RSI OB', location = location.absolute, color = color.new(markerObColor, 70), style = shape.triangledown, size = size.small)
plotshape(cond_Os ? place_Os : na, title = 'UI - RSI OS', location = location.absolute, color = color.new(markerOsColor, 70), style = shape.triangleup, size = size.small)
plotshape(upperReject ? place_Ob : na, title = 'UI - Upper Rejection', location = location.absolute, color = color.new(rejectionObColor, 70), style = shape.circle, size = size.small, offset = -1)
plotshape(lowerReject ? place_Os : na, title = 'UI - Lower Rejection', location = location.absolute, color = color.new(rejectionOsColor, 70), style = shape.circle, size = size.small, offset = -1)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

0

117

//@version=4
//code from linear regression used https://www.tradingview.com/script/CD7y … d-Channel/
// by https://www.tradingview.com/u/midtownsk8rguy
// permission granted by the author https://imgur.com/Pp8k7Q4
// added color option, labels for high and low.

// Learn alert : https://www.tradingview.com/script/V7OV … egression/
// https://www.tradingview.com/scripts/linearregression/

study("Linear Regression Trend Channel with Entries & Alerts", "LRTC 0.2", true)

//###### FUNCTIONS ##################################//
truncate(number, decimals) =>
    factor = pow(10, decimals)
    int(number * factor) / factor
   
nround(x) =>
    n = round(x / syminfo.mintick) * syminfo.mintick

chosenColor(c_)=> c_ == "aqua"    ? #00FFFFff :
                  c_ == "blue"    ? #0040FFff :
                  c_ == "fuchsia" ? #FF00FFff :
                  c_ == "gray"    ? #808080ff :
                  c_ == "green"   ? #008000ff :
                  c_ == "lime"    ? #00FF00ff :
                  c_ == "maroon"  ? #800000ff :
                  c_ == "navy"    ? #000099ff :
                  c_ == "olive"   ? #808000ff :
                  c_ == "orange"  ? #FF8000ff :
                  c_ == "purple"  ? #8000FFff :
                  c_ == "red"     ? #ff0000ff :
                  c_ == "silver"  ? #C0C0C0ff :
                  c_ == "teal"    ? #008080ff :
                  c_ == "white"   ? #FFFFFFff : #00000000
                 
//###### DRAW TREND CHANNEL#########################//
period     = input(     40, "Period"       , input.integer, minval=3)
deviations = input(    2.0, "Deviation(s)" , input.float  , minval=0.1, step=0.1)
extendType = input("Right", "Extend Method", input.string , options=["Right","None"])=="None" ? extend.none : extend.right
periodMinusOne = period-1
Ex = 0.0,
Ey = 0.0,
Ex2 = 0.0,
Exy = 0.0,
for i=0 to periodMinusOne
    closeI = nz(close[i]),
    Ex := Ex + i,
    Ey := Ey + closeI,
    Ex2 := Ex2 + (i * i),
    Exy := Exy + (closeI * i)
ExEx = Ex * Ex, slope = Ex2==ExEx ? 0.0 : (period * Exy - Ex * Ey) / (period * Ex2 - ExEx)
linearRegression = (Ey - slope * Ex) / period
intercept = linearRegression + bar_index * slope
deviation = 0.0, for i=0 to periodMinusOne
    deviation := deviation + pow(nz(close[i]) - (intercept - slope * (bar_index[i])), 2.0)
deviation := deviations * sqrt(deviation / periodMinusOne)
startingPointY = linearRegression + slope * periodMinusOne

//####### DRAWING LINES SECTION ####
var line upperChannelLine = na  ,
var line medianChannelLine = na  ,
var line lowerChannelLine = na
line.delete(upperChannelLine[1]),
line.delete(medianChannelLine[1]),
line.delete(lowerChannelLine[1])

// added color inputs
upperLineColor = input(title="Upper Channel Color", defval="red", options=["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow"])
middleLineColor = input(title="Middle Channel Color", defval="orange", options=["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow"])
lowerChannelColor = input(title="Lower Channel Color", defval="green", options=["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow"])

// draw channels
upperChannelLine  := line.new(bar_index - period + 1, startingPointY + deviation, bar_index, linearRegression + deviation, xloc.bar_index, extendType, chosenColor(upperLineColor)    , line.style_solid , 2)
medianChannelLine := line.new(bar_index - period + 1, startingPointY            , bar_index, linearRegression            , xloc.bar_index, extendType, chosenColor(middleLineColor), line.style_solid , 1)
lowerChannelLine  := line.new(bar_index - period + 1, startingPointY - deviation, bar_index, linearRegression - deviation, xloc.bar_index, extendType, chosenColor(lowerChannelColor), line.style_solid , 2)

//####### INFORMATION PANEL SECTION ####
// Idea is developed from https://www.tradingview.com/script/gcp7 … -low-high/
// by https://www.tradingview.com/u/RafaelZioni/
disp_panels = input(true, title="Display info panels?")
linear_label_off = input(-1, title="linear label offset", minval = -1)
linear_label_size = input(size.normal, options=[size.tiny, size.small, size.normal, size.large, size.huge], title="linear label size")
pos_x = timenow + round(change(time)*linear_label_off)
pos_y_upper = nround(linearRegression + deviation)
candle_look_back = input(defval = 3, title="Look back", minval = 1, maxval = 5, step=1)
pos_y_upper_previous = nround(linearRegression[candle_look_back] + deviation[candle_look_back])
// pos_y_middle = nround(linearRegression) // doesn't need midde line
pos_y_lower = truncate(nround(linearRegression - deviation), 5)
pos_y_lower_previous = nround(linearRegression[candle_look_back] - deviation[candle_look_back])
label_upper = "Current Sell Entry: " + tostring(pos_y_upper) + "\n Previous Sell Entry (using Look Back): " + tostring(pos_y_upper_previous)
// label_upper = "Entry High: " + tostring(pos_y_upper)
label_lower = "Current Buy Entry: " + tostring(pos_y_lower) + "\n Previous Buy Entry (using Look Back): " + tostring(pos_y_lower_previous)

draw_upper_label = disp_panels ? label.new(x=pos_x, y=pos_y_upper, text=label_upper, xloc=xloc.bar_time, yloc=yloc.price, color=color.red, style=label.style_labeldown, textcolor=color.black, size=linear_label_size) : na
draw_lower_label = disp_panels ? label.new(x=pos_x, y=pos_y_lower, text=label_lower, xloc=xloc.bar_time, yloc=yloc.price, color=color.blue, style=label.style_labelup, textcolor=color.black, size=linear_label_size) : na

label.delete(draw_upper_label[1])
label.delete(draw_lower_label[1])

// to memorize entries
plot(pos_y_upper, title="Upper Entry Line", color=color.fuchsia, transp = 80)
plot(pos_y_lower, title="Lower Entry Line", color=color.fuchsia, transp = 80)
//####### ALERT PANEL SECTION ####
ready_to_sell = crossover(close, pos_y_upper_previous)
ready_to_buy = crossunder(close, pos_y_lower_previous)

alertcondition(ready_to_sell, title='Sell Alert v0.2', message='Sell at {{plot("Upper Entry Line")}}')
alertcondition(ready_to_buy, title='Buy Alert v0.2', message='Buy at {{plot("Lower Entry Line")}}')
alertcondition(ready_to_buy or ready_to_sell, title='General Alert v0.2', message='Price is close to upper/lower channel.')

0

118

linear regression trend channel with Entries & Alerts

0

119

https://ru.tradingview.com/script/OZZpx … es-Alerts/

//@version=4
//code from linear regression used https://www.tradingview.com/script/CD7y … d-Channel/
// by https://www.tradingview.com/u/midtownsk8rguy
// permission granted by the author https://imgur.com/Pp8k7Q4
// added color option, labels for high and low.

// Learn alert : https://www.tradingview.com/script/V7OV … egression/
// https://www.tradingview.com/scripts/linearregression/

study("Linear Regression Trend Channel with Entries & Alerts", "LRTC 0.2", true)

//###### FUNCTIONS ##################################//
truncate(number, decimals) =>
    factor = pow(10, decimals)
    int(number * factor) / factor
   
nround(x) =>
    n = round(x / syminfo.mintick) * syminfo.mintick

chosenColor(c_)=> c_ == "aqua"    ? #00FFFFff :
                  c_ == "blue"    ? #0040FFff :
                  c_ == "fuchsia" ? #FF00FFff :
                  c_ == "gray"    ? #808080ff :
                  c_ == "green"   ? #008000ff :
                  c_ == "lime"    ? #00FF00ff :
                  c_ == "maroon"  ? #800000ff :
                  c_ == "navy"    ? #000099ff :
                  c_ == "olive"   ? #808000ff :
                  c_ == "orange"  ? #FF8000ff :
                  c_ == "purple"  ? #8000FFff :
                  c_ == "red"     ? #ff0000ff :
                  c_ == "silver"  ? #C0C0C0ff :
                  c_ == "teal"    ? #008080ff :
                  c_ == "white"   ? #FFFFFFff : #00000000
                 
//###### DRAW TREND CHANNEL#########################//
period     = input(     40, "Period"       , input.integer, minval=3)
deviations = input(    2.0, "Deviation(s)" , input.float  , minval=0.1, step=0.1)
extendType = input("Right", "Extend Method", input.string , options=["Right","None"])=="None" ? extend.none : extend.right
periodMinusOne = period-1
Ex = 0.0,
Ey = 0.0,
Ex2 = 0.0,
Exy = 0.0,
for i=0 to periodMinusOne
    closeI = nz(close[i]),
    Ex := Ex + i,
    Ey := Ey + closeI,
    Ex2 := Ex2 + (i * i),
    Exy := Exy + (closeI * i)
ExEx = Ex * Ex, slope = Ex2==ExEx ? 0.0 : (period * Exy - Ex * Ey) / (period * Ex2 - ExEx)
linearRegression = (Ey - slope * Ex) / period
intercept = linearRegression + bar_index * slope
deviation = 0.0, for i=0 to periodMinusOne
    deviation := deviation + pow(nz(close[i]) - (intercept - slope * (bar_index[i])), 2.0)
deviation := deviations * sqrt(deviation / periodMinusOne)
startingPointY = linearRegression + slope * periodMinusOne

//####### DRAWING LINES SECTION ####
var line upperChannelLine = na  ,
var line medianChannelLine = na  ,
var line lowerChannelLine = na
line.delete(upperChannelLine[1]),
line.delete(medianChannelLine[1]),
line.delete(lowerChannelLine[1])

// added color inputs
upperLineColor = input(title="Upper Channel Color", defval="red", options=["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow"])
middleLineColor = input(title="Middle Channel Color", defval="orange", options=["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow"])
lowerChannelColor = input(title="Lower Channel Color", defval="green", options=["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow"])

// draw channels
upperChannelLine  := line.new(bar_index - period + 1, startingPointY + deviation, bar_index, linearRegression + deviation, xloc.bar_index, extendType, chosenColor(upperLineColor)    , line.style_solid , 2)
medianChannelLine := line.new(bar_index - period + 1, startingPointY            , bar_index, linearRegression            , xloc.bar_index, extendType, chosenColor(middleLineColor), line.style_solid , 1)
lowerChannelLine  := line.new(bar_index - period + 1, startingPointY - deviation, bar_index, linearRegression - deviation, xloc.bar_index, extendType, chosenColor(lowerChannelColor), line.style_solid , 2)

//####### INFORMATION PANEL SECTION ####
// Idea is developed from https://www.tradingview.com/script/gcp7 … -low-high/
// by https://www.tradingview.com/u/RafaelZioni/
disp_panels = input(true, title="Display info panels?")
linear_label_off = input(-1, title="linear label offset", minval = -1)
linear_label_size = input(size.normal, options=[size.tiny, size.small, size.normal, size.large, size.huge], title="linear label size")
pos_x = timenow + round(change(time)*linear_label_off)
pos_y_upper = nround(linearRegression + deviation)
candle_look_back = input(defval = 3, title="Look back", minval = 1, maxval = 5, step=1)
pos_y_upper_previous = nround(linearRegression[candle_look_back] + deviation[candle_look_back])
// pos_y_middle = nround(linearRegression) // doesn't need midde line
pos_y_lower = truncate(nround(linearRegression - deviation), 5)
pos_y_lower_previous = nround(linearRegression[candle_look_back] - deviation[candle_look_back])
label_upper = "Current Sell Entry: " + tostring(pos_y_upper) + "\n Previous Sell Entry (using Look Back): " + tostring(pos_y_upper_previous)
// label_upper = "Entry High: " + tostring(pos_y_upper)
label_lower = "Current Buy Entry: " + tostring(pos_y_lower) + "\n Previous Buy Entry (using Look Back): " + tostring(pos_y_lower_previous)

draw_upper_label = disp_panels ? label.new(x=pos_x, y=pos_y_upper, text=label_upper, xloc=xloc.bar_time, yloc=yloc.price, color=color.red, style=label.style_labeldown, textcolor=color.black, size=linear_label_size) : na
draw_lower_label = disp_panels ? label.new(x=pos_x, y=pos_y_lower, text=label_lower, xloc=xloc.bar_time, yloc=yloc.price, color=color.blue, style=label.style_labelup, textcolor=color.black, size=linear_label_size) : na

label.delete(draw_upper_label[1])
label.delete(draw_lower_label[1])

// to memorize entries
plot(pos_y_upper, title="Upper Entry Line", color=color.fuchsia, transp = 80)
plot(pos_y_lower, title="Lower Entry Line", color=color.fuchsia, transp = 80)
//####### ALERT PANEL SECTION ####
ready_to_sell = crossover(close, pos_y_upper_previous)
ready_to_buy = crossunder(close, pos_y_lower_previous)

alertcondition(ready_to_sell, title='Sell Alert v0.2', message='Sell at {{plot("Upper Entry Line")}}')
alertcondition(ready_to_buy, title='Buy Alert v0.2', message='Buy at {{plot("Lower Entry Line")}}')
alertcondition(ready_to_buy or ready_to_sell, title='General Alert v0.2', message='Price is close to upper/lower channel.')

0

120

Правильный код NINJA
Со сломанным MTF

//@version=6

indicator('<NINJA>', '<NINJA>', true)
// Настройки МТФ
mtf = input.timeframe('', 'Таймфрейм')

// ВЫБОР ТИПА МУВИНГА
ma_type = input.string('EMA', 'Тип мувинга', options = ['SMA', 'EMA', 'WMA', 'Hull MA', 'VWMA', 'TEMA', 'JMA', 'LSMA', 'ALMA', 'Vidya', 'ZLEMA', 'FRAMA'])

ma_length = input.int(28, 'Период мувинга')
ma_source = input.source(hl2, 'Источник для MA')

// Дополнительные параметры для некоторых MA
ma_offset = input.int(0, 'Смещение MA')
jma_power = input.float(2.0, 'JMA: Мощность', minval = 1, maxval = 10, step = 0.1)
alma_offset = input.float(0.85, 'ALMA: Смещение', minval = 0, maxval = 1, step = 0.01)
alma_sigma = input.float(6.0, 'ALMA: Сигма', minval = 1, maxval = 10, step = 0.1)

// Настройки конвертов
lookback1 = input.int(28, 'Период волатильности 1')
mult1 = input.float(0.1, 'Множитель 1', step = 0.01)
lookback2 = input.int(28, 'Период волатильности 2')
mult2 = input.float(0.1, 'Множитель 2', step = 0.01)

// Получаем данные с нужного ТФ
src = request.security(syminfo.tickerid, mtf, ma_source)
high_mtf = request.security(syminfo.tickerid, mtf, high)
low_mtf = request.security(syminfo.tickerid, mtf, low)

// ФУНКЦИИ РАСЧЕТА РАЗНЫХ MA
// Hull Moving Average
hma(_src, _length) =>
    _wma1 = ta.wma(_src, _length / 2)
    _wma2 = ta.wma(_src, _length)
    2 * _wma1 - _wma2

// Volume Weighted Moving Average
vwma(_src, _length) =>
    _sum = math.sum(_src * volume, _length)
    _vol = math.sum(volume, _length)
    _sum / _vol

// Triple Exponential Moving Average
tema(_src, _length) =>
    _ema1 = ta.ema(_src, _length)
    _ema2 = ta.ema(_ema1, _length)
    _ema3 = ta.ema(_ema2, _length)
    3 * _ema1 - 3 * _ema2 + _ema3

// Jurik Moving Average (упрощенная версия)
jma(_src, _length, _power) =>
    _beta = 0.45 * (_length - 1) / (0.45 * (_length - 1) + 2)
    _alpha = math.pow(_beta, _power)
    _jma = 0.0
    _jma := _alpha * _src + (1 - _alpha) * nz(_jma[1])
    _jma

// Least Squares Moving Average
lsma(_src, _length) =>
    _sum_x = _length * (_length - 1) / 2
    _sum_x2 = _length * (_length - 1) * (2 * _length - 1) / 6
    _sum_xy = 0.0
    _sum_y = 0.0
    for i = 0 to _length - 1 by 1
        _sum_xy := _sum_xy + i * _src[i]
        _sum_y := _sum_y + _src[i]
        _sum_y
    _slope = (_length * _sum_xy - _sum_x * _sum_y) / (_length * _sum_x2 - _sum_x * _sum_x)
    _intercept = (_sum_y - _slope * _sum_x) / _length
    _intercept + _slope * (_length - 1)

// Arnaud Legoux Moving Average
alma(_src, _length, _offset, _sigma) =>
    _m = math.floor(_offset * (_length - 1))
    _s = _length / _sigma
    _weights = array.new_float(0)
    _norm = 0.0
    for i = 0 to _length - 1 by 1
        _w = math.exp(-math.pow(i - _m, 2) / (2 * math.pow(_s, 2)))
        array.push(_weights, _w)
        _norm := _norm + _w
        _norm
    _sum = 0.0
    for i = 0 to _length - 1 by 1
        _sum := _sum + _src[i] * array.get(_weights, i)
        _sum
    _sum / _norm

// Variable Index Dynamic Average
vidya(_src, _length) =>
    _cmos = math.abs(ta.change(_src, 9)) / ta.atr(9)
    _alpha = 2.0 / (_length + 1)
    _vidya = 0.0
    _vidya := _alpha * _cmos * _src + (1 - _alpha * _cmos) * nz(_vidya[1])
    _vidya

// Zero-Lag EMA
zlema(_src, _length) =>
    _lag = math.round((_length - 1) / 2)
    _zlsrc = _src + _src - _src[_lag]
    ta.ema(_zlsrc, _length)

// Fractal Adaptive Moving Average
frama(_src, _length) =>
    float _n1 = math.max(ta.highest(_length), ta.lowest(_length))
    float _n2 = math.max(ta.highest(_length / 2), ta.lowest(_length / 2))
    float _n3 = math.max(ta.highest(_length / 2), ta.lowest(_length / 2))
    float _dimen = 1.0
    if _n1 > 0 and _n2 > 0 and _n3 > 0
        float _temp1 = math.log(_n1 + _n2)
        float _temp2 = math.log(_n3)
        _dimen := (_temp1 - _temp2) / math.log(2)
        _dimen
    float _alpha = math.exp(-4.6 * (_dimen - 1))
    _alpha := math.max(math.min(_alpha, 1), 0.01)
    float _frama = 0.0
    _frama := _alpha * _src + (1 - _alpha) * nz(_frama[1])
    _frama

// ВЫБОР ТИПА MA
get_ma() =>
    switch ma_type
        'SMA' => ta.sma(src, ma_length)
        'EMA' => ta.ema(src, ma_length)
        'WMA' => ta.wma(src, ma_length)
        'Hull MA' => hma(src, ma_length)
        'VWMA' => vwma(src, ma_length)
        'TEMA' => tema(src, ma_length)
        'JMA' => jma(src, ma_length, jma_power)
        'LSMA' => lsma(src, ma_length)
        'ALMA' => alma(src, ma_length, alma_offset, alma_sigma)
        'Vidya' => vidya(src, ma_length)
        'ZLEMA' => zlema(src, ma_length)
        'FRAMA' => frama(src, ma_length)

// Расчет центральной линии
center_line = get_ma()

// ПЕРВЫЙ конверт: Суммарная волатильность
total_hl_diff = 0.0
for i = 0 to lookback1 - 1 by 1
    total_hl_diff := total_hl_diff + high_mtf[i] - low_mtf[i]
    total_hl_diff

upper_band1 = center_line + total_hl_diff * mult1
lower_band1 = center_line - total_hl_diff * mult1

// ВТОРОЙ конверт: Общий диапазон
overall_high = ta.highest(high_mtf, lookback2)
overall_low = ta.lowest(low_mtf, lookback2)
hl_range = overall_high - overall_low

upper_band2 = center_line + hl_range * mult1
lower_band2 = center_line - hl_range * mult2

// Отрисовка
plot(center_line, 'Мувинг', #ff9800, 2)

// Конверт 1
u1 = plot(upper_band1, 'Верх Суммарный', #ff5252, 2)
l1 = plot(lower_band1, 'Низ Суммарный', #ff5252, 2)
fill(u1, l1, color.new(color.red, 90), 'Конверт 1')

// Конверт 2
u2 = plot(upper_band2, 'Верх Общий', #4caf50, 2)
l2 = plot(lower_band2, 'Низ Общий', #4caf50, 2)
fill(u2, l2, color.new(color.green, 90), 'Конверт 2')

// Общие High/Low
plot(overall_high, 'Общий High', #ff0057, 1, plot.style_circles)
plot(overall_low, 'Общий Low', #00ffff, 1, plot.style_circles)

var table logo = table.new(position.bottom_right, 1, 1)
table.cell(logo, 0, 0, 'DM', text_size = size.normal, text_color = #00897b)

//===================================================================

0

Quick post

Write and submit your message



You are here » AD » WOW.that's literally me » #8 investing.com