thinkorswim indicators

3rd Order Polynomial _VM

 

 

#VM_3rd_Order_Polynomial 

#gRowEx 

input n = 50; 

input y = close; 

# y=ax^3+bx^2+cx+d 

script matrix_3x3 { 

    input a11 = 0; 

    input a12 = 0; 

    input a13 = 0; 

    input a21 = 0; 

    input a22 = 0; 

    input a23 = 0; 

    input a31 = 0; 

    input a32 = 0; 

    input a33 = 0; 

    plot delta = a11 * a22 * a33 + a12 * a23 * a31 + a13 * a21 * a32 – (a13 * a22 * a31 + a12 * a21 * a33 + a11 * a23 * a32); 

script matrix_4x4 { 

    input a11 = 0; 

    input a12 = 0; 

    input a13 = 0; 

    input a14 = 0; 

    input a21 = 0; 

    input a22 = 0; 

    input a23 = 0; 

    input a24 = 0; 

    input a31 = 0; 

    input a32 = 0; 

    input a33 = 0; 

    input a34 = 0; 

    input a41 = 0; 

    input a42 = 0; 

    input a43 = 0; 

    input a44 = 0; 

 

    plot delta = a31 * matrix_3x3(a12, a13, a14, a22, a23, a24, a42, a43, a44) – a32 * matrix_3x3(a11, a13, a14, a21, a23, a24, a41, a43, a44) + a33 * matrix_3x3(a11, a12, a14, a21, a22, a24, a41, a42, a44) – a34 * matrix_3x3(a11, a12, a13, a21, a22, a23, a41, a42, a43); 

    ; 

 

#the equations 

#a∑x3i+b∑x2i+c∑xi+nd=∑yi, 

#a∑x4i+b∑x3i+c∑x2i+d∑xi=∑xiyi, 

#a∑x5i+b∑x4i+c∑x3i+d∑x2i=∑x2iyi, 

#a∑x6i+b∑x5i+c∑x4i+d∑x3i=∑x3iyi; 

 

#======================= 

input fb = 1; 

def bar = if barnumber()>=fb then bar[1]+1 else 0; 

 

def x = bar; 

def sx3 = Sum(Power(x, 3), n); 

def sx2 = Sum(Sqr(x), n); 

def sx = Sum(x, n); 

def sx4 = Sum(Power(x, 4), n); 

def sx5 = Sum(Power(x, 5), n); 

def sx6 = Sum(Power(x, 6), n); 

def sy = Sum(y, n); 

def sxy = Sum(x * y, n); 

def sx2y = Sum(Sqr(x) * y, n); 

def sx3y = Sum(Power(x, 3) * y, n); 

#======================== 

#rewrite the equations with the inputs 

#======================== 

# sx3 sx2 sx   n  | a | sy 

# sx4 sx3 sx2 sx  | b | sxy 

# sx5 sx4 sx3 sx2 | c | sx2y 

# sx6 sx5 sx4 sx3 | d | sx3y 

 

#считаем определитель 

def delta = matrix_4x4(sx3, sx2, sx, n, sx4, sx3, sx2, sx, sx5, sx4, sx3, sx2, sx6, sx5, sx4, sx3); 

def delta_a = matrix_4x4(sy, sx2, sx, n, sxy, sx3, sx2, sx, sx2y, sx4, sx3, sx2, sx3y, sx5, sx4, sx3); 

def delta_b = matrix_4x4(sx3, sy, sx, n, sx4, sxy, sx2, sx, sx5, sx2y, sx3, sx2, sx6, sx3y, sx4, sx3); 

def delta_c = matrix_4x4(sx3,sx2,sy,n,sx4,sx3,sxy,sx,sx5,sx4,sx2y,sx2,sx6,sx5,sx3y,sx3); 

def delta_d = matrix_4x4(sx3,sx2,sx,sy,sx4,sx3,sx2,sxy,sx5,sx4,sx3,sx2y,sx6,sx5,sx4,sx3y); 

def a = delta_a/delta; 

def b = delta_b/delta; 

def c = delta_c/delta; 

def d = delta_d/delta; 

 

plot eq = a*power(x,3)+b*sqr(x)+c*x+d; 

Adaptive Gaussian Moving Average Bands

# Designed to achieve Normal Distribution across all aggregations and instruments 

# Mobius 

# V02.02.2019 

#Hint: Plots a Gaussian Mean with Standard deviation Envelope. If Normal Distribution is met, then at minimum, 68.2% of the close values should be inside a One Standard Deviation Envelope and 95.4% of the close values should be inside a 2 Standard Deviation Envelope. 

 

input length  = 21;   #hint length: length for Moving Average  

input price = close;  #hint price: iData used for calculations 

input SdMult = 2.00;  #hint SdMult: Mult. for Standard Deviation Bands 

input ShowBands = yes;#hint ShowBands: yes or no 

input ShowLabel = yes;#hint ShowLabel: yes or no 

input PaintBars = yes;#hint PaintBars: yes or no 

input BandsColor = 5; #hint BandsColor: Color Range from 1 to 9 

 

def h; 

def l; 

def c; 

def betaDenom; 

def w; 

def beta; 

def alpha; 

def G; 

def SD; 

def count; 

def bars; 

def p; 

plot mean; 

plot upper; 

plot lower; 

h = high; 

l = low; 

c = price; 

betaDenom = 10*(Log(Sum((Max(h, c[1]) – Min(l, c[1])), length) / 

            (Highest(h, length) – Lowest(l, length))) 

            / Log(length)); 

w = (2 * Double.Pi / length); 

beta = (1 – Cos(w)) / (Power(1.414, 2.0 / betaDenom) – 1 ); 

alpha = (-beta + Sqrt(beta * beta + 2 * beta)); 

G = Power(alpha, 4) * c +  

                 4 * (1 – alpha) * G[1] – 6 * Power( 1 – alpha, 2 ) * G[2] +  

                 4 * Power( 1 – alpha, 3 ) * G[3] – Power( 1 – alpha, 4 ) * G[4]; 

SD = StDev(close, length); 

mean = G; 

mean.AssignValueColor(if G > G[1] then Color.CYAN else Color.YELLOW); 

mean.SetLineWeight(2); 

mean.HideBubble(); 

mean.HideTitle(); 

upper = mean + (SdMult * SD); 

upper.SetDefaultColor(GetColor(BandsColor)); 

upper.SetHiding(!ShowBands); 

upper.HideBubble(); 

upper.HideTitle(); 

lower = mean + (-SdMult * SD); 

lower.SetDefaultColor(GetColor(BandsColor)); 

lower.SetHiding(!ShowBands); 

lower.HideBubble(); 

lower.HideTitle(); 

count = if (close > upper) or (close < lower) and barNumber() >= 1 

        then compoundValue(1, count[1] + 1, 0) 

        else count[1]; 

bars = if barNumber() >= 1  

       then CompoundValue(1, bars[1] + 1, 1)  

       else 0; 

p = (bars – count) / bars; 

AddLabel(ShowLabel, “At ” + SDmult +  

                  ” Standard Deviations Inside Bell Curve = ” + AsPercent(p),  

                    Color.WHITE); 

#End Code 

Adaptive Moving Average

# MovAvgAdaptiveUpdated_TASC 

# We have put together a study for thinkorswim based on the article Adaptive Moving Averages by Vitali Apirine # in the Apr issue of TASC.  http://tos.mx/MYXu1P#&nbsp; Name it Moving AverageAdaptive_Updated. 

# JQ: the change seems to be in the addition of the mode input 

# TASC April 2018 

 

input price = close; 

input fastLength = 2; 

input slowLength = 30; 

input effRatioLength = 10; 

input mode = {default KAMA, AMA}; 

 

Assert(fastLength > 0, “‘fast length’ must be positive: ” + fastLength); 

Assert(slowLength > 0, “‘slow length’ must be positive: ” + slowLength); 

 

def direction; 

def volatility; 

def ER; 

 

switch (mode) { 

case KAMA: 

    direction = AbsValue(price – price[effRatioLength]); 

    volatility = Sum(AbsValue(price – price[1]), effRatioLength); 

    ER = if volatility != 0 then direction / volatility else 0; 

case AMA: 

    direction = Double.NaN; 

    volatility = Double.NaN; 

    ER = AbsValue((price – Lowest(low, effRatioLength)) – 

(Highest(high, effRatioLength) – price)) / (Highest(high, 

effRatioLength) – Lowest(low, effRatioLength)); 

 

def FastSF = 2 / (fastLength + 1); 

def SlowSF = 2 / (slowLength + 1); 

def ScaledSF = ER * (FastSF – SlowSF) + SlowSF; 

def AMA = CompoundValue(1, AMA[1] + Sqr(ScaledSF) * (price – AMA[1]), 

price); 

 

plot MovAvgAdaptive = AMA; 

MovAvgAdaptive.SetDefaultColor(GetColor(1)); 

Arnaud Legoux Moving Average

# ALMA (Arnaud Legoux Moving Average) 

# ALMA is based on a shifted Gaussian distribution  

# Mobius 

# Chat Room Request 

# ALMA color change added by ZupDog 

 

input offset = 2; 

input sigma = .5; 

input length = 8; 

plot alma_ = (fold n = 0 to length 

              with s 

              do s + getValue(Exp(-Power(n – Floor(offset * length), 2)/ 

                             (2 * Power((length + 1) / sigma, 2)))*  

                     getValue(close, n), n, length)) /  

              fold nn = 0 to length  

              with ss  

              do ss + getValue(Exp(-Power(nn – Floor(offset * length), 2)/ 

                              (2 * Power((length + 1) / sigma, 2))), nn); 

 

 

alma_.DefineColor(“Up”, GetColor(1)); 

alma_.DefineColor(“Down”, GetColor(0)); 

alma_.AssignValueColor(if alma_ > alma_[1] then alma_.color(“Up”) else alma_.color(“Down”)); 

 

# End Code ALMA 

ColoredMovingAverage

# TS_MOVINGAVERAGE 

 

input displace = 0; 

input length = 9; 

input price = close; 

input movingAverageType = {default Simple, Exponential, Weighted, Hull, Variable}; 

 

rec data; 

 

switch (movingAverageType) { 

case Simple: 

    data = compoundValue(1, Average(price[-displace], length), price); 

case Exponential: 

    data = compoundValue(1, ExpAverage(price[-displace], length), price); 

case Weighted: 

    data = compoundValue(1, wma(price[-displace], length), price); 

Case Hull: 

    data = compoundValue(1, hullMovingAvg(price[-displace], length), price); 

case variable: 

    data = VariableMA(price=price, length=length); 

 

plot ave = data; 

ave.SetLineWeight(2); 

ave.AssignValueColor(if ave > ave[1] then color.cyan else color.dark_red); 

ave.HideBubble(); 

#—————- End Of Code ——————– 

Cycle Point Moving Average

# TS_CyclePointMovingAverage 

 

declare fullrange; 

 

input RequiredPointsForCycleReversal = 10; 

input CycleMovingAveragePeriod = 7; 

 

def ZZData = ZigZagSign(“reversal amount” = RequiredPointsForCycleReversal); 

def isHigh = if ZZData[1] < ZZData and ZZData > ZZData[-1] then 1 else 0; 

def isLow = if ZZData[1] > ZZData and ZZData < ZZData[-1] then 1 else 0; 

plot cyclePoint = if isHigh then high else if isLow then low else double.nan; 

plot CPMA = Average(ZZData, CycleMovingAveragePeriod); 

 

CPMA.DefineColor(“Positive Slope”, color.cyan); 

CPMA.DefineColor(“Negative Slope”, color.magenta); 

CPMA.AssignValueColor(if CPMA – CPMA[1] >= 0 then CPMA.color(“Positive Slope”) else CPMA.color(“Negative Slope”)); 

CPMA.setLineWeight(3); 

 

cyclePoint.SetStyle(curve.POINTS); 

cyclePoint.SetDefaultColor(color.white); 

cyclePoint.SetLineWeight(5); 

#—————- End Of Code ——————– 

Dual Moving Average Upper

## This study adjusts the StanL study noted i the header below. 

## In particular it replaces arrows which only pointed upward with arrows  

## identifying the direction of the cross 

 

# Dual Moving Averages with clouds and cross arrows 

#Labels added by SFL 

#TOS Title = CloudBetween2MovingAverages 

#hint:Cloud usage between two moving averages 

 

declare upper; 

 

#  Input Code 

input price = close;#hint close:Select the price of choice 

input fastLength = 8;#hint fastLength:The fast average length 

input fastAvgType = AverageType.SIMPLE;#hint fastAvgType:Select the average type 

input slowLength = 20;#hint slowLength:The slow average length 

input slowAvgType = AverageType.SIMPLE; #hint slowAvgType:Select the average type 

input Show_Crosses = YES;#hint Show_Crosses:Toggles crossing arrows ON/OFF 

 

#  Moving Average Plot Code 

plot FastMva = MovingAverage( fastAvgType, price, fastLength ); 

plot SlowMva = MovingAverage( slowAvgType, price, slowLength ); 

 

#  Cloud Code 

AddCloud( FastMva, SlowMva, Color.YELLOW, Color.RED ); 

 

#  Crossing Code 

def CrossUp =  if Crosses(FastMva, SlowMva, CrossingDirection.above) then 1 else 0; 

Plot UpArrow = If CrossUp && Show_Crosses then low else double.nan; 

UpArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP); 

UpArrow.SetLineWeight(3); 

UpArrow.SetDefaultColor(Color.GREEN); 

 

def CrossDown =  if Crosses(FastMva, SlowMva, CrossingDirection.below) then 1 else 0; 

Plot DownArrow = If CrossDown && Show_Crosses then high else double.nan; 

DownArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN); 

DownArrow.SetLineWeight(3); 

DownArrow.SetDefaultColor(Color.RED); 

#  Label Code 

#AddLabel(Show_Crosses,”Cross = UP ARROW”,color.PINK); 

 

addlabel(1,”Slow MA(” +  slowLength  + “) is ” +  (If fastAvgType == AverageType.EXPONENTIAL then “Exponential average”  

else if  fastAvgType == AverageType.Hull then “Hull average”  

else if fastAvgType == AverageType.simple then “Simple average” 

else if fastAvgType == AverageType.wilders then “Wilders average” 

else if fastAvgType == AverageType.weighted then “Weighted average” 

else “”)   ,color.cyan); 

 

addlabel(1,”Fast MA(” +  fastLength  + “) is ” +  (If slowAvgType == AverageType.EXPONENTIAL then “Exponential average”  

else if  slowAvgType == AverageType.Hull then “Hull average”  

else if slowAvgType == AverageType.simple then “Simple average” 

else if slowAvgType == AverageType.wilders then “Wilders average” 

else if slowAvgType == AverageType.weighted then “Weighted average” 

else “”)   ,color.pink); 

# end 

 

Dual moving averages difference in a histogram format

#hint:<b>Dual moving averages difference in a  histogram format</b> 

declare lower; 

input price = close;#hint price: The basis for both moving averages 

input fastLength = 9;#hint fastLength:Length of the fast MA 

input fastType = {default SMA, EMA};#hint fastType:Select the type of the fast MA 

input slowLength = 18;#hint slowLength:Length of the slow MA 

input slowType = {default SMA, EMA};#hint slowType:Select the type of the slow MA 

input displace = 0;#hint displace:Displacement applied to both MAs 

 

def fastAvg = if fastType == fastType.SMA Then Average(price[-displace], fastLength) else ExpAverage(price[-displace], fastLength); 

 

def slowAvg = if  slowType == slowType.SMA Then Average(price[-displace], slowLength) else ExpAverage(price[-displace], slowLength); 

 

#======== histogram =========== 

Plot Diff = fastAvg – slowAvg; 

plot ZeroLine = 0; 

ZeroLine.SetDefaultColor(GetColor(0)); 

 

Diff.SetDefaultColor(GetColor(5)); 

Diff.SetPaintingStrategy(PaintingStrategy.HISTOGRAM); 

Diff.SetLineWeight(3); 

Diff.DefineColor(“Positive and Up”, Color.GREEN); 

Diff.DefineColor(“Positive and Down”, Color.DARK_GREEN); 

#Diff.DefineColor(“Positive and Down”, Color.GREEN); 

Diff.DefineColor(“Negative and Down”, Color.RED); 

Diff.DefineColor(“Negative and Up”, Color.DARK_RED); 

#Diff.DefineColor(“Negative and Up”, Color.RED); 

Diff.AssignValueColor(if Diff >= 0 then if Diff > Diff[1] then Diff.color(“Positive and Up”) else Diff.color(“Positive and Down”) else if Diff < Diff[1] then Diff.color(“Negative and Down”) else Diff.color(“Negative and Up”)); 

 

Plot Diff_line = fastAvg – slowAvg; 

Diff_line. setdefaultcolor(color.white); 

Diff_line.SetLineWeight(1); 

 

#======= labels ======== 

AddLabel(yes,”FastMA = ” +fastType + “(” + fastLength + “)”,GetColor(1)); 

AddLabel(yes,”SlowMA = ” +slowType + “(” + slowLength + “)”,GetColor(0)); 

#AddLabel(1, “fastAvg = ” + fastAvg,color.white); 

#AddLabel(1, “slowAvg = ” + slowAvg,color.white); 

 

## Educational Plots and Labels by JQ 

def buytoopen = if diff crosses above zeroline then 1 else double.nan; 

def selltoclose = if fastavg crosses below slowAvg then 1 else double.nan; 

 

plot uparrow = buytoopen; 

uparrow.setPaintingStrategy(PaintingStrategy.ARROW_UP); 

 

plot downarrow = selltoclose; 

downarrow.setPaintingStrategy(PaintingStrategy.ARROW_DOWN); 

 

Ehlers Zero Lag EMA

##  Zero Lag EMA (Using an Error Correcting Filter) 

## JQ 

 

## I have no idea how the math works with code but the Standard EMA plot forces the tos charting package to allocate too much space far below the candles.  This adjustment to the ploting code eliminates that issue.   

## One more thing, if the code is broken it’s my fault not Mobius’…. JQ 

 

# Zero Lag EMA (Using an Error Correcting Filter) 

# Mobius 

# Ported to TOS 08.31.2016 from Article by John Ehlers 

# Using an EMA error term, the current price – EMA[1], the amplitude of the error term is altered by multiplying the error by a gain term. The new filter is an EC or Error Corrected EMA. 

 

# Inputs: 

input Length = 20; 

input GainLimit = 50; 

input hideEarlyPlottingError = yes; 

input LabelsOn = yes; 

 

# Vars: 

def alpha; 

def BestGain; 

def EC1; 

def Gain; 

def EC; 

def Error; 

def LeastError; 

def EMA; 

 

 

alpha = 2 / (Length + 1); 

EMA = alpha * close + (1 – alpha) * EMA[1]; 

plot EMAdata = if hideEarlyPlottingError then if barnumber() >= length then EMA else double.nan else EMA; 

EMAdata.SetDefaultColor(Color.Yellow); 

 

 

 

Gain = fold g = -GainLimit to GainLimit 

       do getValue(g / 10, g); 

EC1 = fold V = -GainLimit to GainLimit 

      do alpha * (EMA + (fold i = -GainLimit to GainLimit 

                         do i / 10) * (Close – EC1[1])) + (1 – alpha) * EC1[1]; 

Error = AbsValue(Close – EC1); 

If Error < 1000000 

Then { 

LeastError = Error; 

BestGain = Gain; 

} else { 

LeastError = LeastError[1]; 

BestGain = 0; 

EC = alpha * (EMA + BestGain * (Close – EC1)) + (1 – alpha) * EC1; 

Plot ECdata = if hideearlyplottingerror then if barnumber() >= length then EC else double.nan else EC; 

ECdata.SetDefaultColor(Color.Cyan); 

AddLabel(LabelsOn, “Standard EMA”, color.yellow); 

AddLabel(LabelsOn, “Error Corrected EMA”, color.cyan); 

#End Code Error Corrected EMA 

EhlersForwardReverseEMA

# Forward / Reverse EMA 

 

declare lower; 

 

# Inputs: 

input AA = .1; 

 

# Vars: 

def CC; 

def RE1; 

def RE2; 

def RE3; 

def RE4; 

def RE5; 

def RE6; 

def RE7; 

def RE8; 

def EMA; 

plot Signal; 

plot plot0; 

 

CC = if CC[1] == 0 then .9 else 1 – AA; 

EMA = AA * Close + CC * EMA[1]; 

RE1 = CC * EMA + EMA[1]; 

RE2 = Power(CC, 2)   * RE1 + RE1[1]; 

RE3 = Power(CC, 4)   * RE2 + RE2[1]; 

RE4 = Power(CC, 8)   * RE3 + RE3[1]; 

RE5 = Power(CC, 16)  * RE4 + RE4[1]; 

RE6 = Power(CC, 32)  * RE5 + RE5[1]; 

RE7 = Power(CC, 64)  * RE6 + RE6[1]; 

RE8 = Power(CC, 128) * RE7 + RE7[1]; 

 

Signal = EMA – AA * RE8; 

signal.AssignValueColor(if Signal > Signal[1] 

                        then color.green 

                        else color.red); 

Plot0 = if isNaN(close) then double.nan else 0; 

Plot0.SetDefaultColor(Color.gray); 

addCloud(0, Signal, color.red, color.green); 

# End Code Ehlers Forward / Reverse EMA 

Elders Moving Average Envelope

# Elders Moving Average Envelope 

 

input n = 21; 

input SDlength = 21; 

input value = close; 

input widthOfChannel = 2.0; 

 

def dist = HighestAll(StDev(value, SDlength)) * widthOfChannel; 

plot LR = ExpAverage(value, n); 

plot UpperBand = LR + dist; 

plot LowerBand = LR – dist; 

# End Code 

Fractal Adaptive Moving Average with Standard Deviation Bands

# FRAMA Fractal Adaptive Moving Average with Standard Deviation Bands  

 

input n = 20; 

input price = close; 

input SDmult = 2; 

input ATRmult = 1.5; 

input DisplayBands = yes; 

Assert(n % 2 == 0, “n must be a number divisible by 2”); 

 

def o = open; 

def h = high; 

def l = low; 

def c = close; 

def n1 = (h – l) / (N/2); 

def n2; 

def n3 = (Highest(h, N) – Lowest(l, N)) / N; 

def dimen; 

def alpha; 

def filt; 

def count = fold i = 0 to (n/2) 

            with p 

            do if GetValue(h, GetMaxValueOffset(h, n/2), n) > h  

               then GetValue(h, GetMaxValueOffset(h, n/2), n) 

            else if GetValue(l, GetMinValueOffset(l, n/2), n) < l 

                 then GetValue(l, GetMinValueOffset(l, n/2), n) 

            else count[1]; 

def HH1 = h[n/2]; 

def LL1 = l[n/2]; 

def count2 = fold j = n/2 to n 

             with q 

             do if GetValue(HH1, GetMaxValueOffset(HH1, n/2), n) > HH1 

                then GetValue(HH1, GetMaxValueOffset(HH1, n/2), n) 

             else if GetValue(LL1, GetMinValueOffset(LL1, n/2), n) < LL1 

                  then GetValue(LL1, GetMinValueOffset(LL1, n/2), n) 

             else count[1]; 

 

N2 = (count – count2) / (N / 2); 

dimen = if N1 > 0 and N2 > 0 and N3 > 0 then (Log(N1 + N2) – Log(N3)) / Log(2) else 0; 

alpha = if Dimen == .7  

        then .02  

        else if Dimen == .05  

        then .33  

        else if Exp(-4.6*(Dimen – 1)) < .01  

        then .01 

        else if Exp(-4.6* (Dimen – 1)) > 1 then 1 

        else 0; 

Filt = alpha * Price + (1 – alpha) * Filt[1]; 

 

plot FRAMA = Inertia(filt, n); 

     FRAMA.SetDefaultColor(Color.Yellow); 

 

def SD = StDev(c, n); 

def ATR = Average(TrueRange(h, c, l), n); 

plot upperSD = FRAMA + (SDmult * SD); 

     upperSD.SetHiding(!DisplayBands); 

     upperSD.SetDefaultColor(CreateColor(50,50,50)); 

plot lowerSD = FRAMA + (-SDmult * SD); 

     lowerSD.SetHiding(!DisplayBands); 

     lowerSD.SetDefaultColor(CreateColor(50,50,50)); 

plot upperATR = FRAMA + (ATRmult * ATR); 

     upperATR.SetHiding(!DisplayBands); 

     upperATR.SetDefaultColor(Color.White); 

plot lowerATR = FRAMA + (-ATRmult * ATR); 

     lowerATR.SetHiding(!DisplayBands); 

     lowerATR.SetDefaultColor(Color.White); 

 

AddCloud(lowerATR, lowerSD, Color.Current, Color.White); 

AddCloud(upperSD, upperATR, Color.Current, Color.White); 

#end 

GaussianMeanCrossover

declare lower; 

 

#plot Data = close; 

input GaussianLength = 5; 

input GaussianLengthLong = 20; 

input betaDev = 7.0; #hint betaDev: adjust this value till the label indicates a minimum of 68.2% of closes 

 

# Trying to achieve Normal Distribution 

# Mobius 

# V01.09.2015 

 

def c; 

def w; 

def beta; 

def alpha; 

def G; 

 

plot GaussianMean; 

GaussianMean.SetDefaultColor(Color.WHITE); 

GaussianMean.setLineWeight(2); 

 

c = close; 

w = (2 * Double.Pi / GaussianLength); 

beta = (1 – Cos(w)) / (Power(1.414, 2.0 / betaDev) – 1 ); 

alpha = (-beta + Sqrt(beta * beta + 2 * beta)); 

G = Power(alpha, 4) * c +  

                 4 * (1 – alpha) * G[1] – 6 * Power( 1 – alpha, 2 ) * G[2] +  

                 4 * Power( 1 – alpha, 3 ) * G[3] – Power( 1 – alpha, 4 ) * G[4]; 

 

GaussianMean = G; 

 

 

#*******************************************************************************; 

 

# Trying to achieve Normal Distribution 

# Mobius 

# V01.09.2015 

def c2; 

def w2; 

def beta2; 

def alpha2; 

def G2; 

 

plot GaussianMeanLong; 

GaussianMeanLong.SetDefaultColor(Color.YELLOW); 

GaussianMeanLong.setLineWeight(2); 

 

c2 = close; 

w2 = (2 * Double.Pi / GaussianLengthLong); 

beta2 = (1 – Cos(w2)) / (Power(1.414, 2.0 / betaDev) – 1 ); 

alpha2= (-beta2 + Sqrt(beta2 * beta2 + 2 * beta2)); 

G2 = Power(alpha2, 4) * c2 +  

                 4 * (1 – alpha2) * G2[1] – 6 * Power( 1 – alpha2, 2 ) * G2[2] +  

                 4 * Power( 1 – alpha2, 3 ) * G2[3] – Power( 1 – alpha2, 4 ) * G2[4]; 

 

GaussianMeanLong = G2; 

 

 

     

    # Crosses 

plot BullishCross = GaussianMean crosses above GaussianMeanLong; 

bullishCross.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP); 

bullishCross.setDefaultColor(color.uptick); 

 

Plot BearishCross = GaussianMean crosses below GaussianMeanLong; 

BearishCross.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN); 

BearishCross.setDefaultColor(color.Downtick); 

 

# Total Cross Count in Bubbles 

# TsL for fredw 

# Nube 9.24.18 

 

    # universals 

def bn = BarNumber(); 

#def c  = close; 

def na = Double.NaN; 

    # variables                             

def bullish = GaussianMean > GaussianMeanLong; 

def bearish = GaussianMean < GaussianMeanLong; 

def upCross   = GaussianMean crosses above GaussianMeanLong; 

def upCrossCt = CompoundValue(1, 

                if   upCross 

                then upCrossCt[1] + 1 

                else upCrossCt[1],0); 

def currentUpCrossCount = HighestAll(if !IsNaN(c) && IsNaN(c[-1]) 

                                     then upCrossCt else na); 

def upCrossBar = if   upCross 

                 then bn else upCrossBar[1]; 

 

def dnCross   = GaussianMean crosses below GaussianMeanLong; 

def dnCrossCt = CompoundValue(1, 

                if   dnCross 

                then dnCrossCt[1] + 1 

                else dnCrossCt[1],0); 

def CurrentDnCrossCount = HighestAll(if !IsNaN(c) && IsNaN(c[-1]) 

                                     then dnCrossCt else na); 

def dnCrossBar = if   dnCross 

                 then bn else dnCrossBar[1]; 

 

    # plots                 

AddChartBubble(bullish and (bn == highestall(upCrossBar)),high,””+currentUpCrossCount, Color.Uptick,GaussianMean > GaussianMeanLong); 

AddChartBubble(bearish and (bn == highestall(upCrossBar)), low,””+currentdnCrossCount, Color.Downtick,GaussianMean < GaussianMeanLong); 

 

    # alternative version for those who prefer to also use GetValue() 

#def currentBar = HighestAll(if !IsNaN(c) && IsNaN(c[-1]) 

#                            then bn else na); 

#def getUpCount = GetValue(upCrossCt, bn – currentBar); 

#AddChartBubble(bn == upCrossBar, high,””+getUpCount, Color.Light_Gray); 

 

 

## End GaussianMeanCrossover_v02_20181030_JQ 

Guppy Moving Average

# Guppy Multiple Moving Averages 
 
input price = open; 
input EMA1 = 3; 
input EMA2 = 5; 
input EMA3 = 8; 
input EMA4 = 10; 
input EMA5 = 12; 
input EMA6 = 15; 
input EMA7 = 30; 
input EMA8 = 35; 
input EMA9 = 40; 
input EMA10 = 45; 
input EMA11 = 50; 
input EMA12 = 60; 
 
plot XMA1; 
plot XMA2; 
plot XMA3; 
plot XMA4; 
plot XMA5; 
plot XMA6; 
plot XMA7; 
plot XMA8; 
plot XMA9; 
plot XMA10; 
plot XMA11; 
plot XMA12; 
XMA1 = ExpAverage(price, EMA1); 
XMA2 = ExpAverage(price, EMA2); 
XMA3 = ExpAverage(price, EMA3); 
XMA4 = ExpAverage(price, EMA4); 
XMA5 = ExpAverage(price, EMA5); 
XMA6 = ExpAverage(price, EMA6); 
XMA7 = ExpAverage(price, EMA7); 
XMA8 = ExpAverage(price, EMA8); 
XMA9 = ExpAverage(price, EMA9); 
XMA10 = ExpAverage(price, EMA10); 
XMA11 = ExpAverage(price, EMA11); 
XMA12 = ExpAverage(price, EMA12); 
XMA1.SetDefaultColor(CreateColor(255, 190, 0)); 
XMA2.SetDefaultColor(CreateColor(255, 190, 0)); 
XMA3.SetDefaultColor(CreateColor(255, 190, 0)); 
XMA4.SetDefaultColor(CreateColor(255, 190, 0)); 
XMA5.SetDefaultColor(CreateColor(255, 195, 0)); 
XMA6.SetDefaultColor(CreateColor(255, 190, 0)); 
XMA7.SetDefaultColor(CreateColor(255, 80, 0)); 
XMA8.SetDefaultColor(CreateColor(255, 80, 0)); 
XMA9.SetDefaultColor(CreateColor(255, 80, 0)); 
XMA10.SetDefaultColor(CreateColor(255, 80, 0)); 
XMA11.SetDefaultColor(CreateColor(255, 80, 0)); 
XMA12.SetDefaultColor(CreateColor(255, 80, 0)); 
 
def crossover = Crosses(EMA1, EMA12, CrossingDirection.Above); 
def crossunder = Crosses(EMA1, EMA12, CrossingDirection.below); 
 
alert(crossover, ”hello”, alert.ONCE, sound.Ring); 
alert(crossunder, ”hello”, alert.ONCE, sound.Ring); 
 

 

MA Crossover

# MA Cross Signal 

 

def CL = close; 

def MA8  = ExpAverage(CL, 8); 

def MA21 = ExpAverage(CL, 21); 

def MA34 = ExpAverage(CL, 34); 

def MA55 = ExpAverage(CL, 55); 

def MA89 = ExpAverage(CL, 89); 

 

def greaterUP = MA8 crosses above max(MA21, max (MA34, max(MA55, MA89))); 

plot isTRUEup = greaterUP;  # cond1 + cond2 + cond3 + cond4 >= 1 then 1 else 0; 

        isTRUEup.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP); 

        isTRUEup.SetdefaultColor(Color.GREEN); 

        isTRUEup.SetlineWeight(3); 

 

def greaterDN = MA8 crosses below min(MA21, min (MA34, min(MA55, MA89))); 

plot isTRUEdn = greaterDN;  # cond1 + cond2 + cond3 + cond4 >= 1 then 1 else 0; 

        isTRUEdn.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN); 

        isTRUEdn.SetdefaultColor(color.RED); 

        isTRUEdn.SetlineWeight(3); 

 

AddVerticalLine(greaterUP, “CALL”, Color.GREEN); 

AddVerticalLine(greaterDN, “PUT”, Color.RED); 

 

# To keep track of the number of bars since the cross happened, the  

# following code segment will display what’s happening. 

 

rec countUP = CompoundValue(1, if greaterDN then Double.NaN else if greaterUP then 1 else countUP[1] + 1, Double.NaN); 

 

plot g_c = countUP; 

        g_c.SetPaintingStrategy(PaintingStrategy.VALUES_ABOVE); 

 

rec countDN = CompoundValue(1, if greaterUP then Double.NaN else if greaterDN then 1 else countDN[1] + 1, Double.NaN); 

 

plot gd_c = countDN; 

        gd_c.SetPaintingStrategy(PaintingStrategy.VALUES_BELOW); 

 

# End Study 

MA_SD_Channel

#TOS title = MA_SD_Channel 

#Hint:Plots a Standard Deviation or Linear Deviation channel of the close  MA  

 plot WhiteLabel = Double.NaN; 

WhiteLabel.SetDefaultColor(Color.White); 

 

declare upper; 

Input Type = {default “Standard Deviation”, “Linear Deviation”}; 

def Choice; 

switch (Type){ 

case “Standard Deviation”: 

    Choice = 1; 

case “Linear Deviation”: 

    Choice = 2; 

Input AveType = AverageType.SIMPLE; 

 

#input ArrowSize    = 2;#SFL=This does not respond in the customizing screen. 

input ShowArrows   = Yes; 

input ColoredBands = yes; 

input CloudsOn     = yes; 

input PlotClose    = no; 

input Length       = 10; 

input Dev_Dn       = -0.8; 

input Dev_Up       = +0.8; 

 

plot Data = If PlotClose then Close else Double.Nan; 

def Deviation = If Choice == 1 then stdev(close, Length) else lindev(close,  Length); 

 

plot MidLineDef = MovingAverage(AveType, close, Length); 

MidLineDef.SetDefaultColor(Color.Blue); 

def LowerBandDef = MidLineDef + Dev_Dn * Deviation; 

def UpperBandDef = MidLineDef + Dev_Up * Deviation; 

 

 

def RelativePosition =  

  if close > UpperBandDef then 1 else  # Plot above band =  2   

    if close < LowerBandDef then -1    # Plot below band = -2 

    else 0    ;                        # between  bands  =  0      

 

 

rec PositionStatus = compoundValue(1,  

  if PositionStatus[1] == RelativePosition or RelativePosition == 0 then PositionStatus[1] 

  else  

    if RelativePosition == 1 then 1  

    else -1, 0);  # Keeps track of changes in plot relative to bands  

                  # 2 if changed and above -2 if changed and below 

                  # 0 if no change or inside the bands 

plot Midline   = MidlineDef; 

     Midline.SetDefaultColor(GetColor(1)); 

     Midline.AssignValueColor (Color.Dark_Gray); 

 

plot UpperBand = UpperBandDef; 

     UpperBand.AssignValueColor ( 

        if !ColoredBands then Color.White 

        else  

          if PositionStatus[0] == 1 then CreateColor(0, 160, 0) 

          else CreateColor(160, 0, 0)); 

 

plot LowerBand = LowerBandDef; 

     LowerBand.AssignValueColor ( 

        if !ColoredBands then Color.White 

        else  

          if PositionStatus[0] == -1 then CreateColor(160, 0, 0) 

          else CreateColor(0, 160, 0)); 

 

def space3 = (UpperBandDef – LowerBandDef) / 5; 

 

# Arrows. 

plot UpArrow = 

  if ShowArrows then 

    if PositionStatus[0] == PositionStatus[1] then double.NAN 

    else if PositionStatus[0] == 1 then  

    Min(Low,LowerBandDef) – space3   else double.NAN 

  else double.NAN; 

     UpArrow.SetPaintingStrategy(PaintingStrategy.Arrow_Up); 

     UpArrow.SetDefaultColor(Color.Yellow); 

     UpArrow.SetLineWeight(3); 

 

plot DownArrow = 

  if ShowArrows then 

    if PositionStatus[0] == PositionStatus[1] then Double.NaN 

    else if PositionStatus[0] == -1 then  

    Max(High,UpperBandDef) + space3 else double.NAN 

else double.NAN; 

     DownArrow.SetPaintingStrategy(PaintingStrategy.Arrow_Down); 

     DownArrow.SetDefaultColor(Color.Yellow); 

     DownArrow.SetLineWeight(3); 

 

 

# Clouds 

plot GreenUpperCloud = if CloudsOn and PositionStatus[0] == 1 then  

  UpperBandDef else double.NAN; 

GreenUpperCloud.hide(); 

plot GreenLowerCloud = if CloudsOn and PositionStatus[0] == 1 then  

  LowerBandDef else double.NAN; 

GreenLowerCloud.hide(); 

AddCloud (GreenUpperCloud, GreenLowerCloud, CreateColor(0, 70, 0),CreateColor(0, 70, 0)); 

AddCloud (GreenUpperCloud, GreenLowerCloud, CreateColor(0,255,0),CreateColor(0, 255, 0)); 

 

plot RedUpperCloud = if CloudsOn and PositionStatus[0] == -1 then  

  UpperBandDef else double.NAN; 

RedUpperCloud.hide(); 

plot RedLowerCloud = if CloudsOn and PositionStatus[0] == -1 then 

  LowerBandDef else double.NAN; 

RedLowerCloud.hide();#.SetDefaultColor(CreateColor(200, 0, 0)); 

AddCloud (RedUpperCloud, RedLowerCloud, CreateColor(255, 0, 0),CreateColor(255, 0, 0));  

#end 

Ehler’s Mesa Adaptive Moving Average

# MIT License 

# Copyright (c) <2010> <Radford Juang> 

#Permission is hereby granted, free of charge, to any person obtaining a copy 

#of this software and associated documentation files (the “Software”), to deal 

#in the Software without restriction, including without limitation the rights 

#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 

#copies of the Software, and to permit persons to whom the Software is 

#furnished to do so, subject to the following conditions: 

#The above copyright notice and this permission notice shall be included in 

#all copies or substantial portions of the Software. 

#THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 

#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 

#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 

#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 

#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 

#THE SOFTWARE. 

 

script WMA_Smooth { 

    input price = hl2; 

    plot smooth = (4 * price 

+ 3 * price[1] 

+ 2 * price[2] 

+ price[3]) / 10; 

 

script Phase_Accumulation { 

# This is Ehler’s Phase Accumulation code. It has a full cycle delay. 

# However, it computes the correction factor to a very high degree. 

    input price = hl2; 

 

    rec Smooth; 

    rec Detrender; 

    rec Period; 

    rec Q1; 

    rec I1; 

    rec I1p; 

    rec Q1p; 

    rec Phase1; 

    rec Phase; 

    rec DeltaPhase; 

    rec DeltaPhase1; 

    rec InstPeriod1; 

    rec InstPeriod; 

    def CorrectionFactor; 

 

    if BarNumber() <= 5 

    then { 

        Period = 0; 

        Smooth = 0; 

        Detrender = 0; 

        CorrectionFactor = 0; 

        Q1 = 0; 

        I1 = 0; 

        Q1p = 0; 

        I1p = 0; 

        Phase = 0; 

        Phase1 = 0; 

        DeltaPhase1 = 0; 

        DeltaPhase = 0; 

        InstPeriod = 0; 

        InstPeriod1 = 0; 

    } else { 

        CorrectionFactor = 0.075 * Period[1] + 0.54; 

 

# Smooth and detrend my smoothed signal: 

        Smooth = WMA_Smooth(price); 

        Detrender = ( 0.0962 * Smooth 

+ 0.5769 * Smooth[2] 

– 0.5769 * Smooth[4] 

– 0.0962 * Smooth[6] ) * CorrectionFactor; 

 

# Compute Quadrature and Phase of Detrended signal: 

        Q1p = ( 0.0962 * Detrender 

+ 0.5769 * Detrender[2] 

– 0.5769 * Detrender[4] 

– 0.0962 * Detrender[6] ) * CorrectionFactor; 

        I1p = Detrender[3]; 

 

# Smooth out Quadrature and Phase: 

        I1 = 0.15 * I1p + 0.85 * I1p[1]; 

        Q1 = 0.15 * Q1p + 0.85 * Q1p[1]; 

 

# Determine Phase 

        if I1 != 0 

        then { 

# Normally, ATAN gives results from -pi/2 to pi/2. 

# We need to map this to circular coordinates 0 to 2pi 

 

            if Q1 >= 0 and I1 > 0 

            then { # Quarant 1 

                Phase1 = ATan(AbsValue(Q1 / I1)); 

            } else if Q1 >= 0 and I1 < 0 

            then { # Quadrant 2 

                Phase1 = Double.Pi – ATan(AbsValue(Q1 / I1)); 

            } else if Q1 < 0 and I1 < 0 

            then { # Quadrant 3 

                Phase1 = Double.Pi + ATan(AbsValue(Q1 / I1)); 

            } else { # Quadrant 4 

                Phase1 = 2 * Double.Pi – ATan(AbsValue(Q1 / I1)); 

            } 

        } else if Q1 > 0 

        then { # I1 == 0, Q1 is positive 

            Phase1 = Double.Pi / 2; 

        } else if Q1 < 0 

        then { # I1 == 0, Q1 is negative 

            Phase1 = 3 * Double.Pi / 2; 

        } else { # I1 and Q1 == 0 

            Phase1 = 0; 

        } 

 

# Convert phase to degrees 

        Phase = Phase1 * 180 / Double.Pi; 

 

        if Phase[1] < 90 and Phase > 270 

        then { 

# This occurs when there is a big jump from 360-0 

            DeltaPhase1 = 360 + Phase[1] – Phase; 

        } else { 

            DeltaPhase1 = Phase[1] – Phase; 

        } 

 

# Limit our delta phases between 7 and 60 

        if DeltaPhase1 < 7 

        then { 

            DeltaPhase = 7; 

        } else if DeltaPhase1 > 60 

        then { 

            DeltaPhase = 60; 

        } else { 

            DeltaPhase = DeltaPhase1; 

        } 

 

# Determine Instantaneous period: 

        InstPeriod1 = 

-1 * (fold i = 0 to 40 with v=0 do 

if v < 0 then 

else if v > 360 then 

-i 

else 

v + GetValue(DeltaPhase, i, 41) 

); 

 

        if InstPeriod1 <= 0 

        then { 

            InstPeriod = InstPeriod[1]; 

        } else { 

            InstPeriod = InstPeriod1; 

        } 

 

        Period = 0.25 * InstPeriod + 0.75 * Period[1]; 

    } 

    plot DC = Period; 

 

script Ehler_MAMA { 

    input price = hl2; 

    input FastLimit = 0.5; 

    input SlowLimit = 0.05; 

 

 

    rec Period; 

    rec Period_raw; 

    rec Period_cap; 

    rec Period_lim; 

 

    rec Smooth; 

    rec Detrender; 

    rec I1; 

    rec Q1; 

    rec jI; 

    rec jQ; 

    rec I2; 

    rec Q2; 

    rec I2_raw; 

    rec Q2_raw; 

 

    rec Phase; 

    rec DeltaPhase; 

    rec DeltaPhase_raw; 

    rec alpha; 

    rec alpha_raw; 

 

    rec Re; 

    rec Im; 

    rec Re_raw; 

    rec Im_raw; 

 

    rec SmoothPeriod; 

    rec vmama; 

    rec vfama; 

 

    def CorrectionFactor = Phase_Accumulation(price).CorrectionFactor; 

 

    if BarNumber() <= 5 

    then { 

        Smooth = 0; 

        Detrender = 0; 

 

        Period = 0; 

        Period_raw = 0; 

        Period_cap = 0; 

        Period_lim = 0; 

        I1 = 0; 

        Q1 = 0; 

        I2 = 0; 

        Q2 = 0; 

        jI = 0; 

        jQ = 0; 

        I2_raw = 0; 

        Q2_raw = 0; 

        Re = 0; 

        Im = 0; 

        Re_raw = 0; 

        Im_raw = 0; 

        SmoothPeriod = 0; 

        Phase = 0; 

        DeltaPhase = 0; 

        DeltaPhase_raw = 0; 

        alpha = 0; 

        alpha_raw = 0; 

        vmama = 0; 

        vfama = 0; 

    } else { 

# Smooth and detrend my smoothed signal: 

        Smooth = WMA_Smooth(price); 

        Detrender = ( 0.0962 * Smooth 

+ 0.5769 * Smooth[2] 

– 0.5769 * Smooth[4] 

– 0.0962 * Smooth[6] ) * CorrectionFactor; 

 

        Q1 = ( 0.0962 * Detrender 

+ 0.5769 * Detrender[2] 

– 0.5769 * Detrender[4] 

– 0.0962 * Detrender[6] ) * CorrectionFactor; 

        I1 = Detrender[3]; 

 

        jI = ( 0.0962 * I1 

+ 0.5769 * I1[2] 

– 0.5769 * I1[4] 

– 0.0962 * I1[6] ) * CorrectionFactor; 

 

        jQ = ( 0.0962 * Q1 

+ 0.5769 * Q1[2] 

– 0.5769 * Q1[4] 

– 0.0962 * Q1[6] ) * CorrectionFactor; 

 

# This is the complex conjugate 

        I2_raw = I1 – jQ; 

        Q2_raw = Q1 + jI; 

 

        I2 = 0.2 * I2_raw + 0.8 * I2_raw[1]; 

        Q2 = 0.2 * Q2_raw + 0.8 * Q2_raw[1]; 

 

        Re_raw = I2 * I2[1] + Q2 * Q2[1]; 

        Im_raw = I2 * Q2[1] – Q2 * I2[1]; 

 

        Re = 0.2 * Re_raw + 0.8 * Re_raw[1]; 

        Im = 0.2 * Im_raw + 0.8 * Im_raw[1]; 

 

# Compute the phase 

        if Re != 0 and Im != 0 

        then { 

            Period_raw = 2 * Double.Pi / ATan(Im / Re); 

        } else { 

            Period_raw = 0; 

        } 

 

        if Period_raw > 1.5 * Period_raw[1] 

        then { 

            Period_cap = 1.5 * Period_raw[1]; 

        } else if Period_raw < 0.67 * Period_raw[1] { 

            Period_cap = 0.67 * Period_raw[1]; 

        } else { 

            Period_cap = Period_raw; 

        } 

 

        if Period_cap < 6 

        then { 

            Period_lim = 6; 

        } else if Period_cap > 50 

        then { 

            Period_lim = 50; 

        } else { 

            Period_lim = Period_cap; 

        } 

 

        Period = 0.2 * Period_lim + 0.8 * Period_lim[1]; 

        SmoothPeriod = 0.33 * Period + 0.67 * SmoothPeriod[1]; 

 

        if I1 != 0 

        then { 

            Phase = ATan(Q1 / I1); 

        } else if Q1 > 0 

        then { # Quadrant 1: 

            Phase = Double.Pi / 2; 

        } else if Q1 < 0 

        then { # Quadrant 4: 

            Phase = -Double.Pi / 2; 

        } else { # Both numerator and denominator are 0. 

            Phase = 0; 

        } 

 

        DeltaPhase_raw = Phase[1] – Phase; 

        if DeltaPhase_raw < 1 

        then { 

            DeltaPhase = 1; 

        } else { 

            DeltaPhase = DeltaPhase_raw; 

        } 

 

        alpha_raw = FastLimit / DeltaPhase; 

        if alpha_raw < SlowLimit 

        then { 

            alpha = SlowLimit; 

        } else { 

            alpha = alpha_raw; 

        } 

        vmama = alpha * price + (1 – alpha) * vmama[1]; 

        vfama = 0.5 * alpha * vmama + (1 – 0.5 * alpha) * vfama[1]; 

    } 

 

    plot MAMA = vmama; 

    plot FAMA = vfama; 

 

 

declare upper; 

input price = hl2; 

input FastLimit = 0.5; 

input SlowLimit = 0.05; 

 

plot MAMA = Ehler_MAMA(price, FastLimit, SlowLimit).MAMA; 

plot FAMA = Ehler_MAMA(price, FastLimit, SlowLimit).FAMA; 

 

plot Crossing = Crosses((MAMA < FAMA), yes); 

Crossing.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP); 

 

plot Crossing1 = Crosses((MAMA > FAMA), yes); 

Crossing1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN); 

 

AddLabel(yes, Concat(“MAMA: “, Concat(“”, 

if MAMA > FAMA then “Bull” else “Bear”)), 

 

if MAMA > FAMA then Color.GREEN else Color.RED); 

addcloud (MAMA, FAMA); 

 

Alert(Crossing, “FAMA crosses above MAMA”, alert.bar, sound.bell); 

Alert(Crossing1,”FAMA crosses below MAMA”, alert.bar, sound.bell); 

 

Moving Average Crossover With Arrows, Alerts, Crossing Count and Bubble at Cross

# Moving Average Crossover With Arrows, Alerts, Crossing Count and Bubble at Cross 

# Mobius 

# Chat Room Request 01.25.2017 

 

input price = close; 

input fastLength = 20; 

input slowLength = 50; 

input averageType = AverageType.EXPONENTIAL; 

 

plot FastMA = MovingAverage(averageType, price, fastLength); 

plot SlowMA = MovingAverage(averageType, price, slowLength); 

FastMA.SetDefaultColor(GetColor(1)); 

SlowMA.SetDefaultColor(GetColor(2)); 

 

plot ArrowUp = if FastMA crosses above SlowMA 

               then low 

               else double.nan; 

     ArrowUP.SetPaintingStrategy(PaintingStrategy.Arrow_UP); 

     ArrowUP.SetLineWeight(3); 

     ArrowUP.SetDefaultColor(Color.Green); 

plot ArrowDN = if FastMA crosses below SlowMA 

               then high 

               else double.nan; 

     ArrowDN.SetPaintingStrategy(PaintingStrategy.Arrow_DOWN); 

     ArrowDN.SetLineWeight(3); 

     ArrowDN.SetDefaultColor(Color.Red); 

Alert(ArrowUp, ” “, Alert.Bar, Sound.Chimes); 

Alert(ArrowDN, ” “, Alert.Bar, Sound.Bell); 

def countUP = if FastMA crosses above SlowMA 

              then 1 

              else if FastMA > SlowMA 

                   then countUP[1] + 1 

              else if ArrowDN 

                   then 0 

                   else countUP[1]; 

AddLabel(1, “Count UP = ” + countUP, color.white); 

def CrossBar = if FastMA crosses SlowMa 

               then barNumber() 

               else double.nan; 

AddChartBubble(barNumber() == HighestAll(CrossBar), FastMA, “Cross”, color.cyan); 

# End Code 

Moving Average Plotted as Horizontal Line

http://tos.mx/oRvkoN 

 

 

# Moving Average Plotted as Horizontal Line 

 

input price = FundamentalType.CLOSE; 

input aggregationPeriod = AggregationPeriod.DAY; 

input length = 12; 

input averageType = AverageType.SIMPLE; 

 

def MovAvg = MovingAverage(averageType, Fundamental(price, period = aggregationPeriod), length);  

 

plot MALine = highestAll(if isNaN(close[-1])  

                            then MovAvg 

                            else Double.NaN); 

MALine.SetStyle(Curve.Short_Dash); 

MALine.SetLineWeight(1); 

MALine.SetDefaultColor(CreateColor(50,250,150)); 

Nebual Moving Averages_TSI

declare upper; 

 

input DAYPriceThreshold = 0.75; 

def _50_DAY_pre = Average(close (period = “Day”), 50); 

def Show__50_DAY = between(close, _50_DAY_pre – DAYPriceThreshold, _50_DAY_pre + DAYPriceThreshold); 

plot _50_DAY = if(Show__50_DAY, _50_DAY_pre, Double.NaN); 

_50_DAY.SetDefaultColor(Color.ORANGE); 

AddChartBubble(_50_DAY and !IsNaN(close) and IsNaN(close[-1]), _50_DAY, “50-Day MA”, Color.YELLOW); 

def _200_DAY_pre = Average(close (period = “Day”), 200); 

def Show__200_DAY = between(close, _200_DAY_pre – DAYPriceThreshold, _200_DAY_pre + DAYPriceThreshold); 

plot _200_DAY = if(Show__200_DAY, _200_DAY_pre, Double.NaN); 

_200_DAY.SetDefaultColor(Color.DARK_ORANGE); 

AddChartBubble(_200_DAY and !IsNaN(close) and IsNaN(close[-1]), _200_DAY, “200-Day MA”, Color.YELLOW); 

SD_Channel

#TOS title = MA_SD_Channel 

#Hint:Plots a Standard Deviation or Linear Deviation channel of the close  MA  

 plot WhiteLabel = Double.NaN; 

WhiteLabel.SetDefaultColor(Color.White); 

 

declare upper; 

Input Type = {default “Standard Deviation”, “Linear Deviation”}; 

def Choice; 

switch (Type){ 

case “Standard Deviation”: 

    Choice = 1; 

case “Linear Deviation”: 

    Choice = 2; 

Input AveType = AverageType.SIMPLE; 

 

#input ArrowSize    = 2;#SFL=This does not respond in the customizing screen. 

input ShowArrows   = Yes; 

input ColoredBands = yes; 

input CloudsOn     = yes; 

input PlotClose    = no; 

input Length       = 10; 

input Dev_Dn       = -0.8; 

input Dev_Up       = +0.8; 

 

plot Data = If PlotClose then Close else Double.Nan; 

def Deviation = If Choice == 1 then stdev(close, Length) else lindev(close,  Length); 

 

plot MidLineDef = MovingAverage(AveType, close, Length); 

MidLineDef.SetDefaultColor(Color.Blue); 

def LowerBandDef = MidLineDef + Dev_Dn * Deviation; 

def UpperBandDef = MidLineDef + Dev_Up * Deviation; 

 

 

def RelativePosition =  

  if close > UpperBandDef then 1 else  # Plot above band =  2   

    if close < LowerBandDef then -1    # Plot below band = -2 

    else 0    ;                        # between  bands  =  0      

 

 

rec PositionStatus = compoundValue(1,  

  if PositionStatus[1] == RelativePosition or RelativePosition == 0 then PositionStatus[1] 

  else  

    if RelativePosition == 1 then 1  

    else -1, 0);  # Keeps track of changes in plot relative to bands  

                  # 2 if changed and above -2 if changed and below 

                  # 0 if no change or inside the bands 

plot Midline   = MidlineDef; 

     Midline.SetDefaultColor(GetColor(1)); 

     Midline.AssignValueColor (Color.Dark_Gray); 

 

plot UpperBand = UpperBandDef; 

     UpperBand.AssignValueColor ( 

        if !ColoredBands then Color.White 

        else  

          if PositionStatus[0] == 1 then CreateColor(0, 160, 0) 

          else CreateColor(160, 0, 0)); 

 

plot LowerBand = LowerBandDef; 

     LowerBand.AssignValueColor ( 

        if !ColoredBands then Color.White 

        else  

          if PositionStatus[0] == -1 then CreateColor(160, 0, 0) 

          else CreateColor(0, 160, 0)); 

 

def space3 = (UpperBandDef – LowerBandDef) / 5; 

 

# Arrows. 

plot UpArrow = 

  if ShowArrows then 

    if PositionStatus[0] == PositionStatus[1] then double.NAN 

    else if PositionStatus[0] == 1 then  

    Min(Low,LowerBandDef) – space3   else double.NAN 

  else double.NAN; 

     UpArrow.SetPaintingStrategy(PaintingStrategy.Arrow_Up); 

     UpArrow.SetDefaultColor(Color.Yellow); 

     UpArrow.SetLineWeight(3); 

 

plot DownArrow = 

  if ShowArrows then 

    if PositionStatus[0] == PositionStatus[1] then Double.NaN 

    else if PositionStatus[0] == -1 then  

    Max(High,UpperBandDef) + space3 else double.NAN 

else double.NAN; 

     DownArrow.SetPaintingStrategy(PaintingStrategy.Arrow_Down); 

     DownArrow.SetDefaultColor(Color.Yellow); 

     DownArrow.SetLineWeight(3); 

 

 

# Clouds 

plot GreenUpperCloud = if CloudsOn and PositionStatus[0] == 1 then  

  UpperBandDef else double.NAN; 

GreenUpperCloud.hide(); 

plot GreenLowerCloud = if CloudsOn and PositionStatus[0] == 1 then  

  LowerBandDef else double.NAN; 

GreenLowerCloud.hide(); 

AddCloud (GreenUpperCloud, GreenLowerCloud, CreateColor(0, 70, 0),CreateColor(0, 70, 0)); 

AddCloud (GreenUpperCloud, GreenLowerCloud, CreateColor(0,255,0),CreateColor(0, 255, 0)); 

 

plot RedUpperCloud = if CloudsOn and PositionStatus[0] == -1 then  

  UpperBandDef else double.NAN; 

RedUpperCloud.hide(); 

plot RedLowerCloud = if CloudsOn and PositionStatus[0] == -1 then 

  LowerBandDef else double.NAN; 

RedLowerCloud.hide();#.SetDefaultColor(CreateColor(200, 0, 0)); 

AddCloud (RedUpperCloud, RedLowerCloud, CreateColor(255, 0, 0),CreateColor(255, 0, 0));  

#end 

Stiffness Indicator

# Markos Katsanos Stiffness Indicator 

# From TASC Nov 2018 

# Transalated to Thinkscript 

# Nube 10.18.18 

 

declare lower; 

    # inputs 

input price           = close; 

input averageLength   = 100; 

input indicatorLength = 60; 

    # variables 

def ma = Average(price, averageLength) – .2 * StDev(price, averageLength); 

def aboveMACount = Sum(price > ma, indicatorLength ); 

    # plots 

plot  

Stiffness = aboveMAcount * 100 / indicatorLength; 

Stiffness.  SetPaintingStrategy(PaintingStrategy.SQUARED_HISTOGRAM); 

Stiffness.  AssignValueColor(if   Stiffness < Stiffness[1] 

                             then Color.DownTick 

                             else Color.UpTick); 

# f/ Markos Katsanos Stiffness Indicator 

 

T3 Moving Average

declare upper; 

 

input indicator    = { T1, T2, default T3, T4, T5, T6 }; 

input price        = close; 

input period       = 10; 

input volumeFactor = 0.70; 

input displace = 0; 

input sign         = { default plus, minus }; 

input Label        = No; 

input paintbars    = No; 

 

 

script _gd { 

  input _price  = close; 

  input _period = 10; 

  input _v      = 0.70; 

  input _sign   = { default plus, minus }; 

  def _ema      = ExpAverage( _price, _period ); 

  plot _gd      = ( _ema * ( 1 + _v ) ) – ( ExpAverage( _ema, _period ) * _v ); 

 

def _t1 = _gd( price[-displace], period, volumeFactor, sign ); 

def _t2 = _gd( _t1,   period, volumeFactor, sign ); 

def _t3 = _gd( _t2,   period, volumeFactor, sign ); 

def _t4 = _gd( _t3,   period, volumeFactor, sign ); 

def _t5 = _gd( _t4,   period, volumeFactor, sign ); 

def _t6 = _gd( _t5,   period, volumeFactor, sign ); 

 

plot T3; 

switch( indicator ) { 

  case T1: 

    T3 = _t1; 

  case T2: 

    T3 = _t2; 

  case T3: 

    T3 = _t3; 

  case T4: 

    T3 = _t4; 

  case T5: 

    T3 = _t5; 

  case T6: 

    T3 = _t6; 

 

T3.AssignValueColor(if T3 > T3[1] then Color.Green else Color.Red); 

T3.HideBubble(); 

 

AddLabel(Label, if T3 > T3[1] then ”  A  ” else ”  A  “, if T3 > T3[1] then Color.Green else Color.Red); 

 

assignPriceColor(if paintbars and T3 <T3[1] then color.dark_red else if paintbars and T3 > T3[1] then color.dark_green else color.CURRENT); 

 

 

Zero Lag EMA

# Zero Lag EMA (Using an Error Correcting Filter) 

# Inputs: 

input Length = 20; 

input GainLimit = 50; 

input LabelsOn = yes; 

 

# Vars: 

def alpha; 

def BestGain; 

def EC1; 

def Gain; 

def EC; 

def Error; 

def LeastError; 

def EMA; 

alpha = 2 / (Length + 1); 

EMA = alpha * close + (1 – alpha) * EMA[1]; 

plot EMAdata = EMA; 

EMAdata.SetDefaultColor(Color.Yellow); 

 

# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv 

 

Gain = fold g = -GainLimit to GainLimit 

       do getValue(g / 10, g); 

EC1 = fold V = -GainLimit to GainLimit 

      do alpha * (EMA + (fold i = -GainLimit to GainLimit 

                         do i / 10) * (Close – EC1[1])) + (1 – alpha) * EC1[1]; 

Error = AbsValue(Close – EC1); 

 

If Error < 1000000 

Then { 

LeastError = Error; 

BestGain = Gain; 

} else { 

LeastError = LeastError[1]; 

BestGain = 0; 

 

# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

 

EC = alpha * (EMA + BestGain * (Close – EC1)) + (1 – alpha) * EC1; 

Plot ECdata = EC; 

ECdata.SetDefaultColor(Color.Cyan); 

AddLabel(LabelsOn, “Standard EMA”, color.yellow); 

AddLabel(LabelsOn, “Error Corrected EMA”, color.cyan); 

#End Code Error Corrected EMA 

Detrended MACD

# Detrended MACD 

 

declare lower; 

 

input fastLength = 12; 

input slowLength = 26; 

input MACDLength = 9; 

input averageType = AverageType.EXPONENTIAL; 

input showBreakoutSignals = no; 

 

plot Value = MovingAverage(averageType, close + (close – close[(fastlength-1)/2]), fastLength) – MovingAverage(averageType, close + (close – close[(slowLength-1)/2]), slowLength); 

plot Avg = MovingAverage(averageType, Value, MACDLength); 

 

plot Diff = Value – Avg; 

plot ZeroLine = 0; 

 

plot UpSignal = if Diff crosses above ZeroLine then ZeroLine else Double.NaN; 

plot DownSignal = if Diff crosses below ZeroLine then ZeroLine else Double.NaN; 

 

UpSignal.SetHiding(!showBreakoutSignals); 

DownSignal.SetHiding(!showBreakoutSignals); 

 

Value.SetDefaultColor(GetColor(1)); 

Avg.SetDefaultColor(GetColor(8)); 

Diff.SetDefaultColor(GetColor(5)); 

Diff.SetPaintingStrategy(PaintingStrategy.HISTOGRAM); 

Diff.SetLineWeight(3); 

Diff.DefineColor(“Positive and Up”, Color.GREEN); 

Diff.DefineColor(“Positive and Down”, Color.DARK_GREEN); 

Diff.DefineColor(“Negative and Down”, Color.RED); 

Diff.DefineColor(“Negative and Up”, Color.DARK_RED); 

Diff.AssignValueColor(if Diff >= 0 then if Diff > Diff[1] then Diff.color(“Positive and Up”) else Diff.color(“Positive and Down”) else if Diff < Diff[1] then Diff.color(“Negative and Down”) else Diff.color(“Negative and Up”)); 

ZeroLine.SetDefaultColor(GetColor(0)); 

UpSignal.SetDefaultColor(Color.UPTICK); 

UpSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP); 

DownSignal.SetDefaultColor(Color.DOWNTICK); 

DownSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN); 

# End Code Detrended MACD 

 

Gaussian Average Convergence Divergence

 GACD (G)aussian (A)verage (C)onvergence (D)ivergence  

# V01.01.2019 

# Study shows Long Term Trend with shading above and below the zero line. Short Term Trend with faster and slower Gaussian Average color line plots. Convergence and Divergence is displayed by the Histogram. Crosses of the Averages and therefore crosses of the Histogram above an below zero are marked with corresponding colored vertical lines. A label has been added to remind the user of trend indication. 

# Note: This study plots on Mobile without some of the features. 

 

declare lower; 

 

input length  = 21; 

input length2 = 34; 

input length3 = 21; 

 

script G  

    { 

    input iData = close; 

    input length = 21; 

    def h = high; 

    def l = low; 

    def c = close; 

    def betaDenom = 10 * (Log(Sum((Max(h, c[1]) – Min(l, c[1])), length) / 

            (Highest(h, length) – Lowest(l, length))) 

            / Log(length)); 

    def w = (2 * Double.Pi / length); 

    def beta = (1 – Cos(w)) / (Power(1.414, 2.0 / betaDenom) – 1 ); 

    def alpha = (-beta + Sqrt(beta * beta + 2 * beta)); 

    def G = Power(alpha, 4) * iData +  

                 4 * (1 – alpha) * G[1] – 6 * Power( 1 – alpha, 2 ) * G[2] +  

                 4 * Power( 1 – alpha, 3 ) * G[3] – Power( 1 – alpha, 4 ) * G[4]; 

    plot data = G; 

plot a = G(close, length) – G(close, length2); 

plot b = G(a, length3); 

plot d = a – b; 

plot “0” = if IsNaN(close)  

           then Double.NaN  

           else 0; 

“0”.SetDefaultColor(Color.WHITE); 

“0”.HideTitle(); 

a.AssignValueColor(if a > b  

                        then Color.GREEN  

                        else Color.RED); 

a.HideBubble(); 

a.HideTitle(); 

b.AssignValueColor(if a > b  

                        then Color.GREEN  

                        else Color.RED); 

b.HideBubble(); 

b.HideTitle(); 

d.SetLineWeight(4); 

d.SetPaintingStrategy(PaintingStrategy.HISTOGRAM); 

d.AssignValueColor(if d > 0 and d > d[1]  

                        then Color.GREEN 

                        else if d > 0 and d < d[1]  

                             then Color.BLUE 

                             else if d < 0 and d < d[1]  

                             then Color.RED 

                        else Color.YELLOW); 

d.HideBubble(); 

AddCloud(a, b, Color.GREEN, Color.RED); 

AddVerticalLine(d crosses 0, “”, if d crosses above 0  

                                 then Color.GREEN  

                                 else Color.RED); 

AddCloud(if Max(a, b) < 0  

         then Max(a, b)  

         else Double.NaN, 0, Color.LIGHT_RED, Color.LIGHT_RED); 

AddCloud(if Min(a, b) > 0 

         then 0  

         else Double.NaN, Min(a, b), Color.LIGHT_GREEN, Color.LIGHT_GREEN); 

AddLabel(1, if Max(a, b) < 0 and a < b 

            then “Trend Down” 

            else if Max(a, b) < 0 and a > b 

            then “Trend Down Slowing” 

            else if between(0, b, a) and d > d[1] 

            then “Trend Reversing” 

            else if Min(a, b) > 0 and a > b 

            then “Trend Up” 

            else if Min(a, b) > 0 and a < b 

            then “Trend Up Slowing” 

            else if Min(a, b) > 0 and d > d[1] 

            then “Trend Up Accelerating” 

            else if Min(a, b) > 0 and a < b and  d < d[1] 

            then “Trend Up decelerating” 

            else “Undetermined Trend”, if Max(a, b) < 0 

                                       then color.light_red 

                                       else if Min(a, b) > 0 

                                       then color.light_green 

                                       else color.white); 

            

# End Code GACD

MACD based on Hull Moving Average W/peak/ebb arrows

#SFL made 

#MACD based on Hull Moving Average W/peak/ebb arrows 

#TOS title = MACD_via_Hull_MA_fav 

declare lower; 

 

input fastLength = 12; 

input slowLength = 26; 

input MACDLength = 9; 

input AverageType = {SMA, EMA, default HULL}; 

 

plot Value; 

plot Avg; 

switch (AverageType) { 

case SMA: 

    Value = Average(close, fastLength) – Average(close, slowLength); 

    Avg = Average(Value, MACDLength); 

case EMA: 

    Value = ExpAverage(close, fastLength) – ExpAverage(close, slowLength); 

    Avg = ExpAverage(Value, MACDLength); 

case HULL: 

   Value =  MovingAverage(AverageType.HULL, close, fastLength) –  MovingAverage(AverageType.HULL, close, slowLength); 

   Avg = Average(Value, MACDLength); 

 

plot Diff = Value – Avg; 

plot ZeroLine = 0; 

 

Value.SetDefaultColor(GetColor(1)); 

Avg.SetDefaultColor(GetColor(8)); 

Diff.SetDefaultColor(GetColor(5)); 

Diff.SetPaintingStrategy(PaintingStrategy.HISTOGRAM); 

Diff.SetLineWeight(3); 

Diff.DefineColor(“Positive and Up”, Color.GREEN); 

Diff.DefineColor(“Positive and Down”, Color.DARK_GREEN); 

Diff.DefineColor(“Negative and Down”, Color.RED); 

Diff.DefineColor(“Negative and Up”, Color.DARK_RED); 

Diff.AssignValueColor(if Diff >= 0 then if Diff > Diff[1] then Diff.color(“Positive and Up”) else Diff.color(“Positive and Down”) else if Diff < Diff[1] then Diff.color(“Negative and Down”) else Diff.color(“Negative and Up”)); 

ZeroLine.SetDefaultColor(GetColor(0)); 

 

#*********plot Min arrows********** 

def MinArrow = if (Value < Value[1] and value[1] < Value[2] and value[2] < Value[3] and value[-1] > Value and value < 0)  

then 0 

else if (Value > Value[1]) 

then double.nan 

else double.nan; 

 

plot UpArrow = if(MinArrow == 0, value, double.nan); 

UpArrow.AssignValueColor(Color.Green); 

UpArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP); 

UpArrow.SetLineWeight(1); 

UpArrow.HideBubble(); 

 

#*********plot Max arrows********** 

def MaxArrow = if (Value > Value[1] and value[1] > Value[2] and value[2] > Value[3] and value[-1] < Value and value > 0)  

then 0 

else if (Value > Value[1]) 

then double.nan 

else double.nan; 

 

plot DwnArrow = if(MaxArrow == 0, value, double.nan); 

DwnArrow.AssignValueColor(Color.cyan); 

DwnArrow.SetPaintingStrategy(PaintingStrategy.ARROW_Down); 

DwnArrow.SetLineWeight(1); 

DwnArrow.HideBubble(); 

 

#*********plot Max signal(Avg) arrows********** 

def SignalArrow = if (Avg > Avg[1] and Avg[1] > Avg[2] and Avg[2] > Avg[3] and Avg[-1] < Avg and Avg > 0)  

then 0 

else if (Avg > Avg[1]) 

then double.nan 

else double.nan; 

 

plot downSignalArrow = if(SignalArrow == 0, avg, double.nan); 

downSignalArrow.AssignValueColor(Color.yellow); 

downSignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_Down); 

downSignalArrow.SetLineWeight(1); 

downSignalArrow.HideBubble(); 

 

AddCloud(ZeroLine, Value, color.RED, color.GREEN); 

# end 

MACD BB

# TS_MACD_BB 

  

declare lower; 

  

input price = close; 

input BBlength = 10; 

input BBNum_Dev = 1.0; 

input MACDfastLength = 12; 

input MACDslowLength = 26; 

input MACDLength = 5; 

  

def MACD_Data = MACD(fastLength=MACDfastLength, slowLength=MACDslowLength, MACDLength = MACDLength); 

  

plot MACD_Dots = MACD_Data; 

plot MACD_Line= MACD_Data; 

  

plot BB_Upper = BollingerBandsSMA(price = MACD_Line, length=BBlength, Num_Dev_Dn=-BBNum_Dev, Num_Dev_Up=BBNum_Dev).UpperBand; 

plot BB_Lower = BollingerBandsSMA(price = MACD_Line, length=BBlength, Num_Dev_Dn=-BBNum_Dev, Num_Dev_Up=BBNum_Dev).Lowerband; 

plot BB_Midline = BollingerBandsSMA(price = MACD_Line, length=BBlength, Num_Dev_Dn=-BBNum_Dev, Num_Dev_Up=BBNum_Dev).MidLine; 

  

BB_Upper.SetDefaultColor(color.gray); 

BB_Lower.SetDefaultColor(color.gray); 

BB_MidLine.SetDefaultColor(color.gray); 

BB_MidLine.setStyle(curve.SHORT_DASH); 

  

MACD_Line.setDefaultColor(color.white); 

  

MACD_Dots.setStyle(curve.POINTS); 

MACD_Dots.setLineWeight(2); 

MACD_Dots.assignValueColor(if MACD_Line>MACD_line[1] then color.green else color.red); 

  

plot zero = 0; 

zero.assignValueColor(if MACD_line<0 then color.red else color.green); 

zero.setLineWeight(2); 

MACD Divergence Pivots

# MACD Divergence Pivots 

input n = 2; 

input fastLength = 12; 

input slowLength = 26; 

input MACDLength = 9; 

input averageType = AverageType.EXPONENTIAL; 

 

def h = high; 

def l = low; 

def bar = barNumber(); 

def Diff = MACD(fastLength, slowLength, MACDLength, averageType).Diff; 

def CurrMACDh = if Diff > 0 

                then fold i = 1 to n + 1  

                with p = 1 

                while p  

                do Diff > getValue(Diff, -i) 

                else 0;  

def CurrMACDPivotH = if (bar > n and  

                         Diff == highest(Diff, n) and  

                         CurrMACDh)  

                     then h  

                     else double.NaN; 

def CurrMACDl = if Diff < 0 

                then fold j = 1 to n + 1  

                with q = 1 

                while q  

                do Diff < getValue(Diff, -j) 

                else 0; 

def CurrMACDPivotL = if (bar > n and  

                         Diff == lowest(Diff, n) and  

                         CurrMACDl)  

                     then l  

                     else double.NaN; 

def CurrPHBar = if !isNaN(CurrMACDPivotH)  

                then bar  

                else CurrPHBar[1]; 

def CurrPLBar = if !isNaN(CurrMACDPivotL)  

                then bar  

                else CurrPLBar[1]; 

def PHpoint = if !isNaN(CurrMACDPivotH)  

              then CurrMACDPivotH  

              else PHpoint[1]; 

def priorPHBar = if PHpoint != PHpoint[1]  

                 then CurrPHBar[1]  

                 else priorPHBar[1]; 

def PLpoint = if !isNaN(CurrMACDPivotL)  

              then CurrMACDPivotL  

              else PLpoint[1]; 

def priorPLBar = if PLpoint != PLpoint[1]  

                 then CurrPLBar[1]  

                 else priorPLBar[1]; 

def HighPivots = bar >= highestAll(priorPHBar); 

def LowPivots = bar >= highestAll(priorPLBar); 

def pivotHigh = if HighPivots  

                then CurrMACDPivotH  

                else double.NaN; 

plot PlotHline = pivotHigh; 

    PlotHline.enableApproximation(); 

    PlotHline.SetDefaultColor(GetColor(7)); 

    PlotHline.SetStyle(Curve.Short_DASH); 

plot pivotLow = if LowPivots  

                then CurrMACDPivotL  

                else double.NaN; 

    pivotLow.enableApproximation(); 

    pivotLow.SetDefaultColor(GetColor(7)); 

    pivotLow.SetStyle(Curve.Short_DASH); 

plot PivotDot = if !isNaN(pivotHigh)  

                then pivotHigh  

                else if !isNaN(pivotLow)  

                     then pivotLow 

                     else double.NaN; 

    pivotDot.SetDefaultColor(GetColor(7)); 

    pivotDot.SetPaintingStrategy(PaintingStrategy.POINTS); 

    pivotDot.SetLineWeight(3); 

 

 

# End Code Pivots with Projections 

MACD Histogram Crossover

# MACDHistogramCrossover 

 

# Displays number of bars since the last MACDHistogram Crossover signal 

# Added logic to display direction of last crossover signal 

 

input ShowEducationLabels = yes; ## added by JQ for education purposes 

input fastLength = 12; 

input slowLength = 26; 

input MACDLength = 9; 

input averageType = AverageType.EXPONENTIAL; 

 

def Diff = MACD(fastLength, slowLength, MACDLength, averageType).Diff; 

 

def XUp; 

def XDn; 

 

if Crosses(Diff, 0, CrossingDirection.BELOW) { 

    XUp = no; 

    XDn = yes; 

##  

 

else if (Crosses(Diff, 0, CrossingDirection.ABOVE)) { 

    XUp = yes; 

    XDn = no; 

}  

else { 

    XUp = XUp[1]; 

    XDn = XDn[1]; 

 

def crossBarUp = if XUp and !XUp[1] then BarNumber() else crossBarUp[1]; 

def crossBarDn = if XDn and !XDn[1] then BarNumber() else crossBarDn[1]; 

 

addlabel(yes,”crossBarUp: ” + crossBarUp, color.lime); ## added by JQ for education 

addlabel(yes,”crossBarDn: ” + crossBarDn, color.lime); ## added by JQ for education 

addlabel(yes,”BarNumber(): ” + BarNumber(), color.lime); ## added by JQ for education 

 

 

plot bullSig = if XUp and !XUp[1] then low else Double.NaN; 

     bullSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP); 

     bullSig.SetDefaultColor(Color.YELLOW); 

     bullSig.SetLineWeight(3); 

 

plot bearSig = if XDn and !XDn[1] then high else Double.NaN; 

     bearSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN); 

     bearSig.SetDefaultColor(Color.CYAN); 

     bearSig.SetLineWeight(3); 

 

AddLabel(1, “Bars since last MACD Histogram ” +  

    (if crossBarUp > crossBarDn then “BULLISH”  

                                else “BEARISH”) + ” Crossover:  ” +  

    (if crossBarUp > crossBarDn then BarNumber() – crossBarUp  

                                else BarNumber() – crossBarDn),  

    if crossBarUp > crossBarDn then Color.YELLOW else Color.CYAN); 

 

# END STUDY 

MACD_Three_Agg_MACD

declare lower; 

input agg2 = AggregationPeriod.FIFTEEN_MIN;#hint agg2:Must be larger than or the same as the chart agg. 

input agg3 = AggregationPeriod.HOUR;;#hint agg3:Must be larger than or the same as the chart agg. 

input fast = 12; 

input slow = 26; 

input Length = 9; 

 

plot BaseMACD = ((ExpAverage(close, fast) – ExpAverage(close, slow)) – (ExpAverage((ExpAverage(close, fast) – ExpAverage(close, slow)), Length))); 

 

plot MACD2 = ((ExpAverage(close(period = agg2), fast) – ExpAverage(close(period = agg2), slow)) –  (ExpAverage((ExpAverage(close(period = agg2), fast) – ExpAverage(close(period = agg2),  slow)), Length))); 

 

plot MACD3 = ((ExpAverage(close(period = agg3), fast) –  ExpAverage(close(period = agg3), slow)) – (ExpAverage((ExpAverage(close(period = agg3), fast) – ExpAverage(close(period = agg3), slow)), Length))); 

 

plot zero = 0; 

 

BaseMACD.SetPaintingStrategy(PaintingStrategy.lINE); 

MACD2.SetPaintingStrategy(PaintingStrategy.lINE); 

MACD3.SetPaintingStrategy(PaintingStrategy.LINE); 

 

BaseMACD.SetDefaultColor(Color.cyan); 

MACD2.SetDefaultColor(Color.PINK); 

MACD3.SetDefaultColor(Color.red); 

 

 

AddCloud(BaseMACD, zero, color.green, color.red); 

AddCloud(MACD2, zero, color.Pink, color.LIGHT_RED); 

AddCloud(MACD3, zero, color.YELLOW, color.MAGENTA); 

 

#### Base chart Label #### 

addLabel(yes,”Base chart agg”,color.cyan); 

 

#### Label agg2 definitions ##### 

def ag1M_2 = If (Agg2 == AggregationPeriod.MIN, 1, 0); 

AddLabel(ag1M_2, “The agg period is one minute”, Color.PINK); 

 

def ag2M_2 = If (Agg2== AggregationPeriod.TWO_MIN, 1, 0); 

AddLabel(ag2M_2, “The agg period is two minutes”, Color.PINK); 

 

def ag3M_2 = If (Agg2== AggregationPeriod.THREE_MIN, 1, 0); 

AddLabel(ag3M_2, “The agg period is three minutes”, Color.PINK); 

 

def ag4M_2 = If (Agg2== AggregationPeriod.FOUR_MIN, 1, 0); 

AddLabel(ag4M_2, “The agg period is four minutes”, Color.PINK); 

 

def ag5M_2 = If (Agg2== AggregationPeriod.FIVE_MIN, 1, 0); 

AddLabel(ag5M_2, “The agg period is five minutes”, Color.PINK); 

 

def ag10M_2 = If (Agg2== AggregationPeriod.TEN_MIN, 1, 0); 

AddLabel(ag10M_2, “The agg period is ten minutes”, Color.PINK); 

 

def ag15M_2 = If (Agg2== AggregationPeriod.FIFTEEN_MIN, 1, 0); 

AddLabel(ag15M_2, “The agg period is fifteen minutes”, Color.PINK); 

 

def ag20M_2 = If (Agg2== AggregationPeriod.TWENTY_MIN, 1, 0); 

AddLabel(ag20M_2, “The agg period is twenty minutes”, Color.PINK); 

 

def ag30M_2 = If (Agg2== AggregationPeriod.THIRTY_MIN, 1, 0); 

AddLabel(ag30M_2, “The agg period is thirty minutes”, Color.PINK); 

 

def ag1hr_2 = If (Agg2== AggregationPeriod.HOUR, 1, 0); 

AddLabel(ag1hr_2, “The agg period is one hour”, Color.PINK); 

 

def ag2hr_2 = If (Agg2== AggregationPeriod.TWO_HOURS, 1, 0); 

AddLabel(ag2hr_2, “The agg period is two hours”, Color.PINK); 

 

def ag4hr_2 = If (Agg2== AggregationPeriod.FOUR_HOURS, 1, 0); 

AddLabel(ag4hr_2, “The agg period is four hours”, Color.PINK); 

 

def ag1D_2 = If (Agg2== AggregationPeriod.DAY, 1, 0); 

AddLabel(ag1D_2, “The agg period is one day”, Color.PINK); 

 

def ag2D_2 = If (Agg2== AggregationPeriod.TWO_DAYS, 1, 0); 

AddLabel(ag2D_2, “The agg period is two days”, Color.PINK); 

 

def ag3D_2 = If (Agg2== AggregationPeriod.THREE_DAYS, 1, 0); 

AddLabel(ag3D_2, “The agg period is three days”, Color.PINK); 

 

def ag4D_2 = If (Agg2== AggregationPeriod.FOUR_DAYS, 1, 0); 

AddLabel(ag4D_2, “The agg period is four days”, Color.PINK); 

 

def agwk_2 = If (Agg2== AggregationPeriod.week, 1, 0); 

AddLabel(agwk_2, “The agg period is week”, Color.PINK); 

 

def agmo_2 = If (Agg2== AggregationPeriod.month, 1, 0); 

AddLabel(agmo_2, “The agg period is month”, Color.PINK); 

#### end of label definition for agg2 ########## 

 

#### Label agg3 definitions ##### 

def ag1M_3 = If (Agg3 == AggregationPeriod.MIN, 1, 0); 

AddLabel(ag1M_3, “The agg period is one minute”, Color.RED); 

 

def ag2M_3 = If (Agg3 == AggregationPeriod.TWO_MIN, 1, 0); 

AddLabel(ag2M_3, “The agg period is two minutes”, Color.RED); 

 

def ag3M_3 = If (Agg3 == AggregationPeriod.THREE_MIN, 1, 0); 

AddLabel(ag3M_3, “The agg period is three minutes”, Color.RED); 

 

def ag4M_3 = If (Agg3 == AggregationPeriod.FOUR_MIN, 1, 0); 

AddLabel(ag4M_3, “The agg period is four minutes”, Color.RED); 

 

def ag5M_3 = If (Agg3 == AggregationPeriod.FIVE_MIN, 1, 0); 

AddLabel(ag5M_3, “The agg period is five minutes”, Color.RED); 

 

def ag10M_3 = If (Agg3 == AggregationPeriod.TEN_MIN, 1, 0); 

AddLabel(ag10M_3, “The agg period is ten minutes”, Color.RED); 

 

def ag15M_3 = If (Agg3 == AggregationPeriod.FIFTEEN_MIN, 1, 0); 

AddLabel(ag15M_3, “The agg period is fifteen minutes”, Color.RED); 

 

def ag20M_3 = If (Agg3 == AggregationPeriod.TWENTY_MIN, 1, 0); 

AddLabel(ag20M_3, “The agg period is twenty minutes”, Color.RED); 

 

def ag30M_3 = If (Agg3 == AggregationPeriod.THIRTY_MIN, 1, 0); 

AddLabel(ag30M_3, “The agg period is thirty minutes”, Color.RED); 

 

def ag1hr_3 = If (Agg3 == AggregationPeriod.HOUR, 1, 0); 

AddLabel(ag1hr_3, “The agg period is one hour”, Color.RED); 

 

def ag2hr_3 = If (Agg3 == AggregationPeriod.TWO_HOURS, 1, 0); 

AddLabel(ag2hr_3, “The agg period is two hours”, Color.RED); 

 

def ag4hr_3 = If (Agg3 == AggregationPeriod.FOUR_HOURS, 1, 0); 

AddLabel(ag4hr_3, “The agg period is four hours”, Color.RED); 

 

def ag1D_3 = If (Agg3 == AggregationPeriod.DAY, 1, 0); 

AddLabel(ag1D_3, “The agg period is one day”, Color.RED); 

 

def ag2D_3 = If (Agg3 == AggregationPeriod.TWO_DAYS, 1, 0); 

AddLabel(ag2D_3, “The agg period is two days”, Color.RED); 

 

def ag3D_3 = If (Agg3 == AggregationPeriod.THREE_DAYS, 1, 0); 

AddLabel(ag3D_3, “The agg period is three days”, Color.RED); 

 

def ag4D_3 = If (Agg3 == AggregationPeriod.FOUR_DAYS, 1, 0); 

AddLabel(ag4D_3, “The agg period is four days”, Color.RED); 

 

def agwk_3 = If (Agg3 == AggregationPeriod.week, 1, 0); 

AddLabel(agwk_3, “The agg period is week”, Color.RED); 

 

def agmo_3 = If (Agg3 == AggregationPeriod.month, 1, 0); 

AddLabel(agmo_3, “The agg period is month”, Color.RED); 

#### end of label definition for Agg3  ########## 

#### EOC #### 

Percentage Price Oscillator

declare lower; 

 

def PPO = (ExpAverage(close, 12) – ExpAverage(close, 26) / ExpAverage(close, 26)) * 100; 

def SignalLine = ExpAverage(PPO, 9); 

 

plot PPOline = PPO – SignalLine; 

     PPOLine.SetPaintingStrategy(PaintingStrategy.Histogram); 

     PPOLine.SetLineWeight(4); 

     PPOLine.AssignValueColor(if PPOLine > 0 and 

                                 PPOLine > PPOLine[1] 

                              then Color.Green 

                              else if PPOLine > 0 and 

                                      PPOLine < PPOLine[1] 

                              then Color.Yellow 

                              else if PPOLine < 0 and 

                                      PPOLine < PPOLine[1] 

                              then Color.Red 

                              else Color.Blue); 

plot zero = if isNan(close) then Double.NaN else 0; 

     zero.SetDefaultColor(Color.Gray); 

PPO ReentrySignals

## START STUDY 

## PPO_ReentrySignals

  

#hint: PPO upper study that signals when then Avg line crosses 0 (PPOUp, PPODn plots) and signals when the Val line crosses Avg line as reentry signal (Up, Dn plots). 

  

declare upper; 

declare once_per_bar; 

  

#hint paintBars: Colors the price bars. Val or Avg settings colors them based on the PPO Val or Avg line, PPS colors them based on the PPS study, and Off doesn’t color them. 

input paintBars = {Off, Val, Avg, default PPS}; 

  

#hint nFast: Fast period length for PPO Val. 

input nFast = 8; 

  

#hint nSlow: Slow period length for PPO Val. 

input nSlow = 13; 

  

#hint nSmooth: Smoothing period length for PPO Avg. 

input nSmooth = 5; 

  

#hint type: Type of moving average for PPO. 

input type = AverageType.EXPONENTIAL; 

  

#hint price: Fundamental price type. 

input price = close; 

  

#hint nStops: Period length used to offset Up and Dn signals. 

input nStops = 5; 

  

#hint ticks: Additional offset in ticks for Up and Dn signals. 

input ticks = 2.0; 

  

# PPO Val and Avg lines: PPO is similar to MACD but is expressed as a percentage instead of a difference. 

def MA = MovingAverage(type, price, nSlow); 

def Val = ((MovingAverage(type, price, nFast) – MA) / MA) * 100; 

def Avg = MovingAverage(type, Val, nSmooth); 

  

# Reentry is 1 if Val crosses above Avg line while Avg is above 0, or -1 if Val crosses below Avg while Avg is below 0. 

rec Reentry = compoundValue(1, if Avg > 0 and Val crosses above Avg then 1 else if Avg < 0 and Val crosses below Avg then -1 else Reentry[1], 0); 

  

def tks = tickSize() * ticks; 

  

# External PPS study: ppsDir is 1 if last signal was a buy, or -1 if last signal was a sell. 

rec ppsDir = CompoundValue(1, if !IsNaN(PPS().BuySignal) then 1 else if !IsNaN(PPS().SellSignal) then -1 else ppsDir[1], 0); 

  

plot PPOUp = Avg crosses above 0; 

PPOUp.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP); 

PPOUp.SetDefaultColor(Color.WHITE); 

PPOUp.SetLineWeight(1); 

  

plot PPODn = Avg crosses below 0; 

PPODn.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN); 

PPODn.SetDefaultColor(Color.ORANGE); 

PPODn.SetLineWeight(1); 

  

plot Up = if Reentry crosses above 0 then Lowest(low, nStops) – tks else Double.NaN; 

Up.SetPaintingStrategy(PaintingStrategy.ARROW_UP); 

Up.SetDefaultColor(Color.CYAN); 

Up.SetLineWeight(3); 

  

plot Dn = if Reentry crosses below 0 then Highest(high, nStops) + tks else Double.NaN; 

Dn.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN); 

Dn.SetDefaultColor(Color.PINK); 

Dn.SetLineWeight(3); 

  

def prUp = close > open and close > close[1]; 

def prDn = close < open and close < close[1]; 

  

def prSig = if paintBars == paintBars.Val then Val  

            else if paintBars == paintBars.Avg then Avg  

            else ppsDir; 

  

AssignPriceColor(if !paintBars then Color.CURRENT  

else if prSig > 0 then  

    if prUp then Color.GREEN  

    else Color.DARK_GREEN 

else if prDn then Color.RED  

else Color.PINK); 

  

## END STUDY 

 

PPO_FastWithTrigger

Declare Lower; 

 

 

 

input fastLength = 5; # the other common choice would be 6, 19,1 

input slowLength = 15; 

input MACDlength = 1; 

input triggerDelay = 1; 

Plot PPO = ((expAverage(close, fastLength) – expAverage(close, slowLength)) / expAverage(close, slowLength)) * 100 ; 

PPO.setdefaultColor(color.uptick); 

Plot signal_line = expAverage(PPO, MACDlength); 

plot PPO_trigger = PPO[triggerDelay]; 

ppo_trigger.setDefaultColor(color.downtick); 

plot Zeroline = 0; 

zeroline.setDefaultColor(color.white); 

 

Addcloud(PPO, PPO_trigger, color.green, color.red, no); 

Addcloud(PPO, PPO_trigger, color.green, color.red, no); 

 

 

#  End of Code 

 

#Plot PPO_Histogram = PPO – Signal_line; 

#PPO_Histogram.SetPaintingStrategy(paintingStrategy.HISTOGRAM); 

#PPO_Histogram.SetDefaultColor(GetColor(5)); 

#PPO_Histogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM); 

#PPO_Histogram.SetLineWeight(3); 

#PPO_Histogram.DefineColor(“Positive and Up”, Color.GREEN); 

#PPO_Histogram.DefineColor(“Positive and Down”, Color.DARK_GREEN); 

#PPO_Histogram.DefineColor(“Negative and Down”, Color.RED); 

#PPO_Histogram.DefineColor(“Negative and Up”, Color.DARK_RED); 

#PPO_Histogram.AssignValueColor(if PPO_Histogram >= 0 then if PPO_Histogram > PPO_Histogram[1] then PPO_Histogram.color(“Positive and Up”) else PPO_Histogram.color(“Positive and Down”) else if PPO_Histogram < PPO_Histogram[1] then PPO_Histogram.color(“Negative and Down”) else PPO_Histogram.color(“Negative and Up

BarTrend _MTS

# Declare lower; for trend plot 

  

Input nTrend = 10; #Hint nTrend: Trend Lookback n Bars 

Input HTBC = 2; #Hint HTBC: Number of prior candles to combine Dynamic ‘Higher TimeFrame Prior Candle’ 

Def o = open; 

Def h = High; 

Def l = Low; 

Def c = close; 

Def HTh = highest(h,HTBC); 

Def HTl = lowest(l,HTBC); 

Def B = BarNumber(); 

Def dy =  getyyYYMMDD(); 

#def IB =  l >= HTl[1] and  h <= HTh[1]; 

#IB.SetPaintingStrategy(PaintingStrategy.VALUES_ABOVE); 

  

Def IBRg = CompoundValue(2,if dy[1]>dy[2] then b else if l>= GetValue(lowest(l,HTBC),B-IBRg[1]) and h<= GetValue(highest(h,HTBC),B-IBRg[1]) then IBRg[1] else B,b) ; 

# plot Rg =  (IBRg); 

# Rg.SetPaintingStrategy(PaintingStrategy.VALUES_ABOVE); 

def NB = B>IBRg; 

  

Def U = !NB and (l>=HTl[1] and h>=HTh[1]); 

Def D = !NB and (h<=HTh[1] and l<=HTl[1]); 

Def EU = !NB and (h>HTh[1] and l<HTl[1] and 2*(h-c)<c-l); #Engulfing –  Count as UP Bar  

Def ED = !NB and (l<HTl[1] and h>HTh[1] and h-c>2*(c-l)); #Engulfing –  Count as DOWN Bar  

  

plot  Trend = sum(U+EU-ED-D,nTrend); 

trend.SetPaintingStrategy(PaintingStrategy.HISTOGRAM); 

Trend.DefineColor(“UpTrend”, Color.GREEN); 

Trend.DefineColor(“DownTrend”, Color.RED); 

Trend.DefineColor(“EngulfingUp”, Color.PLUM); 

Trend.DefineColor(“EngulfingDn”, Color.PLUM); 

Trend.DefineColor(“NeutralUp”, Color.ORANGE); 

Trend.DefineColor(“NeutralDn”, Color.ORANGE); 

Trend.DefineColor(” Default”, Color.CYAN); 

Trend.Hide(); 

Plot Zerobase = 0; 

ZeroBase.Hide(); 

  

Input AssignColor = yes; #hint AssignColor: Whether or not to paint trend histogram bars in trend colors or neutral color.  

Trend.AssignValueColor(  

     if AssignColor then  

        if U and D OR NB then   

            if c<o then Trend.Color(“NeutralDn”)  

                else Trend.Color(“NeutralUp”)   

            else if U then Trend.Color(“UpTrend”)   

            else if D then Trend.color(“DownTrend”)  

            else if c<o then Trend.color(“engulfingDn”) 

            else if c>o then Trend.color(“engulfingUp”) 

        else Trend.Color(” Default”) 

     else Trend.Color(” Default”)); 

  

Plot LB = If(IsNaN(close[-1]) ,trend,double.NaN); # Plot Dot @ Current Bar to increase visibility especially at 0 line 

LB.SetPaintingStrategy(PaintingStrategy.POINTS); 

  

input PaintBars = yes; #hint PaintBars: Whether or not to paint price bars in trend colors. Only one script on your chart can paint price candles.  

AssignPriceColor(  

     if PaintBars then  

        if U and D OR NB then   

            if c<o then Trend.Color(“NeutralDn”)  

                else Trend.Color(“NeutralUp”)   

            else if U then Trend.Color(“UpTrend”)   

            else if D then Trend.color(“DownTrend”)  

            else if c<o then Trend.color(“engulfingDn”) 

            else if c>o then Trend.color(“engulfingUp”) 

        else  Color.CURRENT 

     else Color.CURRENT); 

  

# End code Assign Price Color MTS_BarTrend 

Linear Regression Keltner Channel

## START STUDY 

## LRC_KC_Lite 

## linus, 2014-02-10, v0.1 

 
 

#hint: Combination of Linear Regression Channels and Keltner Channels. 

 
 

declare once_per_bar; 

 
 

#hint price: Fundamental price type for channels. (Default is hl2) 

input price = hl2; 

 
 

#hint lrcLength: Period length of linear regression channels. (Default is 200) 

input lrcLength = 200; 

 
 

#hint lrcWidth: Scaling width between linear regression channels. (Default is .5) 

input lrcWidth = .5; 

 
 

#hint kcFactor: Scaling factor for Keltner Channels. (Default is 1.5) 

input kcFactor = 1.5; 

 
 

#hint atrLength: Period length for AverageTrueRange. (Default is 5) 

input atrLength = 5; 

 
 

#hint kcLength: Period length for Keltner Channels. (Default is 10) 

input kcLength = 10; 

 
 

#hint kcSmooth: Smoothing length for Keltner Channels. (Default is 20) 

input kcSmooth = 20; 

 
 

#hint kcType: Moving average type for Keltner Channels. (Default is SIMPLE) 

input kcType = AverageType.SIMPLE; 

 
 

def MCh = InertiaAll(price, lrcLength); 

def dist = HighestAll(AbsValue(MCh – price)) * lrcWidth; 

def HCh = MCh + dist; 

def LCh = MCh – dist; 

 
 

def kcOfst = kcFactor * Average(TrueRange(high,  close,  low),  atrLength); 

def kcAvg = MovingAverage(kcType, price, kcLength); 

 
 

def UB = Inertia((Inertia(kcAvg + kcOfst, kcSmooth) + HCh) / 2, kcSmooth); 

 
 

def LB = Inertia((Inertia(kcAvg – kcOfst, kcSmooth) + LCh) / 2, kcSmooth); 

 
 

def MB = Inertia(if close > kcAvg then (kcAvg + high) / 2 else (kcAvg + low) / 2, kcSmooth); 

 
 

plot UBLR = InertiaAll(Highest(UB, lrcLength / 2), lrcLength / 3); 

plot LBLR = InertiaAll(Lowest(LB, lrcLength / 2), lrcLength / 3); 

plot MBLR = (UBLR + LBLR) / 2; 

 
 

plot HChan = if IsNaN(UBLR[1]) then (InertiaAll(Highest(high[1], lrcLength)) + InertiaAll(Highest(high[1], kcSmooth))) / 2 else (HCh + UBLR[1]) / 2; 

 
 

plot LChan = if IsNaN(LBLR) then (InertiaAll(Lowest(low, lrcLength)) + InertiaAll(Lowest(low, kcSmooth))) / 2 else (LCh + LBLR) / 2; 

 
 

plot MChan = (HChan + LChan) / 2; 

 
 

UBLR.SetDefaultColor(Color.BLUE); 

LBLR.SetDefaultColor(Color.BLUE); 

MBLR.SetDefaultColor(Color.BLUE); 

UBLR.SetStyle(Curve.SHORT_DASH); 

MBLR.SetStyle(Curve.SHORT_DASH); 

LBLR.SetStyle(Curve.SHORT_DASH); 

UBLR.SetLineWeight(2); 

MBLR.SetLineWeight(2); 

LBLR.SetLineWeight(2); 

 
 

HChan.SetDefaultColor(Color.GRAY); 

MChan.SetDefaultColor(Color.GRAY); 

LChan.SetDefaultColor(Color.GRAY); 

HChan.SetPaintingStrategy(PaintingStrategy.DASHES); 

MChan.SetPaintingStrategy(PaintingStrategy.DASHES); 

LChan.SetPaintingStrategy(PaintingStrategy.DASHES); 

HChan.SetLineWeight(2); 

MChan.SetLineWeight(2); 

LChan.SetLineWeight(2); 

 
 

## END STUDY 

 

Thinkorswim custom indicators