name
stringlengths 1
64
| url
stringlengths 44
135
| author
stringlengths 3
30
| author_url
stringlengths 34
61
| likes_count
int64 0
33.2k
| kind
stringclasses 3
values | pine_version
int64 1
5
| license
stringclasses 3
values | source
stringlengths 177
279k
|
---|---|---|---|---|---|---|---|---|
Risk Indicator Overlay | https://www.tradingview.com/script/QyaHJ5Ct-Risk-Indicator-Overlay/ | Trollplogen | https://www.tradingview.com/u/Trollplogen/ | 87 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Trollplogen
//@version=4
study("Risk Indicator Overlay", overlay=true, precision=2)
//input
asset = input(title="Asset", type=input.string, defval="BTC", options=["BTC", "ETH", "ADA", "XRP", "LINK", "VET", "FTM", "RUNE", "HBAR", "Total Crypto Mcap", "Other"], group="Asset and SMAs")
SMAset = input(title="Selected SMA pair", type=input.string, defval="1D/20Wsma", options=["1D/20Wsma","10Dsma/50Wsma","50Dsma/50Wsma","Customized"], group="Asset and SMAs")
//plot input
ColorScheme = input(title="Color Scheme", type=input.string, defval="Rainbow", options=["Rainbow", "Red/Blue", "Customized"], group = "Plots and Colors")
PlotRiskBands = input(title="Plot Risk Bands (Theoretical)", type=input.bool, defval=false, group = "Plots and Colors")
PlotTheoreticalHighLow = input(title="Plot Theoretical High/Lows (According to 20W and 50W SMAs)", type=input.bool, defval=false, group = "Plots and Colors")
PlotLine = input(title="Plot Price With Risk", type=input.bool, defval=true, group = "Plots and Colors")
PlotCircles = input(title="Plot Circles (closing price)", type=input.bool, defval=false, group = "Plots and Colors")
PlotCandles = input(title="Plot Candles", type=input.bool, defval=false, group = "Plots and Colors")
PlotSMAs = input(title="Plot SMAs", type=input.bool, defval=false, group = "Plots and Colors")
//input customized SMA settings
dailySMAlength = input(title="Daily SMA Length", defval=1, group = "Customized SMA Settings")
weeklySMAlength = input(title="Weekly SMA Length", type=input.string, defval="20W SMA", options=["20W SMA", "50W SMA"], group = "Customized SMA Settings")
//input customized Log regression lines
UpperAcustom = input(20.0, title="Logarithmic Upper Regression Start", group="Custom Regression settings")
UpperBcustom = input(-2.0, title="Logarithmic Upper Regression Factor", group="Custom Regression settings")
LowerAcustom = input(0.3, title="Logarithmic Lower Regression Start", group="Custom Regression settings")
LowerBcustom = input(0.0, title="Logarithmic Lower Regression Factor", group="Custom Regression settings")
PlotRawRegr = input(title="Plot Raw SMA Ratio and Regression Lines", type=input.bool, defval=false, group="Custom Regression settings")
HigherDeviationCustomRegA = input(20.0, title="Highest Ratio as Log Regression A+B*ln(x), A =", group="Settings for High/Low Theoretical Price")
HigherDeviationCustomRegB = input(-2.0, title="Highest Ratio as Log Regression A+B*ln(x), B =", group="Settings for High/Low Theoretical Price")
LowerDeviationCustom = input(0.2, title="Lowest Ratio between Daily Price and 20W/50W SMA", group="Settings for High/Low Theoretical Price")
//input customized color settings
CustomRisk1Color = input(title="Risk 0.0 - 0.1", type=input.color, defval=color.new(#1b5e20,0), group = "Customized Risk Colors")
CustomRisk2Color = input(title="Risk 0.1 - 0.2", type=input.color, defval=color.new(#388e3c,0), group = "Customized Risk Colors")
CustomRisk3Color = input(title="Risk 0.2 - 0.3", type=input.color, defval=color.new(#66bb6a,0), group = "Customized Risk Colors")
CustomRisk4Color = input(title="Risk 0.3 - 0.4", type=input.color, defval=color.new(#81c784,0), group = "Customized Risk Colors")
CustomRisk5Color = input(title="Risk 0.4 - 0.5", type=input.color, defval=color.new(#a5d6a7,0), group = "Customized Risk Colors")
CustomRisk6Color = input(title="Risk 0.5 - 0.6", type=input.color, defval=color.new(#faa1a4,0), group = "Customized Risk Colors")
CustomRisk7Color = input(title="Risk 0.6 - 0.7", type=input.color, defval=color.new(#f77c80,0), group = "Customized Risk Colors")
CustomRisk8Color = input(title="Risk 0.7 - 0.8", type=input.color, defval=color.new(#f7525f,0), group = "Customized Risk Colors")
CustomRisk9Color = input(title="Risk 0.8 - 0.9", type=input.color, defval=color.new(#b22833,0), group = "Customized Risk Colors")
CustomUpperRiskColor = input(title="Risk 0.9 - 1.0", type=input.color, defval=color.new(#801922,0), group = "Customized Risk Colors")
//Define colors
Risk1Color = ColorScheme == "Rainbow" ? #311b92 : ColorScheme == "Red/Blue" ? #0c3299 : CustomRisk1Color
Risk2Color = ColorScheme == "Rainbow" ? #1848cc : ColorScheme == "Red/Blue" ? #1848cc : CustomRisk2Color
Risk3Color = ColorScheme == "Rainbow" ? #056656 : ColorScheme == "Red/Blue" ? #3179f5 : CustomRisk3Color
Risk4Color = ColorScheme == "Rainbow" ? #388e3c : ColorScheme == "Red/Blue" ? #5b9cf6 : CustomRisk4Color
Risk5Color = ColorScheme == "Rainbow" ? #81c784 : ColorScheme == "Red/Blue" ? #90bff9 : CustomRisk5Color
Risk6Color = ColorScheme == "Rainbow" ? #fff59d : ColorScheme == "Red/Blue" ? #faa1a4 : CustomRisk6Color
Risk7Color = ColorScheme == "Rainbow" ? #fbc02d : ColorScheme == "Red/Blue" ? #f77c80 : CustomRisk7Color
Risk8Color = ColorScheme == "Rainbow" ? #f57c00 : ColorScheme == "Red/Blue" ? #f7525f : CustomRisk8Color
Risk9Color = ColorScheme == "Rainbow" ? #f7525f : ColorScheme == "Red/Blue" ? #b22833 : CustomRisk9Color
UpperRiskColor = ColorScheme == "Rainbow" ? #b22833 : ColorScheme == "Red/Blue" ? #801922 : CustomUpperRiskColor
Risk1ColorTransp = color.new(Risk1Color,80)
Risk2ColorTransp = color.new(Risk2Color,80)
Risk3ColorTransp = color.new(Risk3Color,80)
Risk4ColorTransp = color.new(Risk4Color,80)
Risk5ColorTransp = color.new(Risk5Color,80)
Risk6ColorTransp = color.new(Risk6Color,80)
Risk7ColorTransp = color.new(Risk7Color,80)
Risk8ColorTransp = color.new(Risk8Color,80)
Risk9ColorTransp = color.new(Risk9Color,80)
UpperRiskColorTransp = color.new(UpperRiskColor,80)
//get values
sma1 = (SMAset == "1D/20Wsma") ? sma(close,1) : (SMAset == "10Dsma/50Wsma") ? sma(close,10) : (SMAset == "50Dsma/50Wsma") ? sma(close,50): (SMAset == "Customized") ? sma(close,dailySMAlength) :na
sma2 = (SMAset == "1D/20Wsma") ? sma(close,20) : (SMAset == "10Dsma/50Wsma" or SMAset == "50Dsma/50Wsma") ? sma(close,50) : (SMAset == "Customized") and (weeklySMAlength == "20W SMA") ? sma(close,20) : (SMAset == "Customized") and (weeklySMAlength == "50W SMA") ? sma(close,50) : na
shortSMA = security(syminfo.tickerid, "1D", sma1)
longSMA = security(syminfo.tickerid, "1W", sma2)
sma20w = security(syminfo.tickerid, "1W", sma(close,20))
sma50w = security(syminfo.tickerid, "1W", sma(close,50))
smaRatio = shortSMA/longSMA
//Set Logarithmic regression settings
UpperA = 0.0
UpperB = 0.0
LowerA = 0.0
LowerB = 0.0
if (asset == "BTC")
UpperA := (SMAset == "1D/20Wsma") ? 28.412 : (SMAset == "10Dsma/50Wsma") ? 33.803 : (SMAset == "50Dsma/50Wsma") ? 12.528 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -3.151 : (SMAset == "10Dsma/50Wsma") ? -3.64 : (SMAset == "50Dsma/50Wsma") ? -1.177 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? -0.74 : (SMAset == "10Dsma/50Wsma") ? 0.42 : (SMAset == "50Dsma/50Wsma") ? 0.51 : (SMAset == "Customized") ? LowerAcustom : na //korrigert fra -0.739 0.425 0.45 0.52
LowerB := (SMAset == "1D/20Wsma") ? 0.156 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "ETH")
UpperA := (SMAset == "1D/20Wsma") ? 19.9 : (SMAset == "10Dsma/50Wsma") ? 30.7 : (SMAset == "50Dsma/50Wsma") ? 10.2 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -2.2 : (SMAset == "10Dsma/50Wsma") ? -3.3 : (SMAset == "50Dsma/50Wsma") ? -0.8 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.35 : (SMAset == "10Dsma/50Wsma") ? 0.17 : (SMAset == "50Dsma/50Wsma") ? 0.25 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "Total Crypto Mcap")
UpperA := (SMAset == "1D/20Wsma") ? 9.0 : (SMAset == "10Dsma/50Wsma") ? 13.4 : (SMAset == "50Dsma/50Wsma") ? 10.2 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -0.8 : (SMAset == "10Dsma/50Wsma") ? -1.1 : (SMAset == "50Dsma/50Wsma") ? -0.9 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.47 : (SMAset == "10Dsma/50Wsma") ? 0.33 : (SMAset == "50Dsma/50Wsma") ? 0.45 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "ADA")
UpperA := (SMAset == "1D/20Wsma") ? 21.7 : (SMAset == "10Dsma/50Wsma") ? 26.0 : (SMAset == "50Dsma/50Wsma") ? 11.0 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -2.4 : (SMAset == "10Dsma/50Wsma") ? -2.7 : (SMAset == "50Dsma/50Wsma") ? -0.9 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.32 : (SMAset == "10Dsma/50Wsma") ? 0.12 : (SMAset == "50Dsma/50Wsma") ? 0.21 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "XRP")
UpperA := (SMAset == "1D/20Wsma") ? 28.8 : (SMAset == "10Dsma/50Wsma") ? 41.7 : (SMAset == "50Dsma/50Wsma") ? 12.9 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -2.9 : (SMAset == "10Dsma/50Wsma") ? -4.3 : (SMAset == "50Dsma/50Wsma") ? -1.1 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? -0.45 : (SMAset == "10Dsma/50Wsma") ? -0.1 : (SMAset == "50Dsma/50Wsma") ? -0.35 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0.121 : (SMAset == "10Dsma/50Wsma") ? 0.05 : (SMAset == "50Dsma/50Wsma") ? 0.1 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "LINK")
UpperA := (SMAset == "1D/20Wsma") ? 17.5 : (SMAset == "10Dsma/50Wsma") ? 22.4 : (SMAset == "50Dsma/50Wsma") ? 7.5 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -1.9 : (SMAset == "10Dsma/50Wsma") ? -2.5 : (SMAset == "50Dsma/50Wsma") ? -0.6 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.1 : (SMAset == "10Dsma/50Wsma") ? 0.45 : (SMAset == "50Dsma/50Wsma") ? 0.45 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0.05 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "VET")
UpperA := (SMAset == "1D/20Wsma") ? 22.5 : (SMAset == "10Dsma/50Wsma") ? 34.0 : (SMAset == "50Dsma/50Wsma") ? 11.8 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -2.5 : (SMAset == "10Dsma/50Wsma") ? -3.9 : (SMAset == "50Dsma/50Wsma") ? -1.1 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.27 : (SMAset == "10Dsma/50Wsma") ? 0.3 : (SMAset == "50Dsma/50Wsma") ? 0.35 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "FTM")
UpperA := (SMAset == "1D/20Wsma") ? 19.3 : (SMAset == "10Dsma/50Wsma") ? 23.3 : (SMAset == "50Dsma/50Wsma") ? 13.3 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -1.9 : (SMAset == "10Dsma/50Wsma") ? -2.5 : (SMAset == "50Dsma/50Wsma") ? -1.1 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? -1.44 : (SMAset == "10Dsma/50Wsma") ? -0.45 : (SMAset == "50Dsma/50Wsma") ? -0.45 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0.266 : (SMAset == "10Dsma/50Wsma") ? 0.1 : (SMAset == "50Dsma/50Wsma") ? 0.1 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "RUNE")
UpperA := (SMAset == "1D/20Wsma") ? 10.5 : (SMAset == "10Dsma/50Wsma") ? 21.9 : (SMAset == "50Dsma/50Wsma") ? 11.6 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -1.0 : (SMAset == "10Dsma/50Wsma") ? -2.3 : (SMAset == "50Dsma/50Wsma") ? -1.1 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.35 : (SMAset == "10Dsma/50Wsma") ? 0.3 : (SMAset == "50Dsma/50Wsma") ? 0.4 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "HBAR")
UpperA := (SMAset == "1D/20Wsma") ? 16.4 : (SMAset == "10Dsma/50Wsma") ? 23.8 : (SMAset == "50Dsma/50Wsma") ? 6.9 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -1.8 : (SMAset == "10Dsma/50Wsma") ? -2.8 : (SMAset == "50Dsma/50Wsma") ? -0.5 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.45 : (SMAset == "10Dsma/50Wsma") ? 0.45 : (SMAset == "50Dsma/50Wsma") ? 0.6 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "Other")
UpperA := UpperAcustom
UpperB := UpperBcustom
LowerA := LowerAcustom
LowerB := LowerBcustom
//Set time intervalls
t=time
genesisBTC=timestamp(2010,7,17,0,0,0) //BTC Index chart
genesisETH=timestamp(2015,8,7,0,0,0) //Ethereum chart
genesisMcap=timestamp(2014,3,1,0,0,0) //total crypto marketcap chart
genesisADA=timestamp(2017,11,30,0,0,0) //ADA chart
genesisVET=timestamp(2018,7,5,0,0,0) //VET chart
genesisXRP=timestamp(2013,8,4,0,0,0) //XRP chart
genesisLink=timestamp(2017,9,28,0,0,0) //LINK chart
genesisRune=timestamp(2019,7,23,0,0,0) //RUNE chart
genesisFTM=timestamp(2018,10,30,0,0,0) //FTM chart
genesisHbar=timestamp(2019,9,17,0,0,0) //Hbar chart
//y=(t-genesis)/604800000
//Alternativt plot av Logaritmisk funksjon, men fungerer kun på én tidsoppløsning av gangen
y = asset == "BTC"? (t-genesisBTC)/86400000 : asset == "ETH"? (t-genesisETH)/86400000 : asset == "Total Crypto Mcap"? (t-genesisMcap)/86400000 : asset == "Total Crypto Mcap"? (t-genesisADA)/86400000 : asset == "Total Crypto Mcap"? (t-genesisVET)/86400000 : asset == "Total Crypto Mcap"? (t-genesisXRP)/86400000 : asset == "Total Crypto Mcap"? (t-genesisLink)/86400000 : asset == "Total Crypto Mcap"? (t-genesisRune)/86400000 : asset == "Total Crypto Mcap"? (t-genesisFTM)/86400000 : asset == "Total Crypto Mcap"? (t-genesisHbar)/86400000 : bar_index
reg1 = UpperA + UpperB*log(y)
reg2 = LowerA + LowerB*log(y)
//Plot Regression in overlay plot
RawRiskLevel = plot(PlotRawRegr ? smaRatio : na, title="SMA Ratio", color=color.white, linewidth=2)
UpperReg = plot(PlotRawRegr ? reg1 : na,title="Upper Regression Line", color=color.purple, linewidth=2)
LowerReg = plot(PlotRawRegr ? reg2 : na,title="Lower Regression Line", color=color.purple, linewidth=2)
LowerDeviation20W = 0.1
LowerDeviation50W = 0.1
sma20wLowestprice = 0.0
sma50wLowestprice = 0.0
LowerBorder = 0.0
HigherDeviation20W = 10.0
HigherDeviation50W = 10.0
sma20wHighestprice = 0.0
sma50wHighestprice = 0.0
HigherBorder = 0.0
//Mål på hvor lavt prisen teoretisk kan gå ifht SMA. Brukes til å sette laveste risikobånd
if (asset == "BTC")
LowerDeviation20W := -0.74+0.156*log(y) //korrigert: skal egentlig være -0.739
LowerDeviation50W := 0.355 //korrigert: skal egentlig være 0.37
sma20wLowestprice := sma20w*LowerDeviation20W
sma50wLowestprice := sma50w*LowerDeviation50W
LowerBorder := max(sma20wLowestprice,sma50wLowestprice)
HigherDeviation20W := 28.412-3.151*log(y) //korrigert: skal egentlig være -0.739
HigherDeviation50W := 46.625-5.156*log(y) //korrigert: skal egentlig være 0.37
sma20wHighestprice := sma20w*HigherDeviation20W
sma50wHighestprice := sma50w*HigherDeviation50W
HigherBorder := min(sma20wHighestprice,sma50wHighestprice)
else if (asset == "ETH")
LowerDeviation20W := 0.35
LowerDeviation50W := 0.16
sma20wLowestprice := sma20w*LowerDeviation20W
sma50wLowestprice := sma50w*LowerDeviation50W
LowerBorder := max(sma20wLowestprice,sma50wLowestprice)
HigherDeviation20W := 19.9-2.2*log(y)
HigherDeviation50W := 37.625-4.1*log(y)
sma20wHighestprice := sma20w*HigherDeviation20W
sma50wHighestprice := sma50w*HigherDeviation50W
HigherBorder := min(sma20wHighestprice,sma50wHighestprice)
else if (asset == "Total Crypto Mcap")
LowerDeviation20W := 0.47
LowerDeviation50W := 0.31
sma20wLowestprice := sma20w*LowerDeviation20W
sma50wLowestprice := sma50w*LowerDeviation50W
LowerBorder := max(sma20wLowestprice,sma50wLowestprice)
HigherDeviation20W := 9-0.8*log(y)
HigherDeviation50W := 25.8-2.7*log(y)
sma20wHighestprice := sma20w*HigherDeviation20W
sma50wHighestprice := sma50w*HigherDeviation50W
HigherBorder := min(sma20wHighestprice,sma50wHighestprice)
else if (asset == "ADA")
LowerDeviation20W := 0.32
LowerDeviation50W := 0.12
sma20wLowestprice := sma20w*LowerDeviation20W
sma50wLowestprice := sma50w*LowerDeviation50W
LowerBorder := max(sma20wLowestprice,sma50wLowestprice)
HigherDeviation20W := 21.7-2.4*log(y)
HigherDeviation50W := 35.8-3.9*log(y)
sma20wHighestprice := sma20w*HigherDeviation20W
sma50wHighestprice := sma50w*HigherDeviation50W
HigherBorder := min(sma20wHighestprice,sma50wHighestprice)
else if (asset == "XRP")
LowerDeviation20W := -0.45+0.121*log(y)
LowerDeviation50W := 0.15+0.03*log(y)
sma20wLowestprice := sma20w*LowerDeviation20W
sma50wLowestprice := sma50w*LowerDeviation50W
LowerBorder := max(sma20wLowestprice,sma50wLowestprice)
HigherDeviation20W := 62-7*log(y)
HigherDeviation50W := 45.8-4.5*log(y)
sma20wHighestprice := sma20w*HigherDeviation20W
sma50wHighestprice := sma50w*HigherDeviation50W
HigherBorder := min(sma20wHighestprice,sma50wHighestprice)
else if (asset == "LINK")
LowerDeviation20W := 0.1+0.05*log(y)
LowerDeviation50W := 0.2
sma20wLowestprice := sma20w*LowerDeviation20W
sma50wLowestprice := sma50w*LowerDeviation50W
LowerBorder := max(sma20wLowestprice,sma50wLowestprice)
HigherDeviation20W := 17.5-1.9*log(y)
HigherDeviation50W := 28.9-3.3*log(y)
sma20wHighestprice := sma20w*HigherDeviation20W
sma50wHighestprice := sma50w*HigherDeviation50W
HigherBorder := min(sma20wHighestprice,sma50wHighestprice)
else if (asset == "VET")
LowerDeviation20W := 0.27
LowerDeviation50W := 0.2
sma20wLowestprice := sma20w*LowerDeviation20W
sma50wLowestprice := sma50w*LowerDeviation50W
LowerBorder := max(sma20wLowestprice,sma50wLowestprice)
HigherDeviation20W := 22.5-2.5*log(y)
HigherDeviation50W := 37.4-4.1*log(y)
sma20wHighestprice := sma20w*HigherDeviation20W
sma50wHighestprice := sma50w*HigherDeviation50W
HigherBorder := min(sma20wHighestprice,sma50wHighestprice)
else if (asset == "FTM")
LowerDeviation20W := -1.44+0.266*log(y)
LowerDeviation50W := 0.16
sma20wLowestprice := sma20w*LowerDeviation20W
sma50wLowestprice := sma50w*LowerDeviation50W
LowerBorder := max(sma20wLowestprice,sma50wLowestprice)
HigherDeviation20W := 19.3-1.9*log(y)
HigherDeviation50W := 33.6-3.8*log(y)
sma20wHighestprice := sma20w*HigherDeviation20W
sma50wHighestprice := sma50w*HigherDeviation50W
HigherBorder := min(sma20wHighestprice,sma50wHighestprice)
else if (asset == "RUNE")
LowerDeviation20W := 0.35
LowerDeviation50W := 0.2
sma20wLowestprice := sma20w*LowerDeviation20W
sma50wLowestprice := sma50w*LowerDeviation50W
LowerBorder := max(sma20wLowestprice,sma50wLowestprice)
HigherDeviation20W := 10.5-1*log(y)
HigherDeviation50W := 20.6-1.9*log(y)
sma20wHighestprice := sma20w*HigherDeviation20W
sma50wHighestprice := sma50w*HigherDeviation50W
HigherBorder := min(sma20wHighestprice,sma50wHighestprice)
else if (asset == "HBAR")
LowerDeviation20W := 0.35
LowerDeviation50W := 0.2
sma20wLowestprice := sma20w*LowerDeviation20W
sma50wLowestprice := sma50w*LowerDeviation50W
LowerBorder := max(sma20wLowestprice,sma50wLowestprice)
HigherDeviation20W := 16.4-1.8*log(y)
HigherDeviation50W := 30.6-3.7*log(y)
sma20wHighestprice := sma20w*HigherDeviation20W
sma50wHighestprice := sma50w*HigherDeviation50W
HigherBorder := min(sma20wHighestprice,sma50wHighestprice)
else if (asset == "Other" and weeklySMAlength == "20W SMA")
LowerDeviation20W := LowerDeviationCustom
HigherDeviation20W := HigherDeviationCustomRegA + HigherDeviationCustomRegB *log(y)
sma20wLowestprice := sma20w*LowerDeviation20W
sma20wHighestprice := sma20w*HigherDeviation20W
LowerBorder := sma20wLowestprice
HigherBorder := sma20wHighestprice
else if (asset == "Other" and weeklySMAlength == "50W SMA")
LowerDeviation50W := LowerDeviationCustom
HigherDeviation50W := HigherDeviationCustomRegA + HigherDeviationCustomRegB *log(y)
sma50wLowestprice := sma50w*LowerDeviation50W
sma50wHighestprice := sma50w*HigherDeviation50W
LowerBorder := sma50wLowestprice
HigherBorder := sma50wHighestprice
//Calculate Risk
Risk = (smaRatio - reg2) / (reg1 - reg2)
RiskColor = Risk < 0.1 ? Risk1Color : Risk < 0.2 ? Risk2Color : Risk < 0.3 ? Risk3Color : Risk < 0.4 ? Risk4Color : Risk < 0.5 ? Risk5Color : Risk < 0.6 ? Risk6Color : Risk < 0.7 ? Risk7Color : Risk < 0.8 ? Risk8Color : Risk < 0.9 ? Risk9Color : Risk < 2 ? UpperRiskColor : na
//Define Risk Bands
MaximumRisk = HigherBorder
Riskband9 = (Risk < 0.9) ? close + (HigherBorder-close)*(0.9-Risk)/(1-Risk) : (Risk > 0.9) ? close - (close-LowerBorder)*(Risk-0.9)/Risk : close
Riskband8 = (Risk < 0.8) ? close + (HigherBorder-close)*(0.8-Risk)/(1-Risk) : (Risk > 0.8) ? close - (close-LowerBorder)*(Risk-0.8)/Risk : close
Riskband7 = (Risk < 0.7) ? close + (HigherBorder-close)*(0.7-Risk)/(1-Risk) : (Risk > 0.7) ? close - (close-LowerBorder)*(Risk-0.7)/Risk : close
Riskband6 = (Risk < 0.6) ? close + (HigherBorder-close)*(0.6-Risk)/(1-Risk) : (Risk > 0.6) ? close - (close-LowerBorder)*(Risk-0.6)/Risk : close
Riskband5 = (Risk < 0.5) ? close + (HigherBorder-close)*(0.5-Risk)/(1-Risk) : (Risk > 0.5) ? close - (close-LowerBorder)*(Risk-0.5)/Risk : close
Riskband4 = (Risk < 0.4) ? close + (HigherBorder-close)*(0.4-Risk)/(1-Risk) : (Risk > 0.4) ? close - (close-LowerBorder)*(Risk-0.4)/Risk : close
Riskband3 = (Risk < 0.3) ? close + (HigherBorder-close)*(0.3-Risk)/(1-Risk) : (Risk > 0.3) ? close - (close-LowerBorder)*(Risk-0.3)/Risk : close
Riskband2 = (Risk < 0.2) ? close + (HigherBorder-close)*(0.2-Risk)/(1-Risk) : (Risk > 0.2) ? close - (close-LowerBorder)*(Risk-0.2)/Risk : close
Riskband1 = (Risk < 0.1) ? close + (HigherBorder-close)*(0.1-Risk)/(1-Risk) : (Risk > 0.1) ? close - (close-LowerBorder)*(Risk-0.1)/Risk : close
MinimumRisk = LowerBorder
RLmax = plot(PlotRiskBands ? MaximumRisk : na, color=UpperRiskColorTransp)
RL9 = plot(PlotRiskBands ? Riskband9 : na, color=Risk9ColorTransp)
RL8 = plot(PlotRiskBands ? Riskband8 : na, color=Risk8ColorTransp)
RL7 = plot(PlotRiskBands ? Riskband7 : na, color=Risk7ColorTransp)
RL6 = plot(PlotRiskBands ? Riskband6 : na, color=Risk6ColorTransp)
RL5 = plot(PlotRiskBands ? Riskband5 : na, color=Risk5ColorTransp)
RL4 = plot(PlotRiskBands ? Riskband4 : na, color=Risk4ColorTransp)
RL3 = plot(PlotRiskBands ? Riskband3 : na, color=Risk3ColorTransp)
RL2 = plot(PlotRiskBands ? Riskband2 : na, color=Risk2ColorTransp)
RL1 = plot(PlotRiskBands ? Riskband1 : na, color=Risk1ColorTransp)
RLmin = plot(PlotRiskBands ? MinimumRisk : na, color=Risk1ColorTransp)
fill(RLmax, RL9, color=UpperRiskColorTransp)
fill(RL9, RL8, color=Risk9ColorTransp)
fill(RL8, RL7, color=Risk8ColorTransp)
fill(RL7, RL6, color=Risk7ColorTransp)
fill(RL6, RL5, color=Risk6ColorTransp)
fill(RL5, RL4, color=Risk5ColorTransp)
fill(RL4, RL3, color=Risk4ColorTransp)
fill(RL3, RL2, color=Risk3ColorTransp)
fill(RL2, RL1, color=Risk2ColorTransp)
fill(RL1, RLmin, color=Risk1ColorTransp)
data = close
plot(PlotLine ? data : na, color=RiskColor, linewidth=4)
plotshape(PlotCircles ? data : na, style=shape.circle, location=location.absolute, size="tiny", color=RiskColor)
plotcandle(PlotCandles ? open : na, high, low, close, color=RiskColor)
plot(PlotSMAs? shortSMA : na, color=color.orange, linewidth=1)
plot(PlotSMAs? longSMA : na, color=color.maroon, linewidth=2)
plot(PlotTheoreticalHighLow? sma50wLowestprice : na, color=color.purple, linewidth=3)
plot(PlotTheoreticalHighLow? sma20wLowestprice : na, color=color.teal, linewidth=3)
plot(PlotTheoreticalHighLow? sma50wHighestprice : na, color=color.purple, linewidth=3)
plot(PlotTheoreticalHighLow? sma20wHighestprice : na, color=color.teal, linewidth=3)
|
Risk Indicator | https://www.tradingview.com/script/YYAAQN00-Risk-Indicator/ | Trollplogen | https://www.tradingview.com/u/Trollplogen/ | 84 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Trollplogen
//@version=4
study("Risk Indicator", overlay=false, precision=3)
//input
asset = input(title="Asset", type=input.string, defval="BTC", options=["BTC", "ETH", "ADA", "XRP", "LINK", "VET", "FTM", "RUNE", "HBAR", "Total Crypto Mcap", "Other"], group="Asset and SMAs")
SMAset = input(title="Selected SMA pair", type=input.string, defval="1D/20Wsma", options=["1D/20Wsma","10Dsma/50Wsma","50Dsma/50Wsma","Customized"], group="Asset and SMAs")
//plot input
PlotRawRatio = input(title="Plot Raw SMA Ratio", type=input.bool, defval=false, group="Plots")
PlotRegression = input(title="Plot Regression Lines", type=input.bool, defval=false, group="Plots")
PlotRiskLevel = input(title="Plot Normalized Risk", type=input.bool, defval=true, group="Plots")
PlotBuySell = input(title="Plot Buy Sell Limits", type=input.bool, defval=true, group="Plots")
buyLimit = input(0.3, title="Buy Limit", group="Buy & Sell Limits")
sellLimit = input(0.7, title="Sell Limit", group="Buy & Sell Limits")
//input customized SMA settings
dailySMAlength = input(title="Daily SMA Length", defval=10, group = "Customized SMA Settings")
weeklySMAlength = input(title="Weekly SMA Length", type=input.string, defval="20W SMA", options=["20W SMA", "50W SMA"], group = "Customized SMA Settings")
//input customized Log regression lines
UpperAcustom = input(20.0, title="Logarithmic Upper Regression Start", group="Custom Regression settings")
UpperBcustom = input(-2.0, title="Logarithmic Upper Regression Factor", group="Custom Regression settings")
LowerAcustom = input(0.3, title="Logarithmic Lower Regression Start", group="Custom Regression settings")
LowerBcustom = input(0.0, title="Logarithmic Lower Regression Factor", group="Custom Regression settings")
//get values
sma1 = (SMAset == "1D/20Wsma") ? sma(close,1) : (SMAset == "10Dsma/50Wsma") ? sma(close,10) : (SMAset == "50Dsma/50Wsma") ? sma(close,50): (SMAset == "Customized") ? sma(close,dailySMAlength) :na
sma2 = (SMAset == "1D/20Wsma") ? sma(close,20) : (SMAset == "10Dsma/50Wsma" or SMAset == "50Dsma/50Wsma") ? sma(close,50) : (SMAset == "Customized") and (weeklySMAlength == "20W SMA") ? sma(close,20) : (SMAset == "Customized") and (weeklySMAlength == "50W SMA") ? sma(close,50) : na
shortSMA = security(syminfo.tickerid, "1D", sma1)
longSMA = security(syminfo.tickerid, "1W", sma2)
smaRatio = shortSMA/longSMA //Simple Relation
//smaRatio = (shortSMA-longSMA)/longSMA //Deviation from longSMA in percent
//Set Logarithmic regression settings
UpperA = 0.0
UpperB = 0.0
LowerA = 0.0
LowerB = 0.0
if (asset == "BTC")
UpperA := (SMAset == "1D/20Wsma") ? 28.412 : (SMAset == "10Dsma/50Wsma") ? 33.803 : (SMAset == "50Dsma/50Wsma") ? 12.528 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -3.151 : (SMAset == "10Dsma/50Wsma") ? -3.64 : (SMAset == "50Dsma/50Wsma") ? -1.177 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? -0.74 : (SMAset == "10Dsma/50Wsma") ? 0.42 : (SMAset == "50Dsma/50Wsma") ? 0.51 : (SMAset == "Customized") ? LowerAcustom : na //korrigert fra -0.739 0.425 0.45 0.52
LowerB := (SMAset == "1D/20Wsma") ? 0.156 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "ETH")
UpperA := (SMAset == "1D/20Wsma") ? 19.9 : (SMAset == "10Dsma/50Wsma") ? 30.7 : (SMAset == "50Dsma/50Wsma") ? 10.2 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -2.2 : (SMAset == "10Dsma/50Wsma") ? -3.3 : (SMAset == "50Dsma/50Wsma") ? -0.8 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.35 : (SMAset == "10Dsma/50Wsma") ? 0.17 : (SMAset == "50Dsma/50Wsma") ? 0.25 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "Total Crypto Mcap")
UpperA := (SMAset == "1D/20Wsma") ? 9.0 : (SMAset == "10Dsma/50Wsma") ? 13.4 : (SMAset == "50Dsma/50Wsma") ? 10.2 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -0.8 : (SMAset == "10Dsma/50Wsma") ? -1.1 : (SMAset == "50Dsma/50Wsma") ? -0.9 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.47 : (SMAset == "10Dsma/50Wsma") ? 0.33 : (SMAset == "50Dsma/50Wsma") ? 0.45 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "ADA")
UpperA := (SMAset == "1D/20Wsma") ? 21.7 : (SMAset == "10Dsma/50Wsma") ? 26.0 : (SMAset == "50Dsma/50Wsma") ? 11.0 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -2.4 : (SMAset == "10Dsma/50Wsma") ? -2.7 : (SMAset == "50Dsma/50Wsma") ? -0.9 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.32 : (SMAset == "10Dsma/50Wsma") ? 0.12 : (SMAset == "50Dsma/50Wsma") ? 0.21 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "XRP")
UpperA := (SMAset == "1D/20Wsma") ? 28.8 : (SMAset == "10Dsma/50Wsma") ? 41.7 : (SMAset == "50Dsma/50Wsma") ? 12.9 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -2.9 : (SMAset == "10Dsma/50Wsma") ? -4.3 : (SMAset == "50Dsma/50Wsma") ? -1.1 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? -0.45 : (SMAset == "10Dsma/50Wsma") ? -0.1 : (SMAset == "50Dsma/50Wsma") ? -0.35 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0.121 : (SMAset == "10Dsma/50Wsma") ? 0.05 : (SMAset == "50Dsma/50Wsma") ? 0.1 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "LINK")
UpperA := (SMAset == "1D/20Wsma") ? 17.5 : (SMAset == "10Dsma/50Wsma") ? 22.4 : (SMAset == "50Dsma/50Wsma") ? 7.5 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -1.9 : (SMAset == "10Dsma/50Wsma") ? -2.5 : (SMAset == "50Dsma/50Wsma") ? -0.6 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.1 : (SMAset == "10Dsma/50Wsma") ? 0.45 : (SMAset == "50Dsma/50Wsma") ? 0.45 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0.05 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "VET")
UpperA := (SMAset == "1D/20Wsma") ? 22.5 : (SMAset == "10Dsma/50Wsma") ? 34.0 : (SMAset == "50Dsma/50Wsma") ? 11.8 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -2.5 : (SMAset == "10Dsma/50Wsma") ? -3.9 : (SMAset == "50Dsma/50Wsma") ? -1.1 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.27 : (SMAset == "10Dsma/50Wsma") ? 0.3 : (SMAset == "50Dsma/50Wsma") ? 0.35 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "FTM")
UpperA := (SMAset == "1D/20Wsma") ? 19.3 : (SMAset == "10Dsma/50Wsma") ? 23.3 : (SMAset == "50Dsma/50Wsma") ? 13.3 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -1.9 : (SMAset == "10Dsma/50Wsma") ? -2.5 : (SMAset == "50Dsma/50Wsma") ? -1.1 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? -1.44 : (SMAset == "10Dsma/50Wsma") ? -0.45 : (SMAset == "50Dsma/50Wsma") ? -0.45 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0.266 : (SMAset == "10Dsma/50Wsma") ? 0.1 : (SMAset == "50Dsma/50Wsma") ? 0.1 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "RUNE")
UpperA := (SMAset == "1D/20Wsma") ? 10.5 : (SMAset == "10Dsma/50Wsma") ? 21.9 : (SMAset == "50Dsma/50Wsma") ? 11.6 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -1.0 : (SMAset == "10Dsma/50Wsma") ? -2.3 : (SMAset == "50Dsma/50Wsma") ? -1.1 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.35 : (SMAset == "10Dsma/50Wsma") ? 0.3 : (SMAset == "50Dsma/50Wsma") ? 0.4 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "HBAR")
UpperA := (SMAset == "1D/20Wsma") ? 16.4 : (SMAset == "10Dsma/50Wsma") ? 23.8 : (SMAset == "50Dsma/50Wsma") ? 6.9 : (SMAset == "Customized") ? UpperAcustom : na
UpperB := (SMAset == "1D/20Wsma") ? -1.8 : (SMAset == "10Dsma/50Wsma") ? -2.8 : (SMAset == "50Dsma/50Wsma") ? -0.5 : (SMAset == "Customized") ? UpperBcustom : na
LowerA := (SMAset == "1D/20Wsma") ? 0.45 : (SMAset == "10Dsma/50Wsma") ? 0.45 : (SMAset == "50Dsma/50Wsma") ? 0.6 : (SMAset == "Customized") ? LowerAcustom : na
LowerB := (SMAset == "1D/20Wsma") ? 0 : (SMAset == "10Dsma/50Wsma") ? 0 : (SMAset == "50Dsma/50Wsma") ? 0 : (SMAset == "Customized") ? LowerBcustom : na
else if (asset == "Other")
UpperA := UpperAcustom
UpperB := UpperBcustom
LowerA := LowerAcustom
LowerB := LowerBcustom
//Set time intervalls
t=time
genesisBTC=timestamp(2010,7,17,0,0,0) //BTC Index chart
genesisETH=timestamp(2015,8,7,0,0,0) //Ethereum chart
genesisMcap=timestamp(2014,3,1,0,0,0) //total crypto marketcap chart
genesisADA=timestamp(2017,11,30,0,0,0) //ADA chart
genesisVET=timestamp(2018,7,5,0,0,0) //VET chart
genesisXRP=timestamp(2013,8,4,0,0,0) //XRP chart
genesisLink=timestamp(2017,9,28,0,0,0) //LINK chart
genesisRune=timestamp(2019,7,23,0,0,0) //RUNE chart
genesisFTM=timestamp(2018,10,30,0,0,0) //FTM chart
genesisHbar=timestamp(2019,9,17,0,0,0) //Hbar chart
//y=(t-genesis)/604800000
//Alternativt plot av Logaritmisk funksjon, men fungerer kun på én tidsoppløsning av gangen
y = asset == "BTC"? (t-genesisBTC)/86400000 : asset == "ETH"? (t-genesisETH)/86400000 : asset == "Total Crypto Mcap"? (t-genesisMcap)/86400000 : asset == "Total Crypto Mcap"? (t-genesisADA)/86400000 : asset == "Total Crypto Mcap"? (t-genesisVET)/86400000 : asset == "Total Crypto Mcap"? (t-genesisXRP)/86400000 : asset == "Total Crypto Mcap"? (t-genesisLink)/86400000 : asset == "Total Crypto Mcap"? (t-genesisRune)/86400000 : asset == "Total Crypto Mcap"? (t-genesisFTM)/86400000 : asset == "Total Crypto Mcap"? (t-genesisHbar)/86400000 : bar_index
reg1 = UpperA + UpperB*log(y)
reg2 = LowerA + LowerB*log(y)
//Calculate Risk
Risk = (smaRatio - reg2) / (reg1 - reg2)
//plotting
RawRiskLevel = plot(PlotRawRatio ? smaRatio : na, title="RiskLevel", color=color.white, linewidth=2)
UpperReg = plot(PlotRegression ? reg1 : na,title="Upper Regression Line", color=color.purple, linewidth=2)
LowerReg = plot(PlotRegression ? reg2 : na,title="Lower Regression Line", color=color.purple, linewidth=2)
RiskLevel = plot(PlotRiskLevel ? Risk : na, title="Normalized Risk Level", color=color.white, linewidth=2)
MaxLevel = plot(PlotRiskLevel ? 1 : na, title="Normalized Risk Level", color=color.gray, linewidth=1)
MinLevel = plot(PlotRiskLevel ? 0 : na, title="Normalized Risk Level", color=color.gray, linewidth=1)
sellLevel = plot(PlotBuySell ? sellLimit : na, title="Sell Limit", color=color.new(color.red,50))
buyLevel = plot(PlotBuySell ? buyLimit : na, title="Sell Limit", color=color.new(color.green,50))
//fill
sellColor = Risk > sellLimit? color.new(color.red,50) : na
buyColor = Risk < buyLimit? color.new(color.green,50) : na
neutralColor = color.new(color.gray, 60)
fill(sellLevel, RiskLevel, color=sellColor)
fill(buyLevel, RiskLevel, color=buyColor)
fill(MinLevel,MaxLevel, color=color.new(color.gray,90))
|
Aggregated Money Flow Index - InFinito | https://www.tradingview.com/script/2Tusyfnl-Aggregated-Money-Flow-Index-InFinito/ | In_Finito_ | https://www.tradingview.com/u/In_Finito_/ | 218 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © In_Finito_
//@version=5
indicator(title='Aggregated Money Flow Index', shorttitle='AMFI', format=format.price, precision=2, timeframe='')
////////////////////MARKET TYPE////////////////////////
aggr = input.bool(defval=true, title='Use Aggregated Data', inline='1', group='Aggregation')
markettype = input.string(defval='Spot', title='Market Type Aggregation', options=['Spot', 'Futures' , 'Perp', 'Derivatives F+P', 'Spot+Derivs'], inline='2', group='Aggregation', tooltip='Disable to check by symbol OR if you want to use this indicator with any other pair than BTC')
length = input.int(title='MFI Length', defval=14, minval=1, maxval=2000)
///////////////////////MA INPUTS///////////////////////////
addma = input.bool(defval=true, title='Add MA to CVD |',inline='1', group='Moving Average')
matype = input.string(defval='SMA', title='MA Type', options=['SMA', 'EMA', 'VWMA', 'WMA', 'SMMA (RMA)'], inline='2', group='Moving Average')
malen = input.int(defval=28, title='MA Lenght', inline='1', group='Moving Average')
//////////////////// Inputs FOR SPOT AGGREGATION///////////////////////////
i_sym1 = input.bool(true, '', inline='1', group='Spot Symbols')
i_sym2 = input.bool(true, '', inline='2', group='Spot Symbols')
i_sym3 = input.bool(true, '', inline='3', group='Spot Symbols')
i_sym4 = input.bool(true, '', inline='4', group='Spot Symbols')
i_sym5 = input.bool(true, '', inline='5', group='Spot Symbols')
i_sym6 = input.bool(true, '', inline='6', group='Spot Symbols')
i_sym7 = input.bool(true, '', inline='7', group='Spot Symbols')
i_sym8 = input.bool(true, '', inline='8', group='Spot Symbols')
i_sym9 = input.bool(true, '', inline='9', group='Spot Symbols')
i_sym10 = input.bool(false, '', inline='10', group='Spot Symbols')
i_sym11 = input.bool(false, '', inline='11', group='Spot Symbols')
i_sym12 = input.bool(true, '', inline='12', group='Spot Symbols')
i_sym13 = input.bool(true, '', inline='13', group='Spot Symbols')
i_sym14 = input.bool(false, '', inline='14', group='Spot Symbols')
i_sym15 = input.bool(false, '', inline='15', group='Spot Symbols')
i_sym16 = input.bool(false, '', inline='16', group='Spot Symbols')
i_sym1_ticker = input.symbol('BINANCE:BTCUSDT', '', inline='1', group='Spot Symbols')
i_sym2_ticker = input.symbol('BINANCE:BTCBUSD', '', inline='2', group='Spot Symbols')
i_sym3_ticker = input.symbol('BITSTAMP:BTCUSD', '', inline='3', group='Spot Symbols')
i_sym4_ticker = input.symbol('HUOBI:BTCUSDT', '', inline='4', group='Spot Symbols')
i_sym5_ticker = input.symbol('OKEX:BTCUSDT', '', inline='5', group='Spot Symbols')
i_sym6_ticker = input.symbol('COINBASE:BTCUSD', '', inline='6', group='Spot Symbols')
i_sym7_ticker = input.symbol('COINBASE:BTCUSDT', '', inline='7', group='Spot Symbols')
i_sym8_ticker = input.symbol('GEMINI:BTCUSD', '', inline='8', group='Spot Symbols')
i_sym9_ticker = input.symbol('KRAKEN:XBTUSD', '', inline='9', group='Spot Symbols')
i_sym10_ticker = input.symbol('FTX:BTCUSD', '', inline='10', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Spot Symbols')
i_sym11_ticker = input.symbol('FTX:BTCUSDT', '', inline='11', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Spot Symbols')
i_sym12_ticker = input.symbol('BITFINEX:BTCUSD', '', inline='12', group='Spot Symbols')
i_sym13_ticker = input.symbol('BINGX:BTCUSDT', '', inline='13', group='Spot Symbols')
i_sym14_ticker = input.symbol('GATEIO:BTCUSDT', '', inline='14', group='Spot Symbols')
i_sym15_ticker = input.symbol('PHEMEX:BTCUSDT', '', inline='15', group='Spot Symbols')
i_sym16_ticker = input.symbol('BITGET:BTCUSDT', '', inline='16', group='Spot Symbols')
sbase1 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='1', group='Spot Symbols')
sbase2 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='2', group='Spot Symbols')
sbase3 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='3', group='Spot Symbols')
sbase4 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='4', group='Spot Symbols')
sbase5 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='5', group='Spot Symbols')
sbase6 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='6', group='Spot Symbols')
sbase7 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='7', group='Spot Symbols')
sbase8 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='8', group='Spot Symbols')
sbase9 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='9', group='Spot Symbols')
sbase10 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='10', group='Spot Symbols')
sbase11 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='11', group='Spot Symbols')
sbase12 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='12', group='Spot Symbols')
sbase13 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='13', group='Spot Symbols')
sbase14 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='14', group='Spot Symbols')
sbase15 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='15', group='Spot Symbols')
sbase16 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='16', group='Spot Symbols')
samount1 = input.float(defval=1, title='#', inline='1', group='Spot Symbols')
samount2 = input.float(defval=1, title='#', inline='2', group='Spot Symbols')
samount3 = input.float(defval=1, title='#', inline='3', group='Spot Symbols')
samount4 = input.float(defval=1, title='#', inline='4', group='Spot Symbols')
samount5 = input.float(defval=1, title='#', inline='5', group='Spot Symbols')
samount6 = input.float(defval=1, title='#', inline='6', group='Spot Symbols')
samount7 = input.float(defval=1, title='#', inline='7', group='Spot Symbols')
samount8 = input.float(defval=1, title='#', inline='8', group='Spot Symbols')
samount9 = input.float(defval=1, title='#', inline='9', group='Spot Symbols')
samount10 = input.float(defval=1, title='#', inline='10', group='Spot Symbols')
samount11 = input.float(defval=1, title='#', inline='11', group='Spot Symbols')
samount12 = input.float(defval=1, title='#', inline='12', group='Spot Symbols')
samount13 = input.float(defval=1, title='#', inline='13', group='Spot Symbols')
samount14 = input.float(defval=1, title='#', inline='14', group='Spot Symbols')
samount15 = input.float(defval=1, title='#', inline='15', group='Spot Symbols')
samount16 = input.float(defval=1, title='#', inline='16', group='Spot Symbols')
//////INPUTS FOR FUTURES AGGREGATION///////////////////
i_sym1b = input.bool(true, '', inline='1', group='Futures Symbols')
i_sym2b = input.bool(true, '', inline='2', group='Futures Symbols')
i_sym3b = input.bool(true, '', inline='3', group='Futures Symbols')
i_sym4b = input.bool(true, '', inline='4', group='Futures Symbols')
i_sym5b = input.bool(true, '', inline='5', group='Futures Symbols')
i_sym6b = input.bool(true, '', inline='6', group='Futures Symbols')
i_sym7b = input.bool(true, '', inline='7', group='Futures Symbols')
i_sym8b = input.bool(true, '', inline='8', group='Futures Symbols')
i_sym9b = input.bool(true, '', inline='9', group='Futures Symbols')
i_sym10b = input.bool(true, '', inline='10', group='Futures Symbols')
i_sym11b = input.bool(false, '', inline='11', group='Futures Symbols')
i_sym12b = input.bool(false, '', inline='12', group='Futures Symbols')
i_sym1b_ticker = input.symbol('BINANCE:BTCUSDTPERP', '', inline='1', group='Futures Symbols')
i_sym2b_ticker = input.symbol('BINANCE:BTCBUSDPERP', '', inline='2', group='Futures Symbols')
i_sym3b_ticker = input.symbol('BYBIT:BTCUSDT.P', '', inline='3', group='Futures Symbols')
i_sym4b_ticker = input.symbol('CME:BTC1!', '', inline='4', tooltip='This volume is reported in 5 BTC and it is recalculated to work properly, beware when changing this symbol',group='Futures Symbols')
i_sym5b_ticker = input.symbol('CME:BTC2!', '', inline='5', tooltip='This volume is reported in 5 BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym6b_ticker = input.symbol('CME:MBT1!', '', inline='6', tooltip='This volume is reported in 0.10 BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym7b_ticker = input.symbol('CME:MBT2!', '', inline='7', tooltip='This volume is reported in 0.10 BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym8b_ticker = input.symbol('PHEMEX:BTCUSDPERP', '', inline='8', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym9b_ticker = input.symbol('OKEX:BTCUSDT.P', '', inline='9', tooltip='This volume is reported in 100x BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym10b_ticker = input.symbol('BITMEX:XBTUSDT', '', inline='10', tooltip='This volume is reported as 1 million per BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym11b_ticker = input.symbol('BITGET:BTCUSDT.P', '', inline='11', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol - THIS IS NOT REPORTED IN REAL TIME', group='Futures Symbols')
i_sym12b_ticker = input.symbol('OKEX:BTCUSDT.P', '', inline='12', group='Futures Symbols')
fbase1 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='1', group='Futures Symbols')
fbase2 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='2', group='Futures Symbols')
fbase3 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='3', group='Futures Symbols')
fbase4 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='4', group='Futures Symbols')
fbase5 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='5', group='Futures Symbols')
fbase6 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='6', group='Futures Symbols')
fbase7 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='7', group='Futures Symbols')
fbase8 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='8', group='Futures Symbols')
fbase9 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='9', group='Futures Symbols')
fbase10 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='10', group='Futures Symbols')
fbase11 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='11', group='Futures Symbols')
fbase12 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='12', group='Futures Symbols')
famount1 = input.float(defval=1, title='#', inline='1', group='Futures Symbols')
famount2 = input.float(defval=1, title='#', inline='2', group='Futures Symbols')
famount3 = input.float(defval=1, title='#', inline='3', group='Futures Symbols')
famount4 = input.float(defval=5, title='#', inline='4', group='Futures Symbols')
famount5 = input.float(defval=5, title='#', inline='5', group='Futures Symbols')
famount6 = input.float(defval=0.1, title='#', inline='6', group='Futures Symbols')
famount7 = input.float(defval=0.1, title='#', inline='7', group='Futures Symbols')
famount8 = input.float(defval=1, title='#', inline='8', group='Futures Symbols')
famount9 = input.float(defval=0.01, title='#', inline='9', group='Futures Symbols')
famount10 = input.float(defval=0.000001, title='#', inline='10', group='Futures Symbols')
famount11 = input.float(defval=1, title='#', inline='11', group='Futures Symbols')
famount12 = input.float(defval=1, title='#', inline='12', group='Futures Symbols')
//, tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol'
////////////////////////////////////////////////////////////////////
//////INPUTS FOR PERP AGGREGATION///////////////////
i_sym1c = input.bool(true, '', inline='1', group='Perpetuals Symbols')
i_sym2c = input.bool(true, '', inline='2', group='Perpetuals Symbols')
i_sym3c = input.bool(true, '', inline='3', group='Perpetuals Symbols')
i_sym4c = input.bool(true, '', inline='4', group='Perpetuals Symbols')
i_sym5c = input.bool(false, '', inline='5', group='Perpetuals Symbols')
i_sym6c = input.bool(true, '', inline='6', group='Perpetuals Symbols')
i_sym7c = input.bool(true, '', inline='7', group='Perpetuals Symbols')
i_sym8c = input.bool(true, '', inline='8', group='Perpetuals Symbols')
i_sym1c_ticker = input.symbol('BINANCE:BTCPERP', '', inline='1', tooltip='This volume is reported in blocks of 100 USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym2c_ticker = input.symbol('OKEX:BTCUSD.P', '', inline='2', tooltip='This volume is reported in blocks of 100 USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym3c_ticker = input.symbol('HUOBI:BTCUSD.P', '', inline='3', group='Perpetuals Symbols')
i_sym4c_ticker = input.symbol('PHEMEX:BTCPERP', '', inline='4', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym5c_ticker = input.symbol('FTX:BTCPERP', '', inline='5', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol' ,group='Perpetuals Symbols')
i_sym6c_ticker = input.symbol('BYBIT:BTCUSD.P', '', inline='6', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym7c_ticker = input.symbol('DERIBIT:BTCUSD.P', '', inline='7', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym8c_ticker = input.symbol('BITMEX:XBTUSD.P', '', inline='8', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
pbase1 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='1', group='Perpetuals Symbols')
pbase2 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='2', group='Perpetuals Symbols')
pbase3 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='3', group='Perpetuals Symbols')
pbase4 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='4', group='Perpetuals Symbols')
pbase5 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='5', group='Perpetuals Symbols')
pbase6 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='6', group='Perpetuals Symbols')
pbase7 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='7', group='Perpetuals Symbols')
pbase8 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='8', group='Perpetuals Symbols')
pamount1 = input.float(defval=100, title='#', inline='1', group='Perpetuals Symbols')
pamount2 = input.float(defval=100, title='#', inline='2', group='Perpetuals Symbols')
pamount3 = input.float(defval=1, title='#', inline='3', group='Perpetuals Symbols')
pamount4 = input.float(defval=1, title='#', inline='4', group='Perpetuals Symbols')
pamount5 = input.float(defval=1, title='#', inline='5', group='Perpetuals Symbols')
pamount6 = input.float(defval=1, title='#', inline='6', group='Perpetuals Symbols')
pamount7 = input.float(defval=1, title='#', inline='7', group='Perpetuals Symbols')
pamount8 = input.float(defval=1, title='#', inline='8', group='Perpetuals Symbols')
////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////AGGREGATED VOLUME CALCULATION///////////////////////
//// VOLUME REQUEST FUNCTION//////////////////////////
f_volume(_ticker) =>
request.security(_ticker, timeframe.period, volume)
//////////////////////////////////////////////////////////
var float finvol = 0
if aggr==true///////////SPOT////////////////////////////////////////////////////////////////////
v1x = (i_sym1 ? f_volume(i_sym1_ticker) : 0)
v1 = sbase1=='Coin' ? v1x*samount1 : sbase1=='USD' or sbase1=='Other' ? (v1x*samount1)/ohlc4 : v1x
v2x = (i_sym2 ? f_volume(i_sym2_ticker) : 0)
v2 = sbase2=='Coin' ? v2x*samount2 : sbase2=='USD' or sbase2=='Other' ? (v2x*samount2)/ohlc4 : v2x
v3x = (i_sym3 ? f_volume(i_sym3_ticker) : 0)
v3 = sbase2=='Coin' ? v3x*samount3 : sbase3=='USD' or sbase3=='Other' ? (v3x*samount4)/ohlc4 : v3x
v4x = (i_sym4 ? f_volume(i_sym4_ticker) : 0)
v4 = sbase4=='Coin' ? v4x*samount4 : sbase4=='USD' or sbase4=='Other' ? (v4x*samount4)/ohlc4 : v4x
v5x = (i_sym5 ? f_volume(i_sym5_ticker) : 0)
v5 = sbase5=='Coin' ? v5x*samount5 : sbase5=='USD' or sbase5=='Other' ? (v5x*samount5)/ohlc4 : v5x
v6x = (i_sym6 ? f_volume(i_sym6_ticker) : 0)
v6 = sbase6=='Coin' ? v6x*samount6 : sbase6=='USD' or sbase6=='Other' ? (v6x*samount6)/ohlc4 : v6x
v7x = (i_sym7 ? f_volume(i_sym7_ticker) : 0)
v7 = sbase7=='Coin' ? v7x*samount7 : sbase7=='USD' or sbase7=='Other' ? (v7x*samount7)/ohlc4 : v7x
v8x = (i_sym8 ? f_volume(i_sym8_ticker) : 0)
v8 = sbase8=='Coin' ? v8x*samount8 : sbase8=='USD' or sbase8=='Other' ? (v8x*samount8)/ohlc4 : v8x
v9x = (i_sym9 ? f_volume(i_sym9_ticker) : 0)
v9 = sbase9=='Coin' ? v9x*samount9 : sbase9=='USD' or sbase9=='Other' ? (v9x*samount9)/ohlc4 : v9x
v10x = (i_sym10 ? f_volume(i_sym10_ticker) : 0) //FTX reported in usd
v10 = sbase10=='Coin' ? v10x*samount10 : sbase10=='USD' or sbase10=='Other' ? (v10x*samount10)/ohlc4 : v10x
v11x = (i_sym11 ? f_volume(i_sym11_ticker) : 0) //FTX reported in usd
v11 = sbase11=='Coin' ? v11x*samount11 : sbase11=='USD' or sbase11=='Other' ? (v11x*samount11)/ohlc4 : v11x
v12x = (i_sym12 ? f_volume(i_sym12_ticker) : 0)
v12 = sbase12=='Coin' ? v12x*samount12 : sbase12=='USD' or sbase12=='Other' ? (v12x*samount10)/ohlc4 : v12x
v13x = (i_sym13 ? f_volume(i_sym13_ticker) : 0)
v13 = sbase13=='Coin' ? v13x*samount13 : sbase13=='USD' or sbase13=='Other' ? (v13x*samount13)/ohlc4 : v13x
v14x = (i_sym14 ? f_volume(i_sym14_ticker) : 0)
v14 = sbase14=='Coin' ? v14x*samount14 : sbase14=='USD' or sbase14=='Other' ? (v14x*samount14)/ohlc4 : v14x
v15x = (i_sym15 ? f_volume(i_sym15_ticker) : 0)
v15 = sbase15=='Coin' ? v15x*samount15 : sbase15=='USD' or sbase15=='Other' ? (v15x*samount15)/ohlc4 : v15x
v16x = (i_sym16 ? f_volume(i_sym16_ticker) : 0)
v16 = sbase16=='Coin' ? v16x*samount16 : sbase16=='USD' or sbase16=='Other' ? (v16x*samount16)/ohlc4 : v16x
vsf=v1+v2+v3+v4+v5+v6+v7+v8+v9+v10+v11+v12+v13+v14+v15+v16
///////////////////////////////////////////////////////////////////////////////////
///////////////////////FUTURES////////////////////////////////////////////////////
v1bx = (i_sym1b ? f_volume(i_sym1b_ticker) : 0)
v1b = fbase1=='Coin' ? v1bx*famount1 : fbase1=='USD' or fbase1=='Other' ? (v1bx*famount1)/ohlc4 : v1bx
v2bx = (i_sym2b ? f_volume(i_sym2b_ticker) : 0)
v2b = fbase2=='Coin' ? v2bx*famount2 : fbase2=='USD' or fbase2=='Other' ? (v2bx*famount2)/ohlc4 : v2bx
v3bx = (i_sym3b ? f_volume(i_sym3b_ticker) : 0)
v3b = fbase3=='Coin' ? v3bx*famount3 : fbase3=='USD' or fbase3=='Other' ? (v3bx*famount3)/ohlc4 : v3bx
v4bx =(i_sym4b ? f_volume(i_sym4b_ticker) : 0) //CME NORMAL (each contract reported equals 5btc)
v4b = fbase4=='Coin' ? v4bx*famount4 : fbase4=='USD' or fbase4=='Other' ? (v4bx*famount4)/ohlc4 : v4bx
v5bx = (i_sym5b ? f_volume(i_sym5b_ticker) : 0)//CME NORMAL (each contract reported equals 5btc)
v5b = fbase5=='Coin' ? v5bx*famount5 : fbase5=='USD' or fbase5=='Other' ? (v5bx*famount5)/ohlc4 : v5bx
v6bx = (i_sym6b ? f_volume(i_sym6b_ticker) : 0)//CME mini (each contract reported equals 0.60btc)
v6b = fbase6=='Coin' ? v6bx*famount6 : fbase6=='USD' or fbase6=='Other' ? (v6bx*famount6)/ohlc4 : v6bx
v7bx = (i_sym7b ? f_volume(i_sym7b_ticker) : 0)//CME mini (each contract reported equals 0.7btc)
v7b = fbase7=='Coin' ? v7bx*famount7 : fbase7=='USD' or fbase7=='Other' ? (v7bx*famount7)/ohlc4 : v7bx
v8bx = (i_sym8b ? f_volume(i_sym8b_ticker) : 0)// PHEMEX reported in usd
v8b = fbase8=='Coin' ? v8bx*famount8 : fbase8=='USD' or fbase8=='Other' ? (v8bx*famount8)/ohlc4 : v8bx
v9bx = (i_sym9b ? f_volume(i_sym9b_ticker) : 0)// OKEX reported in 900xBTC, meaning every 900 contracts is only one
v9b = fbase9=='Coin' ? v9bx*famount9 : fbase9=='USD' or fbase9=='Other' ? (v9bx*famount9)/ohlc4 : v9bx
v10bx = (i_sym10b ? f_volume(i_sym10b_ticker) : 0)// BITMEX REPORTED IN 1 MILLION BTC, MEANING EACH MILLION CONTRACTS ON TV REPRESENT 1 BTC
v10b = fbase10=='Coin' ? v1bx*famount10 : fbase10=='USD' or fbase10=='Other' ? (v10bx*famount10)/ohlc4 : v10bx
v11bx = (i_sym11b ? f_volume(i_sym11b_ticker) : 0)// BITGET REPORTED IN USD - TURNED OFF BECAUSE DOESNT PROVIDE REAL TIME DATA
v11b = fbase11=='Coin' ? v11bx*famount11 : fbase11=='USD' or fbase11=='Other' ? (v11bx*famount11)/ohlc4 : v11bx
v12bx = (i_sym12b ? f_volume(i_sym12b_ticker) : 0)
v12b = fbase12=='Coin' ? v12bx*famount12 : fbase12=='USD' or fbase12=='Other' ? (v12bx*famount12)/ohlc4 : v12bx
vff=v1b+v2b+v3b+v4b+v5b+v6b+v7b+v8b+v9b+v10b+v11b+v12b
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////PERPS///////////////////////////////////////////////////////////
v1cx = (i_sym1c ? f_volume(i_sym1c_ticker) : 0)//BINANCE REPORTED IN BLOCKS OF 100 USD, MEANING EACH CONTRACT REPORTED IS EQUAL TO 100 USD
v1c = pbase1=='Coin' ? v1cx*pamount1 : pbase1=='USD' or pbase1=='Other' ? (v1cx*pamount1)/ohlc4 : v1cx
v2cx = (i_sym2c ? f_volume(i_sym2c_ticker) : 0)//OKEX REPORTED IN BLOCKS OF 100 USD, MEANING EACH CONTRACT REPORTED IS EQUAL TO 100 USD
v2c = pbase2=='Coin' ? v2cx*pamount2 : pbase2=='USD' or pbase2=='Other' ? (v2cx*pamount2)/ohlc4 : v2cx
v3cx = (i_sym3c ? f_volume(i_sym3c_ticker) : 0)// HUOBI REPORTED IN BTC
v3c = pbase3=='Coin' ? v3cx*pamount3 : pbase3=='USD' or pbase3=='Other' ? (v3cx*pamount3)/ohlc4 : v3cx
v4cx =(i_sym4c ? f_volume(i_sym4c_ticker) : 0)// PHEMEX REPORTED IN USD
v4c = pbase4=='Coin' ? v4cx*pamount4 : pbase4=='USD' or pbase4=='Other' ? (v4cx*pamount4)/ohlc4 : v4cx
v5cx = (i_sym5c ? f_volume(i_sym5c_ticker) : 0)// FTX REPORTED IN USD
v5c = pbase5=='Coin' ? v5cx*pamount5 : pbase5=='USD' or pbase5=='Other' ? (v5cx*pamount5)/ohlc4 : v5cx
v6cx = (i_sym6c ? f_volume(i_sym6c_ticker) : 0)//BYBIT REPORTED IN USD
v6c = pbase6=='Coin' ? v6cx*pamount6 : pbase6=='USD' or pbase6=='Other' ? (v6cx*pamount6)/ohlc4 : v6cx
v7cx = (i_sym7c ? f_volume(i_sym7c_ticker) : 0)//DERIBIT REPORTED IN USD
v7c = pbase7=='Coin' ? v7cx*pamount7 : pbase7=='USD' or pbase7=='Other' ? (v7cx*pamount7)/ohlc4 : v7cx
v8cx = (i_sym8c ? f_volume(i_sym8c_ticker) : 0)//BITMEX REPORTED IN USD
v8c = pbase8=='Coin' ? v8cx*pamount8 : pbase8=='USD' or pbase8=='Other' ? (v8cx*pamount8)/ohlc4 : v8cx
vpf=v1c+v2c+v3c+v4c+v5c+v6c+v7c+v8c
///////////////////////////////////////////////////////////////////////////////////////
////////////////////ALL DERIV VOLUME//////////////////////////////////////////////////////////////////
alldvol = vff + vpf
/////////////////////////////////////////////////////////////////////////////////////////
////////////////////ALL VOLUME//////////////////////////////////////////////////////////////////
allvol = vsf + vff + vpf
/////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////FINAL AGGREGATION SELECTION/////////////////////////////////////////
if markettype == 'Spot'
finvol := vsf
finvol
else if markettype == 'Futures'
finvol := vff
finvol
else if markettype == 'Perp'
finvol := vpf
finvol
else if markettype == 'Derivatives F+P'
finvol := alldvol
finvol
else if markettype == 'Spot+Derivs'
finvol := allvol
finvol
else if aggr==false
finvol := volume
///////////////////////////////////AGGREGATED OR BY CHART////////////////////////////////////////////////
vol = finvol
src = hlc3
upper = math.sum(finvol * (ta.change(src) <= 0 ? 0 : src), length)
lower = math.sum(finvol * (ta.change(src) >= 0 ? 0 : src), length)
_rsi(upper, lower) =>
100.0 - 100.0 / (1.0 + upper / lower)
mf = _rsi(upper, lower)
mfp=plot(mf, 'MF', color=color.new(#7E57C2, 0))
overbought = hline(80, title='Overbought', color=#787B86)
oversold = hline(20, title='Oversold', color=#787B86)
vob = hline(90, title='Bought', color=#787B86)
vos = hline(10, title='Sold', color=#787B86)
fill(overbought, oversold, color=color.rgb(126, 87, 194, 95), title='Background')
ceup = hline(55, title='Center Up ', color=color.new(color.black, 100))
cedo = hline(45, title='Center Down', color=color.new(color.black, 100))
fill(ceup, cedo, color=color.new(color.blue, 85), title='Center Range Fill')
////////////////////PLOT MAs SWITCH ALTERNATIVE////////////////////////////////
masrc = mf
ma(source, length, type) =>
switch type
"SMA" => 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)
maline = ma(masrc, malen, matype)
/////////////////////////////////////
maplot = plot(addma? maline : na, title='Moving Average', color=color.purple)
////////MA FILL
var fillcol = color.green
if (maline > mf)
fillcol := color.new(color.red, 90)
else if (maline < mf)
fillcol := color.new(color.green, 90)
fill(mfp , maplot , title='Moving Average Fill', color=fillcol, fillgaps=true)
|
Aarika Balance of Power Trend (ABOPC) | https://www.tradingview.com/script/Ja2BR0tI-Aarika-Balance-of-Power-Trend-ABOPC/ | hlsolanki | https://www.tradingview.com/u/hlsolanki/ | 74 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hlsolanki
//@version=5
//
indicator('Aarika Balance of Power Trend', shorttitle='ABOPT', overlay=false)
//
reg_trend_on = input(true, 'Activate Reg Trend Line')
length = input.int(defval=21, title='Length Reg Trend line=', minval=1)
//
BullTrend_hist = 0.0
BearTrend_hist = 0.0
BullTrend = (close - ta.lowest(low, 50)) / ta.atr(5)
BearTrend = (ta.highest(high, 50) - close) / ta.atr(5)
BearTrend2 = -1 * BearTrend
Trend = BullTrend - BearTrend
hline(0, title='Nivel 0', color=color.new (color.black, 0), linestyle=hline.style_solid, linewidth=1)
niv_0 = plot(0, title='Nivel 0"', color=color.new(color.black, 50), linewidth=1, style=plot.style_line)
hline(2, title='Nivel 2', color=color.new (color.red, 0), linestyle=hline.style_solid, linewidth=2)
niv_2 = plot(2, title='Nivel 2', color=color.new(color.green, 50), linewidth=1, style=plot.style_line)
hline(-2, title='Nivel -2', color=color.new (color.green, 0), linestyle=hline.style_solid, linewidth=2)
niv_22 = plot(-2, title='Nivel -2"', color=color.new(color.red, 50), linewidth=1, style=plot.style_line)
a = plot(BullTrend, title='Bull Trend', color=color.new(color.green, 0), linewidth=1, style=plot.style_line)
b = plot(BearTrend2, title='Bear Trend', color=color.new(color.red, 0), linewidth=1, style=plot.style_line)
fill(a, niv_2, color=color.new(color.green, 50))
fill(b, niv_22, color=color.new(color.red, 50))
fill(niv_22, niv_2, color=color.new(color.yellow, 90))
plot(reg_trend_on == false ? Trend : na, title='Trend', color=color.new(color.black, 0), linewidth=1, style=plot.style_line)
if BearTrend2 > -2
BearTrend_hist := BearTrend2 + 2
BearTrend_hist
plot(BearTrend_hist, title='Bear Trend Hist', color=color.new(color.green, 0), linewidth=1, style=plot.style_columns)
if BullTrend < 2
BullTrend_hist := BullTrend - 2
BullTrend_hist
plot(BullTrend_hist, title='Bull Trend Hist', color=color.new(color.red, 0), linewidth=1, style=plot.style_columns)
x = bar_index
y = Trend
x_ = ta.sma(x, length)
y_ = ta.sma(y, length)
mx = ta.stdev(x, length)
my = ta.stdev(y, length)
c = ta.correlation(x, y, length)
slope = c * (my / mx)
inter = y_ - slope * x_
reg_trend = x * slope + inter
//
plot(reg_trend_on == true ? reg_trend : na, title='Trend', color=color.new(color.black, 100), linewidth=2, style=plot.style_line)
Boolean_1 = input.bool(true, title='--- BOP ---')
THL = high != low ? high - low : 0.01
BullOpen = (high - open) / THL
BearOpen = (open - low) / THL
BullClose = (close - low) / THL
BearClose = (high - close) / THL
BullOC = close > open ? (close - open) / THL : 0
BearOC = open > close ? (open - close) / THL : 0
BullReward = (BullOpen + BullClose + BullOC) / 3
BearReward = (BearOpen + BearClose + BearOC) / 3
BOP = BullReward - BearReward
ma(Type, src, len) =>
A = ta.ema(src, len)
B = ta.sma(src, len)
Type == 'EMA' ? A : Type == 'SMA' ? B : na
EMA = input(50, 'Ema Length')
SmoothBOP = ta.ema(BOP, EMA)
TEMA = input(50, 'Tema Length')
xPrice = SmoothBOP
xEMA1 = ta.ema(SmoothBOP, TEMA)
xEMA2 = ta.ema(xEMA1, TEMA)
xEMA3 = ta.ema(xEMA2, TEMA)
nRes = 3 * xEMA1 - 3 * xEMA2 + xEMA3
SmootherBOP = nRes
plot(SmoothBOP * 100, 'BOP ', color=color.new(color.maroon, 0), linewidth=2)
plot(SmootherBOP * 100, 'SmootherBOP', color=color.new(color.navy, 0), linewidth=2)
//bgcolor(SmoothBOP > SmootherBOP ? color.green : color.red)
|
Aggregated On Balance Volume - InFinito | https://www.tradingview.com/script/rxt6n7ym-Aggregated-On-Balance-Volume-InFinito/ | In_Finito_ | https://www.tradingview.com/u/In_Finito_/ | 148 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © InFinito
//Based of Crypt0rus Aggregation & LonesomeTheBlue Candle Plotting Original Code
//@version=5
indicator(title=" Aggregated On Balance Volume", shorttitle=" Aggregated OBV", format=format.volume, timeframe="", timeframe_gaps=true)
////////////////////MARKET TYPE////////////////////////
aggr = input.bool(defval=true, title='Use Aggregated Data', inline='1', group='Aggregation', tooltip='Disable to check by symbol OR if you want to use this indicator with any other pair than BTC')
markettype = input.string(defval='Spot', title='Market Type Aggregation', options=['Spot', 'Futures' , 'Perp', 'Derivatives F+P', 'Spot+Derivs'], inline='2', group='Aggregation')
bres = input.bool(defval=false, title='', inline='1', group='Reset Basis')
brestf = input.timeframe(defval='12M', title='Reset Basis Periodically', options=['12M', '6M', '3M', 'M', '2W', 'W', 'D', '240', '60' ], inline='1', group='Reset Basis', tooltip='Reset OBV to 0 every X amount of time')
/////////////////////////PLOT STYLE/////////////////////////////
linestyle = input.string(defval='Line', title='Style', options=['Candle', 'Line'], inline='1', group='Line / Candle')
hacandle = input.bool(defval=false, title='Heikin Ashi Candles', inline='1', group='Line / Candle')
////////////////INPUTS FOR CANDLES/////////////////////////////////
colorup = input.color(defval=color.green, title='Body', inline='bcol', group='Candle Coloring')
colordown = input.color(defval=color.red, title='', inline='bcol', group='Candle Coloring')
bcolup = input.color(defval=color.black, title='Border', inline='bocol', group='Candle Coloring')
bcoldown = input.color(defval=color.black, title='', inline='bocol', group='Candle Coloring')
wcolup = input.color(defval=color.black, title='Wicks', inline='wcol', group='Candle Coloring')
wcoldown = input.color(defval=color.black, title='', inline='wcol', group='Candle Coloring')
tw = high - math.max(open, close)
bw = math.min(open, close) - low
body = math.abs(close - open)
///////////////////////MA INPUTS////////////////////////////////////
addma = input.bool(defval=true, title='Add MA |', inline='1', group='Moving Average')
matype = input.string(defval='SMA', title='MA Type', options=['SMA', 'EMA', 'VWMA', 'WMA', 'SMMA (RMA)'], inline='2', group='Moving Average')
malen = input.int(defval=28, title='MA Lenght', inline='1', group='Moving Average')
//////////////////// Inputs FOR SPOT AGGREGATION///////////////////////////
i_sym1 = input.bool(true, '', inline='1', group='Spot Symbols')
i_sym2 = input.bool(true, '', inline='2', group='Spot Symbols')
i_sym3 = input.bool(true, '', inline='3', group='Spot Symbols')
i_sym4 = input.bool(true, '', inline='4', group='Spot Symbols')
i_sym5 = input.bool(true, '', inline='5', group='Spot Symbols')
i_sym6 = input.bool(true, '', inline='6', group='Spot Symbols')
i_sym7 = input.bool(true, '', inline='7', group='Spot Symbols')
i_sym8 = input.bool(true, '', inline='8', group='Spot Symbols')
i_sym9 = input.bool(true, '', inline='9', group='Spot Symbols')
i_sym10 = input.bool(false, '', inline='10', group='Spot Symbols')
i_sym11 = input.bool(false, '', inline='11', group='Spot Symbols')
i_sym12 = input.bool(true, '', inline='12', group='Spot Symbols')
i_sym13 = input.bool(true, '', inline='13', group='Spot Symbols')
i_sym14 = input.bool(false, '', inline='14', group='Spot Symbols')
i_sym15 = input.bool(false, '', inline='15', group='Spot Symbols')
i_sym16 = input.bool(false, '', inline='16', group='Spot Symbols')
i_sym1_ticker = input.symbol('BINANCE:BTCUSDT', '', inline='1', group='Spot Symbols')
i_sym2_ticker = input.symbol('BINANCE:BTCBUSD', '', inline='2', group='Spot Symbols')
i_sym3_ticker = input.symbol('BITSTAMP:BTCUSD', '', inline='3', group='Spot Symbols')
i_sym4_ticker = input.symbol('HUOBI:BTCUSDT', '', inline='4', group='Spot Symbols')
i_sym5_ticker = input.symbol('OKEX:BTCUSDT', '', inline='5', group='Spot Symbols')
i_sym6_ticker = input.symbol('COINBASE:BTCUSD', '', inline='6', group='Spot Symbols')
i_sym7_ticker = input.symbol('COINBASE:BTCUSDT', '', inline='7', group='Spot Symbols')
i_sym8_ticker = input.symbol('GEMINI:BTCUSD', '', inline='8', group='Spot Symbols')
i_sym9_ticker = input.symbol('KRAKEN:XBTUSD', '', inline='9', group='Spot Symbols')
i_sym10_ticker = input.symbol('FTX:BTCUSD', '', inline='10', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Spot Symbols')
i_sym11_ticker = input.symbol('FTX:BTCUSDT', '', inline='11', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Spot Symbols')
i_sym12_ticker = input.symbol('BITFINEX:BTCUSD', '', inline='12', group='Spot Symbols')
i_sym13_ticker = input.symbol('BINGX:BTCUSDT', '', inline='13', group='Spot Symbols')
i_sym14_ticker = input.symbol('GATEIO:BTCUSDT', '', inline='14', group='Spot Symbols')
i_sym15_ticker = input.symbol('PHEMEX:BTCUSDT', '', inline='15', group='Spot Symbols')
i_sym16_ticker = input.symbol('BITGET:BTCUSDT', '', inline='16', group='Spot Symbols')
sbase1 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='1', group='Spot Symbols')
sbase2 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='2', group='Spot Symbols')
sbase3 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='3', group='Spot Symbols')
sbase4 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='4', group='Spot Symbols')
sbase5 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='5', group='Spot Symbols')
sbase6 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='6', group='Spot Symbols')
sbase7 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='7', group='Spot Symbols')
sbase8 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='8', group='Spot Symbols')
sbase9 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='9', group='Spot Symbols')
sbase10 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='10', group='Spot Symbols')
sbase11 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='11', group='Spot Symbols')
sbase12 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='12', group='Spot Symbols')
sbase13 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='13', group='Spot Symbols')
sbase14 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='14', group='Spot Symbols')
sbase15 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='15', group='Spot Symbols')
sbase16 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='16', group='Spot Symbols')
samount1 = input.float(defval=1, title='#', inline='1', group='Spot Symbols')
samount2 = input.float(defval=1, title='#', inline='2', group='Spot Symbols')
samount3 = input.float(defval=1, title='#', inline='3', group='Spot Symbols')
samount4 = input.float(defval=1, title='#', inline='4', group='Spot Symbols')
samount5 = input.float(defval=1, title='#', inline='5', group='Spot Symbols')
samount6 = input.float(defval=1, title='#', inline='6', group='Spot Symbols')
samount7 = input.float(defval=1, title='#', inline='7', group='Spot Symbols')
samount8 = input.float(defval=1, title='#', inline='8', group='Spot Symbols')
samount9 = input.float(defval=1, title='#', inline='9', group='Spot Symbols')
samount10 = input.float(defval=1, title='#', inline='10', group='Spot Symbols')
samount11 = input.float(defval=1, title='#', inline='11', group='Spot Symbols')
samount12 = input.float(defval=1, title='#', inline='12', group='Spot Symbols')
samount13 = input.float(defval=1, title='#', inline='13', group='Spot Symbols')
samount14 = input.float(defval=1, title='#', inline='14', group='Spot Symbols')
samount15 = input.float(defval=1, title='#', inline='15', group='Spot Symbols')
samount16 = input.float(defval=1, title='#', inline='16', group='Spot Symbols')
//////INPUTS FOR FUTURES AGGREGATION///////////////////
i_sym1b = input.bool(true, '', inline='1', group='Futures Symbols')
i_sym2b = input.bool(true, '', inline='2', group='Futures Symbols')
i_sym3b = input.bool(true, '', inline='3', group='Futures Symbols')
i_sym4b = input.bool(false, '', inline='4', group='Futures Symbols')
i_sym5b = input.bool(false, '', inline='5', group='Futures Symbols')
i_sym6b = input.bool(false, '', inline='6', group='Futures Symbols')
i_sym7b = input.bool(false, '', inline='7', group='Futures Symbols')
i_sym8b = input.bool(true, '', inline='8', group='Futures Symbols')
i_sym9b = input.bool(true, '', inline='9', group='Futures Symbols')
i_sym10b = input.bool(true, '', inline='10', group='Futures Symbols')
i_sym11b = input.bool(false, '', inline='11', group='Futures Symbols')
i_sym12b = input.bool(false, '', inline='12', group='Futures Symbols')
i_sym1b_ticker = input.symbol('BINANCE:BTCUSDTPERP', '', inline='1', group='Futures Symbols')
i_sym2b_ticker = input.symbol('BINANCE:BTCBUSDPERP', '', inline='2', group='Futures Symbols')
i_sym3b_ticker = input.symbol('BYBIT:BTCUSDT.P', '', inline='3', group='Futures Symbols')
i_sym4b_ticker = input.symbol('CME:BTC1!', '', inline='4', tooltip='This volume is reported in 5 BTC and it is recalculated to work properly, beware when changing this symbol',group='Futures Symbols')
i_sym5b_ticker = input.symbol('CME:BTC2!', '', inline='5', tooltip='This volume is reported in 5 BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym6b_ticker = input.symbol('CME:MBT1!', '', inline='6', tooltip='This volume is reported in 0.10 BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym7b_ticker = input.symbol('CME:MBT2!', '', inline='7', tooltip='This volume is reported in 0.10 BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym8b_ticker = input.symbol('PHEMEX:BTCUSDPERP', '', inline='8', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym9b_ticker = input.symbol('OKEX:BTCUSDT.P', '', inline='9', tooltip='This volume is reported in 100x BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym10b_ticker = input.symbol('BITMEX:XBTUSDT', '', inline='10', tooltip='This volume is reported as 1 million per BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym11b_ticker = input.symbol('BITGET:BTCUSDT.P', '', inline='11', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol - THIS IS NOT REPORTED IN REAL TIME', group='Futures Symbols')
i_sym12b_ticker = input.symbol('OKEX:BTCUSDT.P', '', inline='12', group='Futures Symbols')
fbase1 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='1', group='Futures Symbols')
fbase2 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='2', group='Futures Symbols')
fbase3 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='3', group='Futures Symbols')
fbase4 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='4', group='Futures Symbols')
fbase5 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='5', group='Futures Symbols')
fbase6 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='6', group='Futures Symbols')
fbase7 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='7', group='Futures Symbols')
fbase8 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='8', group='Futures Symbols')
fbase9 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='9', group='Futures Symbols')
fbase10 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='10', group='Futures Symbols')
fbase11 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='11', group='Futures Symbols')
fbase12 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='12', group='Futures Symbols')
famount1 = input.float(defval=1, title='#', inline='1', group='Futures Symbols')
famount2 = input.float(defval=1, title='#', inline='2', group='Futures Symbols')
famount3 = input.float(defval=1, title='#', inline='3', group='Futures Symbols')
famount4 = input.float(defval=5, title='#', inline='4', group='Futures Symbols')
famount5 = input.float(defval=5, title='#', inline='5', group='Futures Symbols')
famount6 = input.float(defval=0.1, title='#', inline='6', group='Futures Symbols')
famount7 = input.float(defval=0.1, title='#', inline='7', group='Futures Symbols')
famount8 = input.float(defval=1, title='#', inline='8', group='Futures Symbols')
famount9 = input.float(defval=0.01, title='#', inline='9', group='Futures Symbols')
famount10 = input.float(defval=0.000001, title='#', inline='10', group='Futures Symbols')
famount11 = input.float(defval=1, title='#', inline='11', group='Futures Symbols')
famount12 = input.float(defval=1, title='#', inline='12', group='Futures Symbols')
//, tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol'
////////////////////////////////////////////////////////////////////
//////INPUTS FOR PERP AGGREGATION///////////////////
i_sym1c = input.bool(true, '', inline='1', group='Perpetuals Symbols')
i_sym2c = input.bool(true, '', inline='2', group='Perpetuals Symbols')
i_sym3c = input.bool(true, '', inline='3', group='Perpetuals Symbols')
i_sym4c = input.bool(true, '', inline='4', group='Perpetuals Symbols')
i_sym5c = input.bool(false, '', inline='5', group='Perpetuals Symbols')
i_sym6c = input.bool(true, '', inline='6', group='Perpetuals Symbols')
i_sym7c = input.bool(true, '', inline='7', group='Perpetuals Symbols')
i_sym8c = input.bool(true, '', inline='8', group='Perpetuals Symbols')
i_sym1c_ticker = input.symbol('BINANCE:BTCPERP', '', inline='1', tooltip='This volume is reported in blocks of 100 USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym2c_ticker = input.symbol('OKEX:BTCUSD.P', '', inline='2', tooltip='This volume is reported in blocks of 100 USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym3c_ticker = input.symbol('HUOBI:BTCUSD.P', '', inline='3', group='Perpetuals Symbols')
i_sym4c_ticker = input.symbol('PHEMEX:BTCPERP', '', inline='4', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym5c_ticker = input.symbol('FTX:BTCPERP', '', inline='5', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol' ,group='Perpetuals Symbols')
i_sym6c_ticker = input.symbol('BYBIT:BTCUSD.P', '', inline='6', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym7c_ticker = input.symbol('DERIBIT:BTCUSD.P', '', inline='7', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym8c_ticker = input.symbol('BITMEX:XBTUSD.P', '', inline='8', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
pbase1 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='1', group='Perpetuals Symbols')
pbase2 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='2', group='Perpetuals Symbols')
pbase3 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='3', group='Perpetuals Symbols')
pbase4 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='4', group='Perpetuals Symbols')
pbase5 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='5', group='Perpetuals Symbols')
pbase6 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='6', group='Perpetuals Symbols')
pbase7 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='7', group='Perpetuals Symbols')
pbase8 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='8', group='Perpetuals Symbols')
pamount1 = input.float(defval=100, title='#', inline='1', group='Perpetuals Symbols')
pamount2 = input.float(defval=100, title='#', inline='2', group='Perpetuals Symbols')
pamount3 = input.float(defval=1, title='#', inline='3', group='Perpetuals Symbols')
pamount4 = input.float(defval=1, title='#', inline='4', group='Perpetuals Symbols')
pamount5 = input.float(defval=1, title='#', inline='5', group='Perpetuals Symbols')
pamount6 = input.float(defval=1, title='#', inline='6', group='Perpetuals Symbols')
pamount7 = input.float(defval=1, title='#', inline='7', group='Perpetuals Symbols')
pamount8 = input.float(defval=1, title='#', inline='8', group='Perpetuals Symbols')
////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////AGGREGATED VOLUME CALCULATION///////////////////////
//// VOLUME REQUEST FUNCTION//////////////////////////
f_volume(_ticker) =>
request.security(_ticker, timeframe.period, volume)
//////////////////////////////////////////////////////////
var float finvol = 0
if aggr==true ///////////SPOT////////////////////////////////////////////////////////////////////
v1x = (i_sym1 ? f_volume(i_sym1_ticker) : 0)
v1 = sbase1=='Coin' ? v1x*samount1 : sbase1=='USD' or sbase1=='Other' ? (v1x*samount1)/ohlc4 : v1x
v2x = (i_sym2 ? f_volume(i_sym2_ticker) : 0)
v2 = sbase2=='Coin' ? v2x*samount2 : sbase2=='USD' or sbase2=='Other' ? (v2x*samount2)/ohlc4 : v2x
v3x = (i_sym3 ? f_volume(i_sym3_ticker) : 0)
v3 = sbase2=='Coin' ? v3x*samount3 : sbase3=='USD' or sbase3=='Other' ? (v3x*samount4)/ohlc4 : v3x
v4x = (i_sym4 ? f_volume(i_sym4_ticker) : 0)
v4 = sbase4=='Coin' ? v4x*samount4 : sbase4=='USD' or sbase4=='Other' ? (v4x*samount4)/ohlc4 : v4x
v5x = (i_sym5 ? f_volume(i_sym5_ticker) : 0)
v5 = sbase5=='Coin' ? v5x*samount5 : sbase5=='USD' or sbase5=='Other' ? (v5x*samount5)/ohlc4 : v5x
v6x = (i_sym6 ? f_volume(i_sym6_ticker) : 0)
v6 = sbase6=='Coin' ? v6x*samount6 : sbase6=='USD' or sbase6=='Other' ? (v6x*samount6)/ohlc4 : v6x
v7x = (i_sym7 ? f_volume(i_sym7_ticker) : 0)
v7 = sbase7=='Coin' ? v7x*samount7 : sbase7=='USD' or sbase7=='Other' ? (v7x*samount7)/ohlc4 : v7x
v8x = (i_sym8 ? f_volume(i_sym8_ticker) : 0)
v8 = sbase8=='Coin' ? v8x*samount8 : sbase8=='USD' or sbase8=='Other' ? (v8x*samount8)/ohlc4 : v8x
v9x = (i_sym9 ? f_volume(i_sym9_ticker) : 0)
v9 = sbase9=='Coin' ? v9x*samount9 : sbase9=='USD' or sbase9=='Other' ? (v9x*samount9)/ohlc4 : v9x
v10x = (i_sym10 ? f_volume(i_sym10_ticker) : 0) //FTX reported in usd
v10 = sbase10=='Coin' ? v10x*samount10 : sbase10=='USD' or sbase10=='Other' ? (v10x*samount10)/ohlc4 : v10x
v11x = (i_sym11 ? f_volume(i_sym11_ticker) : 0) //FTX reported in usd
v11 = sbase11=='Coin' ? v11x*samount11 : sbase11=='USD' or sbase11=='Other' ? (v11x*samount11)/ohlc4 : v11x
v12x = (i_sym12 ? f_volume(i_sym12_ticker) : 0)
v12 = sbase12=='Coin' ? v12x*samount12 : sbase12=='USD' or sbase12=='Other' ? (v12x*samount10)/ohlc4 : v12x
v13x = (i_sym13 ? f_volume(i_sym13_ticker) : 0)
v13 = sbase13=='Coin' ? v13x*samount13 : sbase13=='USD' or sbase13=='Other' ? (v13x*samount13)/ohlc4 : v13x
v14x = (i_sym14 ? f_volume(i_sym14_ticker) : 0)
v14 = sbase14=='Coin' ? v14x*samount14 : sbase14=='USD' or sbase14=='Other' ? (v14x*samount14)/ohlc4 : v14x
v15x = (i_sym15 ? f_volume(i_sym15_ticker) : 0)
v15 = sbase15=='Coin' ? v15x*samount15 : sbase15=='USD' or sbase15=='Other' ? (v15x*samount15)/ohlc4 : v15x
v16x = (i_sym16 ? f_volume(i_sym16_ticker) : 0)
v16 = sbase16=='Coin' ? v16x*samount16 : sbase16=='USD' or sbase16=='Other' ? (v16x*samount16)/ohlc4 : v16x
vsf=v1+v2+v3+v4+v5+v6+v7+v8+v9+v10+v11+v12+v13+v14+v15+v16
///////////////////////////////////////////////////////////////////////////////////
///////////////////////FUTURES////////////////////////////////////////////////////
v1bx = (i_sym1b ? f_volume(i_sym1b_ticker) : 0)
v1b = fbase1=='Coin' ? v1bx*famount1 : fbase1=='USD' or fbase1=='Other' ? (v1bx*famount1)/ohlc4 : v1bx
v2bx = (i_sym2b ? f_volume(i_sym2b_ticker) : 0)
v2b = fbase2=='Coin' ? v2bx*famount2 : fbase2=='USD' or fbase2=='Other' ? (v2bx*famount2)/ohlc4 : v2bx
v3bx = (i_sym3b ? f_volume(i_sym3b_ticker) : 0)
v3b = fbase3=='Coin' ? v3bx*famount3 : fbase3=='USD' or fbase3=='Other' ? (v3bx*famount3)/ohlc4 : v3bx
v4bx =(i_sym4b ? f_volume(i_sym4b_ticker) : 0) //CME NORMAL (each contract reported equals 5btc)
v4b = fbase4=='Coin' ? v4bx*famount4 : fbase4=='USD' or fbase4=='Other' ? (v4bx*famount4)/ohlc4 : v4bx
v5bx = (i_sym5b ? f_volume(i_sym5b_ticker) : 0)//CME NORMAL (each contract reported equals 5btc)
v5b = fbase5=='Coin' ? v5bx*famount5 : fbase5=='USD' or fbase5=='Other' ? (v5bx*famount5)/ohlc4 : v5bx
v6bx = (i_sym6b ? f_volume(i_sym6b_ticker) : 0)//CME mini (each contract reported equals 0.60btc)
v6b = fbase6=='Coin' ? v6bx*famount6 : fbase6=='USD' or fbase6=='Other' ? (v6bx*famount6)/ohlc4 : v6bx
v7bx = (i_sym7b ? f_volume(i_sym7b_ticker) : 0)//CME mini (each contract reported equals 0.7btc)
v7b = fbase7=='Coin' ? v7bx*famount7 : fbase7=='USD' or fbase7=='Other' ? (v7bx*famount7)/ohlc4 : v7bx
v8bx = (i_sym8b ? f_volume(i_sym8b_ticker) : 0)// PHEMEX reported in usd
v8b = fbase8=='Coin' ? v8bx*famount8 : fbase8=='USD' or fbase8=='Other' ? (v8bx*famount8)/ohlc4 : v8bx
v9bx = (i_sym9b ? f_volume(i_sym9b_ticker) : 0)// OKEX reported in 900xBTC, meaning every 900 contracts is only one
v9b = fbase9=='Coin' ? v9bx*famount9 : fbase9=='USD' or fbase9=='Other' ? (v9bx*famount9)/ohlc4 : v9bx
v10bx = (i_sym10b ? f_volume(i_sym10b_ticker) : 0)// BITMEX REPORTED IN 1 MILLION BTC, MEANING EACH MILLION CONTRACTS ON TV REPRESENT 1 BTC
v10b = fbase10=='Coin' ? v1bx*famount10 : fbase10=='USD' or fbase10=='Other' ? (v10bx*famount10)/ohlc4 : v10bx
v11bx = (i_sym11b ? f_volume(i_sym11b_ticker) : 0)// BITGET REPORTED IN USD - TURNED OFF BECAUSE DOESNT PROVIDE REAL TIME DATA
v11b = fbase11=='Coin' ? v11bx*famount11 : fbase11=='USD' or fbase11=='Other' ? (v11bx*famount11)/ohlc4 : v11bx
v12bx = (i_sym12b ? f_volume(i_sym12b_ticker) : 0)
v12b = fbase12=='Coin' ? v12bx*famount12 : fbase12=='USD' or fbase12=='Other' ? (v12bx*famount12)/ohlc4 : v12bx
vff=v1b+v2b+v3b+v4b+v5b+v6b+v7b+v8b+v9b+v10b+v11b+v12b
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////PERPS///////////////////////////////////////////////////////////
v1cx = (i_sym1c ? f_volume(i_sym1c_ticker) : 0)//BINANCE REPORTED IN BLOCKS OF 100 USD, MEANING EACH CONTRACT REPORTED IS EQUAL TO 100 USD
v1c = pbase1=='Coin' ? v1cx*pamount1 : pbase1=='USD' or pbase1=='Other' ? (v1cx*pamount1)/ohlc4 : v1cx
v2cx = (i_sym2c ? f_volume(i_sym2c_ticker) : 0)//OKEX REPORTED IN BLOCKS OF 100 USD, MEANING EACH CONTRACT REPORTED IS EQUAL TO 100 USD
v2c = pbase2=='Coin' ? v2cx*pamount2 : pbase2=='USD' or pbase2=='Other' ? (v2cx*pamount2)/ohlc4 : v2cx
v3cx = (i_sym3c ? f_volume(i_sym3c_ticker) : 0)// HUOBI REPORTED IN BTC
v3c = pbase3=='Coin' ? v3cx*pamount3 : pbase3=='USD' or pbase3=='Other' ? (v3cx*pamount3)/ohlc4 : v3cx
v4cx =(i_sym4c ? f_volume(i_sym4c_ticker) : 0)// PHEMEX REPORTED IN USD
v4c = pbase4=='Coin' ? v4cx*pamount4 : pbase4=='USD' or pbase4=='Other' ? (v4cx*pamount4)/ohlc4 : v4cx
v5cx = (i_sym5c ? f_volume(i_sym5c_ticker) : 0)// FTX REPORTED IN USD
v5c = pbase5=='Coin' ? v5cx*pamount5 : pbase5=='USD' or pbase5=='Other' ? (v5cx*pamount5)/ohlc4 : v5cx
v6cx = (i_sym6c ? f_volume(i_sym6c_ticker) : 0)//BYBIT REPORTED IN USD
v6c = pbase6=='Coin' ? v6cx*pamount6 : pbase6=='USD' or pbase6=='Other' ? (v6cx*pamount6)/ohlc4 : v6cx
v7cx = (i_sym7c ? f_volume(i_sym7c_ticker) : 0)//DERIBIT REPORTED IN USD
v7c = pbase7=='Coin' ? v7cx*pamount7 : pbase7=='USD' or pbase7=='Other' ? (v7cx*pamount7)/ohlc4 : v7cx
v8cx = (i_sym8c ? f_volume(i_sym8c_ticker) : 0)//BITMEX REPORTED IN USD
v8c = pbase8=='Coin' ? v8cx*pamount8 : pbase8=='USD' or pbase8=='Other' ? (v8cx*pamount8)/ohlc4 : v8cx
vpf=v1c+v2c+v3c+v4c+v5c+v6c+v7c+v8c
//////////////////////////////////////////////////////////////////////////////////////
////////////////////ALL DERIV VOLUME//////////////////////////////////////////////////////////////////
alldvol = vff + vpf
/////////////////////////////////////////////////////////////////////////////////////////
////////////////////ALL VOLUME//////////////////////////////////////////////////////////////////
allvol = vsf + vff + vpf
/////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////FINAL AGGREGATION SELECTION/////////////////////////////////////////
if markettype == 'Spot'
finvol := vsf
finvol
else if markettype == 'Futures'
finvol := vff
finvol
else if markettype == 'Perp'
finvol := vpf
finvol
else if markettype == 'Derivatives F+P'
finvol := alldvol
finvol
else if markettype == 'Spot+Derivs'
finvol := allvol
finvol
/////////////////////////////////////////////////////////////////////////////////////////////////
else if aggr==false
finvol := volume
//////////// RESET BASIS ///////////////////////////////////////////////////////
ftf = (time(timeframe.period) == time(brestf)) ? true : false
timo = time(brestf)
var float minus = 0
var bool sw = false
////////////////////////////////////////////////////////////////////////////////////
///////////////////OBV NORMALIZATION////////////////////////////////////////////////
var float csf = na
////////////////FUNCTION////////////////////////////////////////////////////////////
chn(_ticker) =>
c = request.security(_ticker, timeframe.period, close)
ta.cum(math.sign(ta.change(c)) * finvol)
if aggr==true
//////////////////////////SYMBOL TA CHANGE AND AGGREGATION FOR NORMALIZING OBV IN ALL PAIRS////////////////////////
//////////////////SPOT////////////////////////////////////////////////////////////////////////////////////////////
c1 = chn(i_sym1_ticker)
c2 = chn(i_sym3_ticker)
c3 = chn(i_sym6_ticker)
c4 = chn(i_sym1b_ticker)
csf := (c1+c2+c3+c4)/4
else if aggr==false
csf:=ta.cum(math.sign(ta.change(close)) * finvol)
///////////////////////////////////////////////////////////////////////////////////////////////
/////////////////CALCULATE OBV//////////////////////
var float obv = na
var float obv1 = na
var float obv2 = na
var cumVol = 0.
cumVol += nz(finvol)
if barstate.islast and cumVol == 0
runtime.error("No volume is provided by the data vendor.")
src = close
obv := (csf)
obv2 := (csf - minus)
if ftf and bres
minus := obv[0]
sw := true
if bres == true
if sw==false
obv1 := obv2
else if sw==true
obv2 := 0
obv1 := obv2
sw := false
else if bres == false
obv1 := obv
plotshape(bres and ftf ? 0 : na ,title='Reset Marker', style=shape.xcross, location=location.absolute, color=color.black, size=size.small)
//////////////////////////////////////////////////PLOTTING////////////////////////////////////////////
float ctl = na
float o = na
float h = na
float l = na
float c = na
if linestyle == 'Candle'
o := obv1[1]
h := math.max(obv1, obv1[1])
l := math.min(obv1, obv1[1])
c := obv1
ctl
else
ctl := obv1
ctl
/////////////PLOT OBV LINE///////////////////////
obvp = plot(ctl, color=color.blue, title="OnBalanceVolume")
///////////////////////CANDLES//////////////////////////////////////
float haclose = na
float haopen = na
float hahigh = na
float halow = na
haclose := (o + h + l + c) / 4
haopen := na(haopen[1]) ? (o + c) / 2 : (haopen[1] + haclose[1]) / 2
hahigh := math.max(h, math.max(haopen, haclose))
halow := math.min(l, math.min(haopen, haclose))
c_ = hacandle ? haclose : c
o_ = hacandle ? haopen : o
h_ = hacandle ? hahigh : h
l_ = hacandle ? halow : l
ohlcr = (o_ + h_ + l_ + c_)/4
///////////////////PLOT CANDLES/////////////////////////////
plotcandle(o_, h_, l_, c_, title='OBV Candles', color=o_ <= c_ ? colorup : colordown, bordercolor=o_ <= c_ ? bcolup : bcoldown, wickcolor=o_ <= c_ ? bcolup : bcoldown)
///////////////////////////////////////////////////////////////////////////////////
////////////////////PLOT MAs SWITCH ALTERNATIVE////////////////////////////////
masrc = linestyle=='Candle' ? ohlcr : ctl
ma(source, length, type) =>
switch type
"SMA" => 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)
maline = ma(masrc, malen, matype)
/////////////////////////////////////
maplot = plot(addma ? maline : na, title='Moving Average', color=color.purple)
////////MA FILL
var fillcol = color.green
finp = plot( linestyle=='Candle' ? ohlcr : ctl, color=color.new(color.black,100), editable=false)
if linestyle=='Line' and (maline > ctl)
fillcol := color.new(color.red, 65)
else if linestyle=='Line' and (maline < ctl)
fillcol := color.new(color.green, 65)
else if linestyle=='Candle' and (maline > ohlcr)
fillcol := color.new(color.red, 65)
else if linestyle=='Candle' and (maline < ohlcr)
fillcol := color.new(color.green, 65)
fill(finp , maplot , title='Moving Average Fill', color=fillcol, fillgaps=true)
/////// FILL WHEN RESET BASIS//////////////////////////
hl = plot(bres ? 0 : na , color=color.new(color.black,100), editable=false)
var filcol = color.blue
if ctl or ohlcr > 0
filcol := color.new(color.green, 90)
else if ctl or ohlcr < 0
filcol := color.new(color.red, 90)
fill(finp, hl, title='Zero Line Fill', color=filcol, fillgaps=true )
|
IsPullbackPivotRetested experiment | https://www.tradingview.com/script/eFPeZVgK-IsPullbackPivotRetested-experiment/ | brettosm8 | https://www.tradingview.com/u/brettosm8/ | 17 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © brettosm8
//@version=5
indicator("My script")
// Calculate keltner channel boundaries
length = input.int(20, minval=1)
mult = input(2.0, "Multiplier")
src = input(close, title="Source")
exp = input(true, "Use Exponential MA")
BandsStyle = input.string("Average True Range", options = ["Average True Range", "True Range", "Range"], title="Bands Style")
atrlength = input(14, "ATR Length")
esma(source, length)=>
s = ta.sma(source, length)
e = ta.ema(source, length)
exp ? e : s
ma = esma(src, length)
rangema = BandsStyle == "True Range" ? ta.tr(true) : BandsStyle == "Average True Range" ? ta.atr(atrlength) : ta.rma(high - low, length)
upper = ma + rangema * mult
lower = ma - rangema * mult
var float pivot_high = 0
var float pivot_low = 0
var bool isPivotHighAssigned = false
var bool isPivotLowAssigned = false
var bool isLongPullback = false
var bool isShortPullback = false
var int pullback_resolved_count = 0
var int pullback_failed_count = 0
var int pullback_sum = 0
isPivotHighIdentified = high[1] > upper and high < high[1]
if isPivotHighIdentified and isPivotHighAssigned == false
pivot_high := high[1]
isPivotHighAssigned := true
isLongPullback := true
if isLongPullback and high > pivot_high
pullback_resolved_count += 1
pullback_sum += 1
isLongPullback := false
if isLongPullback and low < lower
pullback_failed_count += 1
pullback_sum -= 1
isLongPullback := false
if isPivotHighIdentified == false
isPivotHighAssigned := false
//------------------------------------------------------------------------------
isPivotLowIdentified = low[1] < lower and low > low[1]
if isPivotLowIdentified and isPivotLowAssigned == false
pivot_low := low[1]
isPivotLowAssigned := true
isShortPullback := true
if isShortPullback and low < pivot_low
pullback_resolved_count += 1
pullback_sum += 1
isShortPullback := false
if isShortPullback and high > upper
pullback_failed_count += 1
pullback_sum -= 1
isShortPullback := false
if isPivotLowIdentified == false
isPivotLowAssigned := false
plot(pullback_resolved_count, color = color.blue)
plot(pullback_failed_count, color = color.red)
plot(pullback_sum, color = color.black)
|
Cosmic Pi Troll Cycle | https://www.tradingview.com/script/5k5WA5ac-Cosmic-Pi-Troll-Cycle/ | Trollplogen | https://www.tradingview.com/u/Trollplogen/ | 27 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © cosmic_indicators / Trollplogen
//@version=4
study("Cosmic Pi Troll Cycle", overlay = true)
// --------------------------------------------------------------------------------
// Variables
// --------------------------------------------------------------------------------
// Input
asset = input(title = "Asset Model", type=input.string, defval="BTC", options=["BTC","ETH","LINK","Custom"], group = "Model and Indicator")
indicatorType = input(title = "Type of Indicator", type=input.string, defval="Top", options=["Top","Bottom"], group = "Model and Indicator")
tresh = input(title = "Width of SMA Band [%]", type = input.float, defval = 10, group = "Warning Threshold")
show_fill = input(title = "Show SMA Band", type = input.bool, defval = true, group = "View")
show_warning = input(title = "Show Warning", type = input.bool, defval = true, group = "View")
CustomNumerator_len = input(title = "Long SMA Length", type = input.integer, defval = 280, group = "Custom Settings")
CustomDenominator_len = input(title = "Short SMA Length", type = input.integer, defval = 138, group = "Custom Settings")
CustomMult = input(title = "Scaling", type = input.float, defval = 1.8, group = "Custom Settings")
numerator_len = 200
denominator_len = 100
mult = 2.0
show_top_markers = true
show_btm_markers = false
// Troll SMAs
if (asset == "BTC")
numerator_len := 355
denominator_len := 113
if (indicatorType == "Top")
mult := 2
else if (indicatorType == "Bottom")
mult := 0.7
else if (asset == "ETH")
numerator_len := 455
denominator_len := 183
if (indicatorType == "Top")
mult := 1.95
else if (indicatorType == "Bottom")
mult := 0.6
else if (asset == "LINK")
numerator_len := 271
denominator_len := 93
if (indicatorType == "Top")
mult := 1.6
else if (indicatorType == "Bottom")
mult := 0.75
else if (asset == "Custom")
numerator_len := CustomNumerator_len
denominator_len := CustomDenominator_len
mult := CustomMult
// Colors
teal_rgb = #005843
teal_0 = color.new(teal_rgb, 0)
teal_33 = color.new(teal_rgb, 33)
violet_rgb = #aa47bc
violet_0 = color.new(violet_rgb, 0)
violet_33 = color.new(violet_rgb, 33)
red_rgb = #ff5252
red_0 = color.new(red_rgb, 0)
transparent = color.new(color.black, 100)
// --------------------------------------------------------------------------------
// Logic
// --------------------------------------------------------------------------------
numerator = sma(close, numerator_len) * mult
denominator = sma(close, denominator_len)
basis = avg(denominator, numerator)
TopWarningLine = denominator * (100+tresh)/100
BottomWarningLine = numerator * (100+tresh)/100
// --------------------------------------------------------------------------------
// View
// --------------------------------------------------------------------------------
numerator_plot = plot(numerator, display = display.none, title = "Numerator")
denominator_plot = plot(denominator, display = display.none, title = "Denominator")
basis_plot = plot(basis, display = display.none, title = "Basis")
//TopWarning_plot = plot(TopWarningLine, title = "Top Warning Buffer", color = red_0)
//BottomWarning_plot = plot(BottomWarningLine, title = "Bottom Warning Buffer", color = red_0)
fill(numerator_plot,
basis_plot,
color = show_fill ? teal_33 : transparent,
title = "Cosmic Pi Troll Cycle Numerator Fill")
fill(denominator_plot, basis_plot,
color = show_fill ? violet_33 : transparent,
title = "Cosmic Pi Troll Cycle Denominator Fill")
if (indicatorType == "Top")
show_top_markers := true
show_btm_markers := false
else if (indicatorType == "Bottom")
show_top_markers := false
show_btm_markers := true
plotshape(show_warning and show_top_markers and crossunder(numerator, TopWarningLine),
color = color.yellow,
style = shape.triangledown,
location = location.abovebar,
size = size.normal,
title = "Cosmic Pi Troll Cycle Top Warning Marker")
plotshape(show_warning and show_btm_markers and crossover(BottomWarningLine, denominator),
color = color.yellow,
style = shape.triangledown,
location = location.abovebar,
size = size.normal,
title = "Cosmic Pi Troll Cycle Bottom Warning Marker")
plotshape(show_top_markers and crossunder(numerator, denominator),
color = teal_0,
style = shape.circle,
location = location.abovebar,
size = size.normal,
title = "Cosmic Pi Troll Cycle Primary Top Marker")
plotshape(show_btm_markers and crossover(numerator, denominator),
color = violet_0,
style = shape.circle,
location = location.belowbar,
size = size.normal,
title = "Cosmic Pi Troll Cycle Primary Bottom Marker")
|
Treasury Yield Spread 10y-2y [TXMC] | https://www.tradingview.com/script/0thtJurP-Treasury-Yield-Spread-10y-2y-TXMC/ | TXMC | https://www.tradingview.com/u/TXMC/ | 120 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @TXMC
//@version=5
indicator(title="Treasury Yield Spread 10y-2y [TXMC]", overlay=false, precision=2)
// Yield curve
curve = request.security("FRED:T10Y2Y", timeframe.period, close) // 10yr minus 2yr Treasury yield
// Inversion band color -- if below zero, show color
plotColor = curve < 0 ? color.new(#00a1e4,75) : na
// Plots
plot(curve, color=#133336, style=plot.style_line, linewidth=1, trackprice=true, title="10y-2y")
bgcolor(plotColor)
hline(0, linewidth=1, color=#fe4a49, title='Zero') |
Simple Calculator | https://www.tradingview.com/script/1xsz5usl-Simple-Calculator/ | Cambo_Guru | https://www.tradingview.com/u/Cambo_Guru/ | 25 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Cambo_Guru
//@version=5
indicator("Calculator", overlay = true)
//Inputs
Num1 = input.float(defval = 0, title = "Input 1", group = "Calculate:")
//Operators
operator = input.string(defval = "+", title = "Operators", options=["+","-","x","÷","x^y"], group = "Calculate:")
//Inputs
Num2 = input.float(defval = 0, title = "Input 2", group = "Calculate:")
float cal = na
string result = na
if operator == "+"
cal := Num1 + Num2
result := (Num1 >= 0 ? str.tostring(Num1) : ("(" + str.tostring(Num1) + ")")) + " + " + (Num2 >= 0 ? str.tostring(Num2) : ("(" + str.tostring(Num2) + ")")) + " = " + str.tostring(cal)
else if operator == "-"
cal := Num1 - Num2
result := (Num1 >= 0 ? str.tostring(Num1) : ("(" + str.tostring(Num1) + ")")) + " - " + (Num2 >= 0 ? str.tostring(Num2) : ("(" + str.tostring(Num2) + ")")) + " = " + str.tostring(cal)
else if operator == "x"
cal := Num1 * Num2
result := (Num1 >= 0 ? str.tostring(Num1) : ("(" + str.tostring(Num1) + ")")) + " x " + (Num2 >= 0 ? str.tostring(Num2) : ("(" + str.tostring(Num2) + ")")) + " = " + str.tostring(cal)
else if operator == "÷"
cal := Num1 / Num2
result := (Num1 >= 0 ? str.tostring(Num1) : ("(" + str.tostring(Num1) + ")")) + " ÷ " + (Num2 >= 0 ? str.tostring(Num2) : ("(" + str.tostring(Num2) + ")")) + " = " + str.tostring(cal)
else if operator == "x^y"
cal := math.pow(Num1,Num2)
result := (Num1 >= 0 ? str.tostring(Num1) : ("(" + str.tostring(Num1) + ")")) + "^(" + str.tostring(Num2) + ") = " + str.tostring(cal)
else
result := "Error"
//Table
//Format
tblPos = input.string(title="Position on Chart", defval="Middle Bottom", options=["Top Left", "Top Right", "Bottom Left", "Bottom Right", "Middle Left", "Middle Right", "Middle Bottom" ], group = "Table Customization")
tblposition = tblPos == "Top Left" ? position.top_left : tblPos == "Top Right" ? position.top_right : tblPos == "Bottom Left" ? position.bottom_left : tblPos == "Bottom Right" ? position.bottom_right : tblPos == "Middle Left" ? position.middle_left : tblPos == "Middle Right" ? position.middle_right : position.bottom_center
text_halign = input.string(defval = "Center", title="Horizontal Alignment", options=["Left", "Center", "Right"], group = "Table Customization")
text_halign_pos = text_halign == "Left" ? text.align_left : text_halign == "Center" ? text.align_center : text.align_right
text_valign = input.string(defval = "Center", title="Vertical Alignment", options=["Top", "Center", "Bottom"], group = "Table Customization")
text_valign_pos = text_valign == "Top" ? text.align_top : text_valign == "Center" ? text.align_center : text.align_bottom
text_size = input.string(defval = "Auto", title="Text Size", options=["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], group = "Table Customization")
text_size_op = text_size == "Auto" ? size.auto : text_size == "Tiny" ? size.tiny : text_size == "Small" ? size.small : text_size == "Normal" ? size.normal : text_size == "Large" ? size.large : size.huge
//Dimensions
border_width = input.int(defval=1, title="Border Width", group = "Dimensions")
frame_width = input.int(defval=4, title="Frame Width", group = "Dimensions")
table_width = input.int(defval=20, title="Cell Width", group = "Dimensions")
table_height = input.int(defval=5, title="Cell Height", group = "Dimensions")
//Colors
tblBorderColor = input.color(title="Border Color", defval=#636363, group = "Table Styles")
celllBgColor = input.color(title="Background Color", defval=#ffffff, group = "Table Styles")
cellTextColor = input.color(title="Text Color", defval=#000000, group = "Table Styles")
var resultsTable = table.new(position = tblposition, columns = 1, rows = 1, bgcolor = #ffffff, border_width = border_width,frame_color = tblBorderColor, frame_width = frame_width)
table.clear(resultsTable, 0, 0)
table.cell(resultsTable, column=0, row=0, width = table_width, height = table_height, text_size = text_size_op, text=result, text_color=cellTextColor, text_halign=text_halign_pos, text_valign=text_valign_pos, bgcolor=celllBgColor)
|
Botvenko Script | https://www.tradingview.com/script/h2hYTI5O-botvenko-script/ | boftei | https://www.tradingview.com/u/boftei/ | 10 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © boftei
//@version=5
indicator("Botvenko Script", shorttitle="BS", precision=4)
nn = input(60, "Histogram Period")
candles = input(60, "Candle Dominance Сhart Period")
float x = 0
float z = 0
float k = 0
y = math.log(close[0]) - math.log(close[nn])
if y>0
x := y
else
k := y
counter_of_candles(kk) =>
float total = 0
int cutter = 10
while kk/10>10
cutter*=10
for i = 0 to kk
if close[i] - close[i+1] > 0
total += 1
else
total -= 1
total/cutter
plot(y > 0 ? x: 0, color = color.green, linewidth = 4)
plot(y <= 0 ? k: 0, color = color.maroon, linewidth = 4)
plot(y, color = color.yellow, linewidth = 1, style = plot.style_histogram)
plot(counter_of_candles(candles), color = color.navy, linewidth = 3)
hline(0, title='zero', color=color.white, linestyle=hline.style_dotted, linewidth=2)
|
ADA Gravity Oscillator | https://www.tradingview.com/script/EIiSM7z8-ADA-Gravity-Oscillator/ | nickolassteel | https://www.tradingview.com/u/nickolassteel/ | 20 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © nickolassteel
//@version=5
indicator(title='ADA Gravity Oscillator', format=format.price, precision=1)
//Variables
ADA = request.security('KRAKEN:ADAUSD', 'W', close)
//COG
ADAcog = ((ta.cog(ADA, 20))+ 13.1) * (10 / 7.3)
fx = math.pow(math.e, -1 * ((bar_index - 100)* 0.01)) + 9.5
ADAadj = (ADAcog / fx) * 10
//Graph
c_grad = color.from_gradient(ADAadj, 0, 10, color.rgb(0, 500, 0, 25), color.rgb(500, 0, 0, 0))
plot(ADAadj, linewidth=2, color=c_grad)
hline(5)
|
4C Inside/Outside Bar | https://www.tradingview.com/script/jzDXf7U7-4C-Inside-Outside-Bar/ | FourC | https://www.tradingview.com/u/FourC/ | 131 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © FourC
//@version=5
//Adapted from Custom Candle color Inside/Outside candles, Highwave, Star Patt. by Craig_Stine
indicator("4C Inside/Outside Bar", "4C I/O Bar", overlay=true)
showdbibar = input.bool(true, 'Show Double Inside Bar Signal')
showdbobar = input.bool(false, 'Show Double Outside Bar Signal')
showoibar = input.bool(false, 'Show Inside + Outside Bar Signal')
showiobar = input.bool(false, 'Show Outside + Inside Bar Signal')
showiolabels = input.bool(false, 'Show I/O Bar Labels')
//Bar Signals
ibar = high <= high[1] and low >= low[1]
obar = high > high[1] and low < low[1]
dbibar = high <= high[1] and low >= low[1] and high[1] <= high[2] and low[1] >= low[2]
dbobar = high > high[1] and low < low[1] and high[1] > high[2] and low[1] < low[2]
//Inside Bar
barcolor(ibar ? color.blue : na, title='Inside Candle')
plotchar(ibar and showiolabels, title='Inside Bar', location=location.belowbar, color=color.new(color.blue, 0), size=size.tiny, text='IB')
//Outside Bar
barcolor(obar ? color.fuchsia : na, title='Outside Bar')
plotchar(obar and showiolabels, title='Outside Bar', location=location.belowbar, color=color.new(color.fuchsia, 0), size=size.tiny, text='OB')
//Double Inside Bar Signal
bgcolor(showdbibar and dbibar ? color.new(color.blue, 50) : na, title = 'Double Inside Bar')
plotchar(dbibar and showiolabels, title='Double Inside Bar', location=location.abovebar, color=color.new(color.white, 0), size=size.tiny, text='DIB')
//Double Outside Bar Signal
bgcolor(showdbobar and dbobar ? color.new(color.fuchsia, 50) : na, title = 'Double Outside Bar')
plotchar(dbobar and showiolabels, title='Double Outside Bar', location=location.abovebar, color=color.new(color.white, 0), size=size.tiny, text='DOB')
//Inside Bar + Outside Bar Signal
bgcolor(showoibar and obar and ibar[1] ? color.new(color.aqua, 50) : na, title = 'Inside Bar + Outside Bar')
plotchar(obar and ibar[1] and showiolabels, title='Inside + Outside Bar', location=location.abovebar, color=color.new(color.white, 0), size=size.tiny, text='IB+OB')
//Outside Bar + Inside Bar Signal
bgcolor(showiobar and ibar and obar[1] ? color.new(color.orange, 50) : na, title = 'Outside Bar + Inside Bar')
plotchar(ibar and obar[1] and showiolabels, title='Outside + Inside Bar', location=location.abovebar, color=color.new(color.white, 0), size=size.tiny, text='OB+IB') |
Fusion: Big Arty Candles | https://www.tradingview.com/script/PBTUNXNq-Fusion-Big-Arty-Candles/ | Koalems | https://www.tradingview.com/u/Koalems/ | 28 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Koalems
// @version=5
indicator(
shorttitle = "Fusion: BAC",
title = "Fusion: Big Arty Candles",
overlay = true
)
maxLabels = 500
Group6300 = '6300 Big Arty Candles - Show'
stgyBACShowOnCandle = input.bool(true, group=Group6300, title='Show on candle')
stgyBACShowLabel = input.bool(true, group=Group6300, title='Show label')
Group6320 = '6320 Big Arty Candles - Source'
stgyBACUseHL = input.bool(true, group=Group6320, title='High/Low')
stgyBACUseOC = input.bool(false, group=Group6320, title='Open/Close')
Group6330 = '6330 Big Arty Candles - High/Low'
stgyBACToAverageHL = input.int(10, group=Group6330, minval=2, title='Number of bars to average')
stgyBACRelativeSizeHL = input.float(3.8, group=Group6330, minval=0, step=0.05, title='Relative size of BAC')
stgyBACColorHL = input.color(color.new(#f57c00, 50), group=Group6330, title='Color')
Group6340 = '6340 Big Arty Candles - Open/Close'
stgyBACToAverageOC = input.int(10, group=Group6340, minval=2, title='Number of bars to average')
stgyBACRelativeSizeOC = input.float(3.8, group=Group6340, minval=0, step=0.05, title='Relative size of BAC')
stgyBACColorOC = input.color(color.new(#7e57c2, 50), group=Group6340, title='Color')
stgyBACAvgHigh = ta.sma(high, stgyBACToAverageHL)
stgyBACAvgLow = ta.sma(low, stgyBACToAverageHL)
bool stgyBAC = na
bool stgyBACHL = na
bool stgyBACOC = na
if stgyBACUseHL
stgyBACHL := high - low >= (stgyBACAvgHigh - stgyBACAvgLow) * stgyBACRelativeSizeHL
if stgyBACUseOC
avg = ta.sma(open > close ? open - close : close - open, stgyBACToAverageOC)
stgyBACOC := stgyBAC or math.abs(open - close) >= avg * stgyBACRelativeSizeOC
//stgyBAC = stgyBACHL or stgyBACOC
barcolor(
stgyBACShowOnCandle and stgyBACHL ? stgyBACColorHL : na,
title='Big arty candle: High/Low')
barcolor(
stgyBACShowOnCandle and stgyBACOC ? stgyBACColorOC : na,
title='Big arty candle: Open/Close')
plotshape(
stgyBACShowLabel and stgyBACHL,
style = shape.labeldown,
location = location.top,
color = stgyBACColorHL,
text = 'BAC',
textcolor = color.new(color.white, 0),
size = size.small,
title = 'Big arty candle: High/Low')
plotshape(
stgyBACShowLabel and stgyBACOC,
style = shape.labeldown,
location = location.top,
color = stgyBACColorOC,
text = 'BAC',
textcolor = color.new(color.white, 0),
size = size.small,
title = 'Big arty candle: High/Low')
|
Bogdan Ciocoiu - Coordinator | https://www.tradingview.com/script/OlJhJjEt-Bogdan-Ciocoiu-Coordinator/ | BogdanCiocoiu | https://www.tradingview.com/u/BogdanCiocoiu/ | 85 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BogdanCiocoiu
//@version=5
indicator("Bogdan Ciocoiu - Coordinator", shorttitle="BC - Coordinator", format=format.price, precision=2, timeframe="", timeframe_gaps=true, explicit_plot_zorder=true)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// Overall
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_All_line_color = input(color.new(color.white, 70), "", inline="Overall", group="Overall")
_All_line_0 = input(80, "Separator 1", inline="Overall", group="Overall")
_All_line_1 = input(50, "2", inline="Overall", group="Overall")
_All_line_2 = input(20, "3", inline="Overall", group="Overall")
_All_layer_0 = hline(_All_line_0, "", color=(_All_line_0>0) ? _All_line_color : na, linestyle=hline.style_dashed)
_All_layer_1 = hline(_All_line_1, "", color=(_All_line_1>0) ? _All_line_color : na, linestyle=hline.style_dashed)
_All_layer_2 = hline(_All_line_2, "", color=(_All_line_2>0) ? _All_line_color : na, linestyle=hline.style_dashed)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// RSI Clouds
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_RC1_enabled = input(true, "", inline="Slow RSI suite", group="Slow RSI suite")
_RC2_enabled = input(true, "", inline="Fast RSI suite", group="Fast RSI suite")
_RC1_col_1 = input(color.gray, "", inline="Slow RSI suite", group="Slow RSI suite")
_RC1_col_2 = input(color.gray, "", inline="Slow RSI suite", group="Slow RSI suite")
_RC1_col_3 = input(color.gray, "", inline="Slow RSI suite", group="Slow RSI suite")
_RC2_col_1 = input(color.green, "", inline="Fast RSI suite", group="Fast RSI suite")
_RC2_col_2 = input(color.red, "", inline="Fast RSI suite", group="Fast RSI suite")
_RC2_col_3 = input(color.yellow, "", inline="Fast RSI suite", group="Fast RSI suite")
_RC1_col_f = input(30, "Col full", inline="Slow RSI suite", group="Slow RSI suite")
_RC1_col_p = input(30, "Part", inline="Slow RSI suite", group="Slow RSI suite")
_RC2_col_f = input(0, "Col full", inline="Fast RSI suite", group="Fast RSI suite")
_RC2_col_p = input(0, "Part", inline="Fast RSI suite", group="Fast RSI suite")
_RC1_input_1 = input(60, "Fast", inline="Slow RSI suite", group="Slow RSI suite")
_RC1_input_2 = input(10, "Slow", inline="Slow RSI suite", group="Slow RSI suite") //var.: 8
_RC1_input_3 = input(60, "Imp", inline="Slow RSI suite", group="Slow RSI suite")
_RC2_input_1 = input(6, "Fast", inline="Fast RSI suite", group="Fast RSI suite")
_RC2_input_2 = input(4, "Slow", inline="Fast RSI suite", group="Fast RSI suite")
_RC2_input_3 = input(10, "Imp", inline="Fast RSI suite", group="Fast RSI suite")
_RC1_ma_enable = input(true, "", inline="Slow RSI MA", group="Slow RSI MA")
_RC1_ma_col = input(color.white, "Col", inline="Slow RSI MA", group="Slow RSI MA")
_RC1_ma_type = input.string("SMA", title="", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], inline="Slow RSI MA", group="Slow RSI MA")
_RC1_ma_len = input(30, "Len", inline="Slow RSI MA", group="Slow RSI MA")
_RC1_ma_width = input(2, "Wid", inline="Slow RSI MA", group="Slow RSI MA")
_RC2_ma_enable = input(true, "", inline="Fast RSI MA", group="Fast RSI MA")
_RC2_ma_col = input(color.yellow, "Col", inline="Fast RSI MA", group="Fast RSI MA")
_RC2_ma_type = input.string("SMA", title="", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], inline="Fast RSI MA", group="Fast RSI MA")
_RC2_ma_len = input(30, "Len", inline="Fast RSI MA", group="Fast RSI MA")
_RC2_ma_width = input(2, "Wid", inline="Fast RSI MA", group="Fast RSI MA")
_RC1_rsi_1 = ta.rsi(close, _RC1_input_1)
_RC1_rsi_2 = ta.rsi(close, _RC1_input_2)
_RC1_rsi_3 = ta.rsi(close, _RC1_input_3)
_RC2_rsi_1 = ta.rsi(close, _RC2_input_1)
_RC2_rsi_2 = ta.rsi(close, _RC2_input_2)
_RC2_rsi_3 = ta.rsi(close, _RC2_input_3)
_RC1_burst_down = (_RC1_rsi_3 > _RC1_rsi_1) and (_RC1_rsi_3 > _RC1_rsi_2)
_RC1_burst_up = (_RC1_rsi_3 < _RC1_rsi_1) and (_RC1_rsi_3 < _RC1_rsi_2)
_RC2_burst_down = (_RC2_rsi_3 > _RC2_rsi_1) and (_RC2_rsi_3 > _RC2_rsi_2)
_RC2_burst_up = (_RC2_rsi_3 < _RC2_rsi_1) and (_RC2_rsi_3 < _RC2_rsi_2)
_RC1_col_fin_1 = _RC1_burst_up ? color.new(_RC1_col_1, _RC1_col_f) : _RC1_burst_down ? color.new(_RC1_col_2, _RC1_col_f) : color.new(_RC1_col_3, _RC1_col_f)
_RC1_col_fin_2 = _RC1_rsi_2 > _RC1_rsi_1 ? color.new(_RC1_col_1, _RC1_col_p) : _RC1_rsi_2 < _RC1_rsi_1 ? color.new(_RC1_col_2, _RC1_col_p) : na
_RC2_col_fin_1 = _RC2_burst_up ? color.new(_RC2_col_1, _RC2_col_f) : _RC2_burst_down ? color.new(_RC2_col_2, _RC2_col_f) : color.new(_RC2_col_3, _RC2_col_f)
_RC2_col_fin_2 = _RC2_rsi_2 > _RC2_rsi_1 ? color.new(_RC2_col_1, _RC2_col_p) : _RC2_rsi_2 < _RC2_rsi_1 ? color.new(_RC2_col_2, _RC2_col_p) : na
_RC1_plot_1 = plot(_RC1_rsi_1, title="Fast", color=na)
_RC1_plot_2 = plot(_RC1_rsi_2, title="Slow", color=na)
_RC1_plot_3 = plot(_RC1_rsi_3, title="Impulse", color=na)
_RC2_plot_1 = plot(_RC2_rsi_1, title="Fast", color=na)
_RC2_plot_2 = plot(_RC2_rsi_2, title="Slow", color=na)
_RC2_plot_3 = plot(_RC2_rsi_3, title="Impulse", color=na)
fill(_RC1_plot_1, _RC1_plot_2, color=(_RC1_enabled) ? _RC1_col_fin_2 : na, fillgaps=false)
fill(_RC1_plot_1, _RC1_plot_3, color=(_RC1_enabled) ? _RC1_col_fin_1 : na, fillgaps=false)
fill(_RC2_plot_1, _RC2_plot_2, color=(_RC2_enabled) ? _RC2_col_fin_2 : na, fillgaps=false)
fill(_RC2_plot_1, _RC2_plot_3, color=(_RC2_enabled) ? _RC2_col_fin_1 : na, fillgaps=false)
_ma(_src, _len, _type) =>
switch _type
"SMA" => ta.sma(_src, _len)
"EMA" => ta.ema(_src, _len)
"WMA" => ta.wma(_src, _len)
"VWMA" => ta.vwma(_src, _len)
"SMMA" =>
_ma = ta.sma ( _src, _len )
_ma_final = 0.0
_ma_final := na ( _ma_final[1] ) ? _ma : ( _ma_final[1] * ( _len - 1 ) + _src ) / _len
_RC1_ma = _ma(_RC1_rsi_3, _RC1_ma_len, _RC1_ma_type)
_RC2_ma = _ma(_RC2_rsi_3, _RC2_ma_len, _RC2_ma_type)
plot(_RC1_ma, color=(_RC1_ma_enable and _RC1_ma_width>0) ? _RC1_ma_col : na, linewidth=_RC1_ma_width)
plot(_RC2_ma, color=(_RC2_ma_enable and _RC2_ma_width>0) ? _RC2_ma_col : na, linewidth=_RC2_ma_width)
plotshape(ta.crossover(math.min(_RC1_rsi_1, _RC1_rsi_2, _RC1_rsi_3), _RC1_ma) ? _RC1_rsi_3 : na, location=location.top, style=shape.circle, size=size.small, color=(_RC1_ma_enable) ? _RC1_ma_col : na)
plotshape(ta.crossunder(math.max(_RC1_rsi_1, _RC1_rsi_2, _RC1_rsi_3), _RC1_ma) ? _RC1_rsi_3 : na, location=location.bottom, style=shape.circle, size=size.small, color=(_RC1_ma_enable) ? _RC1_ma_col : na)
plotshape(ta.crossover(math.min(_RC2_rsi_1, _RC2_rsi_2, _RC2_rsi_3), _RC2_ma) ? _RC2_rsi_3 : na, location=location.top, style=shape.triangleup, size=size.tiny, color=(_RC2_ma_enable) ? _RC2_col_1 : na)
plotshape(ta.crossunder(math.max(_RC2_rsi_1, _RC2_rsi_2, _RC2_rsi_3), _RC2_ma) ? _RC2_rsi_3 : na, location=location.bottom, style=shape.triangledown, size=size.tiny, color=(_RC2_ma_enable) ? _RC2_col_2 : na)
|
Bogdan Ciocoiu - Code runner | https://www.tradingview.com/script/rbxERynO-Bogdan-Ciocoiu-Code-runner/ | BogdanCiocoiu | https://www.tradingview.com/u/BogdanCiocoiu/ | 23 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BogdanCiocoiu
//@version=5
indicator("Bogdan Ciocoiu - Code runner", shorttitle="BC - Code runner", format=format.price, precision=2, timeframe="", timeframe_gaps=true, explicit_plot_zorder=true)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// Overall
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_All_line_1 = input(true, "Median", inline="Overall", group="Overall")
_All_line_color = input(color.new(color.white, 70), "", inline="Overall", group="Overall")
_All_layer_1 = hline(0, "", color=(_All_line_1) ? _All_line_color : na, linestyle=hline.style_dashed)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// TSI
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_TSI_enable = input(true, "", inline="TSI", group="TSI")
_TSI_col_l = input(color.new(color.green, 50), "", inline="TSI", group="TSI")
_TSI_col_s = input(color.new(color.red, 50), "", inline="TSI", group="TSI")
_TSI_col_l_2 = input(color.new(color.green, 20), "", inline="TSI", group="TSI")
_TSI_col_s_2 = input(color.new(color.red, 20), "", inline="TSI", group="TSI")
_TSI_src = input(close, "", inline="TSI", group="TSI")
_TSI_width = input(0, title="Wid", inline="TSI", group="TSI")
_TSI_long_length = input(6, title="Lon", inline="TSI", group="TSI")
_TSI_short_length = input(13, title="Sho", inline="TSI", group="TSI")
_TSI_signal_length = input(4, title="Sig", inline="TSI", group="TSI")
_TSI_mom = ta.change(_TSI_src)
_TSI_numerator = ta.ema(ta.ema(_TSI_mom, _TSI_long_length), _TSI_short_length)
_TSI_denominator = ta.ema(ta.ema(math.abs(_TSI_mom), _TSI_long_length), _TSI_short_length)
_TSI_tsi = 100 * _TSI_numerator / _TSI_denominator
_TSI_signal = ta.ema(_TSI_tsi, _TSI_signal_length)
_TSI_trend_color = (_TSI_tsi > _TSI_signal) ? _TSI_col_l : _TSI_col_s
_TSI_tsi_plot = plot(_TSI_tsi, color=(_TSI_enable and _TSI_width>0) ? _TSI_trend_color : na, linewidth=_TSI_width)
_TSI_signal_plot = plot(_TSI_signal, color=(_TSI_enable and _TSI_width>0) ? _TSI_trend_color : na, linewidth=_TSI_width)
plot(40, title="TSI OB", color=_TSI_enable ? color.new(color.white, 0) : na, linewidth=1)
plot(-40, title="TSI OS", color=_TSI_enable ? color.new(color.white, 0) : na, linewidth=1)
fill(_TSI_tsi_plot, _TSI_signal_plot, color=(_TSI_enable) ? _TSI_trend_color : na)
plotshape(ta.crossover(_TSI_tsi, _TSI_signal) ? _TSI_tsi : na, location=location.absolute, style=shape.circle, size=size.tiny, color=(_TSI_enable) ? _TSI_col_l_2 : na)
plotshape(ta.crossunder(_TSI_tsi, _TSI_signal) ? _TSI_tsi : na, location=location.absolute, style=shape.circle, size=size.tiny, color=(_TSI_enable) ? _TSI_col_s_2 : na)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// Stochastic
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_Stoch_on = input(true, "", inline="Stoch", group="Stoch")
_Stoch_col_up = input(color.new(color.yellow, 50), "", inline="Stoch", group="Stoch")
_Stoch_col_down = input(color.new(color.blue, 50), "", inline="Stoch", group="Stoch")
_Stoch_col_up_2 = input(color.new(color.yellow, 20), "", inline="Stoch", group="Stoch")
_Stoch_col_down_2 = input(color.new(color.blue, 20), "", inline="Stoch", group="Stoch")
_Stoch_wid = input(0, "Wid", inline="Stoch", group="Stoch")
_Stoch_period_K = input(8, "K per", inline="Stoch", group="Stoch")
_Stoch_smooth_K = input(3, "K smo", inline="Stoch", group="Stoch")
_Stoch_period_D = input(5, "D per", inline="Stoch", group="Stoch")
_Stoch_factor = input(1, title="Fact (scale!)", group="Stoch", inline="Stoch")
_Stoch_factor_2 = input(-50, title="Fact 2 (scale!)", group="Stoch", inline="Stoch")
_Stoch_K = (ta.sma(ta.stoch(close, high, low, _Stoch_period_K), _Stoch_smooth_K))*_Stoch_factor+_Stoch_factor_2
_Stoch_D = (ta.sma(_Stoch_K, _Stoch_period_D))
_Stoch_K_plot = plot(_Stoch_K, title="Stoch K", color=(_Stoch_on and _Stoch_wid > 0) ? (_Stoch_K > _Stoch_D ? _Stoch_col_up : _Stoch_col_down ) : na, linewidth=_Stoch_wid)
_Stoch_D_plot = plot(_Stoch_D, title="Stoch D", color=(_Stoch_on and _Stoch_wid > 0) ? (_Stoch_K > _Stoch_D ? _Stoch_col_up : _Stoch_col_down ) : na, linewidth=_Stoch_wid)
plot(80+_Stoch_factor_2, title="Stoch OB", color=(_Stoch_on) ? color.new(color.white, 0) : na, linewidth=1)
plot(20+_Stoch_factor_2, title="Stoch OS", color=(_Stoch_on) ? color.new(color.white, 0) : na, linewidth=1)
fill(_Stoch_K_plot, _Stoch_D_plot, color=(_Stoch_on) ? (_Stoch_K > _Stoch_D ? _Stoch_col_up : _Stoch_col_down ) : na)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// MACD
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_MACD_enable = input(true, "", inline="MACD", group="MACD histogram")
_MACD_col = input(color.silver, "", inline="MACD", group="MACD histogram")
_MACD_src = input(close, "", inline="MACD", group="MACD histogram")
_MACD_width = input(2, title="Wid", inline="MACD", group="MACD histogram")
_MACD_factor = input(3, "Fact", inline="MACD", group="MACD histogram")
_MACD_fast_len = input(12, "Fast", inline="MACD", group="MACD histogram")
_MACD_slow_len = input(26, "Slow", inline="MACD", group="MACD histogram")
_MACD_sig_len = input(9, "Smo", inline="MACD", group="MACD histogram")
_MACD_sma_src = input.string("EMA", title="Oscillator MA", options=["SMA", "EMA"], inline="MACD", group="MACD histogram")
_MACD_sma_sig = input.string("EMA", title="Signal MA", options=["SMA", "EMA"], inline="MACD", group="MACD histogram")
_MACD_ma_f = _MACD_sma_src == "SMA" ? ta.sma(_MACD_src, _MACD_fast_len) : ta.ema(_MACD_src, _MACD_fast_len)
_MACD_ma_s = _MACD_sma_src == "SMA" ? ta.sma(_MACD_src, _MACD_slow_len) : ta.ema(_MACD_src, _MACD_slow_len)
_MACD_md = _MACD_ma_f - _MACD_ma_s
_MACD_sig = _MACD_sma_sig == "SMA" ? ta.sma(_MACD_md, _MACD_sig_len) : ta.ema(_MACD_md, _MACD_sig_len)
_MACD_his = _MACD_md - _MACD_sig
_MACD_his := _MACD_his * _MACD_factor
plot(_MACD_his, style=plot.style_line, color=(_MACD_enable and _MACD_width>0) ? _MACD_col : na, linewidth=_MACD_width)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// AO
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_AO_enable = input(true, "", inline="AO", group="AO")
_AO_col = input(color.orange, "", inline="AO", group="AO")
_AO_width = input(2, title="Wid", inline="AO", group="AO")
_AO_factor = input(0.8, "Fact", inline="AO", group="AO")
_AO_ao = ta.sma(hl2,5) - ta.sma(hl2,34)
_AO_ao := _AO_ao * _AO_factor
plot(_AO_ao, color=(_AO_enable and _AO_width>0) ? _AO_col : na, style=plot.style_line, linewidth=_AO_width)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// CCI
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_CCI_on = input(true, "", inline="CCI", group="CCI")
_CCI_col = input(color.blue, "", inline="CCI", group="CCI")
_CCI_width = input(2, "Wid", inline="CCI", group="CCI")
_CCI_factor = input(0.4, "Fact (scale!)", inline="CCI", group="CCI")
_CCI_factor_2 = input(-0, "Fact 2 (scale!)", inline="CCI", group="CCI")
_CCI_src = input(hlc3, "", inline="CCI", group="CCI")
_CCI_length = input(20, "Len", inline="CCI", group="CCI")
_CCI_ma = ta.sma(_CCI_src, _CCI_length)
_CCI_cci = (_CCI_src - _CCI_ma) / (0.015 * ta.dev(_CCI_src, _CCI_length))
_CCI_cci := _CCI_cci * _CCI_factor + _CCI_factor_2
plot(100*_CCI_factor + _CCI_factor_2, title="CCI OB", color=(_CCI_on and _CCI_width>0) ? color.new(_CCI_col, 0) : na, linewidth=1)
plot(_CCI_cci, "CCI", color=(_CCI_on and _CCI_width>0) ? _CCI_col : na, linewidth=_CCI_width)
plot(-100*_CCI_factor + _CCI_factor_2, title="CCI OS", color=(_CCI_on and _CCI_width>0) ? color.new(_CCI_col, 0) : na, linewidth=1)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// RSI
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_RSI_on=input(false, "", inline="RSI", group="RSI")
_RSI_col=input(color.fuchsia, "", inline="RSI", group="RSI")
_RSI_len=input(14, "", inline="RSI", group="RSI")
_RSI_src=input(close, "", inline="RSI", group="RSI")
_RSI_width=input(2, "Wid", inline="RSI", group="RSI")
_RSI_factor=input(1, "Fact (scale!)", inline="RSI", group="RSI")
_RSI_factor_2=input(-50, "Fact 2 (scale!)", inline="RSI", group="RSI")
_RSI_1=ta.rsi(_RSI_src, _RSI_len)*_RSI_factor+_RSI_factor_2
plot(70+_RSI_factor_2, title="RSI OB", color=(_RSI_on and _RSI_width>0) ? color.new(_RSI_col, 0) : na, linewidth=1)
plot(_RSI_1, color=(_RSI_on and _RSI_width>0) ? _RSI_col : na, linewidth=_RSI_width)
plot(30+_RSI_factor_2, title="RSI OS", color=(_RSI_on and _RSI_width>0) ? color.new(_RSI_col, 0) : na, linewidth=1)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// UO
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_UO_on = input(true, "", inline="UO", group="UO (7, 14, 28 for NQ or 4, 8, 16 or 10, 20, 40)")
_UO_color = input(color.aqua, "", inline="UO", group="UO (7, 14, 28 for NQ or 4, 8, 16 or 10, 20, 40)")
_UO_width = input(2, "Wid", inline="UO", group="UO (7, 14, 28 for NQ or 4, 8, 16 or 10, 20, 40)")
_UO_factor = input(1, "Fact (scale!)", inline="UO", group="UO (7, 14, 28 for NQ or 4, 8, 16 or 10, 20, 40)")
_UO_factor_2 = input(-50, title="Fact 2 (scale!)", inline="UO", group="UO (7, 14, 28 for NQ or 4, 8, 16 or 10, 20, 40)")
_UO_length_1 = input.int(7, "Len 1", inline="UO", group="UO (7, 14, 28 for NQ or 4, 8, 16 or 10, 20, 40)")
_UO_length_2 = input.int(14, "2", inline="UO", group="UO (7, 14, 28 for NQ or 4, 8, 16 or 10, 20, 40)")
_UO_length_3 = input.int(28, "3", inline="UO", group="UO (7, 14, 28 for NQ or 4, 8, 16 or 10, 20, 40)")
_UO_average(_UO_bp, _UO_tr, _UO_length) => math.sum(_UO_bp, _UO_length) / math.sum(_UO_tr, _UO_length)
_UO_high = math.max(high, close[1])
_UO_low = math.min(low, close[1])
_UO_bp = close - _UO_low
_UO_tr = _UO_high - _UO_low
_UO_avg7 = _UO_average(_UO_bp, _UO_tr, _UO_length_1)
_UO_avg14 = _UO_average(_UO_bp, _UO_tr, _UO_length_2)
_UO_avg28 = _UO_average(_UO_bp, _UO_tr, _UO_length_3)
_UO_out = (100 * (4*_UO_avg7 + 2*_UO_avg14 + _UO_avg28)/7) * _UO_factor + _UO_factor_2
plot(70+_UO_factor_2, title="UO OB", color=(_UO_on and _UO_width>0) ? color.new(_UO_color, 0) : na, linewidth=1)
plot(_UO_out, title="UO", color=(_UO_on and _UO_width>0) ? _UO_color : na, linewidth=_UO_width)
plot(30+_UO_factor_2, title="UO OS", color=(_UO_on and _UO_width>0) ? color.new(_UO_color, 0) : na, linewidth=1)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// MFI
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_MFI_on = input(true, title="", group="MFI", inline="MFI")
_MFI_color = input(color.maroon, title="", group="MFI", inline="MFI")
_MFI_width = input(2, title="Wid", group="MFI", inline="MFI")
_MFI_length = input(14, title="Len", group="MFI", inline="MFI")
_MFI_src = input(hlc3, title="", group="MFI", inline="MFI")
_MFI_factor = input(1, title="Fact (scale!)", group="MFI", inline="MFI")
_MFI_factor_2 = input(-50, title="Fact 2 (scale!)", group="MFI", inline="MFI")
_MFI_mf = ta.mfi(_MFI_src, _MFI_length)*_MFI_factor+_MFI_factor_2
plot(80+_MFI_factor_2, title="MFI OB", color=(_MFI_on) ? color.new(_MFI_color, 0) : na, linewidth=1)
plot(20+_MFI_factor_2, title="MFI OS", color=(_MFI_on) ? color.new(_MFI_color, 0) : na, linewidth=1)
plot(_MFI_mf, color=(_MFI_on and _MFI_width>0) ? _MFI_color : na, linewidth=_MFI_width)
|
ADR in 0.5 / 1 / 3 / 5 | https://www.tradingview.com/script/7R6h9sGd-ADR-in-0-5-1-3-5/ | superbeeki | https://www.tradingview.com/u/superbeeki/ | 27 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © superbeeki
//@version=5
indicator(title='ADR in 0.5 / 1 / 3 / 5', shorttitle='ADR indicator', overlay=true, precision=2)
//adr information
show_adrp = input(true, title='Show ADR')
adrp_length = input.int(20, title='ADR length')
adrp_col = input(color.white, title='Text color (ADR%)')
//adr * 3
show_adrp3 = input(true, title='Show ADR*3')
adrp3_col = input(color.white, title='Text color (ADR*3)')
//adr * 5
show_adrp5 = input(true, title='Show ADR*5')
adrp5_col = input(color.white, title='Text color (ADR*5)')
//adr * 0.5 in dollar
show_adrd05 = input(true, title='Show ADR*0.5 in $')
adrd05_col = input(color.white, title='Text color ADR*0.5 in $')
//data creation
arp = 100 * (ta.sma(high / low, adrp_length) - 1)
adrp = request.security(syminfo.tickerid, 'D', arp)
adrp3 = 3 * adrp
adrp5 = 5* adrp
adrp05 = 0.5 * adrp
adrd05 = (open * adrp05) / 100
//table
bg_col = input(#00000000, title='Background color')
table t = table.new(position.bottom_right, 2, 5, bgcolor=bg_col, frame_color=color.white)
if barstate.islast
if show_adrd05
table.cell(t, 0, 0, 'ADR*0.5', text_color=adrd05_col, text_size=size.normal)
table.cell(t, 1, 0, str.tostring(math.round(adrd05, 2)) + '$', text_color=adrd05_col, text_size=size.normal)
if show_adrp
table.cell(t, 0, 1, 'ADR', text_color=adrp_col, text_size=size.normal)
table.cell(t, 1, 1, str.tostring(math.round(adrp, 2)) + '%', text_color=adrp_col, text_size=size.normal)
if show_adrp3
table.cell(t, 0, 2, 'ADR*3', text_color=adrp3_col, text_size=size.normal)
table.cell(t, 1, 2, str.tostring(math.round(adrp3, 2)) + '%', text_color=adrp3_col, text_size=size.normal)
if show_adrp5
table.cell(t, 0, 3, 'ADR*5', text_color=adrp5_col, text_size=size.normal)
table.cell(t, 1, 3, str.tostring(math.round(adrp5, 2)) + '%', text_color=adrp5_col, text_size=size.normal)
|
Multi Asset + Correlation Overlay | https://www.tradingview.com/script/dtMhahYx-Multi-Asset-Correlation-Overlay/ | TradeAutomation | https://www.tradingview.com/u/TradeAutomation/ | 75 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version = 5
// Author = TradeAutomation
indicator("Multi Asset + Correlation Overlay", shorttitle="Multi Asset + Correlation Overlay", overlay=true)
//Selects Ticker and Provides Inputs
Asset = input.string(title="Overlay Ticker", defval="SPY", tooltip="Input the ticker of the symbol you want to overlay on your chart here.")
Source = input.source(close, "Source", tooltip="Select the type of data you want to pull in for the asset. I.e. close=closing price.")
Offset = input.int(0, "Ticker Offset", tooltip="This can be a positive or negative number that you can use to move the overlayed asset up/down to better align with your current chart's layout")
Length = input.int(200, "# of Bars for Correlation Calculation", tooltip="The overlayed asset's correlation coeffecient prints on the chart next to the ticker of the added asset")
//Pulls in Ticker Data
Resolution = input.timeframe(title="Resolution", defval="60")
Ticker = request.security(Asset, Resolution, Source)
//Calculates Correlation
Correlation = str.tostring(ta.correlation(Source, Ticker, Length), '#.##')
//Plots and Labels
color1 = input.color(color.purple, "Color of Plot")
plot(Ticker+Offset, color = color1)
var label label1 = na
if time > time[1]
label.delete(label1)
label1 := label.new(x=bar_index+1, y=Ticker+Offset, text=Asset+", CC:"+Correlation, xloc=xloc.bar_index, color=color.new(color1,100), style= label.style_label_left, textcolor=color1, size=size.small)
|
SuperJump QQE MOD MTF | https://www.tradingview.com/script/xmfRcsMq/ | SuperJump | https://www.tradingview.com/u/SuperJump/ | 320 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SuperJump
//@version=5
//By Glaz, By Mihkel00 Modified
indicator("SuperJump QQE MOD MTF", shorttitle = "Sjump QQE MOD MTF", timeframe="",timeframe_gaps =true)
RSI_Period = input.int(6, title='RSI Length')
SF = input.int(5, title='RSI Smoothing')
QQE = input.int(3, title='Fast QQE Factor')
ThreshHold = input.int(3, title="Threshold")
src = input.source(close, title="RSI Source")
QQELongColor = input.color(color.new(color.green,50), "QQE Long")
QQEShortColor = input.color(color.new(color.red,50), "QQE Short")
QQEWeakColor = input.color(color.new(color.gray,50), "QQE Weak")
isFillBackGround = input.bool(false,"Fill BackGround for higherTimeFrame")
GetQQEDefaultValue(_src, _rsi_period, _sf, _qqe) =>
_Wilders_Period = _rsi_period * 2 - 1
_RSI = ta.rsi(_src, _rsi_period)
_RsiMa = ta.ema(_RSI, _sf)
_AtrRsi = math.abs(_RsiMa[1] - _RsiMa)
_MaAtrRsi = ta.ema(_AtrRsi, _Wilders_Period)
_dar = ta.ema(_MaAtrRsi, _Wilders_Period) * _qqe
[_Wilders_Period, _RSI, _RsiMa, _AtrRsi, _dar]
[Wilders_Period, Rsi,RsiMa,AtrRsi,dar] = GetQQEDefaultValue(src, RSI_Period, SF, QQE)
GetFastAtrRsiTL(_dar, _RsiMa)=>
longband = 0.0
shortband = 0.0
trend = 0
DeltaFastAtrRsi = _dar
RSIndex = _RsiMa
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? math.max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? math.min(shortband[1], newshortband) : newshortband
cross_1 = ta.cross(longband[1], RSIndex)
trend := ta.cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
FastAtrRsiTL = GetFastAtrRsiTL(dar, RsiMa)
length = input.int(50, minval=1, title="Bollinger Length")
mult = input.float(0.35, minval=0.001, maxval=5, step=0.1, title="BB Multiplier")
basis = ta.sma(FastAtrRsiTL - 50, length)
dev = mult * ta.stdev(FastAtrRsiTL - 50, length)
upper = basis + dev
lower = basis - dev
Zero = hline(0, color=color.white, linestyle=hline.style_dotted, linewidth=1)
////////////////////////////////////////////////////////////////
RSI_Period2 = input(6, title='RSI Length')
SF2 = input(5, title='RSI Smoothing')
QQE2 = input(1.61, title='Fast QQE2 Factor')
ThresHold2 = input(3, title="Threshold")
src2 = input(close, title="RSI Source")
[Wilders_Period2, Rsi2,RsiMa2,AtrRsi2,dar2] = GetQQEDefaultValue(src2, RSI_Period2, SF2, QQE2)
FastAtrRsi2TL = GetFastAtrRsiTL(dar2, RsiMa2)
Greenbar1 = RsiMa2 - 50 > ThresHold2
Greenbar2 = RsiMa - 50 > upper
Redbar1 = RsiMa2 - 50 < 0 - ThresHold2
Redbar2 = RsiMa - 50 < lower
isLongTrend = Greenbar1 and Greenbar2 == 1
isShortTrend = Redbar1 and Redbar2 == 1
plot(isFillBackGround == false? FastAtrRsi2TL - 50:na , title='QQE Line', color=color.white, transp=0, linewidth=2)
plot(isFillBackGround == false ? RsiMa2 - 50 :na , title="QQE Area", style=plot.style_area, color= isLongTrend ? QQELongColor : isShortTrend ? QQEShortColor : QQEWeakColor)
isLongSignal = FastAtrRsi2TL - 50 >=0 and ta.crossunder(RsiMa2 - 50,FastAtrRsi2TL - 50) and isFillBackGround == false
isShortSignal = FastAtrRsi2TL - 50 <0 and ta.crossover(RsiMa2 - 50,FastAtrRsi2TL - 50) and isFillBackGround == false
|
Profit Reminder | https://www.tradingview.com/script/ecdAwhqp-Profit-Reminder/ | SamRecio | https://www.tradingview.com/u/SamRecio/ | 104 | study | 5 | MPL-2.0 | // 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("Profit Reminder", shorttitle = "Take Profits!", overlay = true)
phrase1 = input.string("Don't Be Greedy. \nTake Profits! 💸", title = "Phrase 1")
day_target = input.float(250, title = "Profit")
phrase2 = input.string("Consistency is 🔑! \nIt's YOUR Money!", title = "Phrase 2")
tl1 = input.string("middle", title = "Table Location", options = ["top", "middle", "bottom"], group = "Table Settings", inline = "1")
tl2 = input.string("right", title = "", options = ["left", "center", "right"], group = "Table Settings", inline = "1")
color1 = input.color(color.rgb(0,0,0), title = "Text Color", inline = "c_1", group = "Table Settings")
color3 = input.color(color.rgb(255,150,0), title = "Outline Color", inline = "c_2", group = "Table Settings")
color2 = input.color(color.rgb(255, 255, 0), title = "Background Color", inline = "c_2", group = "Table Settings")
week_prof = day_target * 5
month_prof = day_target * 20
year_prof = day_target * 252
var table t1 = table.new(tl1 +"_" + tl2,2,7, frame_color = color3, frame_width = 3, border_color = color3, border_width = 1)
if barstate.islast
table.cell(t1,1,0, text = phrase1 , bgcolor = color2, text_color = color1, text_halign = text.align_right, text_size = size.large)
table.cell(t1,1,1, text = "Day: " + str.tostring(str.format("{0, number, currency}",day_target)), bgcolor = color2, text_color = color1, text_halign = text.align_right)
table.cell(t1,1,2, text = "Week: " + str.tostring(str.format("{0, number, currency}",week_prof)), bgcolor = color2, text_color = color1, text_halign = text.align_right, tooltip = "5 Days")
table.cell(t1,1,3, text = "Month: " + str.tostring(str.format("{0, number, currency}",month_prof)), bgcolor = color2, text_color = color1, text_halign = text.align_right, tooltip = "30 Days")
table.cell(t1,1,4, text = "Year: " + str.tostring(str.format("{0, number, currency}",year_prof)), bgcolor = color2, text_color = color1, text_halign = text.align_right, tooltip = "252 Days")
table.cell(t1,1,5, text = phrase2 , bgcolor = color2, text_color = color1, text_halign = text.align_right, text_size = size.large) |
Bogdan Ciocoiu - Moonshot | https://www.tradingview.com/script/UZZ8Yz3P-Bogdan-Ciocoiu-Moonshot/ | BogdanCiocoiu | https://www.tradingview.com/u/BogdanCiocoiu/ | 107 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BogdanCiocoiu
//@version=5
indicator("Bogdan Ciocoiu - Moonshot", shorttitle="BC - Moonshot", format=format.price, precision=2, timeframe="", timeframe_gaps=true, explicit_plot_zorder=true)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// Overall
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_All_line_0 = input(40, "Separator 1", inline="Overall", group="Overall")
_All_line_1 = input(0, "2", inline="Overall", group="Overall")
_All_line_2 = input(-40, "3", inline="Overall", group="Overall")
_All_line_color = input(color.new(color.white, 70), "", inline="Overall", group="Overall")
_All_layer_0 = hline(_All_line_0, "", color=_All_line_color, linestyle=hline.style_dashed)
_All_layer_1 = hline(_All_line_1, "", color=_All_line_color, linestyle=hline.style_dashed)
_All_layer_2 = hline(_All_line_2, "", color=_All_line_color, linestyle=hline.style_dashed)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// TSI
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_TSI_enable = input(true, "", inline="TSI", group="TSI")
_TSI_col_l = input(color.new(color.green, 50), "", inline="TSI", group="TSI")
_TSI_col_s = input(color.new(color.red, 50), "", inline="TSI", group="TSI")
_TSI_col_l_2 = input(color.new(color.green, 20), "", inline="TSI", group="TSI")
_TSI_col_s_2 = input(color.new(color.red, 20), "", inline="TSI", group="TSI")
_TSI_src = input(close, "", inline="TSI", group="TSI")
_TSI_width = input(0, title="Wid", inline="TSI", group="TSI")
_TSI_long_length = input(6, title="Lon", inline="TSI", group="TSI")
_TSI_short_length = input(13, title="Sho", inline="TSI", group="TSI")
_TSI_signal_length = input(4, title="Sig", inline="TSI", group="TSI")
_TSI_mom = ta.change(_TSI_src)
_TSI_numerator = ta.ema(ta.ema(_TSI_mom, _TSI_long_length), _TSI_short_length)
_TSI_denominator = ta.ema(ta.ema(math.abs(_TSI_mom), _TSI_long_length), _TSI_short_length)
_TSI_tsi = 100 * _TSI_numerator / _TSI_denominator
_TSI_signal = ta.ema(_TSI_tsi, _TSI_signal_length)
_TSI_trend_color = (_TSI_tsi > _TSI_signal) ? _TSI_col_l : _TSI_col_s
_TSI_tsi_plot = plot(_TSI_tsi, color=(_TSI_enable and _TSI_width>0) ? _TSI_trend_color : na, linewidth=_TSI_width)
_TSI_signal_plot = plot(_TSI_signal, color=(_TSI_enable and _TSI_width>0) ? _TSI_trend_color : na, linewidth=_TSI_width)
fill(_TSI_tsi_plot, _TSI_signal_plot, color=(_TSI_enable) ? _TSI_trend_color : na)
plotshape(ta.crossover(_TSI_tsi, _TSI_signal) ? _TSI_tsi : na, location=location.absolute, style=shape.circle, size=size.tiny, color=(_TSI_enable) ? _TSI_col_l_2 : na)
plotshape(ta.crossunder(_TSI_tsi, _TSI_signal) ? _TSI_tsi : na, location=location.absolute, style=shape.circle, size=size.tiny, color=(_TSI_enable) ? _TSI_col_s_2 : na)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// MACD
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_MACD_enable = input(false, "", inline="MACD", group="MACD")
_MACD_col = input(color.aqua, "", inline="MACD", group="MACD")
_MACD_src = input(close, "", inline="MACD", group="MACD")
_MACD_width = input(2, title="Wid", inline="MACD", group="MACD")
_MACD_multi_factor = input(5, "Fact", inline="MACD", group="MACD")
_MACD_fast_len = input(12, "Fast", inline="MACD", group="MACD")
_MACD_slow_len = input(26, "Slow", inline="MACD", group="MACD")
_MACD_sig_len = input(9, "Smo", inline="MACD", group="MACD")
_MACD_sma_src = input.string("EMA", title="Oscillator MA", options=["SMA", "EMA"], inline="MACD", group="MACD")
_MACD_sma_sig = input.string("EMA", title="Signal MA", options=["SMA", "EMA"], inline="MACD", group="MACD")
_MACD_ma_f = _MACD_sma_src == "SMA" ? ta.sma(_MACD_src, _MACD_fast_len) : ta.ema(_MACD_src, _MACD_fast_len)
_MACD_ma_s = _MACD_sma_src == "SMA" ? ta.sma(_MACD_src, _MACD_slow_len) : ta.ema(_MACD_src, _MACD_slow_len)
_MACD_md = _MACD_ma_f - _MACD_ma_s
_MACD_sig = _MACD_sma_sig == "SMA" ? ta.sma(_MACD_md, _MACD_sig_len) : ta.ema(_MACD_md, _MACD_sig_len)
_MACD_his = _MACD_md - _MACD_sig
_MACD_his := _MACD_his * _MACD_multi_factor
plot(_MACD_his, style=plot.style_line, color=(_MACD_enable and _MACD_width>0) ? _MACD_col : na, linewidth=_MACD_width)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// AO
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_AO_enable = input(true, "", inline="AO", group="AO")
_AO_col = input(color.orange, "", inline="AO", group="AO")
_AO_width = input(2, title="Wid", inline="AO", group="AO")
_AO_multi_factor = input(1, "Fact", inline="AO", group="AO")
_AO_ao = ta.sma(hl2,5) - ta.sma(hl2,34)
_AO_ao := _AO_ao * _AO_multi_factor
_AO_diff = _AO_ao - _AO_ao[1]
plot(_AO_ao, color=(_AO_enable and _AO_width>0) ? _AO_col : na, style=plot.style_line, linewidth=_AO_width)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// CCI
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_CCI_enable = input(true, "", inline="CCI", group="CCI")
_CCI_col = input(color.fuchsia, "", inline="CCI", group="CCI")
_CCI_width = input(2, "Wid", inline="CCI", group="CCI")
_CCI_multi_factor = input(0.2, "Fac", inline="CCI", group="CCI")
_CCI_src = input(hlc3, "", inline="CCI", group="CCI")
_CCI_length = input(20, "Len", inline="CCI", group="CCI")
_CCI_ma = ta.sma(_CCI_src, _CCI_length)
_CCI_cci = (_CCI_src - _CCI_ma) / (0.015 * ta.dev(_CCI_src, _CCI_length))
_CCI_cci := _CCI_cci * _CCI_multi_factor
plot(_CCI_cci, "CCI", color=(_CCI_enable and _CCI_width>0) ? _CCI_col : na, linewidth=_CCI_width)
|
Relative Strength Index (OSC) | https://www.tradingview.com/script/8ldY7LsD/ | dandrideng | https://www.tradingview.com/u/dandrideng/ | 72 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dandrideng
//@version=5
indicator(title="Relative Strength Index (OSC)", shorttitle="RSI (OSC)", overlay=false, max_bars_back=1000, max_lines_count=400, max_labels_count=400)
import dandrideng/moving_average/1 as ma
import dandrideng/divergence/2 as div
//rsi params
rsi_source = input.source(close, "Source", group="RSI Settings")
rsi_length = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
up = ta.rma(math.max(ta.change(rsi_source), 0), rsi_length)
down = ta.rma(-math.min(ta.change(rsi_source), 0), rsi_length)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
plot(rsi, "RSI", color=#7E57C2)
rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
//rsi divergece paramters
lbR = input.int(defval=2, title="Pivot Lookback Right", group="RSI Divergence")
lbL = input.int(defval=5, title="Pivot Lookback Left", group="RSI Divergence")
range_upper = input.int(defval=60, title="Max of Lookback Range", group="RSI Divergence")
range_lower = input.int(defval=5, title="Min of Lookback Range", group="RSI Divergence")
tolerance = input.int(defval=2, title="Tolerant Kline Number", group="RSI Divergence")
cov_thresh = input.float(defval=-0.1, title="Cov Threshold", group="RSI Divergence")
plot_rbull = input.bool(defval=true, title="Plot Bullish", group="RSI Divergence")
plot_hbull = input.bool(defval=false, title="Plot Hidden Bullish", group="RSI Divergence")
plot_rbear = input.bool(defval=true, title="Plot Bearish", group="RSI Divergence")
plot_hbear = input.bool(defval=false, title="Plot Hidden Bearish", group="RSI Divergence")
osc = rsi
to_intstr(x) => str.tostring(x, "#")
to_floatstr(x) => str.tostring(x, "#.###")
reg_bull = div.regular_bull(low, osc, lbL, lbR, range_lower, range_upper, tolerance)
reg_bull_lsv = array.get(reg_bull, 0)
reg_bull_lsb = int(array.get(reg_bull, 1))
reg_bull_lov = array.get(reg_bull, 2)
reg_bull_lob = int(array.get(reg_bull, 3))
reg_bull_rsv = array.get(reg_bull, 4)
reg_bull_rsb = int(array.get(reg_bull, 5))
reg_bull_rov = array.get(reg_bull, 6)
reg_bull_rob = int(array.get(reg_bull, 7))
reg_bull_cov = array.get(reg_bull, 8)
if not na(reg_bull_lsv) and plot_rbull and reg_bull_cov < cov_thresh
reg_bull_label = label.new(x=bar_index-lbR-reg_bull_rob, y=reg_bull_rov)
label.set_text(reg_bull_label, "REG "+ to_floatstr(reg_bull_cov) +"\nSRC(" + to_intstr(reg_bull_rsb) + "-" + to_intstr(reg_bull_lsb) + ")\nOSC(" + to_intstr(reg_bull_rob) + "-" + to_intstr(reg_bull_lob) + ")")
label.set_color(reg_bull_label, color.new(color.green, 20))
label.set_textcolor(reg_bull_label, color.white)
label.set_style(reg_bull_label, label.style_label_up)
reg_bull_line = line.new(x1=bar_index-lbR-reg_bull_lob, y1=reg_bull_lov, x2=bar_index-lbR-reg_bull_rob, y2=reg_bull_rov)
line.set_color(reg_bull_line, color.new(color.green, 20))
line.set_width(reg_bull_line, 2)
hid_bull = div.hidden_bull(low, osc, lbL, lbR, range_lower, range_upper, tolerance)
hid_bull_lsv = array.get(hid_bull, 0)
hid_bull_lsb = int(array.get(hid_bull, 1))
hid_bull_lov = array.get(hid_bull, 2)
hid_bull_lob = int(array.get(hid_bull, 3))
hid_bull_rsv = array.get(hid_bull, 4)
hid_bull_rsb = int(array.get(hid_bull, 5))
hid_bull_rov = array.get(hid_bull, 6)
hid_bull_rob = int(array.get(hid_bull, 7))
hid_bull_cov = array.get(hid_bull, 8)
if not na(hid_bull_lsv) and plot_hbull and hid_bull_cov < cov_thresh
hid_bull_label = label.new(x=bar_index-lbR-hid_bull_rob, y=hid_bull_rov)
label.set_text(hid_bull_label, "HID "+ to_floatstr(hid_bull_cov) +"\nSRC(" + to_intstr(hid_bull_rsb) + "-" + to_intstr(hid_bull_lsb) + ")\nOSC(" + to_intstr(hid_bull_rob) + "-" + to_intstr(hid_bull_lob) + ")")
label.set_color(hid_bull_label, color.new(color.green, 50))
label.set_textcolor(hid_bull_label, color.white)
label.set_style(hid_bull_label, label.style_label_up)
hid_bull_line = line.new(x1=bar_index-lbR-hid_bull_lob, y1=hid_bull_lov, x2=bar_index-lbR-hid_bull_rob, y2=hid_bull_rov)
line.set_color(hid_bull_line, color.new(color.green, 50))
line.set_width(hid_bull_line, 2)
reg_bear = div.regular_bear(high, osc, lbL, lbR, range_lower, range_upper, tolerance)
reg_bear_lsv = array.get(reg_bear, 0)
reg_bear_lsb = int(array.get(reg_bear, 1))
reg_bear_lov = array.get(reg_bear, 2)
reg_bear_lob = int(array.get(reg_bear, 3))
reg_bear_rsv = array.get(reg_bear, 4)
reg_bear_rsb = int(array.get(reg_bear, 5))
reg_bear_rov = array.get(reg_bear, 6)
reg_bear_rob = int(array.get(reg_bear, 7))
reg_bear_cov = array.get(reg_bear, 8)
if not na(reg_bear_lsv) and plot_rbear and reg_bear_cov < cov_thresh
reg_bear_label = label.new(x=bar_index-lbR-reg_bear_rob, y=reg_bear_rov)
label.set_text(reg_bear_label, "REG "+ to_floatstr(reg_bear_cov) +"\nSRC(" + to_intstr(reg_bear_rsb) + "-" + to_intstr(reg_bear_lsb) + ")\nOSC(" + to_intstr(reg_bear_rob) + "-" + to_intstr(reg_bear_lob) + ")")
label.set_color(reg_bear_label, color.new(color.red, 20))
label.set_textcolor(reg_bear_label, color.white)
label.set_style(reg_bear_label, label.style_label_down)
reg_bear_line = line.new(x1=bar_index-lbR-reg_bear_lob, y1=reg_bear_lov, x2=bar_index-lbR-reg_bear_rob, y2=reg_bear_rov)
line.set_color(reg_bear_line, color.new(color.red, 20))
line.set_width(reg_bear_line, 2)
hid_bear = div.hidden_bear(high, osc, lbL, lbR, range_lower, range_upper, tolerance)
hid_bear_lsv = array.get(hid_bear, 0)
hid_bear_lsb = int(array.get(hid_bear, 1))
hid_bear_lov = array.get(hid_bear, 2)
hid_bear_lob = int(array.get(hid_bear, 3))
hid_bear_rsv = array.get(hid_bear, 4)
hid_bear_rsb = int(array.get(hid_bear, 5))
hid_bear_rov = array.get(hid_bear, 6)
hid_bear_rob = int(array.get(hid_bear, 7))
hid_bear_cov = array.get(hid_bear, 8)
if not na(hid_bear_lsv) and plot_hbear and hid_bear_cov < cov_thresh
hid_bear_label = label.new(x=bar_index-lbR-hid_bear_rob, y=hid_bear_rov)
label.set_text(hid_bear_label, "HID "+ to_floatstr(hid_bear_cov) +"\nSRC(" + to_intstr(hid_bear_rsb) + "-" + to_intstr(hid_bear_lsb) + ")\nOSC(" + to_intstr(hid_bear_rob) + "-" + to_intstr(hid_bear_lob) + ")")
label.set_color(hid_bear_label, color.new(color.red, 50))
label.set_textcolor(hid_bear_label, color.white)
label.set_style(hid_bear_label, label.style_label_down)
hid_bear_line = line.new(x1=bar_index-lbR-hid_bear_lob, y1=hid_bear_lov, x2=bar_index-lbR-hid_bear_rob, y2=hid_bear_rov)
line.set_color(hid_bear_line, color.new(color.red, 50))
line.set_width(hid_bear_line, 2)
//end of file |
Bogdan Ciocoiu - Litigator | https://www.tradingview.com/script/e8780Gkh-Bogdan-Ciocoiu-Litigator/ | BogdanCiocoiu | https://www.tradingview.com/u/BogdanCiocoiu/ | 97 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BogdanCiocoiu
//@version=5
indicator("Bogdan Ciocoiu - Litigator", shorttitle="BC - Litigator", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// Overall
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_All_line_0 = input(80, "Separator 1", inline="Overall", group="Overall")
_All_line_1 = input(50, "2", inline="Overall", group="Overall")
_All_line_2 = input(20, "3", inline="Overall", group="Overall")
_All_line_color = input(color.new(color.white, 70), "", inline="Overall", group="Overall")
_All_layer_0 = hline(_All_line_0, "", color=(_All_line_0>0) ? _All_line_color : na, linestyle=hline.style_dashed)
_All_layer_1 = hline(_All_line_1, "", color=(_All_line_1>0) ? _All_line_color : na, linestyle=hline.style_dashed)
_All_layer_2 = hline(_All_line_2, "", color=(_All_line_2>0) ? _All_line_color : na, linestyle=hline.style_dashed)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// RSI
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_RSI_mode=input(close, "", inline="RSI", group="RSI")
_RSI_width=input(2, "Wid", inline="RSI", group="RSI")
_RSI_factor=input(1.1, "Fact", inline="RSI", group="RSI")
_RSI_on_1=input(false, "", inline="RSI 1", group="RSI")
_RSI_no_1=input(7, "", inline="RSI 1", group="RSI")
_RSI_col_1=input(color.fuchsia, "", inline="RSI 1", group="RSI")
_RSI_on_2=input(true, "", inline="RSI 2", group="RSI")
_RSI_no_2=input(14, "", inline="RSI 2", group="RSI")
_RSI_col_2=input(color.fuchsia, "", inline="RSI 2", group="RSI")
_RSI_on_3=input(false, "", inline="RSI 3", group="RSI")
_RSI_no_3=input(50, "", inline="RSI 3", group="RSI")
_RSI_col_3=input(color.fuchsia, "", inline="RSI 3", group="RSI")
_RSI_1=ta.rsi(_RSI_mode, _RSI_no_1)*_RSI_factor
_RSI_2=ta.rsi(_RSI_mode, _RSI_no_2)*_RSI_factor
_RSI_3=ta.rsi(_RSI_mode, _RSI_no_3)*_RSI_factor
plot(_RSI_1, color=(_RSI_on_1 and _RSI_width>0) ? _RSI_col_1 : na, linewidth=_RSI_width)
plot(_RSI_2, color=(_RSI_on_2 and _RSI_width>0) ? _RSI_col_2 : na, linewidth=_RSI_width)
plot(_RSI_3, color=(_RSI_on_3 and _RSI_width>0) ? _RSI_col_3 : na, linewidth=_RSI_width)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// UO
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_UO_on = input(true, "", inline="UO", group="UO")
_UO_color = input(color.aqua, "", inline="UO", group="UO")
_UO_width = input(2, "Wid", inline="UO", group="UO")
_UO_factor = input(1.2, "Fact", inline="UO", group="UO")
_UO_length_1 = input.int(7, "Len 1", inline="UO", group="UO")
_UO_length_2 = input.int(14, "2", inline="UO", group="UO")
_UO_length_3 = input.int(28, "3", inline="UO", group="UO")
_UO_average(_UO_bp, _UO_tr, _UO_length) => math.sum(_UO_bp, _UO_length) / math.sum(_UO_tr, _UO_length)
_UO_high = math.max(high, close[1])
_UO_low = math.min(low, close[1])
_UO_bp = close - _UO_low
_UO_tr = _UO_high - _UO_low
_UO_avg7 = _UO_average(_UO_bp, _UO_tr, _UO_length_1)
_UO_avg14 = _UO_average(_UO_bp, _UO_tr, _UO_length_2)
_UO_avg28 = _UO_average(_UO_bp, _UO_tr, _UO_length_3)
_UO_out = (100 * (4*_UO_avg7 + 2*_UO_avg14 + _UO_avg28)/7)*_UO_factor
plot(_UO_out, title="UO", color=(_UO_on and _UO_width>0) ? _UO_color : na, linewidth=_UO_width)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// Stochastic
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_Stoch_on = input(true, "", inline="Stoch", group="Stoch")
_Stoch_col_up = input(color.new(color.green, 50), "", inline="Stoch", group="Stoch")
_Stoch_col_down = input(color.new(color.red, 50), "", inline="Stoch", group="Stoch")
_Stoch_col_up_2 = input(color.new(color.green, 20), "", inline="Stoch", group="Stoch")
_Stoch_col_down_2 = input(color.new(color.red, 20), "", inline="Stoch", group="Stoch")
_Stoch_wid = input(0, "Wid", inline="Stoch", group="Stoch")
_Stoch_period_K = input(8, "K per", inline="Stoch", group="Stoch")
_Stoch_smooth_K = input(3, "K smo", inline="Stoch", group="Stoch")
_Stoch_period_D = input(5, "D per", inline="Stoch", group="Stoch")
_Stoch_K = ta.sma(ta.stoch(close, high, low, _Stoch_period_K), _Stoch_smooth_K)
_Stoch_D = ta.sma(_Stoch_K, _Stoch_period_D)
_Stoch_K_plot = plot(_Stoch_K, title="Stoch K", color=(_Stoch_on and _Stoch_wid > 0) ? (_Stoch_K > _Stoch_D ? _Stoch_col_up : _Stoch_col_down ) : na, linewidth=_Stoch_wid)
_Stoch_D_plot = plot(_Stoch_D, title="Stoch D", color=(_Stoch_on and _Stoch_wid > 0) ? (_Stoch_K > _Stoch_D ? _Stoch_col_up : _Stoch_col_down ) : na, linewidth=_Stoch_wid)
fill(_Stoch_K_plot, _Stoch_D_plot, color=(_Stoch_on) ? (_Stoch_K > _Stoch_D ? _Stoch_col_up : _Stoch_col_down ) : na)
plotshape(ta.crossover(_Stoch_K, _Stoch_D) ? _Stoch_K : na, location=location.absolute, style=shape.circle, size=size.tiny, color=(_Stoch_on) ? _Stoch_col_up_2 : na)
plotshape(ta.crossunder(_Stoch_K, _Stoch_D) ? _Stoch_K : na, location=location.absolute, style=shape.circle, size=size.tiny, color=(_Stoch_on) ? _Stoch_col_down_2 : na)
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
// MFI
// ----------------------------------------------------------------------------------------------------------------------------------------------------------------
_MFI_on = input(false, title="", group="MFI", inline="MFI")
_MFI_color = input(color.orange, title="", group="MFI", inline="MFI")
_MFI_width = input(2, title="Wid", group="MFI", inline="MFI")
_MFI_length = input(14, title="Len", group="MFI", inline="MFI")
_MFI_src = input(hlc3, title="", group="MFI", inline="MFI")
_MFI_factor = input(1.1, title="Fact", group="MFI", inline="MFI")
_MFI_mf = ta.mfi(_MFI_src, _MFI_length)*_MFI_factor
plot(_MFI_mf, color=(_MFI_on and _MFI_width>0) ? _MFI_color : na, linewidth=_MFI_width)
|
Aggregated Volume - By InFinito | https://www.tradingview.com/script/RPH1uk5z-Aggregated-Volume-By-InFinito/ | In_Finito_ | https://www.tradingview.com/u/In_Finito_/ | 64 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © In_Finito_ -------- Aggregation Code by Cryptourus
//@version=5
//EXCHANGE NOTES
//BITGET DOES NOT PROVIDE REAL TIME DERIVATIVE VOLUME DATA - DERIV DATA PROVIDED IN USD
//BYBIT BOTH FUTURES AND PERP - NO SPOT - PERP DATA PROVIDED IN USD NOT BTC
//CME NORMAL FUTURES GIVE DATA IN CONTRACTS OF 5 BTC
//CME MINI FUTURES GIVE DATA OF 0.10 BTC
//BINANCE PERP GIVES AMOUNT IN USD/100 (FOR EVERY USD REPORTED ON TV, THERE WERE 100 TRADED) - USDTPERPS IS PROVIDED CORRECTLY IN BTC - SPOT PROVIDED IN BTC
//OKEX PERP GIVES AMOUNT IN BLOCKS OF 100 USD (FOR EVERY USD REPORTED ON TV, THERE WERE 100 TRADED) - FUTURES GIVES THE DATA IN BTC*100 - SPOT AS IS IN BTC
//HUOBI PERP GIVES AMOUNT AS IS IN BTC - FUTURES NOT AVAILABLE IN TV AS OF NOW (03/27/2022) - SPOT AS IS
//DERIBIT PERP GIVEN IN USD AMOUNT AS IS
//BITMEX PERP GIVEN IN USD TERMS - FUTURES GIVEN IN 1 MILLIONTH OF BTC (1 MILLION REPORTED ON TV EQUAL 1 BTC)
indicator('Aggregated Volume', format=format.volume, precision=0)
////////////////////MARKET TYPE////////////////////////
markettype = input.string(defval='Spot', title='Market Type Aggregation', options=['Spot', 'Futures' , 'Perp', 'Derivatives F+P', 'Spot+Derivs'], tooltip='Volume is calculated to be reported in terms of the main asset of the pair (i.e BTC). Exchanges report volume data in different ways. In order to make aggregation as accurate as possible, you can manually introduce the base currency it is reported on and the size of the lots reported. In case asset is quoted in another currency (i.e EUR), select Other and intruduce the value of that other currency in USD Terms')
aggr = input.bool(defval=true, title='Use Aggregated Data', inline='1', group='Aggregation', tooltip='Disable to check by symbol OR if you want to use this indicator with any other pair than BTC')
addma = input.bool(defval=false, title='Add MA |', inline='1', group='Moving Average')
malen = input.int(defval=28, title='MA Lenght', inline='1', group='Moving Average')
//////////////////// Inputs FOR SPOT AGGREGATION///////////////////////////
i_sym1 = input.bool(true, '', inline='1', group='Spot Symbols')
i_sym2 = input.bool(true, '', inline='2', group='Spot Symbols')
i_sym3 = input.bool(true, '', inline='3', group='Spot Symbols')
i_sym4 = input.bool(true, '', inline='4', group='Spot Symbols')
i_sym5 = input.bool(true, '', inline='5', group='Spot Symbols')
i_sym6 = input.bool(true, '', inline='6', group='Spot Symbols')
i_sym7 = input.bool(true, '', inline='7', group='Spot Symbols')
i_sym8 = input.bool(true, '', inline='8', group='Spot Symbols')
i_sym9 = input.bool(true, '', inline='9', group='Spot Symbols')
i_sym10 = input.bool(false, '', inline='10', group='Spot Symbols')
i_sym11 = input.bool(false, '', inline='11', group='Spot Symbols')
i_sym12 = input.bool(true, '', inline='12', group='Spot Symbols')
i_sym13 = input.bool(true, '', inline='13', group='Spot Symbols')
i_sym14 = input.bool(false, '', inline='14', group='Spot Symbols')
i_sym15 = input.bool(false, '', inline='15', group='Spot Symbols')
i_sym16 = input.bool(false, '', inline='16', group='Spot Symbols')
i_sym1_ticker = input.symbol('BINANCE:BTCUSDT', '', inline='1', group='Spot Symbols')
i_sym2_ticker = input.symbol('BINANCE:BTCBUSD', '', inline='2', group='Spot Symbols')
i_sym3_ticker = input.symbol('BITSTAMP:BTCUSD', '', inline='3', group='Spot Symbols')
i_sym4_ticker = input.symbol('HUOBI:BTCUSDT', '', inline='4', group='Spot Symbols')
i_sym5_ticker = input.symbol('OKEX:BTCUSDT', '', inline='5', group='Spot Symbols')
i_sym6_ticker = input.symbol('COINBASE:BTCUSD', '', inline='6', group='Spot Symbols')
i_sym7_ticker = input.symbol('COINBASE:BTCUSDT', '', inline='7', group='Spot Symbols')
i_sym8_ticker = input.symbol('GEMINI:BTCUSD', '', inline='8', group='Spot Symbols')
i_sym9_ticker = input.symbol('KRAKEN:XBTUSD', '', inline='9', group='Spot Symbols')
i_sym10_ticker = input.symbol('FTX:BTCUSD', '', inline='10', group='Spot Symbols')
i_sym11_ticker = input.symbol('FTX:BTCUSDT', '', inline='11', group='Spot Symbols')
i_sym12_ticker = input.symbol('BITFINEX:BTCUSD', '', inline='12', group='Spot Symbols')
i_sym13_ticker = input.symbol('BINGX:BTCUSDT', '', inline='13', group='Spot Symbols')
i_sym14_ticker = input.symbol('GATEIO:BTCUSDT', '', inline='14', group='Spot Symbols')
i_sym15_ticker = input.symbol('PHEMEX:BTCUSDT', '', inline='15', group='Spot Symbols')
i_sym16_ticker = input.symbol('BITGET:BTCUSDT', '', inline='16', group='Spot Symbols')
sbase1 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='1', group='Spot Symbols')
sbase2 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='2', group='Spot Symbols')
sbase3 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='3', group='Spot Symbols')
sbase4 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='4', group='Spot Symbols')
sbase5 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='5', group='Spot Symbols')
sbase6 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='6', group='Spot Symbols')
sbase7 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='7', group='Spot Symbols')
sbase8 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='8', group='Spot Symbols')
sbase9 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='9', group='Spot Symbols')
sbase10 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='10', group='Spot Symbols')
sbase11 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='11', group='Spot Symbols')
sbase12 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='12', group='Spot Symbols')
sbase13 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='13', group='Spot Symbols')
sbase14 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='14', group='Spot Symbols')
sbase15 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='15', group='Spot Symbols')
sbase16 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='16', group='Spot Symbols')
samount1 = input.float(defval=1, title='#', inline='1', group='Spot Symbols')
samount2 = input.float(defval=1, title='#', inline='2', group='Spot Symbols')
samount3 = input.float(defval=1, title='#', inline='3', group='Spot Symbols')
samount4 = input.float(defval=1, title='#', inline='4', group='Spot Symbols')
samount5 = input.float(defval=1, title='#', inline='5', group='Spot Symbols')
samount6 = input.float(defval=1, title='#', inline='6', group='Spot Symbols')
samount7 = input.float(defval=1, title='#', inline='7', group='Spot Symbols')
samount8 = input.float(defval=1, title='#', inline='8', group='Spot Symbols')
samount9 = input.float(defval=1, title='#', inline='9', group='Spot Symbols')
samount10 = input.float(defval=1, title='#', inline='10', group='Spot Symbols')
samount11 = input.float(defval=1, title='#', inline='11', group='Spot Symbols')
samount12 = input.float(defval=1, title='#', inline='12', group='Spot Symbols')
samount13 = input.float(defval=1, title='#', inline='13', group='Spot Symbols')
samount14 = input.float(defval=1, title='#', inline='14', group='Spot Symbols')
samount15 = input.float(defval=1, title='#', inline='15', group='Spot Symbols')
samount16 = input.float(defval=1, title='#', inline='16', group='Spot Symbols')
///////INPUTS FOR FUTURES AGGREGATION///////////////////
i_sym1b = input.bool(true, '', inline='1', group='Futures Symbols')
i_sym2b = input.bool(true, '', inline='2', group='Futures Symbols')
i_sym3b = input.bool(true, '', inline='3', group='Futures Symbols')
i_sym4b = input.bool(true, '', inline='4', group='Futures Symbols')
i_sym5b = input.bool(true, '', inline='5', group='Futures Symbols')
i_sym6b = input.bool(true, '', inline='6', group='Futures Symbols')
i_sym7b = input.bool(true, '', inline='7', group='Futures Symbols')
i_sym8b = input.bool(true, '', inline='8', group='Futures Symbols')
i_sym9b = input.bool(true, '', inline='9', group='Futures Symbols')
i_sym10b = input.bool(true, '', inline='10', group='Futures Symbols')
i_sym11b = input.bool(false, '', inline='11', group='Futures Symbols')
i_sym12b = input.bool(false, '', inline='12', group='Futures Symbols')
i_sym1b_ticker = input.symbol('BINANCE:BTCUSDTPERP', '', inline='1', group='Futures Symbols')
i_sym2b_ticker = input.symbol('BINANCE:BTCBUSDPERP', '', inline='2', group='Futures Symbols')
i_sym3b_ticker = input.symbol('BYBIT:BTCUSDT.P', '', inline='3', group='Futures Symbols')
i_sym4b_ticker = input.symbol('CME:BTC1!', '', inline='4', tooltip='This volume is reported in 5 BTC and it is recalculated to work properly, beware when changing this symbol',group='Futures Symbols')
i_sym5b_ticker = input.symbol('CME:BTC2!', '', inline='5', tooltip='This volume is reported in 5 BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym6b_ticker = input.symbol('CME:MBT1!', '', inline='6', tooltip='This volume is reported in 0.10 BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym7b_ticker = input.symbol('CME:MBT2!', '', inline='7', tooltip='This volume is reported in 0.10 BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym8b_ticker = input.symbol('PHEMEX:BTCUSDPERP', '', inline='8', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym9b_ticker = input.symbol('OKEX:BTCUSDT.P', '', inline='9', tooltip='This volume is reported in 100x BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym10b_ticker = input.symbol('BITMEX:XBTUSDT', '', inline='10', tooltip='This volume is reported as 1 million per BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym11b_ticker = input.symbol('BITGET:BTCUSDT.P', '', inline='11', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol - THIS IS NOT REPORTED IN REAL TIME', group='Futures Symbols')
i_sym12b_ticker = input.symbol('OKEX:BTCUSDT.P', '', inline='12', group='Futures Symbols')
fbase1 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='1', group='Futures Symbols')
fbase2 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='2', group='Futures Symbols')
fbase3 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='3', group='Futures Symbols')
fbase4 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='4', group='Futures Symbols')
fbase5 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='5', group='Futures Symbols')
fbase6 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='6', group='Futures Symbols')
fbase7 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='7', group='Futures Symbols')
fbase8 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='8', group='Futures Symbols')
fbase9 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='9', group='Futures Symbols')
fbase10 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='10', group='Futures Symbols')
fbase11 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='11', group='Futures Symbols')
fbase12 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='12', group='Futures Symbols')
famount1 = input.float(defval=1, title='#', inline='1', group='Futures Symbols')
famount2 = input.float(defval=1, title='#', inline='2', group='Futures Symbols')
famount3 = input.float(defval=1, title='#', inline='3', group='Futures Symbols')
famount4 = input.float(defval=5, title='#', inline='4', group='Futures Symbols')
famount5 = input.float(defval=5, title='#', inline='5', group='Futures Symbols')
famount6 = input.float(defval=0.1, title='#', inline='6', group='Futures Symbols')
famount7 = input.float(defval=0.1, title='#', inline='7', group='Futures Symbols')
famount8 = input.float(defval=1, title='#', inline='8', group='Futures Symbols')
famount9 = input.float(defval=0.01, title='#', inline='9', group='Futures Symbols')
famount10 = input.float(defval=0.000001, title='#', inline='10', group='Futures Symbols')
famount11 = input.float(defval=1, title='#', inline='11', group='Futures Symbols')
famount12 = input.float(defval=1, title='#', inline='12', group='Futures Symbols')
//, tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol'
////////////////////////////////////////////////////////////////////
//////INPUTS FOR PERP AGGREGATION///////////////////
i_sym1c = input.bool(true, '', inline='1', group='Perpetuals Symbols')
i_sym2c = input.bool(true, '', inline='2', group='Perpetuals Symbols')
i_sym3c = input.bool(true, '', inline='3', group='Perpetuals Symbols')
i_sym4c = input.bool(true, '', inline='4', group='Perpetuals Symbols')
i_sym5c = input.bool(false, '', inline='5', group='Perpetuals Symbols')
i_sym6c = input.bool(true, '', inline='6', group='Perpetuals Symbols')
i_sym7c = input.bool(true, '', inline='7', group='Perpetuals Symbols')
i_sym8c = input.bool(true, '', inline='8', group='Perpetuals Symbols')
i_sym1c_ticker = input.symbol('BINANCE:BTCPERP', '', inline='1', tooltip='This volume is reported in blocks of 100 USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym2c_ticker = input.symbol('OKEX:BTCUSD.P', '', inline='2', tooltip='This volume is reported in blocks of 100 USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym3c_ticker = input.symbol('HUOBI:BTCUSD.P', '', inline='3', group='Perpetuals Symbols')
i_sym4c_ticker = input.symbol('PHEMEX:BTCPERP', '', inline='4', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym5c_ticker = input.symbol('FTX:BTCPERP', '', inline='5', group='Perpetuals Symbols')
i_sym6c_ticker = input.symbol('BYBIT:BTCUSD.P', '', inline='6', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym7c_ticker = input.symbol('DERIBIT:BTCUSD.P', '', inline='7', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym8c_ticker = input.symbol('BITMEX:XBTUSD.P', '', inline='8', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
pbase1 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='1', group='Perpetuals Symbols')
pbase2 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='2', group='Perpetuals Symbols')
pbase3 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='3', group='Perpetuals Symbols')
pbase4 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='4', group='Perpetuals Symbols')
pbase5 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='5', group='Perpetuals Symbols')
pbase6 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='6', group='Perpetuals Symbols')
pbase7 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='7', group='Perpetuals Symbols')
pbase8 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='8', group='Perpetuals Symbols')
pamount1 = input.float(defval=100, title='#', inline='1', group='Perpetuals Symbols')
pamount2 = input.float(defval=100, title='#', inline='2', group='Perpetuals Symbols')
pamount3 = input.float(defval=1, title='#', inline='3', group='Perpetuals Symbols')
pamount4 = input.float(defval=1, title='#', inline='4', group='Perpetuals Symbols')
pamount5 = input.float(defval=1, title='#', inline='5', group='Perpetuals Symbols')
pamount6 = input.float(defval=1, title='#', inline='6', group='Perpetuals Symbols')
pamount7 = input.float(defval=1, title='#', inline='7', group='Perpetuals Symbols')
pamount8 = input.float(defval=1, title='#', inline='8', group='Perpetuals Symbols')
////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////AGGREGATED VOLUME CALCULATION///////////////////////
//// VOLUME REQUEST FUNCTION//////////////////////////
f_volume(_ticker) =>
request.security(_ticker, timeframe.period, volume, ignore_invalid_symbol=true)
//ohlcdat(_ticker) =>
// o = request.security(_ticker, timeframe.period, open)
// h = request.security(_ticker, timeframe.period, high)
//l = request.security(_ticker, timeframe.period, low)
//c = request.security(_ticker, timeframe.period, close)
//[o, h, l, c]
//////////////////////////////////////////////////////////
//[o, h, l, c] = ohlcdat(i_sym1_ticker)
//plot((o+h+l+c)/4)
///////////SPOT////////////////////////////////////////////////////////////////////
var float finvol = 0
if aggr==true ///////////SPOT////////////////////////////////////////////////////////////////////
v1x = (i_sym1 ? f_volume(i_sym1_ticker) : 0)
v1 = sbase1=='Coin' ? v1x*samount1 : sbase1=='USD' or sbase1=='Other' ? (v1x*samount1)/ohlc4 : v1x
v2x = (i_sym2 ? f_volume(i_sym2_ticker) : 0)
v2 = sbase2=='Coin' ? v2x*samount2 : sbase2=='USD' or sbase2=='Other' ? (v2x*samount2)/ohlc4 : v2x
v3x = (i_sym3 ? f_volume(i_sym3_ticker) : 0)
v3 = sbase2=='Coin' ? v3x*samount3 : sbase3=='USD' or sbase3=='Other' ? (v3x*samount4)/ohlc4 : v3x
v4x = (i_sym4 ? f_volume(i_sym4_ticker) : 0)
v4 = sbase4=='Coin' ? v4x*samount4 : sbase4=='USD' or sbase4=='Other' ? (v4x*samount4)/ohlc4 : v4x
v5x = (i_sym5 ? f_volume(i_sym5_ticker) : 0)
v5 = sbase5=='Coin' ? v5x*samount5 : sbase5=='USD' or sbase5=='Other' ? (v5x*samount5)/ohlc4 : v5x
v6x = (i_sym6 ? f_volume(i_sym6_ticker) : 0)
v6 = sbase6=='Coin' ? v6x*samount6 : sbase6=='USD' or sbase6=='Other' ? (v6x*samount6)/ohlc4 : v6x
v7x = (i_sym7 ? f_volume(i_sym7_ticker) : 0)
v7 = sbase7=='Coin' ? v7x*samount7 : sbase7=='USD' or sbase7=='Other' ? (v7x*samount7)/ohlc4 : v7x
v8x = (i_sym8 ? f_volume(i_sym8_ticker) : 0)
v8 = sbase8=='Coin' ? v8x*samount8 : sbase8=='USD' or sbase8=='Other' ? (v8x*samount8)/ohlc4 : v8x
v9x = (i_sym9 ? f_volume(i_sym9_ticker) : 0)
v9 = sbase9=='Coin' ? v9x*samount9 : sbase9=='USD' or sbase9=='Other' ? (v9x*samount9)/ohlc4 : v9x
v10x = (i_sym10 ? f_volume(i_sym10_ticker) : 0) //FTX reported in usd
v10 = sbase10=='Coin' ? v10x*samount10 : sbase10=='USD' or sbase10=='Other' ? (v10x*samount10)/ohlc4 : v10x
v11x = (i_sym11 ? f_volume(i_sym11_ticker) : 0) //FTX reported in usd
v11 = sbase11=='Coin' ? v11x*samount11 : sbase11=='USD' or sbase11=='Other' ? (v11x*samount11)/ohlc4 : v11x
v12x = (i_sym12 ? f_volume(i_sym12_ticker) : 0)
v12 = sbase12=='Coin' ? v12x*samount12 : sbase12=='USD' or sbase12=='Other' ? (v12x*samount10)/ohlc4 : v12x
v13x = (i_sym13 ? f_volume(i_sym13_ticker) : 0)
v13 = sbase13=='Coin' ? v13x*samount13 : sbase13=='USD' or sbase13=='Other' ? (v13x*samount13)/ohlc4 : v13x
v14x = (i_sym14 ? f_volume(i_sym14_ticker) : 0)
v14 = sbase14=='Coin' ? v14x*samount14 : sbase14=='USD' or sbase14=='Other' ? (v14x*samount14)/ohlc4 : v14x
v15x = (i_sym15 ? f_volume(i_sym15_ticker) : 0)
v15 = sbase15=='Coin' ? v15x*samount15 : sbase15=='USD' or sbase15=='Other' ? (v15x*samount15)/ohlc4 : v15x
v16x = (i_sym16 ? f_volume(i_sym16_ticker) : 0)
v16 = sbase16=='Coin' ? v16x*samount16 : sbase16=='USD' or sbase16=='Other' ? (v16x*samount16)/ohlc4 : v16x
vsf=v1+v2+v3+v4+v5+v6+v7+v8+v9+v10+v11+v12+v13+v14+v15+v16
///////////////////////////////////////////////////////////////////////////////////
///////////////////////FUTURES////////////////////////////////////////////////////
v1bx = (i_sym1b ? f_volume(i_sym1b_ticker) : 0)
v1b = fbase1=='Coin' ? v1bx*famount1 : fbase1=='USD' or fbase1=='Other' ? (v1bx*famount1)/ohlc4 : v1bx
v2bx = (i_sym2b ? f_volume(i_sym2b_ticker) : 0)
v2b = fbase2=='Coin' ? v2bx*famount2 : fbase2=='USD' or fbase2=='Other' ? (v2bx*famount2)/ohlc4 : v2bx
v3bx = (i_sym3b ? f_volume(i_sym3b_ticker) : 0)
v3b = fbase3=='Coin' ? v3bx*famount3 : fbase3=='USD' or fbase3=='Other' ? (v3bx*famount3)/ohlc4 : v3bx
v4bx =(i_sym4b ? f_volume(i_sym4b_ticker) : 0) //CME NORMAL (each contract reported equals 5btc)
v4b = fbase4=='Coin' ? v4bx*famount4 : fbase4=='USD' or fbase4=='Other' ? (v4bx*famount4)/ohlc4 : v4bx
v5bx = (i_sym5b ? f_volume(i_sym5b_ticker) : 0)//CME NORMAL (each contract reported equals 5btc)
v5b = fbase5=='Coin' ? v5bx*famount5 : fbase5=='USD' or fbase5=='Other' ? (v5bx*famount5)/ohlc4 : v5bx
v6bx = (i_sym6b ? f_volume(i_sym6b_ticker) : 0)//CME mini (each contract reported equals 0.60btc)
v6b = fbase6=='Coin' ? v6bx*famount6 : fbase6=='USD' or fbase6=='Other' ? (v6bx*famount6)/ohlc4 : v6bx
v7bx = (i_sym7b ? f_volume(i_sym7b_ticker) : 0)//CME mini (each contract reported equals 0.7btc)
v7b = fbase7=='Coin' ? v7bx*famount7 : fbase7=='USD' or fbase7=='Other' ? (v7bx*famount7)/ohlc4 : v7bx
v8bx = (i_sym8b ? f_volume(i_sym8b_ticker) : 0)// PHEMEX reported in usd
v8b = fbase8=='Coin' ? v8bx*famount8 : fbase8=='USD' or fbase8=='Other' ? (v8bx*famount8)/ohlc4 : v8bx
v9bx = (i_sym9b ? f_volume(i_sym9b_ticker) : 0)// OKEX reported in 900xBTC, meaning every 900 contracts is only one
v9b = fbase9=='Coin' ? v9bx*famount9 : fbase9=='USD' or fbase9=='Other' ? (v9bx*famount9)/ohlc4 : v9bx
v10bx = (i_sym10b ? f_volume(i_sym10b_ticker) : 0)// BITMEX REPORTED IN 1 MILLION BTC, MEANING EACH MILLION CONTRACTS ON TV REPRESENT 1 BTC
v10b = fbase10=='Coin' ? v1bx*famount10 : fbase10=='USD' or fbase10=='Other' ? (v10bx*famount10)/ohlc4 : v10bx
v11bx = (i_sym11b ? f_volume(i_sym11b_ticker) : 0)// BITGET REPORTED IN USD - TURNED OFF BECAUSE DOESNT PROVIDE REAL TIME DATA
v11b = fbase11=='Coin' ? v11bx*famount11 : fbase11=='USD' or fbase11=='Other' ? (v11bx*famount11)/ohlc4 : v11bx
v12bx = (i_sym12b ? f_volume(i_sym12b_ticker) : 0)
v12b = fbase12=='Coin' ? v12bx*famount12 : fbase12=='USD' or fbase12=='Other' ? (v12bx*famount12)/ohlc4 : v12bx
vff=v1b+v2b+v3b+v4b+v5b+v6b+v7b+v8b+v9b+v10b+v11b+v12b
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////PERPS///////////////////////////////////////////////////////////
v1cx = (i_sym1c ? f_volume(i_sym1c_ticker) : 0)//BINANCE REPORTED IN BLOCKS OF 100 USD, MEANING EACH CONTRACT REPORTED IS EQUAL TO 100 USD
v1c = pbase1=='Coin' ? v1cx*pamount1 : pbase1=='USD' or pbase1=='Other' ? (v1cx*pamount1)/ohlc4 : v1cx
v2cx = (i_sym2c ? f_volume(i_sym2c_ticker) : 0)//OKEX REPORTED IN BLOCKS OF 100 USD, MEANING EACH CONTRACT REPORTED IS EQUAL TO 100 USD
v2c = pbase2=='Coin' ? v2cx*pamount2 : pbase2=='USD' or pbase2=='Other' ? (v2cx*pamount2)/ohlc4 : v2cx
v3cx = (i_sym3c ? f_volume(i_sym3c_ticker) : 0)// HUOBI REPORTED IN BTC
v3c = pbase3=='Coin' ? v3cx*pamount3 : pbase3=='USD' or pbase3=='Other' ? (v3cx*pamount3)/ohlc4 : v3cx
v4cx =(i_sym4c ? f_volume(i_sym4c_ticker) : 0)// PHEMEX REPORTED IN USD
v4c = pbase4=='Coin' ? v4cx*pamount4 : pbase4=='USD' or pbase4=='Other' ? (v4cx*pamount4)/ohlc4 : v4cx
v5cx = (i_sym5c ? f_volume(i_sym5c_ticker) : 0)// FTX REPORTED IN USD
v5c = pbase5=='Coin' ? v5cx*pamount5 : pbase5=='USD' or pbase5=='Other' ? (v5cx*pamount5)/ohlc4 : v5cx
v6cx = (i_sym6c ? f_volume(i_sym6c_ticker) : 0)//BYBIT REPORTED IN USD
v6c = pbase6=='Coin' ? v6cx*pamount6 : pbase6=='USD' or pbase6=='Other' ? (v6cx*pamount6)/ohlc4 : v6cx
v7cx = (i_sym7c ? f_volume(i_sym7c_ticker) : 0)//DERIBIT REPORTED IN USD
v7c = pbase7=='Coin' ? v7cx*pamount7 : pbase7=='USD' or pbase7=='Other' ? (v7cx*pamount7)/ohlc4 : v7cx
v8cx = (i_sym8c ? f_volume(i_sym8c_ticker) : 0)//BITMEX REPORTED IN USD
v8c = pbase8=='Coin' ? v8cx*pamount8 : pbase8=='USD' or pbase8=='Other' ? (v8cx*pamount8)/ohlc4 : v8cx
vpf=v1c+v2c+v3c+v4c+v5c+v6c+v7c+v8c
//////////////////////////////////////////////////////////////////////////////////////
////////////////////ALL DERIV VOLUME//////////////////////////////////////////////////////////////////
alldvol = vff + vpf
/////////////////////////////////////////////////////////////////////////////////////////
////////////////////ALL VOLUME//////////////////////////////////////////////////////////////////
allvol = vsf + vff + vpf
/////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////FINAL AGGREGATION SELECTION/////////////////////////////////////////
if markettype == 'Spot'
finvol := vsf
finvol
else if markettype == 'Futures'
finvol := vff
finvol
else if markettype == 'Perp'
finvol := vpf
finvol
else if markettype == 'Derivatives F+P'
finvol := alldvol
finvol
else if markettype == 'Spot+Derivs'
finvol := allvol
finvol
/////////////////////////////////////////////////////////////////////////////////////////////////
else if aggr==false
finvol := volume
///////////////////////////////////////////////////////////////////////////////////
palette = open > close ? color.red : color.green
plot(finvol, color=palette, style=plot.style_columns, linewidth=3, title='Volume')
/////////////////MA//////////////////////////////////////
plot(addma ? ta.sma(finvol,malen): na, title='Moving Average')
|
Multi Timeframe Moving Averages | https://www.tradingview.com/script/nFs56VUZ/ | Limonetti | https://www.tradingview.com/u/Limonetti/ | 87 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © pripalda
//@version=5
//Thanks and refferences:
//This script includes code from other tradingview community users. I'd like to thank and mention them abobe:
//User Frien_dd-DisDev (https://es.tradingview.com/u/Frien_dd-DisDev/)
//https://es.tradingview.com/script/MPZkvXfR-Chart-Champions-Part-1-nPOC-Levels-VWAPs/
indicator(title='Multi Timeframe Moving Averages', shorttitle='MTF MAs', overlay=true)
////////////////////////////////////////////////// Inputs
//Inputs - Moving Averages General Configuration
lenFastEMA = input(20, 'Length', inline='Fast', group='Fast Moving Average (EMA) Configuration:')
srcFastEMA = input(close, 'Source', inline='Fast', group='Fast Moving Average (EMA) Configuration:')
colorFastEMA = input.color(color.white, title='Color', inline='Fast', group='Fast Moving Average (EMA) Configuration:')
showCTFastEMA = input(title='Show on All Timeframes', defval=true, inline='Fast', group='Fast Moving Average (EMA) Configuration:')
lenMidSMA = input(50, 'Length ', inline='Mid', group='Middle Moving Average (SMA) Configuration:')
srcMidSMA = input(close, 'Source', inline='Mid', group='Middle Moving Average (SMA) Configuration:')
colorMidSMA = input.color(color.yellow, title='Color', inline='Mid', group='Middle Moving Average (SMA) Configuration:')
showCTMidSMA = input(title='Show on All Timeframes ', defval=true, inline='Mid', group='Middle Moving Average (SMA) Configuration:')
lenSlowSMA = input(200, 'Length', inline='Slow', group='Slow Moving Average (SMA) Configuration:')
srcSlowSMA = input(close, 'Source', inline='Slow', group='Slow Moving Average (SMA) Configuration:')
colorSlowSMA = input.color(color.red, title='Color', inline='Slow', group='Slow Moving Average (SMA) Configuration:')
showCTSlowSMA = input(title='Show on All Timeframes', defval=true, inline='Slow', group='Slow Moving Average (SMA) Configuration:')
colorVWAP = input.color(color.aqua, title='Color', inline='VWAP', group='Daily VWAP Configuration:')
showVWAP = input(title='Show on All Timeframes', defval=true, inline='VWAP', group='Daily VWAP Configuration:')
history_VWAP = input(title='Show History', defval=true, inline='VWAP', group='Daily VWAP Configuration:')
//Inputs - Select options for PDC VWAP
colorpdVWAP = input.color(color.fuchsia, title='Color', inline='pdVWAP', group='Previous Day VWAP Close Configuration:')
showpdVWAP = input(title='Show on All Timeframes', defval=true, inline='pdVWAP', group='Previous Day VWAP Close Configuration:')
history_pdVWAP = input(title='Show History', defval=false, inline='pdVWAP', group='Previous Day VWAP Close Configuration:')
//Assign Length and Source from general configuration to all timeframe
//In case we want to config one by one use the code comented
lenOHFastEMA = lenFastEMA//input(20, 'EMA #1 FH Length')
srcOHFastEMA = srcFastEMA//input(close, 'Source')
lenOHMidSMA = lenMidSMA//input(50, 'MA1 FH Length')
srcOHMidSMA = srcMidSMA//input(close, 'Source')
lenOHSlowSMA = lenSlowSMA//input(200, 'MA2 FH Length')
srcOHSlowSMA = srcSlowSMA//input(close, 'Source')
lenFHFastEMA = lenFastEMA//input(20, 'EMA #1 FH Length')
srcFHFastEMA = srcFastEMA//input(close, 'Source')
lenFHMidSMA = lenMidSMA//input(50, 'MA1 FH Length')
srcFHMidSMA = srcMidSMA//input(close, 'Source')
lenFHSlowSMA = lenSlowSMA//input(200, 'MA2 FH Length')
srcFHSlowSMA = srcSlowSMA//input(close, 'Source')
lenDFastEMA = lenFastEMA//input(20, 'EMA1 D Length')
srcDFastEMA = srcFastEMA//input(close, 'Source')
lenDMidSMA = lenMidSMA//input(50, 'MA1 D Length')
srcDMidSMA = srcMidSMA//input(close, 'Source')
lenDSlowSMA = lenSlowSMA//input(200, 'MA2 D Length')
srcDSlowSMA = srcSlowSMA//input(close, 'Source')
lenWFastEMA = lenFastEMA//input(20, 'EMA1 W Length')
srcWFastEMA = srcFastEMA//input(close, 'Source')
lenWMidSMA = lenMidSMA//input(50, 'MA1 W Length')
srcWMidSMA = srcMidSMA//input(close, 'Source')
lenWSlowSMA = lenSlowSMA//input(200, 'MA2 W Length')
srcWSlowSMA = srcSlowSMA//input(close, 'Source')
lenMFastEMA = lenFastEMA//input(20, 'EMA1 M Length')
srcMFastEMA = srcFastEMA//input(close, 'Source')
lenMMidSMA = lenMidSMA//input(50, 'MA1 M Length')
srcMMidSMA = srcMidSMA//input(close, 'Source')
lenMSlowSMA = lenSlowSMA//input(200, 'MA2 M Length')
srcMSlowSMA = srcSlowSMA//input(close, 'Source')
//Inputs - Select and options for 1h Fast
showOHFastEMA = input(title='Show Fast EMA', defval=true, inline='OHFast', group='Configure 1 Hour:')
//track_OHFastEMA = input(title='Extend to the left', defval=false, inline='OHFast', group='Configure 1 Hour:')
history_OHFastEMA = input(title='Show History', defval=false, inline='OHFast', group='Configure 1 Hour:')
//Inputs - Select and options for 1h Mid
showOHMidSMA = input(title='Show Mid SMA ', defval=true, inline='OHMid', group='Configure 1 Hour:')
//track_OHMidSMA = input(title='Extend to the left', defval=false, inline='OHMid', group='Configure 1 Hour:')
history_OHMidSMA = input(title='Show History', defval=false, inline='OHMid', group='Configure 1 Hour:')
//Inputs - Select and options for 1h Slow
showOHSlowSMA = input(title='Show Slow SMA', defval=true, inline='OHSlow', group='Configure 1 Hour:')
//track_OHSlowSMA = input(title='Extend to the left', defval=false, inline='OHSlow', group='Configure 1 Hour:')
history_OHSlowSMA = input(title='Show History', defval=false, inline='OHSlow', group='Configure 1 Hour:')
//Inputs - Select and options for 4h Fast
showFHFastEMA = input(title='Show Fast EMA', defval=true, inline='FHFast', group='Configure 4 Hour:')
//track_FHFastEMA = input(title='Extend to the left', defval=false, inline='FHFast', group='Configure 4 Hour:')
history_FHFastEMA = input(title='Show History', defval=false, inline='FHFast', group='Configure 4 Hour:')
//Inputs - Select and options for 4h Mid
showFHMidSMA = input(title='Show Mid SMA ', defval=true, inline='FHMid', group='Configure 4 Hour:')
//track_FHMidSMA = input(title='Extend to the left', defval=false, inline='FHMid', group='Configure 4 Hour:')
history_FHMidSMA = input(title='Show History', defval=false, inline='FHMid', group='Configure 4 Hour:')
//Inputs - Select and options for 4h Slow
showFHSlowSMA = input(title='Show Slow SMA', defval=true, inline='FHSlow', group='Configure 4 Hour:')
//track_FHSlowSMA = input(title='Extend to the left', defval=false, inline='FHSlow', group='Configure 4 Hour:')
history_FHSlowSMA = input(title='Show History', defval=false, inline='FHSlow', group='Configure 4 Hour:')
//Inputs - Select and options for D Fast
showDFastEMA = input(title='Show Fast EMA', defval=true, inline='DFast', group='Configure Daily:')
//track_DFastEMA = input(title='Extend to the left', defval=false, inline='DFast', group='Configure Daily:')
history_DFastEMA = input(title='Show History', defval=false, inline='DFast', group='Configure Daily:')
//Inputs - Select and options for D Mid
showDMidSMA = input(title='Show Mid SMA ', defval=true, inline='DMid', group='Configure Daily:')
//track_DMidSMA = input(title='Extend to the left', defval=false, inline='DMid', group='Configure Daily:')
history_DMidSMA = input(title='Show History', defval=false, inline='DMid', group='Configure Daily:')
//Inputs - Select and options for D Slow
showDSlowSMA = input(title='Show Slow SMA', defval=true, inline='DSlow', group='Configure Daily:')
//track_DSlowSMA = input(title='Extend to the left', defval=false, inline='DSlow', group='Configure Daily:')
history_DSlowSMA = input(title='Show History', defval=false, inline='DSlow', group='Configure Daily:')
//Inputs - Select and options for W Fast
showWFastEMA = input(title='Show Fast EMA', defval=true, inline='WFast', group='Configure Weekly:')
//track_WFastEMA = input(title='Extend to the left', defval=false, inline='WFast', group='Configure Weekly:')
history_WFastEMA = input(title='Show History', defval=false, inline='WFast', group='Configure Weekly:')
//Inputs - Select and options for W Mid
showWMidSMA = input(title='Show Mid SMA ', defval=true, inline='WMid', group='Configure Weekly:')
//track_WMidSMA = input(title='Extend to the left', defval=false, inline='WMid', group='Configure Weekly:')
history_WMidSMA = input(title='Show History', defval=false, inline='WMid', group='Configure Weekly:')
//Inputs - Select and options for W Slow
showWSlowSMA = input(title='Show Slow SMA', defval=true, inline='WSlow', group='Configure Weekly:')
//track_WSlowSMA = input(title='Extend to the left', defval=false, inline='WSlow', group='Configure Weekly:')
history_WSlowSMA = input(title='Show History', defval=false, inline='WSlow', group='Configure Weekly:')
//Inputs - Select and options for M Fast
showMFastEMA = input(title='Show Fast EMA', defval=true, inline='MFast', group='Configure Monthly:')
//track_MFastEMA = input(title='Extend to the left', defval=false, inline='MFast', group='Configure Monthly:')
history_MFastEMA = input(title='Show History', defval=false, inline='MFast', group='Configure Monthly:')
//Inputs - Select and options for M Mid
showMMidSMA = input(title='Show Mid SMA ', defval=true, inline='MMid', group='Configure Monthly:')
//track_MMidSMA = input(title='Extend to the left', defval=false, inline='MMid', group='Configure Monthly:')
history_MMidSMA = input(title='Show History', defval=false, inline='MMid', group='Configure Monthly:')
//Inputs - Select and options for M Slow
showMSlowSMA = input(title='Show Slow SMA', defval=true, inline='MSlow', group='Configure Monthly:')
//track_MSlowSMA = input(title='Extend to the left', defval=false, inline='MSlow', group='Configure Monthly:')
history_MSlowSMA = input(title='Show History', defval=false, inline='MSlow', group='Configure Monthly:')
//Inputs - Labels configuration
showlabels = input(title='Show Labels', defval=true, group='Labels Configuration:')
ext_labels = input(title='Use Extended Text Labels', defval=false, group='Labels Configuration:')
popup_label = input(title='Show current MA price Pop Up when mouse is over label', defval=true, group='Labels Configuration:')
offset_label = input(title='Label Offset', defval=15, group='Labels Configuration:')
offset_line = input(title='Dashed Line before label Offset', defval=1, group='Labels Configuration:')
//Create the input with pull-down menu
styleOption = input.string(title="Labels Style",
options=["Triangle up (▲)", "Triangle down (▼)",
"Arrow up (↑)", "Arrow down (↓)", "Label Center", "Label up (⬆)",
"Label down (⬇)", "Label left (⬇)", "Label right (⬇)",
"Label upper left (⬇)", "Label upper right (⬇)",
"Label lower left (⬇)", "Label lower right (⬇)", "Plus (+)",
"Cross (⨯)", "Circle (●)", "Diamond (◆)", "Flag (⚑)",
"Square (■)", "None"],
defval="Label left (⬇)", group='Labels Configuration:')
sizeOption = input.string(title="Labels Size",
options=["Auto", "Tiny", "Small", "Normal", "Large",
"Huge"], defval="Normal", group='Labels Configuration:')
//Turn the input into a proper label style value
labelStyle = (styleOption == "Triangle up (▲)") ? label.style_triangleup :
(styleOption == "Triangle down (▼)") ? label.style_triangledown :
(styleOption == "Arrow up (↑)") ? label.style_arrowup :
(styleOption == "Arrow down (↓)") ? label.style_arrowdown :
(styleOption == "Label Center") ? label.style_label_center :
(styleOption == "Label up (⬆)") ? label.style_label_up :
(styleOption == "Label down (⬇)") ? label.style_label_down :
(styleOption == "Label left (⬇)") ? label.style_label_left :
(styleOption == "Label right (⬇)") ? label.style_label_right :
(styleOption == "Label upper left (⬇)") ? label.style_label_upper_left :
(styleOption == "Label upper right (⬇)") ? label.style_label_upper_right :
(styleOption == "Label lower left (⬇)") ? label.style_label_lower_left :
(styleOption == "Label lower right (⬇)") ? label.style_label_lower_right :
(styleOption == "Plus (+)") ? label.style_cross:
(styleOption == "Cross (⨯)") ? label.style_xcross :
(styleOption == "Circle (●)") ? label.style_circle :
(styleOption == "Diamond (◆)") ? label.style_diamond :
(styleOption == "Flag (⚑)") ? label.style_flag :
(styleOption == "Square (■)") ? label.style_square :
(styleOption == "None") ? label.style_none :
label.style_none
//Turn the input into a proper label style value
labelSize = (sizeOption == "Auto") ? size.auto :
(sizeOption == "Tiny") ? size.tiny :
(sizeOption == "Small") ? size.small :
(sizeOption == "Normal") ? size.normal :
(sizeOption == "Large") ? size.large :
(sizeOption == "Huge") ? size.huge :
size.normal
////////////////////////////////////////////////// VWAP
//Calculate if it is the current day. We´ll use this var later as a condition for plotting the VWAP and pdVWAP
//Taken from "Chart Champions - Part 1 - nPOC - Levels - VWAPs" script writen by user Frien_dd-DisDev
is_today = year == year(timenow) and month == month(timenow) and dayofmonth == dayofmonth(timenow)
///VWAP rounding issue resolution
//Taken from "Chart Champions - Part 1 - nPOC - Levels - VWAPs" script writen by user Frien_dd-DisDev
f_round_up_to_tick(x, mintick) =>
mult = 1 / mintick
value = math.ceil(x * mult) / mult
value
f_round_down_to_tick(x, mintick) =>
mult = 1 / mintick
value = math.floor(x * mult) / mult
value
//Daily VWAP
//Taken from "Chart Champions - Part 1 - nPOC - Levels - VWAPs" script writen by user Frien_dd-DisDev
roundedVWAP = f_round_up_to_tick(ta.vwap, syminfo.mintick)
VWAP = roundedVWAP
//Previous Day's Closing Vwap
//Taken from "Chart Champions - Part 1 - nPOC - Levels - VWAPs" script writen by user Frien_dd-DisDev
newday(res) =>
t = time(res)
ta.change(t) != 0 ? 1 : 0
new_day = newday('D')
pdVWAP = request.security(syminfo.tickerid, '1', ta.valuewhen(new_day, VWAP[1], 0))
////////////////////////////////////////////////// Moving Averages
//Calculate Moving Averages for each timeframe
//Current Time
CTFastEMA = ta.ema(srcFastEMA, lenFastEMA)
CTMidSMA = ta.sma(srcMidSMA, lenMidSMA)
CTSlowSMA = ta.sma(srcSlowSMA, lenSlowSMA)
//1 Hour
OHFastEMA = request.security(syminfo.tickerid, '60', ta.ema(srcOHFastEMA, lenOHFastEMA))
OHMidSMA = request.security(syminfo.tickerid, '60', ta.sma(srcOHMidSMA, lenOHMidSMA))
OHSlowSMA = request.security(syminfo.tickerid, '60', ta.sma(srcOHSlowSMA, lenOHSlowSMA))
//4 Hours
FHFastEMA = request.security(syminfo.tickerid, '240', ta.ema(srcFHFastEMA, lenFHFastEMA))
FHMidSMA = request.security(syminfo.tickerid, '240', ta.sma(srcFHMidSMA, lenFHMidSMA))
FHSlowSMA = request.security(syminfo.tickerid, '240', ta.sma(srcFHSlowSMA, lenFHSlowSMA))
//Daily
DFastEMA = request.security(syminfo.tickerid, 'D', ta.ema(srcDFastEMA, lenDFastEMA))
DMidSMA = request.security(syminfo.tickerid, 'D', ta.sma(srcDMidSMA, lenDMidSMA))
DSlowSMA = request.security(syminfo.tickerid, 'D', ta.sma(srcDSlowSMA, lenDSlowSMA))
//Weekly
WFastEMA = request.security(syminfo.tickerid, 'W', ta.ema(srcWFastEMA, lenWFastEMA))
WMidSMA = request.security(syminfo.tickerid, 'W', ta.sma(srcWMidSMA, lenWMidSMA))
WSlowSMA = request.security(syminfo.tickerid, 'W', ta.sma(srcWSlowSMA, lenWSlowSMA))
//Monthly
MFastEMA = request.security(syminfo.tickerid, 'M', ta.ema(srcMFastEMA, lenMFastEMA))
MMidSMA = request.security(syminfo.tickerid, 'M', ta.sma(srcMMidSMA, lenMMidSMA))
MSlowSMA = request.security(syminfo.tickerid, 'M', ta.sma(srcMSlowSMA, lenMSlowSMA))
////////////////////////////////////////////////// Plot labels
//Create Current Timeframe-based Moving Averages labels (uncomment if you want to see labels on current timeframe)
//CTFastEMA_label = showlabels and showCTFastEMA ? label.new(x=bar_index+offset_label, y=CTFastEMA, text = ext_labels ? "Fast EMA " + str.tostring(lenFastEMA) + " (1 Hour)" : "1h EMA " + str.tostring(lenFastEMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 50), style=labelStyle, textcolor=color.new(color.white, 0), size=labelSize, tooltip = popup_label ? str.tostring(CTFastEMA, "#.##") : "") :na
//label.delete(CTFastEMA_label[1])
//CTMidSMA_label = showlabels and showCTMidSMA ? label.new(x=bar_index+offset_label, y=CTMidSMA, text = ext_labels ? "Mid SMA " + str.tostring(lenMidSMA) + " (1 Hour)" : "1h SMA " + str.tostring(lenMidSMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 50), style=labelStyle, textcolor=color.new(color.white, 0), size=labelSize, tooltip = popup_label ? str.tostring(CTMidSMA, "#.##") : "") :na
//label.delete(CTMidSMA_label[1])
//CTSlowSMA_label = showlabels and showCTSlowSMA ? label.new(x=bar_index+offset_label, y=CTSlowSMA, text = ext_labels ? "Slow SMA " + str.tostring(lenSlowSMA) + " (1 Hour)" : "1h SMA " + str.tostring(lenSlowSMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 50), style=labelStyle, textcolor=color.new(color.white, 0), size=labelSize, tooltip = popup_label ? str.tostring(CTSlowSMA, "#.##") : "") :na
//label.delete(CTSlowSMA_label[1])
//Create 1 Hour labels
OHFastEMA_label = showlabels and showOHFastEMA and (timeframe.period != '60') ? label.new(x=bar_index+offset_label, y=OHFastEMA, text = ext_labels ? "Fast EMA " + str.tostring(lenOHFastEMA) + " (1 Hour)" : "1h EMA " + str.tostring(lenOHFastEMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorFastEMA, size=labelSize, tooltip = popup_label ? str.tostring(OHFastEMA, "#.##") : "") :na
label.delete(OHFastEMA_label[1])
OHMidSMA_label = showlabels and showOHMidSMA and (timeframe.period != '60') ? label.new(x=bar_index+offset_label, y=OHMidSMA, text = ext_labels ? "Mid SMA " + str.tostring(lenOHMidSMA) + " (1 Hour)" : "1h SMA " + str.tostring(lenOHMidSMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorMidSMA, size=labelSize, tooltip = popup_label ? str.tostring(OHMidSMA, "#.##") : "") :na
label.delete(OHMidSMA_label[1])
OHSlowSMA_label = showlabels and showOHSlowSMA and (timeframe.period != '60') ? label.new(x=bar_index+offset_label, y=OHSlowSMA, text = ext_labels ? "Slow SMA " + str.tostring(lenOHSlowSMA) + " (1 Hour)" : "1h SMA " + str.tostring(lenOHSlowSMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorSlowSMA, size=labelSize, tooltip = popup_label ? str.tostring(OHSlowSMA, "#.##") : "") :na
label.delete(OHSlowSMA_label[1])
//Create 4 Hours labels
FHFastEMA_label = showlabels and showFHFastEMA and (timeframe.period != '240') ? label.new(x=bar_index+offset_label, y=FHFastEMA, text = ext_labels ? "Fast EMA " + str.tostring(lenFHFastEMA) + " (4 Hours)" : "4h EMA " + str.tostring(lenFHFastEMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorFastEMA, size=labelSize, tooltip = popup_label ? str.tostring(FHFastEMA, "#.##") : "") :na
label.delete(FHFastEMA_label[1])
FHMidSMA_label = showlabels and showFHMidSMA and (timeframe.period != '240') ? label.new(x=bar_index+offset_label, y=FHMidSMA, text = ext_labels ? "Mid SMA " + str.tostring(lenFHMidSMA) + " (4 Hours)" : "4h SMA " + str.tostring(lenFHMidSMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorMidSMA, size=labelSize, tooltip = popup_label ? str.tostring(FHMidSMA, "#.##") : "") :na
label.delete(FHMidSMA_label[1])
FHSlowSMA_label = showlabels and showFHSlowSMA and (timeframe.period != '240') ? label.new(x=bar_index+offset_label, y=FHSlowSMA, text = ext_labels ? "Slow SMA " + str.tostring(lenFHSlowSMA) + " (4 Hours)" : "4h SMA " + str.tostring(lenFHSlowSMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorSlowSMA, size=labelSize, tooltip = popup_label ? str.tostring(FHSlowSMA, "#.##") : "") :na
label.delete(FHSlowSMA_label[1])
//Create Daily labels
DFastEMA_label = showlabels and showDFastEMA and (timeframe.period != 'D') ? label.new(x=bar_index+offset_label, y=DFastEMA, text = ext_labels ? "Fast EMA " + str.tostring(lenDFastEMA) + " (Daily)" : "D EMA " + str.tostring(lenDFastEMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorFastEMA, size=labelSize, tooltip = popup_label ? str.tostring(DFastEMA, "#.##") : "") :na
label.delete(DFastEMA_label[1])
DMidSMA_label = showlabels and showDMidSMA and (timeframe.period != 'D') ? label.new(x=bar_index+offset_label, y=DMidSMA, text = ext_labels ? "Mid SMA " + str.tostring(lenDMidSMA) + " (Daily)" : "D SMA " + str.tostring(lenDMidSMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorMidSMA, size=labelSize, tooltip = popup_label ? str.tostring(DMidSMA, "#.##") : "") :na
label.delete(DMidSMA_label[1])
DSlowSMA_label = showlabels and showDSlowSMA and (timeframe.period != 'D') ? label.new(x=bar_index+offset_label, y=DSlowSMA, text = ext_labels ? "Slow SMA " + str.tostring(lenDSlowSMA) + " (Daily)" : "D SMA " + str.tostring(lenDSlowSMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorSlowSMA, size=labelSize, tooltip = popup_label ? str.tostring(DSlowSMA, "#.##") : "") :na
label.delete(DSlowSMA_label[1])
//Create Weekly labels
WFastEMA_label = showlabels and showWFastEMA and (timeframe.period != 'W') ? label.new(x=bar_index+offset_label, y=WFastEMA, text = ext_labels ? "Fast EMA " + str.tostring(lenWFastEMA) + " (Weekly)" : "W EMA " + str.tostring(lenWFastEMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorFastEMA, size=labelSize, tooltip = popup_label ? str.tostring(WFastEMA, "#.##") : "") :na
label.delete(WFastEMA_label[1])
WMidSMA_label = showlabels and showWMidSMA and (timeframe.period != 'W') ? label.new(x=bar_index+offset_label, y=WMidSMA, text = ext_labels ? "Mid SMA " + str.tostring(lenWMidSMA) + " (Weekly)" : "W SMA " + str.tostring(lenWMidSMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorMidSMA, size=labelSize, tooltip = popup_label ? str.tostring(WMidSMA, "#.##") : "") :na
label.delete(WMidSMA_label[1])
WSlowSMA_label = showlabels and showWSlowSMA and (timeframe.period != 'W') ? label.new(x=bar_index+offset_label, y=WSlowSMA, text = ext_labels ? "Slow SMA " + str.tostring(lenWSlowSMA) + " (Weekly)" : "W SMA " + str.tostring(lenWSlowSMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorSlowSMA, size=labelSize, tooltip = popup_label ? str.tostring(WSlowSMA, "#.##") : "") :na
label.delete(WSlowSMA_label[1])
//Create Monthly labels
MFastEMA_label = showlabels and showMFastEMA and (timeframe.period != 'M') ? label.new(x=bar_index+offset_label, y=MFastEMA, text = ext_labels ? "Fast EMA " + str.tostring(lenMFastEMA) + " (Monthly)" : "M EMA " + str.tostring(lenMFastEMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorFastEMA, size=labelSize, tooltip = popup_label ? str.tostring(MFastEMA, "#.##") : "") :na
label.delete(MFastEMA_label[1])
MMidSMA_label = showlabels and showMMidSMA and (timeframe.period != 'M') ? label.new(x=bar_index+offset_label, y=MMidSMA, text = ext_labels ? "Mid SMA " + str.tostring(lenMMidSMA) + " (Monthly)" : "M SMA " + str.tostring(lenMMidSMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorMidSMA, size=labelSize, tooltip = popup_label ? str.tostring(MMidSMA, "#.##") : "") :na
label.delete(MMidSMA_label[1])
MSlowSMA_label = showlabels and showMSlowSMA and (timeframe.period != 'M') ? label.new(x=bar_index+offset_label, y=MSlowSMA, text = ext_labels ? "Slow SMA " + str.tostring(lenMSlowSMA) + " (Monthly)" : "M SMA " + str.tostring(lenMSlowSMA), xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorSlowSMA, size=labelSize, tooltip = popup_label ? str.tostring(MSlowSMA, "#.##") : "") :na
label.delete(MSlowSMA_label[1])
//Create VWAP labels
VWAP_label = showlabels and showVWAP ? label.new(x=bar_index+offset_label, y=VWAP, text = ext_labels ? "VWAP (Daily)" : "D VWAP", xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorVWAP, size=labelSize, tooltip = popup_label ? str.tostring(VWAP, "#.##") : "") :na
label.delete(VWAP_label[1])
pdVWAP_label = showlabels and showpdVWAP ? label.new(x=bar_index+offset_label, y=pdVWAP, text = ext_labels ? "Previous Day Close VWAP (Daily)" : "PDC VWAP", xloc=xloc.bar_index, yloc=yloc.price, color=color.new(#2066D5, 100), style=labelStyle, textcolor=colorpdVWAP, size=labelSize, tooltip = popup_label ? str.tostring(pdVWAP, "#.##") : "") :na
label.delete(pdVWAP_label[1])
//Create Current Timeframe-based Moving Averages lines (uncomment if you want to see lines on current timeframe)
//CTFastEMA_line = showCTFastEMA ? line.new(x1=bar_index+offset_line, y1=CTFastEMA, x2=bar_index+offset_label, y2=CTFastEMA, xloc=xloc.bar_index, style=line.style_dashed, extend=track_CTFastEMA ? extend.left : extend.none, color=color.white) :na
//line.delete(CTFastEMA_line[1]) // remove the previous line when new bar appears
//CTMidSMA_line = showCTMidSMA ?line.new(x1=bar_index+offset_line, y1=CTMidSMA, x2=bar_index+offset_label, y2=CTMidSMA, xloc=xloc.bar_index, style=line.style_dashed, extend=track_CTMidSMA ? extend.left : extend.none, color=color.yellow) :na
//line.delete(CTMidSMA_line[1]) // remove the previous line when new bar appears
//CTSlowSMA_line = showCTSlowSMA ?line.new(x1=bar_index+offset_line, y1=CTSlowSMA, x2=bar_index+offset_label, y2=CTSlowSMA, xloc=xloc.bar_index, style=line.style_dashed, extend=track_CTSlowSMA ? extend.left : extend.none, color=color.red) :na
//line.delete(CTSlowSMA_line[1]) // remove the previous line when new bar appears
//Create 1 Hour lines
OHFastEMA_line = showOHFastEMA and (timeframe.period != '60') ? line.new(x1=bar_index+offset_line, y1=OHFastEMA, x2=bar_index+offset_label, y2=OHFastEMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorFastEMA) :na
line.delete(OHFastEMA_line[1]) // remove the previous line when new bar appears
OHMidSMA_line = showOHMidSMA and (timeframe.period != '60') ? line.new(x1=bar_index+offset_line, y1=OHMidSMA, x2=bar_index+offset_label, y2=OHMidSMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorMidSMA) :na
line.delete(OHMidSMA_line[1]) // remove the previous line when new bar appears
OHSlowSMA_line = showOHSlowSMA and (timeframe.period != '60') ? line.new(x1=bar_index+offset_line, y1=OHSlowSMA, x2=bar_index+offset_label, y2=OHSlowSMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorSlowSMA) :na
line.delete(OHSlowSMA_line[1]) // remove the previous line when new bar appears
//Create 4 Hours lines
FHFastEMA_line = showFHFastEMA and (timeframe.period != '240') ? line.new(x1=bar_index+offset_line, y1=FHFastEMA, x2=bar_index+offset_label, y2=FHFastEMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorFastEMA) :na
line.delete(FHFastEMA_line[1]) // remove the previous line when new bar appears
FHMidSMA_line = showFHMidSMA and (timeframe.period != '240') ?line.new(x1=bar_index+offset_line, y1=FHMidSMA, x2=bar_index+offset_label, y2=FHMidSMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorMidSMA) :na
line.delete(FHMidSMA_line[1]) // remove the previous line when new bar appears
FHSlowSMA_line = showFHSlowSMA and (timeframe.period != '240') ?line.new(x1=bar_index+offset_line, y1=FHSlowSMA, x2=bar_index+offset_label, y2=FHSlowSMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorSlowSMA) :na
line.delete(FHSlowSMA_line[1]) // remove the previous line when new bar appears
//Create Daily lines
DFastEMA_line = showDFastEMA and (timeframe.period != 'D') ? line.new(x1=bar_index+offset_line, y1=DFastEMA, x2=bar_index+offset_label, y2=DFastEMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorFastEMA) :na
line.delete(DFastEMA_line[1]) // remove the previous line when new bar appears
DMidSMA_line = showDMidSMA and (timeframe.period != 'D') ? line.new(x1=bar_index+offset_line, y1=DMidSMA, x2=bar_index+offset_label, y2=DMidSMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorMidSMA) :na
line.delete(DMidSMA_line[1]) // remove the previous line when new bar appears
DSlowSMA_line = showDSlowSMA and (timeframe.period != 'D') ? line.new(x1=bar_index+offset_line, y1=DSlowSMA, x2=bar_index+offset_label, y2=DSlowSMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorSlowSMA) :na
line.delete(DSlowSMA_line[1]) // remove the previous line when new bar appears
//Create Weekly lines
WFastEMA_line = showWFastEMA and (timeframe.period != 'W') ? line.new(x1=bar_index+offset_line, y1=WFastEMA, x2=bar_index+offset_label, y2=WFastEMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorFastEMA) :na
line.delete(WFastEMA_line[1]) // remove the previous line when new bar appears
WMidSMA_line = showWMidSMA and (timeframe.period != 'W')? line.new(x1=bar_index+offset_line, y1=WMidSMA, x2=bar_index+offset_label, y2=WMidSMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorMidSMA) :na
line.delete(WMidSMA_line[1]) // remove the previous line when new bar appears
WSlowSMA_line = showWSlowSMA and (timeframe.period != 'W') ? line.new(x1=bar_index+offset_line, y1=WSlowSMA, x2=bar_index+offset_label, y2=WSlowSMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorSlowSMA) :na
line.delete(WSlowSMA_line[1]) // remove the previous line when new bar appears
//Create Monthly lines
MFastEMA_line = showMFastEMA and (timeframe.period != 'M') ? line.new(x1=bar_index+offset_line, y1=MFastEMA, x2=bar_index+offset_label, y2=MFastEMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorFastEMA) :na
line.delete(MFastEMA_line[1]) // remove the previous line when new bar appears
MMidSMA_line = showMMidSMA and (timeframe.period != 'M') ? line.new(x1=bar_index+offset_line, y1=MMidSMA, x2=bar_index+offset_label, y2=MMidSMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorMidSMA) :na
line.delete(MMidSMA_line[1]) // remove the previous line when new bar appears
MSlowSMA_line = showMSlowSMA and (timeframe.period != 'M') ? line.new(x1=bar_index+offset_line, y1=MSlowSMA, x2=bar_index+offset_label, y2=MSlowSMA, xloc=xloc.bar_index, style=line.style_dashed, color=colorSlowSMA) :na
line.delete(MSlowSMA_line[1]) // remove the previous line when new bar appeana
//Create VWAP lines
VWAP_line = showVWAP ? line.new(x1=bar_index+offset_line, y1=VWAP, x2=bar_index+offset_label, y2=VWAP, xloc=xloc.bar_index, style=line.style_dashed, color=colorVWAP) :na
line.delete(VWAP_line[1]) // remove the previous line when new bar appeana
pdVWAP_line = showpdVWAP ? line.new(x1=bar_index+offset_line, y1=pdVWAP, x2=bar_index+offset_label, y2=pdVWAP, xloc=xloc.bar_index, style=line.style_dashed, color=colorpdVWAP) :na
line.delete(pdVWAP_line[1]) // remove the previous line when new bar appeana
////////////////////////////////////////////////// Plot Moving Averages
//Plot current timeframe-based Moving Averages
plot(showCTFastEMA ? CTFastEMA : na, title='Current timeframe Fast EMA', style=plot.style_line, color=colorFastEMA, linewidth=2)
plot(showCTMidSMA ? CTMidSMA : na, title='Current timeframe Mid SMA', style=plot.style_line, color=color.new(color.yellow, 0), linewidth=2)
plot(showCTSlowSMA ? CTSlowSMA : na, title='Current timeframe Slow SMA', style=plot.style_line, color=colorSlowSMA, linewidth=2)
//Plot 1 Hour Moving Averages
plot(showOHFastEMA and history_OHFastEMA and (timeframe.period != '60') ? OHFastEMA : na, title='1 Hour Fast EMA', style=plot.style_line, color=colorFastEMA, show_last=history_OHFastEMA ? na : 1, offset=history_OHFastEMA ? 0 : -99999)
plot(showOHMidSMA and history_OHMidSMA and (timeframe.period != '60') ? OHMidSMA : na, title='1 Hour Mid SMA', style=plot.style_line, color=colorMidSMA, show_last=history_OHMidSMA ? na : 1, offset=history_OHMidSMA ? 0 : -99999)
plot(showOHSlowSMA and history_OHSlowSMA and (timeframe.period != '60') ? OHSlowSMA : na, title='1 Hour Slow SMA', style=plot.style_line, color=colorSlowSMA, show_last=history_OHSlowSMA ? na : 1, offset=history_OHSlowSMA ? 0 : -99999)
//Plot 4 Hours Moving Averages
plot(showFHFastEMA and history_FHFastEMA and (timeframe.period != '240') ? FHFastEMA : na, title='4 Hours Fast EMA', style=plot.style_line, color=colorFastEMA, show_last=history_FHFastEMA ? na : 1, offset=history_FHFastEMA ? 0 : -99999)
plot(showFHMidSMA and history_FHFastEMA and (timeframe.period != '240') ? FHMidSMA : na, title='4 Hours Mid SMA', style=plot.style_line, color=colorMidSMA, show_last=history_FHMidSMA ? na : 1, offset=history_FHMidSMA ? 0 : -99999)
plot(showFHSlowSMA and history_FHFastEMA and (timeframe.period != '240') ? FHSlowSMA : na, title='4 Hours Slow SMA', style=plot.style_line, color=colorSlowSMA, show_last=history_FHSlowSMA ? na : 1, offset=history_FHSlowSMA ? 0 : -99999)
//Plot Daily Moving Averages
plot(showDFastEMA and history_DFastEMA and (timeframe.period != 'D') ? DFastEMA : na, title='Daily Fast EMA', style=plot.style_line, color=colorFastEMA, show_last=history_DFastEMA ? na : 1, offset=history_DFastEMA ? 0 : -99999)
plot(showDMidSMA and history_DMidSMA and (timeframe.period != 'D') ? DMidSMA : na, title='Daily Mid SMA', style=plot.style_line, color=colorMidSMA, show_last=history_DMidSMA ? na : 1, offset=history_DMidSMA ? 0 : -99999)
plot(showDSlowSMA and history_DSlowSMA and (timeframe.period != 'D') ? DSlowSMA : na, title='Daily Slow SMA', style=plot.style_line, color=colorSlowSMA, show_last=history_DSlowSMA ? na : 1, offset=history_DSlowSMA ? 0 : -99999)
//Plot Weekly Moving Averages
plot(showWFastEMA and history_WFastEMA and (timeframe.period != 'W') ? WFastEMA : na, title='Weekly Fast EMA', style=plot.style_line, color=colorFastEMA, show_last=history_WFastEMA ? na : 1, offset=history_WFastEMA ? 0 : -99999)
plot(showWMidSMA and history_WMidSMA and (timeframe.period != 'W') ? WMidSMA : na, title='Weekly Mid SMA', style=plot.style_line, color=colorMidSMA, show_last=history_WMidSMA ? na : 1, offset=history_WMidSMA ? 0 : -99999)
plot(showWSlowSMA and history_WSlowSMA and (timeframe.period != 'W') ? WSlowSMA : na, title='Weekly Slow SMA', style=plot.style_line, color=colorSlowSMA, show_last=history_WSlowSMA ? na : 1, offset=history_WSlowSMA ? 0 : -99999)
//Plot Monthly Moving Averages
plot(showMFastEMA and history_MFastEMA and (timeframe.period != 'M') ? MFastEMA : na, title='Monthly Fast EMA', style=plot.style_line, color=colorFastEMA, show_last=history_MFastEMA ? na : 1, offset=history_MFastEMA ? 0 : -99999)
plot(showMMidSMA and history_MMidSMA and (timeframe.period != 'M') ? MMidSMA : na, title='Monthly Mid SMA', style=plot.style_line, color=colorMidSMA, show_last=history_MMidSMA ? na : 1, offset=history_MMidSMA ? 0 : -99999)
plot(showMSlowSMA and history_MSlowSMA and (timeframe.period != 'M') ? MSlowSMA : na, title='Monthly Slow SMA', style=plot.style_line, color=colorSlowSMA, show_last=history_MSlowSMA ? na : 1, offset=history_MSlowSMA ? 0 : -99999)
//Plot VWAP Moving Averages
plot(showVWAP and history_VWAP and is_today ? VWAP : na, title='VWAP', style=plot.style_line, color=colorVWAP)
plot(showpdVWAP and history_pdVWAP and is_today ? pdVWAP : na, title='pdVWAP', style=plot.style_line, color=colorpdVWAP)
|
Day High_Low levels with Candle high low | https://www.tradingview.com/script/yeTHqKoL-Day-High-Low-levels-with-Candle-high-low/ | Traderanalyst202 | https://www.tradingview.com/u/Traderanalyst202/ | 41 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © convicted
//@version=4
study(title="High_Low levels", shorttitle="HL levels", overlay=true)
//Daily high and low
dailyhigh = security(syminfo.tickerid, 'D', high)
dailylow = security(syminfo.tickerid, 'D', low)
//Yesterday high and low
previousdayhigh = security(syminfo.tickerid, 'D', high[1])
previousdaylow = security(syminfo.tickerid, 'D', low[1])
//Premarket high and low
t = time("1440","0400-0930") // 1440 is the number of minutes in a whole day.
is_first = na(t[1]) and not na(t) or t[1] < t
ending_hour = 9
ending_minute = 30
pm_high = float(na)
pm_low = float(na)
k = int(na)
if is_first and barstate.isnew and ((hour < ending_hour or hour >= 16) or (hour == ending_hour and minute < ending_minute))
pm_high := high
pm_low := low
else
pm_high := pm_high[1]
pm_low := pm_low[1]
if high > pm_high and ((hour < ending_hour or hour >= 1600) or (hour == ending_hour and minute < ending_minute))
pm_high := high
if low < pm_low and ((hour < ending_hour or hour >= 1600) or (hour == ending_hour and minute < ending_minute))
pm_low := low
LastOnly = true
if LastOnly==true
k:=-9999
else
k:=0
//After Hours high and low
ti = time("1440","1600-2000") // 1440 is the number of minutes in a whole day.
is_first1 = na(ti[1]) and not na(ti) or ti[1] < ti
ending_hour1 = 20
ending_minute1 = 00
ah_high = float(na)
ah_low = float(na)
g = int(na)
if is_first1 and barstate.isnew and ((hour < ending_hour1 or hour >= 20) or (hour == ending_hour1 and minute < ending_minute1))
ah_high := high
ah_low := low
else
ah_high := ah_high[1]
ah_low := ah_low[1]
if high > ah_high and ((hour < ending_hour1 or hour >= 2000) or (hour == ending_hour1 and minute < ending_minute1))
ah_high := high
if low < ah_low and ((hour < ending_hour1 or hour >= 2000) or (hour == ending_hour1 and minute < ending_minute1))
ah_low := low
LastOnly1 = true
if LastOnly1==true
g:=-9999
else
g:=0
//Just a variable here for the label coordinates
td = time - time[5]
//Daily high and low lines
plot(dailyhigh, style=plot.style_line,title="Daily high", color=#1b5e20, linewidth=2, trackprice=true,offset=k)
dh = label.new(x=time+td, y=dailyhigh, text = "Day High", xloc = xloc.bar_time, style = label.style_none, textcolor = #1b5e20, size = size.small, textalign = text.align_right)
label.delete(dh[1])
plot(dailylow, style=plot.style_line,title="Daily low",color=#b71c1c, linewidth=2, trackprice=true,offset=k)
dl = label.new(x=time+td, y=dailylow, text = "Day low", xloc = xloc.bar_time, style = label.style_none, textcolor = #b71c1c, size = size.small, textalign = text.align_right)
label.delete(dl[1])
//Previous day high and low lines
plot(previousdayhigh, style=plot.style_line,title="Yesterday's high",color=#a5d6a7, linewidth=2, trackprice=true,offset=k)
pdh = label.new(x=time+td, y=previousdayhigh, text = "Y H", xloc = xloc.bar_time, style = label.style_none, textcolor = #a5d6a7, size = size.small, textalign = text.align_right)
label.delete(pdh[1])
plot(previousdaylow, style=plot.style_line,title="Yesterday's low",color=#f8bbd0, linewidth=2, trackprice=true,offset=k)
pdl = label.new(x=time+td, y=previousdaylow, text = "Y L", xloc = xloc.bar_time, style = label.style_none, textcolor = #f8bbd0, size = size.small, textalign = text.align_right)
label.delete(pdl[1])
//Premarket high and low lines
plot(pm_high, style=plot.style_line,title="Premarket high", trackprice=true, color=#4caf50, linewidth=2,offset=k)
pmh = label.new(x=time+td, y=pm_high, text = "PM High", xloc = xloc.bar_time, style = label.style_none, textcolor = #4caf50, size = size.small, textalign = text.align_right)
label.delete(pmh[1])
plot(pm_low, style=plot.style_line,title="Premarket low", trackprice=true, color=#f44336, linewidth=2,offset=k)
pml = label.new(x=time+td, y=pm_low, text = "PM Low", xloc = xloc.bar_time, style = label.style_none, textcolor = #f44336, size = size.small, textalign = text.align_right)
label.delete(pml[1])
//AfterHours high and low lines
plot(ah_high, style=plot.style_line,title="After Hours high", trackprice=true, color=#679eca, linewidth=2,offset=k)
ahh = label.new(x=time+td, y=ah_high, text = "AH High", xloc = xloc.bar_time, style = label.style_none, textcolor = #679eca, size = size.small, textalign = text.align_right)
label.delete(ahh[1])
plot(ah_low, style=plot.style_line,title="After Hours low", trackprice=true, color=#679eca, linewidth=2,offset=k)
ahl = label.new(x=time+td, y=ah_low, text = "AH Low", xloc = xloc.bar_time, style = label.style_none, textcolor = #679eca, size = size.small, textalign = text.align_right)
label.delete(ahl[1])
patternLabelPosLow = low[1] - abs(atr(30) * 0.6)
patternLabelPosHigh = high[1] + abs(atr(30) * 0.6)
l1 = label.new(bar_index[1], patternLabelPosHigh, text=tostring(high[1]), style=label.style_label_down, color = color.green, textcolor=color.white)
l2 = label.new(bar_index[1], patternLabelPosLow, text=tostring(low[1]), style=label.style_label_up, color = color.red, textcolor=color.white)
label.delete(l1[1])
label.delete(l2[1]) |
Benjamin Cowen's Simplified Risk Metric | https://www.tradingview.com/script/H4iCbDci-Benjamin-Cowen-s-Simplified-Risk-Metric/ | jacdelosreyes | https://www.tradingview.com/u/jacdelosreyes/ | 97 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jacdelosreyes013
//@version=4
study("Benjamin Cowen's Simplified Risk Metric")
var colorway = color.white
n50 = (timeframe.isweekly) ? 7 :
(timeframe.isdaily) ? 50 : 0
n350 = (timeframe.isweekly) ? 50 :
(timeframe.isdaily) ? 350 : 0
sma_50 = sma(close, n50)
sma_350 = sma(close, n350)
newsma = sma_50/sma_350
rescale(_src, _oldMin, _oldMax) =>
_src / _oldMax
risk_metric = rescale(newsma, 0.55, 3)
if (risk_metric >=1)
colorway := color.red
else if (risk_metric >= 0.9)
colorway := color.orange
else if (risk_metric >= 0.8)
colorway := color.yellow
else if (risk_metric >= 0.7)
colorway := color.lime
else if (risk_metric >= 0.6)
colorway := color.green
else if (risk_metric >= 0.5)
colorway := color.aqua
else if (risk_metric >= 0.4)
colorway := color.blue
else if (risk_metric >= 0.3)
colorway := color.navy
else if (risk_metric >= 0.2)
colorway := color.purple
else if (risk_metric >= 0.1)
colorway := color.fuchsia
plot(risk_metric, color=colorway, title="Risk Metric") |
Recession indicator US2/10 Y | https://www.tradingview.com/script/R8UogR9T-Recession-indicator-US2-10-Y/ | jacdelosreyes | https://www.tradingview.com/u/jacdelosreyes/ | 42 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jacdelosreyes013
//@version=5
indicator("Recession indicator US2/10 Y")
US02Y = request.security("TVC:US02Y",timeframe.period,close)
US10Y = request.security("TVC:US10Y",timeframe.period,close)
recession = US02Y/US10Y
color c_rec = color.red
color c_nrec = color.yellow
color ind_color = recession > 1 ? c_rec : c_nrec
plot(recession, color=ind_color) |
Intraday Super Sectors | https://www.tradingview.com/script/Iff03iNm-Intraday-Super-Sectors/ | TIG_That-Indicator-Guy | https://www.tradingview.com/u/TIG_That-Indicator-Guy/ | 144 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © stuarthenryjames
// @version=5
indicator("Intraday Super Sectors", overlay = false)
// VERSION 2.0 CHANGELOG
// NEW FEATURES
// User can choose whether a sector is 'Cyclical' or 'Defensive'
// User can display spaghetti, if they really want
// BUG FIXES
// Small (display-related) bug fix
/////////////////////////////////////////////////
// LET'S GET THIS PARTY STARTED
/////////////////////////////////////////////////
// Input Variables
var oGroup1 = "Line Color Width"
oColorCyclical = input.color(color.rgb(0, 192, 0, 50), "Cyclical Super Sector ", inline = "11", group = oGroup1)
oLineWidthCyclical = input.int(5, "", options = [1, 2, 3, 4, 5], inline = "11", group = oGroup1)
oColorDefensive = input.color(color.rgb(192, 0, 0, 50), "Defensive Super Sector ", inline = "12", group = oGroup1)
oLineWidthDefensive = input.int(4, "", options = [1, 2, 3, 4, 5], inline = "12", group = oGroup1)
oMidTick = input.string("SPX", "Midline ticker?", inline = "13", group = oGroup1)
oColorSpx = input.color(color.rgb(255, 255, 255, 50), "", inline = "13", group = oGroup1)
oLineWidthSpx = input.int(3, "", options = [1, 2, 3, 4, 5], inline = "13", group = oGroup1)
var oGroup2 = "If you're just using SPX / Cash Session, no need to touch this. Unfortunately, TradingView doesn't know if the clocks are forwards or backwards!"
// If I'm wrong about this, please let me know in the comments :) ... (and yes, I know there is a workaround, but I'm not sure it'd be robust)
oSessionInfo = input.string("Regular", "What sessions are you displaying?", options = ["Regular", "Extended"], inline = "21", group = oGroup2)
oClocks = input.string("Summer Time", "What are the clocks doing? ", options = ["Summer Time", "Winter Time"], inline = "22", group = oGroup2)
oSummerTime = oClocks == "Summer Time" ? true : false
var oGroup4 = "Soft Background Clouds"
oSoftGreen = input.color(color.rgb(0, 255, 0, 97), "Cyclical > Defensive?", inline = "41", group = oGroup4)
oSoftRed = input.color(color.rgb(255, 0, 0, 95), "Defensive > Cyclical?", inline = "41", group = oGroup4)
var oGroup5 = "Random Stuff"
oEma = input.int(5, "EMA Smoothing", options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], inline = "51", group = oGroup5)
oTextColor = input.color(color.rgb(128, 128, 128, 0), "Title Text Color", inline = "52", group = oGroup5)
oTextGreen = input.color(color.rgb(64, 192, 64, 0), "Up Text Color ", inline = "53", group = oGroup5)
oTextRed = input.color(color.rgb(255, 0, 0, 0), "Down Text Color", inline = "53", group = oGroup5)
var oGroup6 = "Sector Settings"
oWeightXLB = input.float(2.6, "XLB Weight / Sector ", minval = 0, inline = "61", group = oGroup6)
oSectorXLB = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "61", group = oGroup6)
oWeightXLC = input.float(10.8, "XLC Weight / Sector ", minval = 0, inline = "62", group = oGroup6)
oSectorXLC = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "62", group = oGroup6)
oWeightXLE = input.float(2.3, "XLE Weight / Sector ", minval = 0, inline = "63", group = oGroup6)
oSectorXLE = input.string("Defensive", "", options = ["Cyclical", "Defensive"], inline = "63", group = oGroup6)
oWeightXLF = input.float(10.4, "XLF Weight / Sector ", minval = 0, inline = "64", group = oGroup6)
oSectorXLF = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "64", group = oGroup6)
oWeightXLI = input.float(8.4, "XLI Weight / Sector ", minval = 0, inline = "65", group = oGroup6)
oSectorXLI = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "65", group = oGroup6)
oWeightXLK = input.float(27.6, "XLK Weight / Sector ", minval = 0, inline = "66", group = oGroup6)
oSectorXLK = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "66", group = oGroup6)
oWeightXLP = input.float(6.5, "XLP Weight / Sector ", minval = 0, inline = "67", group = oGroup6)
oSectorXLP = input.string("Defensive", "", options = ["Cyclical", "Defensive"], inline = "67", group = oGroup6)
oWeightXLRE = input.float(2.4, "XLRE Weight / Sector", minval = 0, inline = "68", group = oGroup6)
oSectorXLRE = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "68", group = oGroup6)
oWeightXLU = input.float(2.8, "XLU Weight / Sector ", minval = 0, inline = "69", group = oGroup6)
oSectorXLU = input.string("Defensive", "", options = ["Cyclical", "Defensive"], inline = "69", group = oGroup6)
oWeightXLV = input.float(13.5, "XLV Weight / Sector ", minval = 0, inline = "6A", group = oGroup6)
oSectorXLV = input.string("Defensive", "", options = ["Cyclical", "Defensive"], inline = "6A", group = oGroup6)
oWeightXLY = input.float(12.7, "XLY Weight / Sector ", minval = 0, inline = "6B", group = oGroup6)
oSectorXLY = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "6B", group = oGroup6)
var oGroup7 = "Would you like a side of spaghetti with your order?"
oSpaghetti = input.string("Nope, keep it clean!", "Side dish of spaghetti?", options = ["Nope, keep it clean!", "Go for it!"], inline = "71", group = oGroup7)
oSpagCyclical = input.color(color.rgb(0, 192, 0, 70), "Cyclical Spaghetti Color", inline = "72", group = oGroup7)
oSpagDefensive = input.color(color.rgb(192, 0, 0, 60), "Defensive Spaghetti Color", inline = "73", group = oGroup7)
oSpagWidth = input.int(1, "Spaghetti Width", options = [1, 2, 3, 4, 5], inline = "74", group = oGroup7)
oSpagFlag = oSpaghetti == "Nope, keep it clean!" ? false : true
// Initialize / Global Variables
oColorNone = color.rgb(0, 0, 0, 255)
oColorGray = color.rgb(128, 128, 128, 50)
var oOpenSpx = 0.0
var oOpenCyclical = 0.0
var oOpenDefensive = 0.0
var oOpenXLB = 0.0
var oOpenXLC = 0.0
var oOpenXLE = 0.0
var oOpenXLF = 0.0
var oOpenXLI = 0.0
var oOpenXLK = 0.0
var oOpenXLP = 0.0
var oOpenXLRE = 0.0
var oOpenXLU = 0.0
var oOpenXLV = 0.0
var oOpenXLY = 0.0
var oRTH = true
var oNewSession = false
/////////////////////////////////////////////////
// DO SOME CALCULATIONS
/////////////////////////////////////////////////
// Intialize for a new session
if oSessionInfo == "Regular"
oNewSession := dayofweek != dayofweek[1] ? true : false
if oSessionInfo == "Extended"
oRTH := time(timeframe.period, oSummerTime ? "0830-1500" : "0930-1600") != 0 ? true : false
oNewSession := oRTH and (oRTH[1] == false) ? true : false
oOpenSpx := oNewSession ? request.security(oMidTick, timeframe.period, open) : oOpenSpx
oOpenXLB := oNewSession ? request.security("XLB", timeframe.period, open) : oOpenXLB
oOpenXLC := oNewSession ? request.security("XLC", timeframe.period, open) : oOpenXLC
oOpenXLE := oNewSession ? request.security("XLE", timeframe.period, open) : oOpenXLE
oOpenXLF := oNewSession ? request.security("XLF", timeframe.period, open) : oOpenXLF
oOpenXLI := oNewSession ? request.security("XLI", timeframe.period, open) : oOpenXLI
oOpenXLK := oNewSession ? request.security("XLK", timeframe.period, open) : oOpenXLK
oOpenXLP := oNewSession ? request.security("XLP", timeframe.period, open) : oOpenXLP
oOpenXLRE := oNewSession ? request.security("XLRE", timeframe.period, open) : oOpenXLRE
oOpenXLU := oNewSession ? request.security("XLU", timeframe.period, open) : oOpenXLU
oOpenXLV := oNewSession ? request.security("XLV", timeframe.period, open) : oOpenXLV
oOpenXLY := oNewSession ? request.security("XLY", timeframe.period, open) : oOpenXLY
if oNewSession
oOpenCyclical := (oSectorXLB == "Cyclical" ? oOpenXLB * oWeightXLB : 0) +
(oSectorXLC == "Cyclical" ? oOpenXLC * oWeightXLC : 0) +
(oSectorXLE == "Cyclical" ? oOpenXLE * oWeightXLE : 0) +
(oSectorXLF == "Cyclical" ? oOpenXLF * oWeightXLF : 0) +
(oSectorXLI == "Cyclical" ? oOpenXLI * oWeightXLI : 0) +
(oSectorXLK == "Cyclical" ? oOpenXLK * oWeightXLK : 0) +
(oSectorXLP == "Cyclical" ? oOpenXLP * oWeightXLP : 0) +
(oSectorXLRE == "Cyclical" ? oOpenXLRE * oWeightXLRE : 0) +
(oSectorXLU == "Cyclical" ? oOpenXLU * oWeightXLU : 0) +
(oSectorXLV == "Cyclical" ? oOpenXLV * oWeightXLV : 0) +
(oSectorXLY == "Cyclical" ? oOpenXLY * oWeightXLY : 0)
oOpenDefensive := (oSectorXLB == "Defensive" ? oOpenXLB * oWeightXLB : 0) +
(oSectorXLC == "Defensive" ? oOpenXLC * oWeightXLC : 0) +
(oSectorXLE == "Defensive" ? oOpenXLE * oWeightXLE : 0) +
(oSectorXLF == "Defensive" ? oOpenXLF * oWeightXLF : 0) +
(oSectorXLI == "Defensive" ? oOpenXLI * oWeightXLI : 0) +
(oSectorXLK == "Defensive" ? oOpenXLK * oWeightXLK : 0) +
(oSectorXLP == "Defensive" ? oOpenXLP * oWeightXLP : 0) +
(oSectorXLRE == "Defensive" ? oOpenXLRE * oWeightXLRE : 0) +
(oSectorXLU == "Defensive" ? oOpenXLU * oWeightXLU : 0) +
(oSectorXLV == "Defensive" ? oOpenXLV * oWeightXLV : 0) +
(oSectorXLY == "Defensive" ? oOpenXLY * oWeightXLY : 0)
// yes, I know we should do '1 - Cyclical' to get the Defensive value, but for development purposes this (slightly duplicate) approach is easier
// also, if/when this script is ever 'final final' I will convert everything to arrays / loops
// So where are we now?
oCurrentSpx = request.security(oMidTick, timeframe.period, close)
oCurrentXLB = request.security("XLB", timeframe.period, close)
oCurrentXLC = request.security("XLC", timeframe.period, close)
oCurrentXLE = request.security("XLE", timeframe.period, close)
oCurrentXLF = request.security("XLF", timeframe.period, close)
oCurrentXLI = request.security("XLI", timeframe.period, close)
oCurrentXLK = request.security("XLK", timeframe.period, close)
oCurrentXLP = request.security("XLP", timeframe.period, close)
oCurrentXLRE = request.security("XLRE", timeframe.period, close)
oCurrentXLU = request.security("XLU", timeframe.period, close)
oCurrentXLV = request.security("XLV", timeframe.period, close)
oCurrentXLY = request.security("XLY", timeframe.period, close)
oCurrentCyclical = (oSectorXLB == "Cyclical" ? oCurrentXLB * oWeightXLB : 0) +
(oSectorXLC == "Cyclical" ? oCurrentXLC * oWeightXLC : 0) +
(oSectorXLE == "Cyclical" ? oCurrentXLE * oWeightXLE : 0) +
(oSectorXLF == "Cyclical" ? oCurrentXLF * oWeightXLF : 0) +
(oSectorXLI == "Cyclical" ? oCurrentXLI * oWeightXLI : 0) +
(oSectorXLK == "Cyclical" ? oCurrentXLK * oWeightXLK : 0) +
(oSectorXLP == "Cyclical" ? oCurrentXLP * oWeightXLP : 0) +
(oSectorXLRE == "Cyclical" ? oCurrentXLRE * oWeightXLRE : 0) +
(oSectorXLU == "Cyclical" ? oCurrentXLU * oWeightXLU : 0) +
(oSectorXLV == "Cyclical" ? oCurrentXLV * oWeightXLV : 0) +
(oSectorXLY == "Cyclical" ? oCurrentXLY * oWeightXLY : 0)
oCurrentDefensive = (oSectorXLB == "Defensive" ? oCurrentXLB * oWeightXLB : 0) +
(oSectorXLC == "Defensive" ? oCurrentXLC * oWeightXLC : 0) +
(oSectorXLE == "Defensive" ? oCurrentXLE * oWeightXLE : 0) +
(oSectorXLF == "Defensive" ? oCurrentXLF * oWeightXLF : 0) +
(oSectorXLI == "Defensive" ? oCurrentXLI * oWeightXLI : 0) +
(oSectorXLK == "Defensive" ? oCurrentXLK * oWeightXLK : 0) +
(oSectorXLP == "Defensive" ? oCurrentXLP * oWeightXLP : 0) +
(oSectorXLRE == "Defensive" ? oCurrentXLRE * oWeightXLRE : 0) +
(oSectorXLU == "Defensive" ? oCurrentXLU * oWeightXLU : 0) +
(oSectorXLV == "Defensive" ? oCurrentXLV * oWeightXLV : 0) +
(oSectorXLY == "Defensive" ? oCurrentXLY * oWeightXLY : 0)
// Calculate the changes
oSpx = 100 * (oCurrentSpx / oOpenSpx - 1)
oCyclical = 100 * (oCurrentCyclical / oOpenCyclical - 1)
oDefensive = 100 * (oCurrentDefensive / oOpenDefensive - 1)
// Calculate the plot values
oSpxPlot = ta.ema(oSpx, oEma)
oCyclicalPlot = ta.ema(oCyclical, oEma)
oDefensivePlot = ta.ema(oDefensive, oEma)
/////////////////////////////////////////////////
// DISPLAY STUFF
/////////////////////////////////////////////////
// Spaghetti
oXLB = 100 * (oCurrentXLB / oOpenXLB - 1)
oXLC = 100 * (oCurrentXLC / oOpenXLC - 1)
oXLE = 100 * (oCurrentXLE / oOpenXLE - 1)
oXLF = 100 * (oCurrentXLF / oOpenXLF - 1)
oXLI = 100 * (oCurrentXLI / oOpenXLI - 1)
oXLK = 100 * (oCurrentXLK / oOpenXLK - 1)
oXLP = 100 * (oCurrentXLP / oOpenXLP - 1)
oXLRE = 100 * (oCurrentXLRE / oOpenXLRE - 1)
oXLU = 100 * (oCurrentXLU / oOpenXLU - 1)
oXLV = 100 * (oCurrentXLV / oOpenXLV - 1)
oXLY = 100 * (oCurrentXLY / oOpenXLY - 1)
oXLBPlot = ta.ema(oXLB, oEma)
oXLCPlot = ta.ema(oXLC, oEma)
oXLEPlot = ta.ema(oXLE, oEma)
oXLFPlot = ta.ema(oXLF, oEma)
oXLIPlot = ta.ema(oXLI, oEma)
oXLKPlot = ta.ema(oXLK, oEma)
oXLPPlot = ta.ema(oXLP, oEma)
oXLREPlot = ta.ema(oXLRE, oEma)
oXLUPlot = ta.ema(oXLU, oEma)
oXLVPlot = ta.ema(oXLV, oEma)
oXLYPlot = ta.ema(oXLY, oEma)
plot(oXLBPlot, linewidth = oSpagWidth, color = oSpagFlag and oRTH ? oSectorXLB == "Cyclical" ? oSpagCyclical : oSpagDefensive : oColorNone)
plot(oXLCPlot, linewidth = oSpagWidth, color = oSpagFlag and oRTH ? oSectorXLC == "Cyclical" ? oSpagCyclical : oSpagDefensive : oColorNone)
plot(oXLEPlot, linewidth = oSpagWidth, color = oSpagFlag and oRTH ? oSectorXLE == "Cyclical" ? oSpagCyclical : oSpagDefensive : oColorNone)
plot(oXLFPlot, linewidth = oSpagWidth, color = oSpagFlag and oRTH ? oSectorXLF == "Cyclical" ? oSpagCyclical : oSpagDefensive : oColorNone)
plot(oXLIPlot, linewidth = oSpagWidth, color = oSpagFlag and oRTH ? oSectorXLI == "Cyclical" ? oSpagCyclical : oSpagDefensive : oColorNone)
plot(oXLKPlot, linewidth = oSpagWidth, color = oSpagFlag and oRTH ? oSectorXLK == "Cyclical" ? oSpagCyclical : oSpagDefensive : oColorNone)
plot(oXLPPlot, linewidth = oSpagWidth, color = oSpagFlag and oRTH ? oSectorXLP == "Cyclical" ? oSpagCyclical : oSpagDefensive : oColorNone)
plot(oXLREPlot, linewidth = oSpagWidth, color = oSpagFlag and oRTH ? oSectorXLRE == "Cyclical" ? oSpagCyclical : oSpagDefensive : oColorNone)
plot(oXLUPlot, linewidth = oSpagWidth, color = oSpagFlag and oRTH ? oSectorXLU == "Cyclical" ? oSpagCyclical : oSpagDefensive : oColorNone)
plot(oXLVPlot, linewidth = oSpagWidth, color = oSpagFlag and oRTH ? oSectorXLV == "Cyclical" ? oSpagCyclical : oSpagDefensive : oColorNone)
plot(oXLYPlot, linewidth = oSpagWidth, color = oSpagFlag and oRTH ? oSectorXLY == "Cyclical" ? oSpagCyclical : oSpagDefensive : oColorNone)
// Plot the lines and infill
plot(0, color = oColorGray)
oPlotSpx = plot(oSpxPlot, linewidth = oLineWidthSpx, color = oNewSession or not(oRTH) ? oColorNone : oColorSpx)
oPlotCyclical = plot(oCyclicalPlot, linewidth = oLineWidthCyclical, color = oNewSession or not(oRTH) ? oColorNone : oColorCyclical)
oPlotDefensive = plot(oDefensivePlot, linewidth = oLineWidthDefensive, color = oNewSession or not(oRTH) ? oColorNone : oColorDefensive)
fill(oPlotCyclical, oPlotDefensive, color = oNewSession or not(oRTH) ? oColorNone : oCyclicalPlot > oDefensivePlot ? oSoftGreen : oSoftRed)
// Plot the table
var table oTable1 = table.new(position.bottom_left, 13, 6)
var oCount = 9
if barstate.isfirst
table.cell(oTable1, 1, 0, syminfo.ticker, text_color = oTextColor, text_halign = text.align_left)
table.cell(oTable1, 0, 2, " ", bgcolor = not(oRTH) ? oColorNone : oColorDefensive)
table.cell(oTable1, 0, 3, " ", bgcolor = not(oRTH) ? oColorNone : oColorDefensive)
table.cell(oTable1, 1, 2, "Defensive", text_color = oTextColor, text_halign = text.align_left)
table.cell(oTable1, 0, 4, " ", bgcolor = not(oRTH) ? oColorNone : oColorCyclical)
table.cell(oTable1, 0, 5, " ", bgcolor = not(oRTH) ? oColorNone : oColorCyclical)
table.cell(oTable1, 1, 4, "Cyclical", text_color = oTextColor, text_halign = text.align_left)
oCount := 2
if oSectorXLB == "Defensive"
table.cell(oTable1, oCount, 2, "XLB", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLC == "Defensive"
table.cell(oTable1, oCount, 2, "XLC", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLE == "Defensive"
table.cell(oTable1, oCount, 2, "XLE", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLF == "Defensive"
table.cell(oTable1, oCount, 2, "XLF", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLI == "Defensive"
table.cell(oTable1, oCount, 2, "XLI", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLK == "Defensive"
table.cell(oTable1, oCount, 2, "XLK", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLP == "Defensive"
table.cell(oTable1, oCount, 2, "XLP", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLRE == "Defensive"
table.cell(oTable1, oCount, 2, "XLRE", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLU == "Defensive"
table.cell(oTable1, oCount, 2, "XLU", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLV == "Defensive"
table.cell(oTable1, oCount, 2, "XLV", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLY == "Defensive"
table.cell(oTable1, oCount, 2, "XLY", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
oCount := 2
if oSectorXLB == "Cyclical"
table.cell(oTable1, oCount, 4, "XLB", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLC == "Cyclical"
table.cell(oTable1, oCount, 4, "XLC", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLE == "Cyclical"
table.cell(oTable1, oCount, 4, "XLE", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLF == "Cyclical"
table.cell(oTable1, oCount, 4, "XLF", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLI == "Cyclical"
table.cell(oTable1, oCount, 4, "XLI", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLK == "Cyclical"
table.cell(oTable1, oCount, 4, "XLK", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLP == "Cyclical"
table.cell(oTable1, oCount, 4, "XLP", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLRE == "Cyclical"
table.cell(oTable1, oCount, 4, "XLRE", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLU == "Cyclical"
table.cell(oTable1, oCount, 4, "XLU", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLV == "Cyclical"
table.cell(oTable1, oCount, 4, "XLV", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLY == "Cyclical"
table.cell(oTable1, oCount, 4, "XLY", text_color = oTextColor, text_halign = text.align_center)
oCount := oCount + 1
table.cell(oTable1, 1, 1, str.format("{0, number, #.##}", math.abs(oSpx)), text_color = not(oRTH) ? oColorNone : oSpx > 0 ? oTextGreen : oTextRed, text_halign = text.align_left)
table.cell(oTable1, 1, 3, str.format("{0, number, #.##}", math.abs(oDefensive)), text_color = not(oRTH) ? oColorNone : oDefensive > 0 ? oTextGreen : oTextRed, text_halign = text.align_left)
table.cell(oTable1, 1, 5, str.format("{0, number, #.##}", math.abs(oCyclical)), text_color = not(oRTH) ? oColorNone : oCyclical > 0 ? oTextGreen : oTextRed, text_halign = text.align_left)
oCount := 2
if oSectorXLB == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLB)), text_color = not(oRTH) ? oColorNone : oXLB > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLC == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLC)), text_color = not(oRTH) ? oColorNone : oXLC > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLE == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLE)), text_color = not(oRTH) ? oColorNone : oXLE > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLF == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLF)), text_color = not(oRTH) ? oColorNone : oXLF > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLI == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLI)), text_color = not(oRTH) ? oColorNone : oXLI > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLK == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLK)), text_color = not(oRTH) ? oColorNone : oXLK > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLP == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLP)), text_color = not(oRTH) ? oColorNone : oXLP > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLRE == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLRE)), text_color = not(oRTH) ? oColorNone : oXLRE > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLU == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLU)), text_color = not(oRTH) ? oColorNone : oXLU > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLV == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLV)), text_color = not(oRTH) ? oColorNone : oXLV > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLY == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLY)), text_color = not(oRTH) ? oColorNone : oXLY > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
oCount := 2
if oSectorXLB == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLB)), text_color = not(oRTH) ? oColorNone : oXLB > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLC == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLC)), text_color = not(oRTH) ? oColorNone : oXLC > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLE == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLE)), text_color = not(oRTH) ? oColorNone : oXLE > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLF == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLF)), text_color = not(oRTH) ? oColorNone : oXLF > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLI == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLI)), text_color = not(oRTH) ? oColorNone : oXLI > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLK == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLK)), text_color = not(oRTH) ? oColorNone : oXLK > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLP == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLP)), text_color = not(oRTH) ? oColorNone : oXLP > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLRE == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLRE)), text_color = not(oRTH) ? oColorNone : oXLRE > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLU == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLU)), text_color = not(oRTH) ? oColorNone : oXLU > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLV == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLV)), text_color = not(oRTH) ? oColorNone : oXLV > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
if oSectorXLY == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLY)), text_color = not(oRTH) ? oColorNone : oXLY > 0 ? oTextGreen : oTextRed, text_halign = text.align_center)
oCount := oCount + 1
// That's all folks
|
Quarter theory and whole numbers | https://www.tradingview.com/script/kxWkVFGI-Quarter-theory-and-whole-numbers/ | Rain5369 | https://www.tradingview.com/u/Rain5369/ | 173 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Rain5369
//@version=5
indicator('Quarter Levels', overlay=true)
var largeLines = 2
var majorLines = 4
var picoLines = 8
var femtoLines = 8
StepSize = input.float(1000, title='Step Size [pip]', step=0.00001, tooltip = 'The value That should be entered here is 1000 pips. e.g. FX = 1000, BTC(depends on decimal point)- 10 000/ 100 000, ETH(depends on decimal point) - 1 000/10 000')
var step = syminfo.mintick * (StepSize*10)
var majorStep = syminfo.mintick * (StepSize*2.5)
var picoStep = syminfo.mintick * (StepSize*1)
var FemtoStep = syminfo.mintick * (StepSize*0.25)
line ln = na
lstyle1 = input.string(title='Resistance Line Style', defval='Solid', options=['Solid', 'Dotted', 'Dashed'], group='Resistance')
lstyle2 = input.string(title='Support Line Style', defval='Solid', options=['Solid', 'Dotted', 'Dashed'], group='Support')
resistanceStyle = lstyle1 == 'Solid' ? line.style_solid : lstyle1 == 'Dotted' ? line.style_dotted : line.style_dashed
supportStyle = lstyle2 == 'Solid' ? line.style_solid : lstyle2 == 'Dotted' ? line.style_dotted : line.style_dashed
LineCol = input.color(color.new(#FFFFFF, 0), title='1000 pip', inline='LineCol', group='Resistance')
lineWidth = input.int(3, title='', minval=1, maxval=4, inline='LineCol', group='Resistance')
LineCol2 = input.color(color.new(#FFFFFF, 0), title='1000 pip', inline='LineCol2', group='Support')
lineWidth2 = input.int(3, title='', minval=1, maxval=4, inline='LineCol2', group='Support')
LineCol3 = input.color(color.new(#FFFFFF, 50), title='250 pip', inline='LineCol3', group='Resistance')
lineWidth3 = input.int(2, title='', minval=1, maxval=4, inline='LineCol3', group='Resistance')
LineCol4 = input.color(color.new(#FFFFFF, 50), title='250 pip', inline='LineCol4', group='Support')
lineWidth4 = input.int(2, title='', minval=1, maxval=4, inline='LineCol4', group='Support')
LineCol5 = input.color(color.new(#f23645, 50), title='100 pip', inline='LineCol5', group='Resistance')
lineWidth5 = input.int(1, title='', minval=1, maxval=4, inline='LineCol5', group='Resistance')
LineCol6 = input.color(color.new(#4caf50, 50), title='100 pip', inline='LineCol6', group='Support')
lineWidth6 = input.int(1, title='', minval=1, maxval=4, inline='LineCol6', group='Support')
LineCol7 = input.color(color.new(#f23645, 50), title='25 pip', inline='LineCol7', group='Resistance')
lineWidth7 = input.int(1, title='', minval=1, maxval=4, inline='LineCol7', group='Resistance')
LineCol8 = input.color(color.new(#4caf50, 50), title='25 pip', inline='LineCol8', group='Support')
lineWidth8 = input.int(1, title='', minval=1, maxval=4, inline='LineCol8', group='Support')
ll_offset = timenow + math.round(ta.change(time) * 40)
ll_offset2 = timenow + math.round(ta.change(time) * 30)
ll_offset3 = timenow + math.round(ta.change(time) * 20)
ll_offset4 = timenow + math.round(ta.change(time) * 10)
if barstate.islast
for counter = 0 to largeLines - 1 by 1
stepUp = math.ceil(close / step) * step + counter * step
line.new(bar_index, stepUp, bar_index - 1, stepUp, xloc=xloc.bar_index, extend=extend.both, color=LineCol, width=lineWidth, style=resistanceStyle)
label.new(ll_offset, stepUp, 'MW' , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol, tooltip = 'Major Whole')
stepDown = math.floor(close / step) * step - counter * step
line.new(bar_index, stepDown, bar_index - 1, stepDown, xloc=xloc.bar_index, extend=extend.both, color=LineCol2, width=lineWidth2, style=supportStyle)
label.new(ll_offset, stepDown, 'MW' , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol2, tooltip = 'Major Whole')
if barstate.islast
for counter = 0 to majorLines - 1 by 1
stepUp = math.ceil(close / majorStep) * majorStep + counter * majorStep
line.new(bar_index, stepUp, bar_index - 1, stepUp, xloc=xloc.bar_index, extend=extend.both, color=LineCol3, width=lineWidth3, style=resistanceStyle)
label.new(ll_offset2, stepUp, 'MQ' , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol3, tooltip = 'Major Quarter')
stepDown = math.floor(close / majorStep) * majorStep - counter * majorStep
line.new(bar_index, stepDown, bar_index - 1, stepDown, xloc=xloc.bar_index, extend=extend.both, color=LineCol4, width=lineWidth4, style=supportStyle)
label.new(ll_offset2, stepDown, 'MQ' , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol4, tooltip = 'Major Quarter')
if barstate.islast and timeframe.isintraday
for counter = 0 to picoLines - 1 by 1
stepUp = math.ceil(close / picoStep) * picoStep + counter * picoStep
line.new(bar_index, stepUp, bar_index - 1, stepUp, xloc=xloc.bar_index, extend=extend.both, color=LineCol5, width=lineWidth5, style=resistanceStyle)
label.new(ll_offset3, stepUp, '100' , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol5, tooltip = 'Minor Whole')
stepDown = math.floor(close / picoStep) * picoStep - counter * picoStep
line.new(bar_index, stepDown, bar_index - 1, stepDown, xloc=xloc.bar_index, extend=extend.both, color=LineCol6, width=lineWidth6, style=supportStyle)
label.new(ll_offset3, stepDown, '100' , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol6, tooltip = 'Minor Whole')
if barstate.islast and timeframe.isminutes
for counter = 0 to femtoLines - 1 by 1
stepUp = math.ceil(close / FemtoStep) * FemtoStep + counter * FemtoStep
line.new(bar_index, stepUp, bar_index - 1, stepUp, xloc=xloc.bar_index, extend=extend.both, color=LineCol7, width=lineWidth7, style=resistanceStyle)
label.new(ll_offset4, stepUp, '25' , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol7, tooltip = 'Minor quarter')
stepDown = math.floor(close / FemtoStep) * FemtoStep - counter * FemtoStep
line.new(bar_index, stepDown, bar_index - 1, stepDown, xloc=xloc.bar_index, extend=extend.both, color=LineCol8, width=lineWidth8, style=supportStyle)
label.new(ll_offset4, stepDown, '25' , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol8, tooltip = 'Minor quarter')
|
Bitcoin Risk Long Term indicator | https://www.tradingview.com/script/Y17Db8kX/ | Julien-PH | https://www.tradingview.com/u/Julien-PH/ | 69 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
// © Julien-PH
indicator(title="Bitcoin Risk Long Term indicator", shorttitle="BTC Risk LT", overlay=false)
//---- Commons Variables
bwClose = request.security("INDEX:BTCUSD", "W", close)
bwHigh = request.security("INDEX:BTCUSD", "W", high)
bwLow = request.security("INDEX:BTCUSD", "W", low)
//---- Display
display_input = input.bool(false, title="Display raw input indicators ?" , group="Display")
offsetDisplay = input.int(defval=-100, title="Offset raw input indicators", group="Display")
display_output = input.bool(true, title="Display output indicators ?" , group="Display")
//######## INPUT
//---- BTC log curve
// INPUTS
HighIntercept = input.float(1.097 , title="Top Curve Intercept" , step=0.001 , group="Logarithme curve Settings")
HighSlope = input.float(0.00076 , title="Top Curve Slope" , step=0.00001 , group="Logarithme curve Settings")
LowIntercept = input.float(-2.9 , title="Bottom Curve Intercept", step=0.001 , group="Logarithme curve Settings")
LowSlope = input.float(0.0011 , title="Bottom Curve Slope" , step=0.00001 , group="Logarithme curve Settings")
// TIME CALCS
TimeIndex = time < 1279670400000 ? 3.0 : (time - 1279670400000) / 86400000
Weight = (math.log10(TimeIndex + 10) * TimeIndex * TimeIndex - TimeIndex) / 30000
// TOP OF CHANNEL INTERCEPT & SLOPE CALCS
HighSlopeCum = HighSlope * TimeIndex
HighLogDev = TimeIndex > 2 ? math.log(Weight) + HighIntercept + HighSlopeCum : na
// BOTTOM OF CHANNEL INTERCEPT & SLOPE CALCS
LowSlopeCum = LowSlope * TimeIndex
LowLogDev = TimeIndex > 2 ? math.log(Weight) + LowIntercept + LowSlopeCum : na
// TOTAL CHANNEL LOG RANGE
//LogRange = HighLogDev - LowLogDev
// Curve
HighDev = math.pow(2.718281828459, HighLogDev)
LowDev = math.pow(2.718281828459, LowLogDev)
ChannelRange = HighDev - LowDev
// Delta price/curves
logCurveHighValue = math.max(math.min( (((bwHigh - LowDev) / ChannelRange)*100) ,100),0)
logCurveLowValue = math.max(math.min( (((bwLow - LowDev) / ChannelRange)*100) ,100),0)
//logCurveHighValue2 = math.max(math.min( (((math.log(bwHigh) - LowDev) / ChannelRange)*100) ,100),0) //TODO tester avec racine de e
//logCurveLowValue2 = math.max(math.min( (((math.log(bwLow) - LowDev) / ChannelRange)*100) ,100),0)
// Plot
display_LogCurve = input.bool(true, title="Display logarithme curve indicators ?" , group="Logarithme curve Settings", tooltip="Strongly based on 'Bitcoin Logarithmic Growth Curves & Zones' develop by mabonyi but in a oscillator")
//colorScheme = input.color(color.new(color.white,0) , title="Logarithme curve color" , group="Logarithme curve Settings")
colorLogCurve = input.color(color.new(color.white,0) , title="Logarithme curve top&bottom color" , group="Logarithme curve Settings")
colorFillLogCurve = input.color(color.new(color.blue ,60), title="Logarithme curve fill color" , group="Logarithme curve Settings")
//p10000 = plot(HighDev, color=colorScheme, title="Top of log channel")
//p0 = plot(LowDev , color=colorScheme, title="Bottom of log channel")
plotLogCurveHigh = plot(display_input ? display_LogCurve ? logCurveHighValue+offsetDisplay : na : na, title="Distance from highest logarithme curve", color=colorLogCurve, linewidth = 1)
plotLogCurveLow = plot(display_input ? display_LogCurve ? logCurveLowValue +offsetDisplay : na : na, title="Distance from lowest logarithme curve" , color=colorLogCurve, linewidth = 1)
fill(plotLogCurveHigh, plotLogCurveLow, color=colorFillLogCurve)
//---- WaveTrend
display_wt = input.bool(false, title="Display WaveTrend indicator ?", group="WaveTrend Settings", tooltip="WaveTrend Oscillator develop by LazyBear")
display_wtDelta = input.bool(false, title="Display WaveTrend delta ?" , group="WaveTrend Settings", tooltip="Represents the difference between the WaveTrend and its SMA")
length1WT = input.int(10, minval=1, title="Channel Length" , group="WaveTrend Settings")
length2WT = input.int(21, minval=1, title="Average Length" , group="WaveTrend Settings")
wtMethod(l1, l2) =>
esa = ta.ema(hlc3, l1)
ci = (hlc3 - esa) / (0.015 * ta.ema(math.abs(hlc3 - esa), l1))
wt1 = nz(math.max(math.min( ta.ema(ci, l2)*0.45 + 40 ,100),0),50)
wt2 = nz(ta.sma(wt1,4),50)
[nz(wt1,0),nz(wt2,0)]
[wt1,wt2] = request.security("INDEX:BTCUSD", "W", wtMethod(length1WT,length2WT) )
wtDelta = math.max(math.min( (wt1 - wt2)*5 + 50 ,100),0)
// Plot
colorWT1 = input.color(color.new(color.aqua,0) , title="WaveTrend color" , group="WaveTrend Settings")
colorWT2 = input.color(color.new(color.aqua,50) , title="WaveTrend MA color" , group="WaveTrend Settings")
colorWTBull = input.color(color.new(color.red,50) , title="Bull WaveTrend color" , group="WaveTrend Settings")
colorWTBear = input.color(color.new(color.green,50), title="Bear WaveTrend color" , group="WaveTrend Settings")
pwt1 = plot(display_input ? display_wt ? wt1+offsetDisplay : na : na, title="WaveTrend" , color=colorWT1, linewidth = 1)
pwt2 = plot(display_input ? display_wt ? wt2+offsetDisplay : na : na, title="WaveTrendMA" , color=colorWT2, linewidth = 1)
//fill(pwt1,pwt2, wt1<wt2 ? colorWTBull : colorWTBear)
plot(display_input ? display_wtDelta ? wtDelta+offsetDisplay : na : na, title="WaveTrend Delta" , color=colorWT1, linewidth = 1)
//---- Distance ATH
display_DistanceATH = input.bool(false, title="Display distance from ATH indicator ?" , group="Distance ATH Settings")
distance_from_ATH = nz(100+request.security("GLASSNODE:BTC_ATHDRAWDOWN", "W", close)*100,0)
// Plot
colorDistanceATH = input.color(color.new(color.navy,0) , title="Distance ATH color", group="Distance ATH Settings")
plot(display_input ? display_DistanceATH ? distance_from_ATH+offsetDisplay : na : na, title="Distance from ATH (%)", color=colorDistanceATH, linewidth = 1)
distanceMA(l,amp,offset) =>
smaFix = nz(request.security("INDEX:BTCUSD", "W", nz(ta.sma(close, l),LowDev) ),0)
math.max(math.min( (((bwClose - smaFix) / (amp*smaFix))*100)+offset ,100),0)
//---- Distance short weekly moving average
display_DistanceShortSMA= input.bool(false,title="Display distance from short weekly moving average ?" , group="Distance short MA weekly Settings")
lengthSSMA = input.int( 7 , title="Short MA Length", minval=1 , group="Distance short MA weekly Settings")
amplSSMA = input.float(1.0, title="Short MA Amplitude" , group="Distance short MA weekly Settings")
offsetSSMA = input.int( 30 , title="Short MA Offset" , group="Distance short MA weekly Settings")
distance_close_shortsma = distanceMA(lengthSSMA,amplSSMA,offsetSSMA)
// Plot
colorDistanceShortSMA = input.color(color.new(color.aqua,0), title="Distance short MA weekly color" , group="Distance short MA weekly Settings")
plot(display_input ? display_DistanceShortSMA ? distance_close_shortsma+offsetDisplay : na : na, title='Distance from short MA Weekly', color=colorDistanceShortSMA, linewidth=1)
//---- Distance long weekly moving average
display_DistanceLongSMA = input.bool(true, title="Display distance from long weekly moving average ?" , group="Distance long MA weekly Settings")
lengthLSMA = input.int( 200 , title="Long MA Length", minval=1 , group="Distance long MA weekly Settings")
amplLSMA = input.float(6.0, title="Long MA Amplitude" , group="Distance long MA weekly Settings")
offsetLSMA = input.int( 0 , title="Long MA Offset" , group="Distance long MA weekly Settings")
distance_close_longsma = distanceMA(lengthLSMA,amplLSMA,offsetLSMA)
// Plot
colorDistanceLongSMA = input.color(color.new(color.aqua,0), title="Distance long MA weekly color" , group="Distance long MA weekly Settings")
plot(display_input ? display_DistanceLongSMA ? distance_close_longsma+offsetDisplay : na : na , title='Distance from long MA Weekly' , color=colorDistanceLongSMA , linewidth=1)
//---- Williams Percent Range
display_wr = input.bool(false, title="Display Williams Percent Range indicator ?" , group="Williams %R Settings")
lengthWR = input.int(14, minval=1, title="Williams %R Length" , group="Williams %R Settings")
williamsRangeMethod(length) =>
(100 * (close - ta.highest(length)) / (ta.highest(length) - ta.lowest(length))) + 100
wr = nz(request.security("INDEX:BTCUSD", "W", williamsRangeMethod(lengthWR) ),0)
// Plot
colorWR = input.color(color.new(color.purple,0) , title="Williams %R color", group="Williams %R Settings")
plot(display_input ? display_wr ? wr+offsetDisplay : na : na, title="W%R", color=colorWR, linewidth=1)
//---- Momentum adjusted
display_mom = input.bool(false, title="Display Momentum indicator ?", group="Momentum adjusted Settings")
momLengthInput = input.int(10, minval=1, title="Mom Length" , group="Momentum adjusted Settings")
securityMom = request.security("INDEX:BTCUSD", "W", close[momLengthInput]/close)
mom = nz(math.max(math.min( ((1 - securityMom) + 2.3)*30 ,100),0),0)
// Plot
colorMom = input.color(color.rgb(0,0,255,0), title="Mom color" , group="Momentum adjusted Settings")
plot(display_input ? display_mom ? mom+offsetDisplay : na : na, title="Mom", color=colorMom, linewidth=1)
//---- RSI + Stoch
//RSI
display_rsi = input.bool(false, title="Display RSI indicator ?" , group="Relative Strength Index Settings")
rsiLengthInput = input.int(14, minval=1, title="RSI Length" , group="Relative Strength Index Settings")
rsi = nz(request.security("INDEX:BTCUSD", "W", ta.rsi(close,rsiLengthInput)),0)
//Stoch
display_stoch = input.bool(true , title="Display Stochastic indicators ?" , group="Stochastic Settings")
display_kdDelta = input.bool(false, title="Display delta between K and D ?" , group="Stochastic Settings", tooltip="Represents the difference between the stochastic and its SMA")
smoothK = input.int(3, minval=1, title="K Length" , group="Stochastic Settings")
smoothD = input.int(3, minval=1, title="D Length" , group="Stochastic Settings")
k = nz(request.security("INDEX:BTCUSD", "W", ta.sma(ta.stoch(rsi, rsi, rsi, rsiLengthInput), smoothK)),0)
d = nz(request.security("INDEX:BTCUSD", "W", ta.sma(k, smoothD)),0)
kdDelta = nz(math.max(math.min( (k - d) + 50 ,100),0),0)
// Plot
colorRSI = input.color(color.rgb(255,127,0,0) , title="RSI color" , group="Relative Strength Index Settings")
colorStoch = input.color(color.new(color.orange,0) , title="Stochastic color" , group="Stochastic Settings")
//colorStochD = input.color(color.new(color.blue ,0) , title="Stochastic D color", group="Stochastic Settings")
plot(display_input ? display_rsi ? rsi+offsetDisplay : na : na, title="RSI" , color=colorRSI , linewidth=1)
plot(display_input ? display_stoch ? k+offsetDisplay : na : na, title="K" , color=colorStoch , linewidth=1)
//plot(display_input ? display_stoch ? d+offsetDisplay : na : na, title="D" , color=colorStochD , linewidth=1)
plot(display_input ? display_kdDelta ? kdDelta+offsetDisplay : na : na, title="KDDelta" , color=colorStoch , linewidth=1)
//---- Relative Volatility Index
display_rvi = input.bool(false, title="Display RVI indicator ?" , group="Relative Volatility Index Settings")
lengthStDevRVI = input.int(10, minval=1, title="RVI Length price deviation", group="Relative Volatility Index Settings")
lengthEMARVI = input.int(14, minval=1, title="RVI Length EMA" , group="Relative Volatility Index Settings")
stddevRVI = nz(request.security("INDEX:BTCUSD", "W", ta.stdev(close,lengthStDevRVI)),0)
upperRVI = nz(request.security("INDEX:BTCUSD", "W", ta.ema(ta.change(close) <= 0 ? 0 : stddevRVI, lengthEMARVI)),0)
lowerRVI = nz(request.security("INDEX:BTCUSD", "W", ta.ema(ta.change(close) > 0 ? 0 : stddevRVI, lengthEMARVI)),0)
rvi = nz(upperRVI / (upperRVI + lowerRVI) * 100,0)
// Plot
colorRVI = input.color(color.new(color.purple,0) , title="RVI color", group="Relative Volatility Index Settings")
plot(display_input ? display_rvi ? rvi+offsetDisplay : na : na, title="RVI", color=colorRVI, linewidth=1)
//---- True Strength Indicator
display_tsi = input.bool(false, title="Display TSI indicator ?" , group="True Strength Indicator Settings")
longTSI = input.int(25, minval=1, title="TSI Long Length" , group="True Strength Indicator Settings")
shortTSI = input.int(13, minval=1, title="TSI Short Length" , group="True Strength Indicator Settings")
double_smoothTSI(closeTSI, longTSI, shortTSI) =>
ta.ema(ta.ema(closeTSI, longTSI), shortTSI)
double_smoothed_pcTSI = nz(request.security("INDEX:BTCUSD", "W", double_smoothTSI(ta.change(close), longTSI, shortTSI)),0)
double_smoothed_abs_pcTSI = nz(request.security("INDEX:BTCUSD", "W", double_smoothTSI(math.abs(ta.change(close)), longTSI, shortTSI)),0)
tsi = nz(math.max(math.min( 70 * ((double_smoothed_pcTSI / double_smoothed_abs_pcTSI) + 0.4) ,100),0),0)
// Plot
colorTSI = input.color(color.new(color.yellow,0), title="TSI color" , group="True Strength Indicator Settings")
plot(display_input ? display_tsi ? tsi+offsetDisplay : na : na, title="TSI", color=colorTSI, linewidth=1)
//---- Bollinger Bands
display_bb = input.bool(true, title="Display BB ratio indicator ?" , group="Bollinger Bands Settings")
lengthBB = input.int( 20 , minval=1 , step=1 , title="Bollinger Period Length" , group="Bollinger Bands Settings")
multBB = input.float( 2.0, minval=0.1, step=0.1, title="Bollinger Bands Standard Deviation", group="Bollinger Bands Settings")
basisBB = request.security("INDEX:BTCUSD", "W", ta.sma(close, lengthBB))
devBB = request.security("INDEX:BTCUSD", "W", multBB * ta.stdev(close, lengthBB))
upperBB = basisBB + devBB
lowerBB = basisBB - devBB
RangeBB = upperBB - lowerBB
ratioBB = nz(math.max(math.min( (((bwClose - lowerBB) / RangeBB)*100) ,100),0),0)
// Plot
colorBB = input.color(color.new(color.red,0) , title="BB ratio color", group="Bollinger Bands Settings")
plot(display_input ? display_bb ? ratioBB+offsetDisplay : na : na, title="BB", color=colorBB, linewidth=1)
//---- Donchian oscillator
display_dc = input.bool(false , title="Display Donchian indicator ?" , group="Donchian Oscillator Settings")
lengthDC = input.int(20, minval=1, step=1, title="Donchian Period Length" , group="Donchian Oscillator Settings")
ratioDC = nz(request.security("INDEX:BTCUSD", "W", ((close-ta.lowest(lengthDC))/(ta.highest(lengthDC)-ta.lowest(lengthDC)))*100 ),0)
// Plot
colorDC = input.color(color.new(color.blue,0) , title="DC ratio color", group="Donchian Oscillator Settings")
plot(display_input ? display_dc ? ratioDC+offsetDisplay : na : na, title="DC", color=colorDC, linewidth=1)
//---- Schaff Trend Cycle
display_stc = input.bool(true,title="Display Schaff Trend Cycle indicator ?", group="Schaff Trend Cycle Settings")
lengthSTC = input.int(10, minval=1, title="Schaff Trend Cycle length" , group="Schaff Trend Cycle Settings")
fastLengthSTC = input.int(23, minval=1, title="Schaff Trend Cycle fast length", group="Schaff Trend Cycle Settings")
slowLengthSTC = input.int(50, minval=1, title="Schaff Trend Cycle slow length", group="Schaff Trend Cycle Settings")
stcMethod(length, fastLength, slowLength) =>
m = ta.ema(close, fastLength) - ta.ema(close, slowLength)
Kstc = nz(fixnan(ta.stoch(m, m, m, length)))
Dstc = ta.ema(Kstc, 3)
KDstc = nz(fixnan(ta.stoch(Dstc, Dstc, Dstc, 3)))
stc = ta.ema(KDstc, 3)
stc := math.max(math.min(stc, 100), 0)
stc = nz(request.security("INDEX:BTCUSD", "W", stcMethod(lengthSTC,fastLengthSTC,slowLengthSTC)),0)
// Plot
colorSTC = input.color(color.rgb(128,0,128,0), title="Schaff Trend Cycle color" , group="Schaff Trend Cycle Settings")
plot(display_input ? display_stc ? stc+offsetDisplay : na : na, title="STC", color=colorSTC, linewidth=1)
//---- Aroon
display_aroonUp = input.bool(true ,title="Display AroonUp indicator ?" , group="Aroon Settings")
display_aroonDown = input.bool(false,title="Display AroonDown indicator ?" , group="Aroon Settings")
lengthAroonUp = input.int(14, minval=1, title="AroonUp length" , group="Aroon Settings")
lengthAroonDown = input.int(14, minval=1, title="AroonDown length" , group="Aroon Settings")
aroonUp = nz(request.security("INDEX:BTCUSD", "W",( 100 * (ta.highestbars(high, lengthAroonUp+1) + lengthAroonUp) /lengthAroonUp ) ),0)
aroonDown = nz(request.security("INDEX:BTCUSD", "W",(-100 * (ta.lowestbars(low , lengthAroonDown+1) + lengthAroonDown)/lengthAroonDown) + 100 ),0)
// Plot
colorAroonUp = input.color(color.orange , title="AroonUp color" , group="Aroon Settings")
colorAroonDown = input.color(color.blue , title="AroonDown color" , group="Aroon Settings")
plot(display_input ? display_aroonUp ? aroonUp +offsetDisplay : na : na, title="AroonUp" , color=colorAroonUp , linewidth=1)
plot(display_input ? display_aroonDown ? aroonDown +offsetDisplay : na : na, title="AroonDown" , color=colorAroonDown , linewidth=1)
//---- Ultimate Oscillator
display_uo = input.bool(false,title="Display Ultimate Oscillator ?", group="Ultimate Oscillator Settings")
length1UO = input.int(7 , minval=1, title = "Fast UO Length")
length2UO = input.int(14, minval=1, title = "Middle UO Length")
length3UO = input.int(28, minval=1, title = "Slow UO Length")
average(bp, tr, length) => math.sum(bp, length) / math.sum(tr, length)
uoMethod(l1,l2,l3) =>
highUO = math.max(high, close[1])
lowUO = math.min(low, close[1])
bpUO = close - highUO
trUO = highUO - lowUO
uoAvg7 = average(bpUO, trUO, l1)
uoAvg14 = average(bpUO, trUO, l2)
uoAvg28 = average(bpUO, trUO, l2)
uo = 100 * (4*uoAvg7 + 2*uoAvg14 +uoAvg28)/7
uo = nz(math.max(math.min( request.security("INDEX:BTCUSD", "W", uoMethod(length1UO,length2UO,length3UO)*1.5 + 100) ,100),0),0)
// Plot
colorUO = input.color(color.red , title="UO color" , group="Ultimate Oscillator Settings")
plot(display_input ? display_uo ? uo+offsetDisplay : na : na, title="UO", color=colorUO, linewidth=1)
//---- Money Flow Index
display_mfi = input.bool(false, title="Display Money Flow Index indicator ?", group="Money Flow Index Settings")
lengthMFI = input.int(14, minval=1, maxval=2000 , title="MFI Length" , group="Money Flow Index Settings")
mfi = nz(request.security("INDEX:BTCUSD", "W", ta.mfi(hlc3, lengthMFI)),0)
// Plot
colorMFI = input.color(color.new(color.green,0) , title="MFI color" , group="Money Flow Index Settings")
plot(display_input ? display_mfi ? mfi+offsetDisplay : na : na, title="MFI", color=colorMFI, linewidth=1)
//---- Chaikin Money Flow
display_cmf = input.bool(false, title="Display Chaikin Money Flow indicator ?" , group="Chaikin Money Flow Settings")
lengthCMF = input.int(21, minval=1, maxval=1000, title="Chaikin Money Flow Length", group="Chaikin Money Flow Settings")
mfvCMF = nz(request.security("INDEX:BTCUSD", "W", math.sum(((high == low) ? 0 : ((close - low) - (high - close)) / (high - low)) * volume, lengthCMF) / math.sum(volume, lengthCMF) ),0)
cmf = nz(math.max(math.min( (mfvCMF * 150) + 30 ,100),0),0)
// Plot
colorCMF = input.color(color.new(color.lime,0), title="Chaikin Money Flow color" , group="Chaikin Money Flow Settings")
plot(display_input ? display_cmf ? cmf+offsetDisplay : na : na, title="CMF", color=colorCMF, linewidth=1)
//---- Volume Weighted Moving Average
display_vwma = input.bool(false, title="Display distance from Volume Weighted Moving Average indicator ?", group="Volume Weighted Moving Average Settings")
lengthVWMA = input.int(16, minval=1, maxval=1000, title="Volume Weighted Moving Average Length" , group="Volume Weighted Moving Average Settings")
vwmaReq = nz(request.security("INDEX:BTCUSD", "W", close/ta.vwma(close, lengthVWMA)),0)
vwma = nz(math.max(math.min( vwmaReq*50 - 25 ,100),0),0)
// Plot
colorVWMA = input.color(color.new(color.silver,0), title="Volume Weighted Moving Average color" , group="Volume Weighted Moving Average Settings")
plot(display_input ? display_vwma ? vwma+offsetDisplay : na : na, title="VWMA", color=colorVWMA, linewidth=1)
//---- Volume Oscillator
display_vo = input.bool(false, title="Display Volume Oscillator ?" , group="Volume Oscillator Settings")
shortLenVO = input.int(5 , minval=1, title = "Short Length")
longLenVO = input.int(10, minval=1, title = "Long Length")
vo = nz(request.security("INDEX:BTCUSD", "W", math.max(math.min((100 * (ta.ema(volume, shortLenVO) - ta.ema(volume, longLenVO)) / ta.ema(volume, longLenVO)) + 50,100),0) ),0)
// Plot
colorVO = input.color(color.red, title="Volume Oscillator color", group="Volume Oscillator Settings")
plot(display_input ? display_vo ? vo+offsetDisplay : na : na, title="VO", color=colorVO, linewidth=1)
//---- BTC Supply / BTC Max Supply
display_supply = input.bool(false, title="Display Bitcoin supply ratio ?" , group="Supply Settings", tooltip="Represents the ratio between the current and max supply of bitcoin")
supplyBTC = nz(request.security("GLASSNODE:BTC_SUPPLY", "W", close),0)
supplyRatio = supplyBTC/210000 //21M divide by 100
//Plot
colorSupply = input.color(color.new(color.white,0), title="Supply color" , group="Supply Settings")
plot(display_input ? display_supply ? supplyRatio+offsetDisplay : na : na, title='Supply Ratio' , color=colorSupply , linewidth=1)
//---- Mayer Multiple
display_mayer = input.bool(false, title="Display Mayer Multiple indicator ?" , group="Mayer Settings")
psma_length = input.int(200, minval=1, title="Price SMA Length" , group="Mayer Settings")
mayerMultiple = nz(request.security("INDEX:BTCUSD", "D", ((close / ta.sma(close, psma_length))*600)/(100-supplyRatio/1.3) ),0)
//Plot
colorMayer = input.color(color.new(color.maroon,0), title="Mayer color" , group="Mayer Settings")
plot(display_input ? display_mayer ? mayerMultiple+offsetDisplay : na : na, title='Mayer Multiple' , color=colorMayer , linewidth=1)
//---- Moon Phases
display_moon= input.bool(false, title="Display Moon phases ?", group="Moon phases Settings")
cycle = 2551442876.8992
day = 8.64e+7
moon = ((timestamp("2021-01-13:05:00") + time + day)%cycle/cycle)*100
moonCycle = (moon<50 ? moon : 100-moon)*2
//Plot
colorMoon = input.color(color.new(color.gray,0), title="Moon phases color", group="Moon phases Settings")
plot(display_input ? display_moon ? moonCycle+offsetDisplay : na : na, title='Moon phases' , color=colorMoon , linewidth=1)
//---- Heikin Ashi
display_haDelta = input.bool(false, title="Display Delta between price Heikin Ashi ?", group="Heikin Ashi Indicator Settings", tooltip="Represents the difference between close price and close Heikin Ashi")
display_haTrend = input.bool(false, title="Display Heikin Ashi trend indicator ?" , group="Heikin Ashi Indicator Settings", tooltip="100 if Heikin Ashi candle is green, 0 if red")
ha_open = nz(request.security(ticker.heikinashi("INDEX:BTCUSD"), "W", open),0)
ha_close = nz(request.security(ticker.heikinashi("INDEX:BTCUSD"), "W", close),0)
haDelta = nz(math.max(math.min( (bwClose / ha_close) * 200 - 150 ,100),0),0)
//haTrend = nz(math.max(math.min( (ha_close / ha_open) * 100 - 50 ,100),0),0)
haTrend = nz( ha_close > ha_open ? 100 : 0 ,0)
// Plot
colorHA = input.color(color.new(color.silver,0), title="Heikin Ashi color" , group="Heikin Ashi Indicator Settings")
plot(display_input ? display_haDelta ? haDelta+offsetDisplay : na : na, title="HA Delta", color=colorHA, linewidth=1)
plot(display_input ? display_haTrend ? haTrend+offsetDisplay : na : na, title="HA Trend", color=colorHA, linewidth=1)
//######## OUTPUT
// Variable
avgIndicators() =>
sumIndicators = (display_LogCurve ? logCurveHighValue : 0) + (display_wt ? wt1 : 0) + (display_DistanceATH ? distance_from_ATH : 0) + (display_DistanceShortSMA ? distance_close_shortsma : 0) + (display_DistanceLongSMA ? distance_close_longsma : 0) + (display_wr ? wr : 0) + (display_mom ? mom : 0) + (display_rsi ? rsi : 0) + (display_stoch ? k : 0) + (display_rvi ? rvi : 0) + (display_tsi ? tsi : 0) + (display_haDelta ? haDelta : 0) + (display_haTrend ? haTrend : 0) + (display_bb ? ratioBB : 0) + (display_dc ? ratioDC : 0) + (display_stc ? stc : 0) + (display_aroonUp ? aroonUp : 0) + (display_aroonDown ? aroonDown : 0) + (display_uo ? uo : 0) + (display_mfi ? mfi : 0) + (display_cmf ? cmf : 0) + (display_vwma ? vwma : 0) + (display_mayer ? mayerMultiple : 0) + (display_moon ? moonCycle : 0)
nbIndicators = (display_LogCurve ? 1 : 0) + (display_wt ? 1 : 0) + (display_DistanceATH ? 1 : 0) + (display_DistanceShortSMA ? 1 : 0) + (display_DistanceLongSMA ? 1 : 0) + (display_wr ? 1 : 0) + (display_mom ? 1 : 0) + (display_rsi ? 1 : 0) + (display_stoch ? 1 : 0) + (display_rvi ? 1 : 0) + (display_tsi ? 1 : 0) + (display_haDelta ? 1 : 0) + (display_haTrend ? 1 : 0) + (display_bb ? 1 : 0) + (display_dc ? 1 : 0) + (display_stc ? 1 : 0) + (display_aroonUp ? 1 : 0) + (display_aroonDown ? 1 : 0) + (display_uo ? 1 : 0) + (display_mfi ? 1 : 0) + (display_cmf ? 1 : 0) + (display_vwma ? 1 : 0) + (display_mayer ? 1 : 0) + (display_moon ? 1 : 0)
sumIndicators / nbIndicators
//---- Risk Indicator
riskRatio = avgIndicators()
display_Risk = input.bool(true, title="Display Risk indicator ?" , group="Risk Settings", tooltip="It is a synthetic output indicator that simply averages all the input indicators you have selected")
barcolor_Risk = input.bool(true,title="Display barcolor with Risk indicator ?" , group="Risk Settings")
levelRiskSafe = input.int(10, minval=0, maxval=100, title="Level risk safe" , group="Risk Settings")
colorRiskSafe = input.color(color.rgb(0,0,255,0) , title="Risk safe color" , group="Risk Settings")
levelRiskOk = input.int(30, minval=0, maxval=100, title="Level risk ok" , group="Risk Settings")
colorRiskOk = input.color(color.rgb(0,255,0,0) , title="Risk ok color" , group="Risk Settings")
levelRiskWarn = input.int(50, minval=0, maxval=100, title="Level risk warn" , group="Risk Settings")
colorRiskWarn = input.color(color.rgb(255,255,0,0), title="Risk warning color" , group="Risk Settings")
levelRiskDanger = input.int(90, minval=0, maxval=100, title="Level risk danger" , group="Risk Settings")
colorRiskDanger = input.color(color.rgb(255,0,0,0) , title="Risk danger color" , group="Risk Settings")
colorRisk = riskRatio > levelRiskOk ? riskRatio > levelRiskWarn ? color.from_gradient(riskRatio, levelRiskWarn, levelRiskDanger, colorRiskWarn, colorRiskDanger) : color.from_gradient(riskRatio, levelRiskOk, levelRiskWarn, colorRiskOk, colorRiskWarn) : color.from_gradient(riskRatio, levelRiskSafe, levelRiskOk, colorRiskSafe, colorRiskOk)
// Plot
band1 = hline(display_input ? offsetDisplay : 0 , color=color.gray, linestyle=hline.style_solid)
band0 = hline(0 , color=color.gray, linestyle=hline.style_solid)
bandMinus1 = hline(display_output ? 100 : 0 , color=color.gray, linestyle=hline.style_solid)
plot(display_output ? display_Risk ? riskRatio : na : na, title="Risk Ratio", color=colorRisk, linewidth = 2)
barcolor(color=barcolor_Risk ? colorRisk : na)
|
Swap Trading Pair Price | https://www.tradingview.com/script/fmakH52e/ | jasonyl13579 | https://www.tradingview.com/u/jasonyl13579/ | 7 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jasonyl13579
//@version=4
study("Swap Pair", overlay=false, precision=6)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
symbol_in1 = input("SOL", "Symbol", type=input.string, group='Swap pair symbol1')
exchange_symbol1 = input("BINANCE", "Exchange", type=input.string, options=["BINANCE", "FTX","OKEX","COINEX"], group='Swap pair symbol1')
symbol_in2 = input("GST", "Symbol", type=input.string, group='Swap pair symbol2')
exchange_symbol2 = input("COINEX", "Exchange", type=input.string, options=["BINANCE", "FTX","OKEX","COINEX"], group='Swap pair symbol2')
src = input(hlc3, title="Source", type=input.source)
upper = input(23, "Upper", type=input.float, step=0.001, minval=0, group='Threshold')
lower = input(31, "Lower", type=input.float, step=0.001, maxval=0, group='Threshold')
mid = (upper + lower) / 2
// get datas
f() => [src, volume]
[p1, v1] = security(exchange_symbol1 +':' + symbol_in1 + "USDT", timeframe.period, f())
[p2, v2] = security(exchange_symbol2 +':' + symbol_in2 + "USDT", timeframe.period, f())
swap_price = p1/p2
plot(swap_price, title="Swap")
h0 = hline(mid, "mid")
h1 = hline(upper, "upper")
h2 = hline(lower, "lower")
fill(h0, h1, color=color.green, transp=85, title="upper area")
fill(h0, h2, color=color.red, transp=85, title="lower area") |
Pinbar Indicator | https://www.tradingview.com/script/cLr1b2ee-Pinbar-Indicator/ | dandrideng | https://www.tradingview.com/u/dandrideng/ | 270 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dandrideng
//@version=5
indicator(title="Pinbar Indicator", shorttitle="Pinbar", overlay=true, max_bars_back=1000, max_lines_count=400, max_labels_count=400)
import dandrideng/merge_pinbar/1 as mp
//pinbar pattern
draw_pinbar = input.bool(defval=true, title="Draw Pinbar Pattern Alert?", group="Pinbar Patttern")
pinbar_period = input.int(defval=240, title="Pinbar Statistic Period", minval=1, step=1, group="Pinbar Patttern")
max_merged_bars = input.int(defval=2, title="Max Merged Bars", minval=1, step=1, group="Pinbar Patttern")
min_strength = input.float(defval=1.5, title="Min Pinbar Strength", minval=0.1, step=0.1, group="Pinbar Patttern")
to_intstr(x) =>
str.tostring(x, "#")
to_floatstr(x) =>
str.tostring(x, "#.###")
[pinbar_type, pinbar_bars, pinbar_strength] = mp.merge_pinbar(pinbar_period, max_merged_bars)
if pinbar_type == 1 and pinbar_strength >= min_strength and draw_pinbar
pinbar_label = label.new(x=bar_index, y=low)
label.set_text(pinbar_label, "Bull Pinbar: "+ to_intstr(pinbar_bars) + "\nStrength: " + to_floatstr(pinbar_strength))
label.set_color(pinbar_label, color.new(color.blue, 40))
label.set_textcolor(pinbar_label, color.white)
label.set_style(pinbar_label, label.style_label_up)
if pinbar_type == -1 and pinbar_strength >= min_strength and draw_pinbar
pinbar_label = label.new(x=bar_index, y=high)
label.set_text(pinbar_label, "Bear Pinbar: "+ to_intstr(pinbar_bars) + "\nStrength: " + to_floatstr(pinbar_strength))
label.set_color(pinbar_label, color.new(color.purple, 40))
label.set_textcolor(pinbar_label, color.white)
label.set_style(pinbar_label, label.style_label_down)
//end of file |
YTD | https://www.tradingview.com/script/IOVfTwNH-YTD/ | ChartingCycles | https://www.tradingview.com/u/ChartingCycles/ | 49 | study | 5 | MPL-2.0 | //This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//©ChartingCycles
//@version=5
indicator('YTD', scale=scale.none, overlay=true, precision=0, format=format.percent)
//YTD % Gain Calculation
specificDate = time >= timestamp(year(timenow), 1, 1, 00, 00)
var float closeOnDate = na
if specificDate and not specificDate[1]
closeOnDate := close
closeOnDate
YTD = (close - closeOnDate) / closeOnDate
//Panel
var string GP2 = 'Display'
show_header = timeframe.isdaily ? input.bool(true, title='Show Table Header', inline='10', group=GP2) : false
string i_tableYpos = input.string('top', 'Panel Position', inline='11', options=['top', 'middle', 'bottom'], group=GP2)
string i_tableXpos = input.string('right', '', inline='11', options=['left', 'center', 'right'], group=GP2)
string textsize = input.string('normal', 'Text Size', inline='12', options=['small', 'normal', 'large'], group=GP2)
var table dtrDisplay = table.new(i_tableYpos + '_' + i_tableXpos, 3, 2, frame_width=1, frame_color=color.black, border_width=1, border_color=color.black)
if barstate.islast
// We only populate the table on the last bar.
if show_header == true
table.cell(dtrDisplay, 1, 0, 'YTD %', bgcolor=color.black, text_size=textsize, text_color=color.white)
table.cell(dtrDisplay, 1, 1, str.tostring(math.round((YTD*100),1)) + '%', bgcolor= YTD>0 ? color.teal : color.red, text_size=textsize, text_color=color.white)
|
Relative Performance Table | https://www.tradingview.com/script/7c2oS4Sl-Relative-Performance-Table/ | Wheeelman | https://www.tradingview.com/u/Wheeelman/ | 59 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wheeelman
// This script takes the Performance Indicator that was first published by @BeeHolder) and compares the performance of the chart
// ticker to the performance of a selected index/ticker.
//@version=5
indicator("Relative Performance", overlay=true)
// === USER INPUTS PERFORMANCE TABLE ===
//Table Structure/format
//i_transpose = input(true, title="Transpose Table ", group="Table Settings")
//i_tablecolumns = input.int(15, "Number of columns", group = "Table Settings")
i_cell_width = input.float(0, title="Cell Width", group="Perfomance Table Settings", tooltip="Adjust Cell Width (0 will auto adjust width)")
i_border_width = input.int(2, title="Border Width", group="Perfomance Table Settings", tooltip="Adjust Cell Border Size")
i_text_size = input.string(title="Text Size", options=["Large", "Normal", "Small"], defval="Normal",group="Perfomance Table Settings")
i_posColor = input(color(#089981), title='Positive Color',group="Perfomance Table Settings")
i_negColor = input(color(#f23645), title='Negative Color',group="Perfomance Table Settings")
i_ticColor = input(color.new(#999999, 0), title='Ticker Color',group="Perfomance Table Settings")
i_sym_compare = input.symbol(title='Index/Ticker Compare', defval='SP:SPX',group="Perfomance Table Settings")
i_tablePositionY = input.string('bottom', title='Y-Position', options=['top', 'middle', 'bottom'], group="Perfomance Table Settings", inline="pos")
i_tablePositionX = input.string('right', title='X-Position', options=['left', 'center', 'right'], group="Perfomance Table Settings", inline="pos")
//Timeframe Inputs Performance Table
tooltipText = "Custom timeframes can be added via the chart's Timeframe dropdown. Until added, custom timeframes show up as 'Chart' instead."
showTF1 = input.bool(true, "", inline = "TF1", group = "Performance: Absolute timeframes")
tf1 = input.timeframe("1W", "", inline = "TF1", group = "Performance: Absolute timeframes", tooltip = "Select any timeframe > D, intraday is not compatible")
showTF2 = input.bool(true, "", inline = "TF2", group = "Performance: Absolute timeframes")
tf2 = input.timeframe("1M", "", inline = "TF2", group = "Performance: Absolute timeframes")
showTF3 = input.bool(true, "", inline = "TF3", group = "Performance: Absolute timeframes")
tf3 = input.timeframe("3M", "", inline = "TF3", group = "Performance: Absolute timeframes")
showTF4 = input.bool(true, "", inline = "TF4", group = "Performance: Absolute timeframes")
tf4 = input.timeframe("6M", "", inline = "TF4", group = "Performance: Absolute timeframes")
showTF5 = input.bool(true, "", inline = "TF5", group = "Performance: Absolute timeframes")
tf5 = input.timeframe("9M", "", inline = "TF5", group = "Performance: Absolute timeframes")
showTF6 = input.bool(true, "", inline = "TF6", group = "Performance: Absolute timeframes")
tf6 = input.timeframe("52W", "", inline = "TF6", group = "Performance: Absolute timeframes")
showTF7 = input.bool(true, "", inline = "TF7", group = "Performance: To-Date timeframes")
tf7 = input.timeframe("1W", "", inline = "TF7", group = "Performance: To-Date timeframes")
showTF8 = input.bool(true, "", inline = "TF8", group = "Performance: To-Date timeframes")
tf8 = input.timeframe("1M", "", inline = "TF8", group = "Performance: To-Date timeframes")
showTF9 = input.bool(true, "", inline = "TF9", group = "Performance: To-Date timeframes")
tf9 = input.timeframe("12M", "", inline = "TF9", group = "Performance: To-Date timeframes")
//===MISC Variables
lightTransp = 90
avgTransp = 80
heavyTransp = 70
text_size_output(type) =>
type == 'Large' ? size.large : type == 'Normal' ? size.normal : type == 'Small' ? size.small : na
text_size_ = text_size_output(i_text_size)
//==========Performance Array
var showTFArray = array.from(showTF1, showTF2, showTF3, showTF4, showTF5, showTF6, showTF7, showTF8, showTF9,showTF1, showTF2, showTF3, showTF4, showTF5, showTF6, showTF7, showTF8, showTF9)
var timeframesArray = array.from(tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8, tf9,tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8, tf9)
if barstate.isfirst
for i = 0 to array.size(showTFArray) - 1
tf = array.get(timeframesArray, i)
if not na(str.tonumber(tf))
runtime.error(str.format("Intraday timeframes (`{0}` in Timeframe #{1}) are not compatible with this indicator.", tf, i + 1))
//====Timeframe Logic====================
timeframeInMS(timeframe) =>
numTf = str.tonumber(timeframe)
tfLength = str.length(timeframe)
float tfNumber = na
string tfLetter = na
if numTf
tfNumber := numTf
else
tfLetter := str.substring(timeframe, tfLength - 1, tfLength)
tfNumber := str.tonumber(str.substring(timeframe, 0, tfLength - 1))
tfBaseInMS = switch tfLetter
"S" => 60 * 1000
"D" => 24 * 60 * 60 * 1000
"W" => 7 * 24 * 60 * 60 * 1000
"M" => 30 * 24 * 60 * 60 * 1000
=> 60 * 60 * 1000
int(tfBaseInMS * tfNumber)
fastSearch(source, target) =>
max_bars_back(source, 366)
left = 0
right = math.min(bar_index, 366)
mid = 0
if source < target
0
else
for i = 0 to 9
mid := math.ceil(math.avg(left, right))
if left == right
break
else if source[mid] < target
right := mid
continue
else if source[mid] > target
left := mid
continue
else
break
mid
rateOfreturn(v1, v2) => (v1 - v2) * 100 / math.abs(v2)
recentclose(sec) =>
request.security(sec, '1D', close)
performance(timeframe) =>
sourceTime = barstate.isconfirmed ? time_close : timenow
barsBack = fastSearch(time, sourceTime - timeframeInMS(timeframe))
performance = request.security(syminfo.tickerid, "1D", rateOfreturn(close, close[barsBack]), lookahead=barmerge.lookahead_on)
performance
tf7Sec = request.security(syminfo.tickerid, tf7, close[1], lookahead=barmerge.lookahead_on)
tf8Sec = request.security(syminfo.tickerid, tf8, close[1], lookahead=barmerge.lookahead_on)
tf9Sec = request.security(syminfo.tickerid, tf9, close[1], lookahead=barmerge.lookahead_on)
rel_performance(timeframe) =>
rel_sourceTime = barstate.isconfirmed ? time_close : timenow
rel_barsBack = fastSearch(time, rel_sourceTime - timeframeInMS(timeframe))
rel_performance = request.security(i_sym_compare, "1D", rateOfreturn(close, close[rel_barsBack]), lookahead=barmerge.lookahead_on)
rel_performance
rel_tf7Sec = request.security(i_sym_compare, tf7, close[1], lookahead=barmerge.lookahead_on)
rel_tf8Sec = request.security(i_sym_compare, tf8, close[1], lookahead=barmerge.lookahead_on)
rel_tf9Sec = request.security(i_sym_compare, tf9, close[1], lookahead=barmerge.lookahead_on)
//=======END PERFORMANCE LOGIC
//52 Week High
ftwh()=>
fth= ta.highest(high[1],52)
fth
fth = request.security(syminfo.tickerid, 'W', ftwh(),lookahead=barmerge.lookahead_on)
rel_fth = request.security(i_sym_compare, 'W', ftwh(),lookahead=barmerge.lookahead_on)
pricefth = (((recentclose(syminfo.tickerid)/fth)-1)*100 ) // Price Relative to 52 week high >75
rel_pricefth = (((recentclose(i_sym_compare)/rel_fth)-1)*100 ) // Price Relative to 52 week high >75
f_fillCell_fth(_table, _column, _row, _value) =>
_c_color = _value >= -25 ? i_posColor : i_negColor
_transp = heavyTransp
_cellText = str.tostring(_value, '0.00') + '%\n' + '% off 52H'
table.cell(_table, _column, _row, _cellText, bgcolor=color.new(_c_color, _transp), text_color=_c_color, width=i_cell_width,text_size = text_size_)
//PERFORMANCE TABLE
//How many columns are filled divided by number of rows
filled_columns = 0
for i = 0 to (array.size(showTFArray)/2)-1
if array.get(showTFArray, i)
filled_columns += 1
var table perfTable = table.new(i_tablePositionY + '_' + i_tablePositionX, filled_columns+2, 2, border_width = i_border_width)
f_fillCellSec(_table, _column, _row, _value) =>
table.cell(_table, _column, _row, _value, bgcolor=color.new(i_ticColor, avgTransp), text_color=i_ticColor, width=i_cell_width, text_size = text_size_)
fillCell(_table, column, row, value, timeframe) =>
_color = value >= 0 ? i_posColor : i_negColor
transp = math.abs(value) > 10 ? heavyTransp : math.abs(value) > 5 ? avgTransp : lightTransp
_cellText = str.tostring(value, "0.00") + "%\n" + timeframe
table.cell(_table, column, row, _cellText, bgcolor = color.new(_color, transp), text_color = _color, width = i_cell_width, text_size = text_size_)
formatTF(tf) =>
formattedTF = switch tf
"52W" => "1Y"
"12M" => "1Y"
=> tf
perftableArray = array.from(performance(tf1), performance(tf2), performance(tf3),
performance(tf4), performance(tf5), performance(tf6), rateOfreturn(close, tf7Sec),
rateOfreturn(close, tf8Sec),rateOfreturn(close, tf9Sec)
,rel_performance(tf1), rel_performance(tf2), rel_performance(tf3),
rel_performance(tf4), rel_performance(tf5), rel_performance(tf6), rateOfreturn(recentclose(i_sym_compare), rel_tf7Sec),
rateOfreturn(recentclose(i_sym_compare), rel_tf8Sec),rateOfreturn(recentclose(i_sym_compare), rel_tf9Sec))
perflabelArray = array.from(formatTF(tf1), formatTF(tf2), formatTF(tf3), formatTF(tf4),
formatTF(tf5), formatTF(tf6), formatTF(tf7) + "TD", formatTF(tf8) + "TD", formatTF(tf9) + "TD",
formatTF(tf1), formatTF(tf2), formatTF(tf3), formatTF(tf4),
formatTF(tf5), formatTF(tf6), formatTF(tf7) + "TD", formatTF(tf8) + "TD", formatTF(tf9) + "TD")
if barstate.islast
f_fillCellSec(perfTable, 0, 0, syminfo.ticker)
f_fillCellSec(perfTable, 0, 1, i_sym_compare)
f_fillCell_fth(perfTable,1, 0, pricefth)
f_fillCell_fth(perfTable,1, 1, rel_pricefth)
filled = 0
for i = 0 to array.size(showTFArray) - 1
if array.get(showTFArray, i)
fillCell(perfTable, (filled % filled_columns)+2, filled / filled_columns, array.get(perftableArray, i), array.get(perflabelArray, i))
filled += 1 |
EMAs Daily Reset | https://www.tradingview.com/script/5s6ZbphI-EMAs-Daily-Reset/ | SamRecio | https://www.tradingview.com/u/SamRecio/ | 134 | study | 5 | MPL-2.0 | // 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("EMAs Daily Reset", overlay = true)
recalc = input.timeframe("D", title = "Calculation Period:", tooltip = "Moving Averages will recalculate after every period has lapsed.")
type1 = input.string("EMA", title = "MA 1", options=["SMA", "EMA", "RMA", "WMA", "VWMA"], inline = "one")
len1 = input.int(21, minval = 1, title = "", inline = "one")
src1 = input.string("high", options = ["open", "high", "low", "close", "hl2", "hlc3", "ohlc4", "hlcc4", "HoB", "LoB"], title = "", inline = "one")
color1 = input.color(color.rgb(0,110,179), title = "", inline = "one")
type2 = input.string("EMA", title = "MA 2", options=["SMA", "EMA", "RMA", "WMA", "VWMA"], inline = "two")
len2 = input.int(13, minval = 1, title = "", inline = "two")
src2 = input.string("close", options = ["open", "high", "low", "close", "hl2", "hlc3", "ohlc4", "hlcc4", "HoB", "LoB"], title = "", inline = "two")
color2 = input.color(color.rgb(197,70,68), title = "", inline = "two")
type3 = input.string("EMA", title = "MA 3", options=["SMA", "EMA", "RMA", "WMA", "VWMA"], inline = "three")
len3 = input.int(5, minval = 1, title = "", inline = "three")
src3 = input.string("low", options = ["open", "high", "low", "close", "hl2", "hlc3", "ohlc4", "hlcc4", "HoB", "LoB"], title = "", inline = "three")
color3 = input.color(color.rgb(246,235,97), title = "", inline = "three")
src_get(_input) =>
_input == "open"?open:
_input == "high"?high:
_input == "low"?low:
_input == "close"?close:
_input == "hl2"?hl2:
_input == "hlc3"?hlc3:
_input == "ohlc4"?ohlc4:
_input == "hlcc4"?hlcc4:
_input == "HoB"?math.max(open,close):
_input == "LoB"?math.min(open,close):
na
newday = timeframe.change(recalc)
bs_nd = ta.barssince(newday) + 1
//EMA CALC/////////////////////////////////////////////////////
day_ma(_type,s,l) =>
v_len = bs_nd < l?bs_nd:l
var float ma = na
if _type == "EMA"
k = 2/(v_len + 1)
ma := (s*k) + (nz(ma[1])*(1-k))
if _type == "RMA"
a = (1/v_len)
ma := a * s + (1 - a) * nz(ma[1])
if _type == "SMA"
ma := ta.sma(s,v_len)
if _type == "WMA"
ma := ta.wma(s,v_len)
if _type == "VWMA"
ma := ta.vwma(s,v_len)
ma
//////////////////////////////////////////////////////////////
high_ma = day_ma(type1,src_get(src1),len1)
close_ma = day_ma(type2,src_get(src2),len2)
low_ma = day_ma(type3,src_get(src3),len3)
plot(high_ma, color = newday?color.new(color3,100):color1, title = "MA 1")
plot(close_ma, color = newday?color.new(color1,100):color2, title = "MA 2")
plot(low_ma, color = newday?color.new(color2,100):color3, title = "MA 3")
|
Discounted Price Probability | https://www.tradingview.com/script/24jjlUnS-Discounted-Price-Probability/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 409 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __
// / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / |
// $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ |
// $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ |
// $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ |
// $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ |
// $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ |
// $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ |
// $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/
//
//
//
//@version=5
indicator("Discounted Price Probability", overlay=true)
import HeWhoMustNotBeNamed/_matrix/1 as ma
import HeWhoMustNotBeNamed/drawingutils/3 as dr
reference = input.string('Inception', title='Reference', options=['Inception', 'Window'], group='Reference')
startTime = input.time(defval=timestamp('01 Jan 2010 00:00 +0000'), title='Start Time', group='Reference')
endTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), title='End Time', group='Reference')
inDateRange = time >= startTime and time <= endTime
considerEarningPrice = input.bool(true, 'Earning Price', group='Main Factors', inline='1')
considerFundamentalsPerShare = input.bool(true, 'Fundamentals/Share', group='Main Factors', inline='1')
considerMargins = input.bool(true, 'Margins', group='Main Factors', inline='1')
considerReturns = input.bool(true, 'Returns', group='Main Factors', inline='2')
considerInvertedDebtRatios = input.bool(true, 'Inverted Debt Ratios', group='Main Factors', inline='2')
considerBvps = input.bool(true, 'Book Value', group='Fundamentals/Share', inline='1')
considerEps = input.bool(true, 'Earning', group='Fundamentals/Share', inline='1')
considerRps = input.bool(true, 'Revenue', group='Fundamentals/Share', inline='1')
considerFcf = input.bool(true, 'FCF', group='Fundamentals/Share', inline='2')
considerEbit = input.bool(true, 'EBIT', group='Fundamentals/Share', inline='2')
considerEbitda = input.bool(true, 'EBITDA', group='Fundamentals/Share', inline='2')
considerNetMargin = input.bool(true, 'Net', group='Margin', inline='1')
considerGrossMargin = input.bool(true, 'Gross', group='Margin', inline='1')
considerOperatingMargin = input.bool(true, 'Operating', group='Margin', inline='1')
considerEBITDAMargin = input.bool(true, 'EBITDA', group='Margin', inline='1')
considerFCFMargin = input.bool(true, 'FCF', group='Margin', inline='1')
considerROA = input.bool(true, 'ROA', group='Returns', inline='1')
considerROE = input.bool(true, 'ROE', group='Returns', inline='1')
considerROIC = input.bool(true, 'ROIC', group='Returns', inline='1')
considerDTA = input.bool(true, 'DTA', group='Inversed Debt Ratios', inline='1')
considerLDTA = input.bool(true, 'LDTA', group='Inversed Debt Ratios', inline='1')
considerDTE = input.bool(true, 'DTE', group='Inversed Debt Ratios', inline='1')
considerDTR = input.bool(true, 'DTR', group='Inversed Debt Ratios', inline='1')
considerDTEB = input.bool(true, 'DTEBITDA', group='Inversed Debt Ratios', inline='1')
displayTimeframe = input.bool(true, 'Display Timeframe', group='Display')
financialParameters = array.from('Current')
ignoredParameters = array.new_string()
fundamentalParameters = array.new_string()
marginParameters = array.new_string()
returnParameters = array.new_string()
debtParameters = array.new_string()
financialFactorColumns = array.from(1)
financialFactors = array.from('Price')
array.push(considerEarningPrice?financialParameters:ignoredParameters, 'Last Earnings')
array.push(financialFactorColumns, array.get(financialFactorColumns, array.size(financialFactorColumns)-1)+array.size(financialParameters))
array.push(considerFundamentalsPerShare and considerBvps?fundamentalParameters:ignoredParameters, 'Book Value')
array.push(considerFundamentalsPerShare and considerEps?fundamentalParameters:ignoredParameters, 'Earnings')
array.push(considerFundamentalsPerShare and considerRps?fundamentalParameters:ignoredParameters, 'Revenue')
array.push(considerFundamentalsPerShare and considerFcf?fundamentalParameters:ignoredParameters, 'FCF')
array.push(considerFundamentalsPerShare and considerEbit?fundamentalParameters:ignoredParameters, 'EBIT')
array.push(considerFundamentalsPerShare and considerEbitda?fundamentalParameters:ignoredParameters, 'EBITDA')
if(array.size(fundamentalParameters) != 0)
array.concat(financialParameters, fundamentalParameters)
array.push(financialFactorColumns, array.get(financialFactorColumns, array.size(financialFactorColumns)-1)+array.size(fundamentalParameters))
array.push(financialFactors, 'Fundamentals/Share')
array.push(considerMargins and considerNetMargin?marginParameters:ignoredParameters, 'Net')
array.push(considerMargins and considerGrossMargin?marginParameters:ignoredParameters, 'Gross')
array.push(considerMargins and considerOperatingMargin?marginParameters:ignoredParameters, 'Operating')
array.push(considerMargins and considerEBITDAMargin?marginParameters:ignoredParameters, 'EBITDA')
array.push(considerMargins and considerFCFMargin?marginParameters:ignoredParameters, 'FCF')
if(array.size(marginParameters) != 0)
array.concat(financialParameters, marginParameters)
array.push(financialFactorColumns, array.get(financialFactorColumns, array.size(financialFactorColumns)-1)+array.size(marginParameters))
array.push(financialFactors, 'Margin')
array.push(considerReturns and considerROA?returnParameters:ignoredParameters, 'ROA')
array.push(considerReturns and considerROE?returnParameters:ignoredParameters, 'ROE')
array.push(considerReturns and considerROIC?returnParameters:ignoredParameters, 'ROIC')
if(array.size(returnParameters) != 0)
array.concat(financialParameters, returnParameters)
array.push(financialFactorColumns, array.get(financialFactorColumns, array.size(financialFactorColumns)-1)+array.size(returnParameters))
array.push(financialFactors, 'Returns')
array.push(considerInvertedDebtRatios and considerDTA?debtParameters:ignoredParameters, 'Assets')
array.push(considerInvertedDebtRatios and considerLDTA?debtParameters:ignoredParameters, 'Assets(Long Term)')
array.push(considerInvertedDebtRatios and considerDTE?debtParameters:ignoredParameters, 'Equity')
array.push(considerInvertedDebtRatios and considerDTR?debtParameters:ignoredParameters, 'Revenue')
array.push(considerInvertedDebtRatios and considerDTEB?debtParameters:ignoredParameters, 'EBITDA')
if(array.size(debtParameters) != 0)
array.concat(financialParameters, debtParameters)
array.push(financialFactorColumns, array.get(financialFactorColumns, array.size(financialFactorColumns)-1)+array.size(debtParameters))
array.push(financialFactors, 'Inverted Debt Ratios')
f_getFinancials(financial_id, period) =>
request.financial(syminfo.tickerid, financial_id, period)
f_getOptimalFinancialBasic(financial_id) =>
f_getFinancials(financial_id, syminfo.currency == 'USD' ? 'FQ' : 'FY')
tso = request.financial(syminfo.tickerid, 'TOTAL_SHARES_OUTSTANDING', 'FQ')
bvps = request.financial(syminfo.tickerid, 'BOOK_VALUE_PER_SHARE', 'FQ')
eps = request.financial(syminfo.tickerid, 'EARNINGS_PER_SHARE_BASIC', 'TTM')
rps = request.financial(syminfo.tickerid, 'TOTAL_REVENUE', 'TTM') / tso
ebitda = request.financial(syminfo.tickerid, 'EBITDA', 'TTM') / tso
ebit = f_getOptimalFinancialBasic('EBIT') / tso
fcf = f_getOptimalFinancialBasic('FREE_CASH_FLOW') / tso
//currentassets = f_getOptimalFinancialBasic("NCAVPS_RATIO")
nmargin = f_getOptimalFinancialBasic('NET_MARGIN')
gmargin = f_getOptimalFinancialBasic('GROSS_MARGIN')
omargin = f_getOptimalFinancialBasic('OPERATING_MARGIN')
emargin = f_getOptimalFinancialBasic('EBITDA_MARGIN')
fmargin = f_getOptimalFinancialBasic('FREE_CASH_FLOW_MARGIN')
roa = f_getOptimalFinancialBasic('RETURN_ON_ASSETS')
roe = f_getOptimalFinancialBasic('RETURN_ON_EQUITY')
roic = f_getOptimalFinancialBasic('RETURN_ON_INVESTED_CAPITAL')
ldta = 1 / f_getOptimalFinancialBasic('LONG_TERM_DEBT_TO_ASSETS')
dta = 1 / f_getOptimalFinancialBasic('DEBT_TO_ASSET')
dte = 1 / f_getOptimalFinancialBasic('DEBT_TO_EQUITY')
dtr = 1 / f_getOptimalFinancialBasic('DEBT_TO_REVENUE')
dteb = 1 / f_getOptimalFinancialBasic('DEBT_TO_EBITDA')
NUMBER_OF_ITEMS = 20
earnings = request.earnings(syminfo.tickerid, earnings.actual, barmerge.gaps_on, barmerge.lookahead_off, true)
getPercentile(value, defaultToZero = true)=>
var arr = array.new_float()
array.unshift(arr, value)
array.size(arr)==1? 100.0 : array.percentrank(arr, 0)
getPercentileDrawdown(value, defaultToZero = true)=>
var arr = array.new_float()
sIndex = array.binary_search_rightmost(arr, value)
array.insert(arr, sIndex, value)
index = defaultToZero? array.indexof(arr, value) : array.lastindexof(arr, value)
percentile = (index+1)*100/array.size(arr)
percentile
f_calculate_drawdown_stats(value) =>
var float ath = na
var float drawdownPercentile = 0
var drawdown = 0.0
var percentile = 0.0
if(not na(value))
percentile := getPercentile(value)
ath := math.max(value, nz(ath, value))
drawdown := math.round(math.abs(ath - value)*100 / math.max(math.abs(ath), math.abs(value)))
drawdownPercentile := getPercentileDrawdown(drawdown)
percentileColor = color.from_gradient(percentile, 0, 100, color.red, color.green)
drawdownColor = color.from_gradient(drawdownPercentile, 0, 100, color.green, color.red)
[array.from(value, ath, percentile, drawdown, drawdownPercentile),
array.from(percentileColor, percentileColor, percentileColor, drawdownColor, drawdownColor)]
comparitive_drawdown(value, priceDrawdown, pricePercentile, statsMatrix, colorMatrix, condition=true) =>
if(condition)
[statsArray, colorArray] = f_calculate_drawdown_stats(value)
drawdownDiff = priceDrawdown - array.get(statsArray, 3)
percentileDiff = array.get(statsArray, 2)-pricePercentile
diffDrawdownPercentile = getPercentile(drawdownDiff)
diffPricePercentile = getPercentile(percentileDiff)
array.push(statsArray, diffPricePercentile)
array.push(statsArray, diffDrawdownPercentile)
array.push(colorArray, color.from_gradient(diffPricePercentile, 0, 100, color.red, color.green))
array.push(colorArray, color.from_gradient(diffDrawdownPercentile, 0, 100, color.red, color.green))
ma.push(statsMatrix, statsArray, NUMBER_OF_ITEMS)
ma.push(colorMatrix, colorArray, NUMBER_OF_ITEMS)
if reference == 'Inception' or inDateRange
if displayTimeframe
dr.runTimer()
[priceDrawdownStats, priceDrawdownColors] = f_calculate_drawdown_stats(high)
drawdown = array.get(priceDrawdownStats, 3)
percentile = array.get(priceDrawdownStats, 2)
var percentileArray = array.new_float(20, 0)
var diffArray = array.new_float(20, 0)
var drawdownArray = array.new_float(20, 0)
var matrix<float> statMatrix = matrix.new<float>()
var matrix<color> colorMatrix = matrix.new<color>()
statParameters = array.from("Value", "ATH", "Percentile", "Drawdown", "Drawdown\nPercentile", "Differential Percentile\n(Absolute)", "Differential Percentile\n(Drawdown)")
if(not na(earnings))
ma.clear(statMatrix)
ma.clear(colorMatrix)
comparitive_drawdown(close, drawdown, percentile, statMatrix, colorMatrix, considerEarningPrice)
comparitive_drawdown(bvps, drawdown, percentile, statMatrix, colorMatrix, considerFundamentalsPerShare and considerBvps)
comparitive_drawdown(eps, drawdown, percentile, statMatrix, colorMatrix, considerFundamentalsPerShare and considerEps)
comparitive_drawdown(rps, drawdown, percentile, statMatrix, colorMatrix, considerFundamentalsPerShare and considerRps)
comparitive_drawdown(fcf, drawdown, percentile, statMatrix, colorMatrix, considerFundamentalsPerShare and considerFcf)
comparitive_drawdown(ebit, drawdown, percentile, statMatrix, colorMatrix, considerFundamentalsPerShare and considerEbit)
comparitive_drawdown(ebitda, drawdown, percentile, statMatrix, colorMatrix, considerFundamentalsPerShare and considerEbitda)
comparitive_drawdown(nmargin, drawdown, percentile, statMatrix, colorMatrix, considerMargins and considerNetMargin)
comparitive_drawdown(gmargin, drawdown, percentile, statMatrix, colorMatrix, considerMargins and considerGrossMargin)
comparitive_drawdown(omargin, drawdown, percentile, statMatrix, colorMatrix, considerMargins and considerOperatingMargin)
comparitive_drawdown(emargin, drawdown, percentile, statMatrix, colorMatrix, considerMargins and considerEBITDAMargin)
comparitive_drawdown(fmargin, drawdown, percentile, statMatrix, colorMatrix, considerMargins and considerFCFMargin)
comparitive_drawdown(roa, drawdown, percentile, statMatrix, colorMatrix, considerReturns and considerROA)
comparitive_drawdown(roe, drawdown, percentile, statMatrix, colorMatrix, considerReturns and considerROE)
comparitive_drawdown(roic, drawdown, percentile, statMatrix, colorMatrix, considerReturns and considerROIC)
comparitive_drawdown(dta, drawdown, percentile, statMatrix, colorMatrix, considerInvertedDebtRatios and considerDTA)
comparitive_drawdown(ldta, drawdown, percentile, statMatrix, colorMatrix, considerInvertedDebtRatios and considerLDTA)
comparitive_drawdown(dte, drawdown, percentile, statMatrix, colorMatrix, considerInvertedDebtRatios and considerDTE)
comparitive_drawdown(dtr, drawdown, percentile, statMatrix, colorMatrix, considerInvertedDebtRatios and considerDTR)
comparitive_drawdown(dteb, drawdown, percentile, statMatrix, colorMatrix, considerInvertedDebtRatios and considerDTEB)
percentileDAvg = matrix.columns(statMatrix) > 6 ? array.avg(matrix.col(statMatrix, 6)) : na
percentilePAvg = matrix.columns(statMatrix) > 5 ? array.avg(matrix.col(statMatrix, 5)) : na
if(barstate.islastconfirmedhistory)
stats = table.new(position.middle_center, matrix.columns(statMatrix)+2, matrix.rows(statMatrix)+3, border_width=2)
table.clear(stats, 0, 0, matrix.columns(statMatrix)+1, matrix.rows(statMatrix)+2)
table.cell(stats, 0, 0, "P " +str.tostring(percentilePAvg, format.percent), bgcolor=color.from_gradient(percentilePAvg, 0, 100, color.red, color.green),
text_color=color.white, text_size=size.huge, tooltip='Probability based on absolute percentile')
table.cell(stats, 0, 1, "D " +str.tostring(percentileDAvg, format.percent), bgcolor=color.from_gradient(percentileDAvg, 0, 100, color.red, color.green),
text_color=color.white, text_size=size.huge, tooltip='Probability based on drawdown percentile')
for i=0 to array.size(financialFactors)-1
table.cell(stats, 0, array.get(financialFactorColumns, i)+1, array.get(financialFactors, i), bgcolor=color.maroon, text_color=color.white, text_size=size.small)
table.merge_cells(stats, 0, array.get(financialFactorColumns, i)+1, 0, array.get(financialFactorColumns, i+1))
table.merge_cells(stats, 0, 0, 1, 0)
table.merge_cells(stats, 0, 1, 1, 1)
for i=0 to array.size(financialParameters)-1
table.cell(stats, 1, i+2, array.get(financialParameters, i), bgcolor=color.teal, text_color=color.white, text_size=size.small)
for j=0 to array.size(priceDrawdownStats)-1
table.cell(stats, j+2, 2, str.tostring(array.get(priceDrawdownStats,j), j<2? '#.00' : format.percent), bgcolor=color.blue, text_color=color.white, text_size=size.small)
table.cell(stats, array.size(priceDrawdownStats)+2, 2, '', bgcolor=color.blue, text_color=color.white, text_size=size.small)
table.cell(stats, array.size(priceDrawdownStats)+3, 2, '', bgcolor=color.blue, text_color=color.white, text_size=size.small)
for j=0 to array.size(statParameters)-1
table.cell(stats, j+2, 1, array.get(statParameters, j), bgcolor=color.maroon, text_color=color.white, text_size=size.small)
for i=0 to matrix.rows(statMatrix)==0? na : matrix.rows(statMatrix)-1
for j=0 to matrix.columns(statMatrix)-1
table.cell(stats, j+2,i+2+1, str.tostring(matrix.get(statMatrix,i,j), j<2? '#.00' : format.percent), bgcolor=matrix.get(colorMatrix,i,j), text_color=color.white, text_size=size.small)
|
On Balance Volume wi Normalization (OSC) | https://www.tradingview.com/script/9TKSsnvI-On-Balance-Volume-wi-Normalization-OSC/ | dandrideng | https://www.tradingview.com/u/dandrideng/ | 83 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dandrideng
//@version=5
indicator(title="On Balance Volume wi Normalization (OSC)", shorttitle="OBV-wi-N (OSC)", overlay=false, max_bars_back=1000, max_lines_count=400, max_labels_count=400)
//import library
import dandrideng/on_balance_volume/1 as nobv
import dandrideng/divergence/2 as div
//nobv paramters
nobv_ma_type = input.string(defval="EMA", title="MA Type", options=["SMA", "EMA", "DEMA", "TEMA", "WMA", "VWMA", "SMMA", "HullMA", "SSMA", "TMA"], group="Normalized On Balance Volume")
nobv_ma_len = input.int(defval=14, title="MA Period", minval=1, group="Normalized On Balance Volume")
nobv_sigma = input.float(defval=2.0, title="NOBV Sigma", minval=0, step=0.1, group="Normalized On Balance Volume")
nobv = nobv.obv_diff_norm(nobv_ma_type, nobv_ma_len)
plot(series=nobv, title="nobv", linewidth=2, color=#2962FF)
hline (0.0, title="nobv middle line", color=#787B86, linestyle=hline.style_dotted)
obLevel = hline(price= nobv_sigma, title="nobv upper range", color=#787B86, linestyle=hline.style_dotted)
osLevel = hline(price=-nobv_sigma, title="nobv lower range", color=#787B86, linestyle=hline.style_dotted)
fill(hline1=obLevel, hline2=osLevel, title="nobv background", color=color.rgb(33, 150, 243, 90))
bgcolor(color=nobv > nobv_sigma ? color.new(color.green, 85) : nobv < -nobv_sigma ? color.new(color.red, 85) : na)
//nobv divergence paramters
lbR = input.int(defval=2, title="Pivot Lookback Right", group="Normalized On Balance Volume Divergence")
lbL = input.int(defval=5, title="Pivot Lookback Left", group="Normalized On Balance Volume Divergence")
range_upper = input.int(defval=60, title="Max of Lookback Range", group="Normalized On Balance Volume Divergence")
range_lower = input.int(defval=5, title="Min of Lookback Range", group="Normalized On Balance Volume Divergence")
tolerance = input.int(defval=2, title="Tolerant Kline Number", group="Normalized On Balance Volume Divergence")
cov_thresh = input.float(defval=-0.1, title="Cov Threshold", group="Normalized On Balance Volume Divergence")
plot_rbull = input.bool(defval=true, title="Plot Bullish", group="Normalized On Balance Volume Divergence")
plot_hbull = input.bool(defval=false, title="Plot Hidden Bullish", group="Normalized On Balance Volume Divergence")
plot_rbear = input.bool(defval=true, title="Plot Bearish", group="Normalized On Balance Volume Divergence")
plot_hbear = input.bool(defval=false, title="Plot Hidden Bearish", group="Normalized On Balance Volume Divergence")
osc = nobv
to_intstr(x) => str.tostring(x, "#")
to_floatstr(x) => str.tostring(x, "#.###")
reg_bull = div.regular_bull(low, osc, lbL, lbR, range_lower, range_upper, tolerance)
reg_bull_lsv = array.get(reg_bull, 0)
reg_bull_lsb = int(array.get(reg_bull, 1))
reg_bull_lov = array.get(reg_bull, 2)
reg_bull_lob = int(array.get(reg_bull, 3))
reg_bull_rsv = array.get(reg_bull, 4)
reg_bull_rsb = int(array.get(reg_bull, 5))
reg_bull_rov = array.get(reg_bull, 6)
reg_bull_rob = int(array.get(reg_bull, 7))
reg_bull_cov = array.get(reg_bull, 8)
if not na(reg_bull_lsv) and plot_rbull and reg_bull_cov < cov_thresh
reg_bull_label = label.new(x=bar_index-lbR-reg_bull_rob, y=reg_bull_rov)
label.set_text(reg_bull_label, "REG "+ to_floatstr(reg_bull_cov) +"\nSRC(" + to_intstr(reg_bull_rsb) + "-" + to_intstr(reg_bull_lsb) + ")\nOSC(" + to_intstr(reg_bull_rob) + "-" + to_intstr(reg_bull_lob) + ")")
label.set_color(reg_bull_label, color.new(color.green, 20))
label.set_textcolor(reg_bull_label, color.white)
label.set_style(reg_bull_label, label.style_label_up)
reg_bull_line = line.new(x1=bar_index-lbR-reg_bull_lob, y1=reg_bull_lov, x2=bar_index-lbR-reg_bull_rob, y2=reg_bull_rov)
line.set_color(reg_bull_line, color.new(color.green, 20))
line.set_width(reg_bull_line, 2)
hid_bull = div.hidden_bull(low, osc, lbL, lbR, range_lower, range_upper, tolerance)
hid_bull_lsv = array.get(hid_bull, 0)
hid_bull_lsb = int(array.get(hid_bull, 1))
hid_bull_lov = array.get(hid_bull, 2)
hid_bull_lob = int(array.get(hid_bull, 3))
hid_bull_rsv = array.get(hid_bull, 4)
hid_bull_rsb = int(array.get(hid_bull, 5))
hid_bull_rov = array.get(hid_bull, 6)
hid_bull_rob = int(array.get(hid_bull, 7))
hid_bull_cov = array.get(hid_bull, 8)
if not na(hid_bull_lsv) and plot_hbull and hid_bull_cov < cov_thresh
hid_bull_label = label.new(x=bar_index-lbR-hid_bull_rob, y=hid_bull_rov)
label.set_text(hid_bull_label, "HID "+ to_floatstr(hid_bull_cov) +"\nSRC(" + to_intstr(hid_bull_rsb) + "-" + to_intstr(hid_bull_lsb) + ")\nOSC(" + to_intstr(hid_bull_rob) + "-" + to_intstr(hid_bull_lob) + ")")
label.set_color(hid_bull_label, color.new(color.green, 50))
label.set_textcolor(hid_bull_label, color.white)
label.set_style(hid_bull_label, label.style_label_up)
hid_bull_line = line.new(x1=bar_index-lbR-hid_bull_lob, y1=hid_bull_lov, x2=bar_index-lbR-hid_bull_rob, y2=hid_bull_rov)
line.set_color(hid_bull_line, color.new(color.green, 50))
line.set_width(hid_bull_line, 2)
reg_bear = div.regular_bear(high, osc, lbL, lbR, range_lower, range_upper, tolerance)
reg_bear_lsv = array.get(reg_bear, 0)
reg_bear_lsb = int(array.get(reg_bear, 1))
reg_bear_lov = array.get(reg_bear, 2)
reg_bear_lob = int(array.get(reg_bear, 3))
reg_bear_rsv = array.get(reg_bear, 4)
reg_bear_rsb = int(array.get(reg_bear, 5))
reg_bear_rov = array.get(reg_bear, 6)
reg_bear_rob = int(array.get(reg_bear, 7))
reg_bear_cov = array.get(reg_bear, 8)
if not na(reg_bear_lsv) and plot_rbear and reg_bear_cov < cov_thresh
reg_bear_label = label.new(x=bar_index-lbR-reg_bear_rob, y=reg_bear_rov)
label.set_text(reg_bear_label, "REG "+ to_floatstr(reg_bear_cov) +"\nSRC(" + to_intstr(reg_bear_rsb) + "-" + to_intstr(reg_bear_lsb) + ")\nOSC(" + to_intstr(reg_bear_rob) + "-" + to_intstr(reg_bear_lob) + ")")
label.set_color(reg_bear_label, color.new(color.red, 20))
label.set_textcolor(reg_bear_label, color.white)
label.set_style(reg_bear_label, label.style_label_down)
reg_bear_line = line.new(x1=bar_index-lbR-reg_bear_lob, y1=reg_bear_lov, x2=bar_index-lbR-reg_bear_rob, y2=reg_bear_rov)
line.set_color(reg_bear_line, color.new(color.red, 20))
line.set_width(reg_bear_line, 2)
hid_bear = div.hidden_bear(high, osc, lbL, lbR, range_lower, range_upper, tolerance)
hid_bear_lsv = array.get(hid_bear, 0)
hid_bear_lsb = int(array.get(hid_bear, 1))
hid_bear_lov = array.get(hid_bear, 2)
hid_bear_lob = int(array.get(hid_bear, 3))
hid_bear_rsv = array.get(hid_bear, 4)
hid_bear_rsb = int(array.get(hid_bear, 5))
hid_bear_rov = array.get(hid_bear, 6)
hid_bear_rob = int(array.get(hid_bear, 7))
hid_bear_cov = array.get(hid_bear, 8)
if not na(hid_bear_lsv) and plot_hbear and hid_bear_cov < cov_thresh
hid_bear_label = label.new(x=bar_index-lbR-hid_bear_rob, y=hid_bear_rov)
label.set_text(hid_bear_label, "HID "+ to_floatstr(hid_bear_cov) +"\nSRC(" + to_intstr(hid_bear_rsb) + "-" + to_intstr(hid_bear_lsb) + ")\nOSC(" + to_intstr(hid_bear_rob) + "-" + to_intstr(hid_bear_lob) + ")")
label.set_color(hid_bear_label, color.new(color.red, 50))
label.set_textcolor(hid_bear_label, color.white)
label.set_style(hid_bear_label, label.style_label_down)
hid_bear_line = line.new(x1=bar_index-lbR-hid_bear_lob, y1=hid_bear_lov, x2=bar_index-lbR-hid_bear_rob, y2=hid_bear_rov)
line.set_color(hid_bear_line, color.new(color.red, 50))
line.set_width(hid_bear_line, 2)
//end of file |
On Balance Volume wi Normalization (SRC) | https://www.tradingview.com/script/HBOah8yu-On-Balance-Volume-wi-Normalization-SRC/ | dandrideng | https://www.tradingview.com/u/dandrideng/ | 52 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dandrideng
//@version=5
indicator(title="On Balance Volume wi Normalization (SRC)", shorttitle="OBV-wi-N (SRC)", overlay=true, max_bars_back=1000, max_lines_count=400, max_labels_count=400)
//import library
import dandrideng/on_balance_volume/1 as nobv
import dandrideng/divergence/2 as div
//nobv paramters
nobv_ma_type = input.string(defval="EMA", title="MA Type", options=["SMA", "EMA", "DEMA", "TEMA", "WMA", "VWMA", "SMMA", "HullMA", "SSMA", "TMA"], group="Normalized On Balance Volume")
nobv_ma_len = input.int(defval=14, title="MA Period", minval=1, group="Normalized On Balance Volume")
nobv_sigma = input.float(defval=2.0, title="NOBV Sigma", minval=0, step=0.1, group="Normalized On Balance Volume")
nobv = nobv.obv_diff_norm(nobv_ma_type, nobv_ma_len)
// plot(series=nobv, title="nobv", linewidth=2, color=#2962FF)
// hline (0.0, title="nobv middle line", color=#787B86, linestyle=hline.style_dotted)
// obLevel = hline(price= nobv_sigma, title="nobv upper range", color=#787B86, linestyle=hline.style_dotted)
// osLevel = hline(price=-nobv_sigma, title="nobv lower range", color=#787B86, linestyle=hline.style_dotted)
// fill(hline1=obLevel, hline2=osLevel, title="nobv background", color=color.rgb(33, 150, 243, 90))
// bgcolor(color=nobv > nobv_sigma ? color.new(color.green, 85) : nobv < -nobv_sigma ? color.new(color.red, 85) : na)
//nobv divergence paramters
lbR = input.int(defval=2, title="Pivot Lookback Right", group="Normalized On Balance Volume Divergence")
lbL = input.int(defval=5, title="Pivot Lookback Left", group="Normalized On Balance Volume Divergence")
range_upper = input.int(defval=60, title="Max of Lookback Range", group="Normalized On Balance Volume Divergence")
range_lower = input.int(defval=5, title="Min of Lookback Range", group="Normalized On Balance Volume Divergence")
tolerance = input.int(defval=2, title="Tolerant Kline Number", group="Normalized On Balance Volume Divergence")
cov_thresh = input.float(defval=-0.1, title="Cov Threshold", group="Normalized On Balance Volume Divergence")
plot_rbull = input.bool(defval=true, title="Plot Bullish", group="Normalized On Balance Volume Divergence")
plot_hbull = input.bool(defval=false, title="Plot Hidden Bullish", group="Normalized On Balance Volume Divergence")
plot_rbear = input.bool(defval=true, title="Plot Bearish", group="Normalized On Balance Volume Divergence")
plot_hbear = input.bool(defval=false, title="Plot Hidden Bearish", group="Normalized On Balance Volume Divergence")
osc = nobv
to_intstr(x) => str.tostring(x, "#")
to_floatstr(x) => str.tostring(x, "#.###")
reg_bull = div.regular_bull(low, osc, lbL, lbR, range_lower, range_upper, tolerance)
reg_bull_lsv = array.get(reg_bull, 0)
reg_bull_lsb = int(array.get(reg_bull, 1))
reg_bull_lov = array.get(reg_bull, 2)
reg_bull_lob = int(array.get(reg_bull, 3))
reg_bull_rsv = array.get(reg_bull, 4)
reg_bull_rsb = int(array.get(reg_bull, 5))
reg_bull_rov = array.get(reg_bull, 6)
reg_bull_rob = int(array.get(reg_bull, 7))
reg_bull_cov = array.get(reg_bull, 8)
if not na(reg_bull_lsv) and plot_rbull and reg_bull_cov < cov_thresh
reg_bull_label = label.new(x=bar_index-lbR-reg_bull_rsb, y=reg_bull_rsv)
label.set_text(reg_bull_label, "REG "+ to_floatstr(reg_bull_cov) +"\nSRC(" + to_intstr(reg_bull_rsb) + "-" + to_intstr(reg_bull_lsb) + ")\nOSC(" + to_intstr(reg_bull_rob) + "-" + to_intstr(reg_bull_lob) + ")")
label.set_color(reg_bull_label, color.new(color.green, 20))
label.set_textcolor(reg_bull_label, color.white)
label.set_style(reg_bull_label, label.style_label_up)
reg_bull_line = line.new(x1=bar_index-lbR-reg_bull_lsb, y1=reg_bull_lsv, x2=bar_index-lbR-reg_bull_rsb, y2=reg_bull_rsv)
line.set_color(reg_bull_line, color.new(color.green, 20))
line.set_width(reg_bull_line, 2)
hid_bull = div.hidden_bull(low, osc, lbL, lbR, range_lower, range_upper, tolerance)
hid_bull_lsv = array.get(hid_bull, 0)
hid_bull_lsb = int(array.get(hid_bull, 1))
hid_bull_lov = array.get(hid_bull, 2)
hid_bull_lob = int(array.get(hid_bull, 3))
hid_bull_rsv = array.get(hid_bull, 4)
hid_bull_rsb = int(array.get(hid_bull, 5))
hid_bull_rov = array.get(hid_bull, 6)
hid_bull_rob = int(array.get(hid_bull, 7))
hid_bull_cov = array.get(hid_bull, 8)
if not na(hid_bull_lsv) and plot_hbull and hid_bull_cov < cov_thresh
hid_bull_label = label.new(x=bar_index-lbR-hid_bull_rsb, y=hid_bull_rsv)
label.set_text(hid_bull_label, "HID "+ to_floatstr(hid_bull_cov) +"\nSRC(" + to_intstr(hid_bull_rsb) + "-" + to_intstr(hid_bull_lsb) + ")\nOSC(" + to_intstr(hid_bull_rob) + "-" + to_intstr(hid_bull_lob) + ")")
label.set_color(hid_bull_label, color.new(color.green, 50))
label.set_textcolor(hid_bull_label, color.white)
label.set_style(hid_bull_label, label.style_label_up)
hid_bull_line = line.new(x1=bar_index-lbR-hid_bull_lsb, y1=hid_bull_lsv, x2=bar_index-lbR-hid_bull_rsb, y2=hid_bull_rsv)
line.set_color(hid_bull_line, color.new(color.green, 50))
line.set_width(hid_bull_line, 2)
reg_bear = div.regular_bear(high, osc, lbL, lbR, range_lower, range_upper, tolerance)
reg_bear_lsv = array.get(reg_bear, 0)
reg_bear_lsb = int(array.get(reg_bear, 1))
reg_bear_lov = array.get(reg_bear, 2)
reg_bear_lob = int(array.get(reg_bear, 3))
reg_bear_rsv = array.get(reg_bear, 4)
reg_bear_rsb = int(array.get(reg_bear, 5))
reg_bear_rov = array.get(reg_bear, 6)
reg_bear_rob = int(array.get(reg_bear, 7))
reg_bear_cov = array.get(reg_bear, 8)
if not na(reg_bear_lsv) and plot_rbear and reg_bear_cov < cov_thresh
reg_bear_label = label.new(x=bar_index-lbR-reg_bear_rsb, y=reg_bear_rsv)
label.set_text(reg_bear_label, "REG "+ to_floatstr(reg_bear_cov) +"\nSRC(" + to_intstr(reg_bear_rsb) + "-" + to_intstr(reg_bear_lsb) + ")\nOSC(" + to_intstr(reg_bear_rob) + "-" + to_intstr(reg_bear_lob) + ")")
label.set_color(reg_bear_label, color.new(color.red, 20))
label.set_textcolor(reg_bear_label, color.white)
label.set_style(reg_bear_label, label.style_label_down)
reg_bear_line = line.new(x1=bar_index-lbR-reg_bear_lsb, y1=reg_bear_lsv, x2=bar_index-lbR-reg_bear_rsb, y2=reg_bear_rsv)
line.set_color(reg_bear_line, color.new(color.red, 20))
line.set_width(reg_bear_line, 2)
hid_bear = div.hidden_bear(high, osc, lbL, lbR, range_lower, range_upper, tolerance)
hid_bear_lsv = array.get(hid_bear, 0)
hid_bear_lsb = int(array.get(hid_bear, 1))
hid_bear_lov = array.get(hid_bear, 2)
hid_bear_lob = int(array.get(hid_bear, 3))
hid_bear_rsv = array.get(hid_bear, 4)
hid_bear_rsb = int(array.get(hid_bear, 5))
hid_bear_rov = array.get(hid_bear, 6)
hid_bear_rob = int(array.get(hid_bear, 7))
hid_bear_cov = array.get(hid_bear, 8)
if not na(hid_bear_lsv) and plot_hbear and hid_bear_cov < cov_thresh
hid_bear_label = label.new(x=bar_index-lbR-hid_bear_rsb, y=hid_bear_rsv)
label.set_text(hid_bear_label, "HID "+ to_floatstr(hid_bear_cov) +"\nSRC(" + to_intstr(hid_bear_rsb) + "-" + to_intstr(hid_bear_lsb) + ")\nOSC(" + to_intstr(hid_bear_rob) + "-" + to_intstr(hid_bear_lob) + ")")
label.set_color(hid_bear_label, color.new(color.red, 50))
label.set_textcolor(hid_bear_label, color.white)
label.set_style(hid_bear_label, label.style_label_down)
hid_bear_line = line.new(x1=bar_index-lbR-hid_bear_lsb, y1=hid_bear_lsv, x2=bar_index-lbR-hid_bear_rsb, y2=hid_bear_rsv)
line.set_color(hid_bear_line, color.new(color.red, 50))
line.set_width(hid_bear_line, 2)
//end of file |
Tick up/down | https://www.tradingview.com/script/CFxw8CK3-Tick-up-down/ | fikira | https://www.tradingview.com/u/fikira/ | 122 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © fikira
//@version=5
indicator("Tick up/down")
n = input.int(1, 'start', tooltip='start tick count x, end tick count x + 31')
pc = plot.style_circles
check(n) =>
varip vTick = 0
varip vCheck = 0
varip pClose = 0.
if barstate.isnew
vTick := 0
vCheck := 0
else
vTick += 1
if vTick == n
switch
close > pClose =>
vCheck := n
close < pClose =>
vCheck := n +1
close == pClose =>
vCheck := n +2
=>
vCheck := 0
pClose := close
vCheck
col(n) => check(n) == n ? color.lime : check(n) == n +1 ? color.red : check(n) == n +2 ? color.new(color.blue, 50) : color.new(color.blue, 100)
// series, title, color, linewidth, style
plot(check( n) != 0 ? n : na, 'n' , col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 1' , col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 2' , col(n), 2, pc), n += 1
plot(check( n) != 0 ? n : na, 'n + 3' , col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 4' , col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 5' , col(n), 2, pc), n += 1
plot(check( n) != 0 ? n : na, 'n + 6' , col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 7' , col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 8' , col(n), 2, pc), n += 1
plot(check( n) != 0 ? n : na, 'n + 9' , col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 10', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 11', col(n), 2, pc), n += 1
plot(check( n) != 0 ? n : na, 'n + 12', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 13', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 14', col(n), 2, pc), n += 1
plot(check( n) != 0 ? n : na, 'n + 15', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 16', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 17', col(n), 2, pc), n += 1
plot(check( n) != 0 ? n : na, 'n + 18', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 19', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 20', col(n), 2, pc), n += 1
plot(check( n) != 0 ? n : na, 'n + 21', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 22', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 23', col(n), 2, pc), n += 1
plot(check( n) != 0 ? n : na, 'n + 24', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 25', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 26', col(n), 2, pc), n += 1
plot(check( n) != 0 ? n : na, 'n + 27', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 28', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 29', col(n), 2, pc), n += 1
plot(check( n) != 0 ? n : na, 'n + 30', col(n), 2, pc), n += 1, plot(check( n) != 0 ? n : na, 'n + 31', col(n), 2, pc)
|
Relative Strength Index (SRC) | https://www.tradingview.com/script/82kE0dnh/ | dandrideng | https://www.tradingview.com/u/dandrideng/ | 135 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dandrideng
//@version=5
indicator(title="Relative Strength Index (SRC)", shorttitle="RSI (SRC)", overlay=true, max_bars_back=1000, max_lines_count=400, max_labels_count=400)
import dandrideng/moving_average/1 as ma
import dandrideng/divergence/2 as div
//rsi params
rsi_source = input.source(close, "Source", group="RSI Settings")
rsi_length = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
up = ta.rma(math.max(ta.change(rsi_source), 0), rsi_length)
down = ta.rma(-math.min(ta.change(rsi_source), 0), rsi_length)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
// plot(rsi, "RSI", color=#7E57C2)
// rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
// hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
// rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86)
// fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
//rsi divergece paramters
lbR = input.int(defval=2, title="Pivot Lookback Right", group="RSI Divergence")
lbL = input.int(defval=5, title="Pivot Lookback Left", group="RSI Divergence")
range_upper = input.int(defval=60, title="Max of Lookback Range", group="RSI Divergence")
range_lower = input.int(defval=5, title="Min of Lookback Range", group="RSI Divergence")
tolerance = input.int(defval=2, title="Tolerant Kline Number", group="RSI Divergence")
cov_thresh = input.float(defval=-0.1, title="Cov Threshold", group="RSI Divergence")
plot_rbull = input.bool(defval=true, title="Plot Bullish", group="RSI Divergence")
plot_hbull = input.bool(defval=false, title="Plot Hidden Bullish", group="RSI Divergence")
plot_rbear = input.bool(defval=true, title="Plot Bearish", group="RSI Divergence")
plot_hbear = input.bool(defval=false, title="Plot Hidden Bearish", group="RSI Divergence")
osc = rsi
to_intstr(x) => str.tostring(x, "#")
to_floatstr(x) => str.tostring(x, "#.###")
reg_bull = div.regular_bull(low, osc, lbL, lbR, range_lower, range_upper, tolerance)
reg_bull_lsv = array.get(reg_bull, 0)
reg_bull_lsb = int(array.get(reg_bull, 1))
reg_bull_lov = array.get(reg_bull, 2)
reg_bull_lob = int(array.get(reg_bull, 3))
reg_bull_rsv = array.get(reg_bull, 4)
reg_bull_rsb = int(array.get(reg_bull, 5))
reg_bull_rov = array.get(reg_bull, 6)
reg_bull_rob = int(array.get(reg_bull, 7))
reg_bull_cov = array.get(reg_bull, 8)
if not na(reg_bull_lsv) and plot_rbull and reg_bull_cov < cov_thresh
reg_bull_label = label.new(x=bar_index-lbR-reg_bull_rsb, y=reg_bull_rsv)
label.set_text(reg_bull_label, "REG "+ to_floatstr(reg_bull_cov) +"\nSRC(" + to_intstr(reg_bull_rsb) + "-" + to_intstr(reg_bull_lsb) + ")\nOSC(" + to_intstr(reg_bull_rob) + "-" + to_intstr(reg_bull_lob) + ")")
label.set_color(reg_bull_label, color.new(color.green, 20))
label.set_textcolor(reg_bull_label, color.white)
label.set_style(reg_bull_label, label.style_label_up)
reg_bull_line = line.new(x1=bar_index-lbR-reg_bull_lsb, y1=reg_bull_lsv, x2=bar_index-lbR-reg_bull_rsb, y2=reg_bull_rsv)
line.set_color(reg_bull_line, color.new(color.green, 20))
line.set_width(reg_bull_line, 2)
hid_bull = div.hidden_bull(low, osc, lbL, lbR, range_lower, range_upper, tolerance)
hid_bull_lsv = array.get(hid_bull, 0)
hid_bull_lsb = int(array.get(hid_bull, 1))
hid_bull_lov = array.get(hid_bull, 2)
hid_bull_lob = int(array.get(hid_bull, 3))
hid_bull_rsv = array.get(hid_bull, 4)
hid_bull_rsb = int(array.get(hid_bull, 5))
hid_bull_rov = array.get(hid_bull, 6)
hid_bull_rob = int(array.get(hid_bull, 7))
hid_bull_cov = array.get(hid_bull, 8)
if not na(hid_bull_lsv) and plot_hbull and hid_bull_cov < cov_thresh
hid_bull_label = label.new(x=bar_index-lbR-hid_bull_rsb, y=hid_bull_rsv)
label.set_text(hid_bull_label, "HID "+ to_floatstr(hid_bull_cov) +"\nSRC(" + to_intstr(hid_bull_rsb) + "-" + to_intstr(hid_bull_lsb) + ")\nOSC(" + to_intstr(hid_bull_rob) + "-" + to_intstr(hid_bull_lob) + ")")
label.set_color(hid_bull_label, color.new(color.green, 50))
label.set_textcolor(hid_bull_label, color.white)
label.set_style(hid_bull_label, label.style_label_up)
hid_bull_line = line.new(x1=bar_index-lbR-hid_bull_lsb, y1=hid_bull_lsv, x2=bar_index-lbR-hid_bull_rsb, y2=hid_bull_rsv)
line.set_color(hid_bull_line, color.new(color.green, 50))
line.set_width(hid_bull_line, 2)
reg_bear = div.regular_bear(high, osc, lbL, lbR, range_lower, range_upper, tolerance)
reg_bear_lsv = array.get(reg_bear, 0)
reg_bear_lsb = int(array.get(reg_bear, 1))
reg_bear_lov = array.get(reg_bear, 2)
reg_bear_lob = int(array.get(reg_bear, 3))
reg_bear_rsv = array.get(reg_bear, 4)
reg_bear_rsb = int(array.get(reg_bear, 5))
reg_bear_rov = array.get(reg_bear, 6)
reg_bear_rob = int(array.get(reg_bear, 7))
reg_bear_cov = array.get(reg_bear, 8)
if not na(reg_bear_lsv) and plot_rbear and reg_bear_cov < cov_thresh
reg_bear_label = label.new(x=bar_index-lbR-reg_bear_rsb, y=reg_bear_rsv)
label.set_text(reg_bear_label, "REG "+ to_floatstr(reg_bear_cov) +"\nSRC(" + to_intstr(reg_bear_rsb) + "-" + to_intstr(reg_bear_lsb) + ")\nOSC(" + to_intstr(reg_bear_rob) + "-" + to_intstr(reg_bear_lob) + ")")
label.set_color(reg_bear_label, color.new(color.red, 20))
label.set_textcolor(reg_bear_label, color.white)
label.set_style(reg_bear_label, label.style_label_down)
reg_bear_line = line.new(x1=bar_index-lbR-reg_bear_lsb, y1=reg_bear_lsv, x2=bar_index-lbR-reg_bear_rsb, y2=reg_bear_rsv)
line.set_color(reg_bear_line, color.new(color.red, 20))
line.set_width(reg_bear_line, 2)
hid_bear = div.hidden_bear(high, osc, lbL, lbR, range_lower, range_upper, tolerance)
hid_bear_lsv = array.get(hid_bear, 0)
hid_bear_lsb = int(array.get(hid_bear, 1))
hid_bear_lov = array.get(hid_bear, 2)
hid_bear_lob = int(array.get(hid_bear, 3))
hid_bear_rsv = array.get(hid_bear, 4)
hid_bear_rsb = int(array.get(hid_bear, 5))
hid_bear_rov = array.get(hid_bear, 6)
hid_bear_rob = int(array.get(hid_bear, 7))
hid_bear_cov = array.get(hid_bear, 8)
if not na(hid_bear_lsv) and plot_hbear and hid_bear_cov < cov_thresh
hid_bear_label = label.new(x=bar_index-lbR-hid_bear_rsb, y=hid_bear_rsv)
label.set_text(hid_bear_label, "HID "+ to_floatstr(hid_bear_cov) +"\nSRC(" + to_intstr(hid_bear_rsb) + "-" + to_intstr(hid_bear_lsb) + ")\nOSC(" + to_intstr(hid_bear_rob) + "-" + to_intstr(hid_bear_lob) + ")")
label.set_color(hid_bear_label, color.new(color.red, 50))
label.set_textcolor(hid_bear_label, color.white)
label.set_style(hid_bear_label, label.style_label_down)
hid_bear_line = line.new(x1=bar_index-lbR-hid_bear_lsb, y1=hid_bear_lsv, x2=bar_index-lbR-hid_bear_rsb, y2=hid_bear_rsv)
line.set_color(hid_bear_line, color.new(color.red, 50))
line.set_width(hid_bear_line, 2)
//end of file |
Strat FTFC Vip3rr | https://www.tradingview.com/script/7lM8py7E-Strat-FTFC-Vip3rr/ | vip3rr | https://www.tradingview.com/u/vip3rr/ | 46 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator(title='Strat FTFC Vip3rr', shorttitle='FTFC Vip3rr', overlay=true)
_performanceGreenColor = input(color.rgb(38, 166, 154), title='Green Color')
_performanceRedColor = input(color.rgb(240, 83, 80), title='Red Color')
insideColor = input.color(color.yellow, title='Bearish color', group='Colors')
tfTableOpacity = input.int(80, title='Multi time frame table opacity', group='Colors')
tableposition = input.string(defval = position.top_right, title = "Table Position", options = [position.top_left, position.top_center, position.top_right, position.bottom_left, position.bottom_center, position.bottom_right])
isTfEnabled = input.bool(true, title='Enabled', group='Time frame continuation')
usePreviousClose = input.bool(false, title='Use previous close', group='Time frame continuation')
tf1 = input.timeframe('60', title='Time Frame 1', group='Time frame continuation')
tf2 = input.timeframe('D', title='Time Frame 2', group='Time frame continuation')
tf3 = input.timeframe('W', title='Time Frame 3', group='Time frame continuation')
tf4 = input.timeframe('1M', title='Time Frame 4', group='Time frame continuation')
tf5 = input.timeframe('1M', title='Time Frame 5', group='Time frame continuation')
cdayhigh = request.security(syminfo.tickerid, 'D', high)
cdaylow = request.security(syminfo.tickerid, 'D', low)
dAtr = request.security(syminfo.tickerid, 'D', ta.atr(14), lookahead=barmerge.lookahead_on)
tf1open = request.security(syminfo.tickerid, tf1, open)
tf1close = request.security(syminfo.tickerid, tf1, close)
tf2open = request.security(syminfo.tickerid, tf2, open)
tf2close = request.security(syminfo.tickerid, tf2, close)
tf3open = request.security(syminfo.tickerid, tf3, open)
tf3close = request.security(syminfo.tickerid, tf3, close)
tf4open = request.security(syminfo.tickerid, tf4, open)
tf4close = request.security(syminfo.tickerid, tf4, close)
tf5open = request.security(syminfo.tickerid, tf5, open)
tf5close = request.security(syminfo.tickerid, tf5, close)
var table tcTable = table.new(position = tableposition, columns = 7, rows = 2, border_width=1)
[tf1PrevClose, tf1Close] = request.security(syminfo.tickerid, tf1, [usePreviousClose ? close[1] : open[0], close[0]], barmerge.gaps_off)
[tf2PrevClose, tf2Close] = request.security(syminfo.tickerid, tf2, [usePreviousClose ? close[1] : open[0], close[0]], barmerge.gaps_off)
[tf3PrevClose, tf3Close] = request.security(syminfo.tickerid, tf3, [usePreviousClose ? close[1] : open[0], close[0]], barmerge.gaps_off)
[tf4PrevClose, tf4Close] = request.security(syminfo.tickerid, tf4, [usePreviousClose ? close[1] : open[0], close[0]], barmerge.gaps_off)
[tf5PrevClose, tf5Close] = request.security(syminfo.tickerid, tf4, [usePreviousClose ? close[1] : open[0], close[0]], barmerge.gaps_off)
h = high
l = low
c = close
o = open
onebar = h <= h[1] and l >= l[1]
twobar = h <= h[1] and l < l[1] or h > h[1] and l >= l[1]
threebar = h > h[1] and l < l[1]
greenbar = o <= c
red = o >= c
LIGHTTRANSP = 90
AVGTRANSP = 80
HEAVYTRANSP = 70
if barstate.islast and isTfEnabled
tf1Bullish = tf1open <= tf1close
tf2Bullish = tf2open <= tf2close
tf3Bullish = tf3open <= tf3close
tf4Bullish = tf4open <= tf4close
tf5Bullish = tf5open <= tf5close
tf1Chg = (tf1close - tf1open) * 100.0 / math.abs(tf1open)
tf1Color = tf1Chg >= 0 ? _performanceGreenColor : _performanceRedColor
tf1opacity = math.abs(tf1Chg) > 2 ? HEAVYTRANSP : math.abs(tf1Chg) > 1 ? AVGTRANSP : LIGHTTRANSP
tf2Chg = (tf2close - tf2open) * 100.0 / math.abs(tf2open)
tf2Color = tf2Chg >= 0 ? _performanceGreenColor : _performanceRedColor
tf2opacity = math.abs(tf2Chg) > 2 ? HEAVYTRANSP : math.abs(tf2Chg) > 1 ? AVGTRANSP : LIGHTTRANSP
tf3Chg = (tf3close - tf3open) * 100.0 / math.abs(tf3open)
tf3Color = tf3Chg >= 0 ? _performanceGreenColor : _performanceRedColor
tf3opacity = math.abs(tf3Chg) > 2 ? HEAVYTRANSP : math.abs(tf3Chg) > 1 ? AVGTRANSP : LIGHTTRANSP
tf4Chg = (tf4close - tf4open) * 100.0 / math.abs(tf4open)
tf4Color = tf4Chg >= 0 ? _performanceGreenColor : _performanceRedColor
tf4opacity = math.abs(tf4Chg) > 2 ? HEAVYTRANSP : math.abs(tf4Chg) > 1 ? AVGTRANSP : LIGHTTRANSP
tf5Chg = (tf5close - tf5open) * 100.0 / math.abs(tf5open)
tf5Color = tf5Chg >= 0 ? _performanceGreenColor : _performanceRedColor
tf5opacity = math.abs(tf5Chg) > 2 ? HEAVYTRANSP : math.abs(tf5Chg) > 1 ? AVGTRANSP : LIGHTTRANSP
table.cell(tcTable, 0, 0, tf1 + '\n' + str.tostring(tf1Chg, '#.##') + '%', bgcolor=color.new(tf1Color, tf1opacity), text_color=tf1Color, text_size=size.normal, width=0)
table.cell(tcTable, 1, 0, tf2 + '\n' + str.tostring(tf2Chg, '#.##') + '%', bgcolor=color.new(tf2Color, tf2opacity), text_color=tf2Color, text_size=size.normal, width=0)
table.cell(tcTable, 2, 0, tf3 + '\n' + str.tostring(tf3Chg, '#.##') + '%', bgcolor=color.new(tf3Color, tf3opacity), text_color=tf3Color, text_size=size.normal, width=0)
table.cell(tcTable, 3, 0, tf4 + '\n' + str.tostring(tf4Chg, '#.##') + '%', bgcolor=color.new(tf4Color, tf4opacity), text_color=tf4Color, text_size=size.normal, width=0)
table.cell(tcTable, 4, 0, tf5 + "\n" + str.tostring(tf5Chg, '#.##') + "%", bgcolor=color.new(tf5Color, tf5opacity), text_color=tf5Color, text_size=size.normal, width = 0)
table.cell(tcTable, 5, 0, 'DTR' + '\n' + str.tostring(cdayhigh - cdaylow, '#.##'), bgcolor=color.new(color.gray, tfTableOpacity), text_color=color.white, text_size=size.normal, width=0)
table.cell(tcTable, 6, 0, 'ATR' + '\n' + str.tostring(dAtr, '#.##'), bgcolor=color.new(color.gray, tfTableOpacity), text_color=color.white, text_size=size.normal, width=0)
|
Distance/Drawdown from a period high/low | https://www.tradingview.com/script/twBCphKs-Distance-Drawdown-from-a-period-high-low/ | Cryptauk | https://www.tradingview.com/u/Cryptauk/ | 21 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Cryptauk
//@version=5
indicator("Distance from High-Low")
prev_candles = input.int(title="Period (ie candles of selected timeframe)", defval=364, minval=1)
res = input.timeframe(title="Timeframe", defval="")
src = input.source(title="Source", defval=high)
high_or_low = input.string(title="from highest/lowest ?", defval="highest", options=["highest","lowest"])
x_est = request.security(syminfo.tickerid, res, high_or_low == "highest" ? ta.highest(src, prev_candles) : ta.lowest(src, prev_candles))
plot(-(x_est-src)/x_est*100, style = plot.style_columns)
|
Crypto Market Caps (BTC/ETH) | https://www.tradingview.com/script/OZ2Xe6OX-Crypto-Market-Caps-BTC-ETH/ | cyatophilum | https://www.tradingview.com/u/cyatophilum/ | 20 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Cyatophilum
//@version=5
indicator('Crypto Market Caps (BTC/ETH)')
// inputs
btc = input.symbol(title='Market Cap BTC', defval='CRYPTOCAP:BTC', group='Market Cap')
eth = input.symbol(title='Market Cap ETH', defval='CRYPTOCAP:ETH', group='Market Cap')
// Get BTC & alt market caps
b = request.security(btc, timeframe=timeframe.period, expression=close)
e = request.security(eth, timeframe=timeframe.period, expression=close)
// Plot
plot(b/e, 'BTC/ETH', color=color.new(color.orange, 0))
hline(1,title="Flippening",color=color.red,linewidth=2,linestyle=hline.style_solid) |
Market Sector Scanner/Screener With MOM + RSI + MFI + DMI + MACD | https://www.tradingview.com/script/MbeReAPF-Market-Sector-Scanner-Screener-With-MOM-RSI-MFI-DMI-MACD/ | FriendOfTheTrend | https://www.tradingview.com/u/FriendOfTheTrend/ | 364 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © FriendOfTheTrend
//@version=5
indicator("Market Sector Scanner MOM + RSI + MFI + DMI + MACD - Crypto, Stocks & Forex", shorttitle="Market Scanner", overlay=true)
//Indicator Value Inputs
tableOn = input.bool(true, title="Turn Table On/Off", group="Table Settings")
bright = position.bottom_right
bleft = position.bottom_left
bcenter = position.bottom_center
tright = position.top_right
tleft = position.top_left
tcenter = position.top_center
mright = position.middle_right
mleft = position.middle_left
mcenter = position.middle_center
tablePosition = input.string(bleft, title="Table Position", options=[bright, bleft, bcenter, tright, tleft, tcenter, mright, mleft, mcenter], group="Table Settings")
indSource = input.source(close, title="Indicator Source", group="Source")
momLength = input.int(14, title="Momentum Length", group="Indicator Length Settings")
rsiLength = input.int(14, title="RSI Length", group="Indicator Length Settings")
mfiLength = input.int(14, title="MFI Length", group="Indicator Length Settings")
dmiLength = input.int(14, title="DMI Length", group="Indicator Length Settings")
dmiSmoothing = input.int(14, title="DMI Smoothing", group="DMI Smoothing")
macdFastLength = input.int(12, title="MACD Fast Length", group="MACD Settings")
macdSlowLength = input.int(26, title="MACD Slow Length", group="MACD Settings")
macdSmoothing = input.int(9, title="MACD Smoothing", group="MACD Settings")
//Indicators
momValue = ta.mom(indSource, momLength)
[macdLine, macdSignalLine, macdHistLine] = ta.macd(indSource, macdFastLength, macdSlowLength, macdSmoothing)
rsiValue = ta.rsi(indSource, rsiLength)
mfiValue = ta.mfi(indSource, mfiLength)
[dmiPlus, dmiMinus, dmiAdx] = ta.dmi(dmiLength, dmiSmoothing)
//Ticker 1
ticker1 = input.symbol("COINBASE:BTCUSD", title="Ticker #1", group="Tickers To Scan")
ticker1momV = request.security(ticker1, "", momValue)
ticker1rsiV = request.security(ticker1, "", rsiValue)
ticker1mfiV = request.security(ticker1, "", mfiValue)
ticker1dmiPlus = request.security(ticker1, "", dmiPlus - dmiMinus)
ticker1macdLine = request.security(ticker1, "", macdHistLine)
ticker1text = str.tostring(ticker1)
ticker1mom = str.tostring(ticker1momV, format.mintick)
ticker1rsi = str.tostring(ticker1rsiV, format.mintick)
ticker1mfi = str.tostring(ticker1mfiV, format.mintick)
ticker1dmi = str.tostring(ticker1dmiPlus, format.mintick)
ticker1macd = str.tostring(ticker1macdLine, format.mintick)
ticker1bg = color.aqua
if ticker1momV > 0 and ticker1rsiV > 50 and ticker1mfiV > 50 and ticker1dmiPlus > 0 and ticker1macdLine > 0
ticker1bg := color.lime
else if ticker1momV < 0 and ticker1rsiV < 50 and ticker1mfiV < 50 and ticker1dmiPlus < 0 and ticker1macdLine < 0
ticker1bg := color.red
else
ticker1bg := color.aqua
ticker1mombg = color.aqua
if ticker1momV > 0
ticker1mombg := color.lime
else if ticker1momV < 0
ticker1mombg := color.red
else
ticker1mombg := color.aqua
ticker1rsibg = color.aqua
if ticker1rsiV > 50
ticker1rsibg := color.lime
else if ticker1rsiV < 50
ticker1rsibg := color.red
else
ticker1rsibg := color.aqua
ticker1mfibg = color.aqua
if ticker1mfiV > 50
ticker1mfibg := color.lime
else if ticker1mfiV < 50
ticker1mfibg := color.red
else
ticker1mfibg := color.aqua
ticker1dmibg = color.aqua
if ticker1dmiPlus > 0
ticker1dmibg := color.lime
else if ticker1dmiPlus < 0
ticker1dmibg := color.red
else
ticker1dmibg := color.aqua
ticker1macdbg = color.aqua
if ticker1macdLine > 0
ticker1macdbg := color.lime
else if ticker1macdLine < 0
ticker1macdbg := color.red
else
ticker1macdbg := color.aqua
//Ticker 2
ticker2 = input.symbol("COINBASE:ETHUSD", title="Ticker #2", group="Tickers To Scan")
ticker2momV = request.security(ticker2, "", momValue)
ticker2rsiV = request.security(ticker2, "", rsiValue)
ticker2mfiV = request.security(ticker2, "", mfiValue)
ticker2dmiPlus = request.security(ticker2, "", dmiPlus - dmiMinus)
ticker2macdLine = request.security(ticker2, "", macdHistLine)
ticker2text = str.tostring(ticker2)
ticker2mom = str.tostring(ticker2momV, format.mintick)
ticker2rsi = str.tostring(ticker2rsiV, format.mintick)
ticker2mfi = str.tostring(ticker2mfiV, format.mintick)
ticker2dmi = str.tostring(ticker2dmiPlus, format.mintick)
ticker2macd = str.tostring(ticker2macdLine, format.mintick)
ticker2bg = color.aqua
if ticker2momV > 0 and ticker2rsiV > 50 and ticker2mfiV > 50 and ticker2dmiPlus > 0 and ticker2macdLine > 0
ticker2bg := color.lime
else if ticker2momV < 0 and ticker2rsiV < 50 and ticker2mfiV < 50 and ticker2dmiPlus < 0 and ticker2macdLine < 0
ticker2bg := color.red
else
ticker2bg := color.aqua
ticker2mombg = color.aqua
if ticker2momV > 0
ticker2mombg := color.lime
else if ticker2momV < 0
ticker2mombg := color.red
else
ticker2mombg := color.aqua
ticker2rsibg = color.aqua
if ticker2rsiV > 50
ticker2rsibg := color.lime
else if ticker2rsiV < 50
ticker2rsibg := color.red
else
ticker2rsibg := color.aqua
ticker2mfibg = color.aqua
if ticker2mfiV > 50
ticker2mfibg := color.lime
else if ticker2mfiV < 50
ticker2mfibg := color.red
else
ticker2mfibg := color.aqua
ticker2dmibg = color.aqua
if ticker2dmiPlus > 0
ticker2dmibg := color.lime
else if ticker2dmiPlus < 0
ticker2dmibg := color.red
else
ticker2dmibg := color.aqua
ticker2macdbg = color.aqua
if ticker2macdLine > 0
ticker2macdbg := color.lime
else if ticker2macdLine < 0
ticker2macdbg := color.red
else
ticker2macdbg := color.aqua
//Ticker 3
ticker3 = input.symbol("COINBASE:XRPUSD", title="Ticker #3", group="Tickers To Scan")
ticker3momV = request.security(ticker3, "", momValue)
ticker3rsiV = request.security(ticker3, "", rsiValue)
ticker3mfiV = request.security(ticker3, "", mfiValue)
ticker3dmiPlus = request.security(ticker3, "", dmiPlus - dmiMinus)
ticker3macdLine = request.security(ticker3, "", macdHistLine)
ticker3text = str.tostring(ticker3)
ticker3mom = str.tostring(ticker3momV, format.mintick)
ticker3rsi = str.tostring(ticker3rsiV, format.mintick)
ticker3mfi = str.tostring(ticker3mfiV, format.mintick)
ticker3dmi = str.tostring(ticker3dmiPlus, format.mintick)
ticker3macd = str.tostring(ticker3macdLine, format.mintick)
ticker3bg = color.aqua
if ticker3momV > 0 and ticker3rsiV > 50 and ticker3mfiV > 50 and ticker3dmiPlus > 0 and ticker3macdLine > 0
ticker3bg := color.lime
else if ticker3momV < 0 and ticker3rsiV < 50 and ticker3mfiV < 50 and ticker3dmiPlus < 0 and ticker3macdLine < 0
ticker3bg := color.red
else
ticker3bg := color.aqua
ticker3mombg = color.aqua
if ticker3momV > 0
ticker3mombg := color.lime
else if ticker3momV < 0
ticker3mombg := color.red
else
ticker3mombg := color.aqua
ticker3rsibg = color.aqua
if ticker3rsiV > 50
ticker3rsibg := color.lime
else if ticker3rsiV < 50
ticker3rsibg := color.red
else
ticker3rsibg := color.aqua
ticker3mfibg = color.aqua
if ticker3mfiV > 50
ticker3mfibg := color.lime
else if ticker3mfiV < 50
ticker3mfibg := color.red
else
ticker3mfibg := color.aqua
ticker3dmibg = color.aqua
if ticker3dmiPlus > 0
ticker3dmibg := color.lime
else if ticker3dmiPlus < 0
ticker3dmibg := color.red
else
ticker3dmibg := color.aqua
ticker3macdbg = color.aqua
if ticker3macdLine > 0
ticker3macdbg := color.lime
else if ticker3macdLine < 0
ticker3macdbg := color.red
else
ticker3macdbg := color.aqua
//Ticker 4
ticker4 = input.symbol("COINBASE:ADAUSD", title="Ticker #4", group="Tickers To Scan")
ticker4momV = request.security(ticker4, "", momValue)
ticker4rsiV = request.security(ticker4, "", rsiValue)
ticker4mfiV = request.security(ticker4, "", mfiValue)
ticker4dmiPlus = request.security(ticker4, "", dmiPlus - dmiMinus)
ticker4macdLine = request.security(ticker4, "", macdHistLine)
ticker4text = str.tostring(ticker4)
ticker4mom = str.tostring(ticker4momV, format.mintick)
ticker4rsi = str.tostring(ticker4rsiV, format.mintick)
ticker4mfi = str.tostring(ticker4mfiV, format.mintick)
ticker4dmi = str.tostring(ticker4dmiPlus, format.mintick)
ticker4macd = str.tostring(ticker4macdLine, format.mintick)
ticker4bg = color.aqua
if ticker4momV > 0 and ticker4rsiV > 50 and ticker4mfiV > 50 and ticker4dmiPlus > 0 and ticker4macdLine > 0
ticker4bg := color.lime
else if ticker4momV < 0 and ticker4rsiV < 50 and ticker4mfiV < 50 and ticker4dmiPlus < 0 and ticker4macdLine < 0
ticker4bg := color.red
else
ticker4bg := color.aqua
ticker4mombg = color.aqua
if ticker4momV > 0
ticker4mombg := color.lime
else if ticker4momV < 0
ticker4mombg := color.red
else
ticker4mombg := color.aqua
ticker4rsibg = color.aqua
if ticker4rsiV > 50
ticker4rsibg := color.lime
else if ticker4rsiV < 50
ticker4rsibg := color.red
else
ticker4rsibg := color.aqua
ticker4mfibg = color.aqua
if ticker4mfiV > 50
ticker4mfibg := color.lime
else if ticker4mfiV < 50
ticker4mfibg := color.red
else
ticker4mfibg := color.aqua
ticker4dmibg = color.aqua
if ticker4dmiPlus > 0
ticker4dmibg := color.lime
else if ticker4dmiPlus < 0
ticker4dmibg := color.red
else
ticker4dmibg := color.aqua
ticker4macdbg = color.aqua
if ticker4macdLine > 0
ticker4macdbg := color.lime
else if ticker4macdLine < 0
ticker4macdbg := color.red
else
ticker4macdbg := color.aqua
//Ticker 5
ticker5 = input.symbol("COINBASE:SOLUSD", title="Ticker #5", group="Tickers To Scan")
ticker5momV = request.security(ticker5, "", momValue)
ticker5rsiV = request.security(ticker5, "", rsiValue)
ticker5mfiV = request.security(ticker5, "", mfiValue)
ticker5dmiPlus = request.security(ticker5, "", dmiPlus - dmiMinus)
ticker5macdLine = request.security(ticker5, "", macdHistLine)
ticker5text = str.tostring(ticker5)
ticker5mom = str.tostring(ticker5momV, format.mintick)
ticker5rsi = str.tostring(ticker5rsiV, format.mintick)
ticker5mfi = str.tostring(ticker5mfiV, format.mintick)
ticker5dmi = str.tostring(ticker5dmiPlus, format.mintick)
ticker5macd = str.tostring(ticker5macdLine, format.mintick)
ticker5bg = color.aqua
if ticker5momV > 0 and ticker5rsiV > 50 and ticker5mfiV > 50 and ticker5dmiPlus > 0 and ticker5macdLine > 0
ticker5bg := color.lime
else if ticker5momV < 0 and ticker5rsiV < 50 and ticker5mfiV < 50 and ticker5dmiPlus < 0 and ticker5macdLine < 0
ticker5bg := color.red
else
ticker5bg := color.aqua
ticker5mombg = color.aqua
if ticker5momV > 0
ticker5mombg := color.lime
else if ticker5momV < 0
ticker5mombg := color.red
else
ticker5mombg := color.aqua
ticker5rsibg = color.aqua
if ticker5rsiV > 50
ticker5rsibg := color.lime
else if ticker5rsiV < 50
ticker5rsibg := color.red
else
ticker5rsibg := color.aqua
ticker5mfibg = color.aqua
if ticker5mfiV > 50
ticker5mfibg := color.lime
else if ticker5mfiV < 50
ticker5mfibg := color.red
else
ticker5mfibg := color.aqua
ticker5dmibg = color.aqua
if ticker5dmiPlus > 0
ticker5dmibg := color.lime
else if ticker5dmiPlus < 0
ticker5dmibg := color.red
else
ticker5dmibg := color.aqua
ticker5macdbg = color.aqua
if ticker5macdLine > 0
ticker5macdbg := color.lime
else if ticker5macdLine < 0
ticker5macdbg := color.red
else
ticker5macdbg := color.aqua
//Ticker 6
ticker6 = input.symbol("COINBASE:DOTUSD", title="Ticker #6", group="Tickers To Scan")
ticker6momV = request.security(ticker6, "", momValue)
ticker6rsiV = request.security(ticker6, "", rsiValue)
ticker6mfiV = request.security(ticker6, "", mfiValue)
ticker6dmiPlus = request.security(ticker6, "", dmiPlus - dmiMinus)
ticker6macdLine = request.security(ticker6, "", macdHistLine)
ticker6text = str.tostring(ticker6)
ticker6mom = str.tostring(ticker6momV, format.mintick)
ticker6rsi = str.tostring(ticker6rsiV, format.mintick)
ticker6mfi = str.tostring(ticker6mfiV, format.mintick)
ticker6dmi = str.tostring(ticker6dmiPlus, format.mintick)
ticker6macd = str.tostring(ticker6macdLine, format.mintick)
ticker6bg = color.aqua
if ticker6momV > 0 and ticker6rsiV > 50 and ticker6mfiV > 50 and ticker6dmiPlus > 0 and ticker6macdLine > 0
ticker6bg := color.lime
else if ticker6momV < 0 and ticker6rsiV < 50 and ticker6mfiV < 50 and ticker6dmiPlus < 0 and ticker6macdLine < 0
ticker6bg := color.red
else
ticker6bg := color.aqua
ticker6mombg = color.aqua
if ticker6momV > 0
ticker6mombg := color.lime
else if ticker6momV < 0
ticker6mombg := color.red
else
ticker6mombg := color.aqua
ticker6rsibg = color.aqua
if ticker6rsiV > 50
ticker6rsibg := color.lime
else if ticker6rsiV < 50
ticker6rsibg := color.red
else
ticker6rsibg := color.aqua
ticker6mfibg = color.aqua
if ticker6mfiV > 50
ticker6mfibg := color.lime
else if ticker6mfiV < 50
ticker6mfibg := color.red
else
ticker6mfibg := color.aqua
ticker6dmibg = color.aqua
if ticker6dmiPlus > 0
ticker6dmibg := color.lime
else if ticker6dmiPlus < 0
ticker6dmibg := color.red
else
ticker6dmibg := color.aqua
ticker6macdbg = color.aqua
if ticker6macdLine > 0
ticker6macdbg := color.lime
else if ticker6macdLine < 0
ticker6macdbg := color.red
else
ticker6macdbg := color.aqua
//Ticker 7
ticker7 = input.symbol("COINBASE:LTCUSD", title="Ticker #7", group="Tickers To Scan")
ticker7momV = request.security(ticker7, "", momValue)
ticker7rsiV = request.security(ticker7, "", rsiValue)
ticker7mfiV = request.security(ticker7, "", mfiValue)
ticker7dmiPlus = request.security(ticker7, "", dmiPlus - dmiMinus)
ticker7macdLine = request.security(ticker7, "", macdHistLine)
ticker7text = str.tostring(ticker7)
ticker7mom = str.tostring(ticker7momV, format.mintick)
ticker7rsi = str.tostring(ticker7rsiV, format.mintick)
ticker7mfi = str.tostring(ticker7mfiV, format.mintick)
ticker7dmi = str.tostring(ticker7dmiPlus, format.mintick)
ticker7macd = str.tostring(ticker7macdLine, format.mintick)
ticker7bg = color.aqua
if ticker7momV > 0 and ticker7rsiV > 50 and ticker7mfiV > 50 and ticker7dmiPlus > 0 and ticker7macdLine > 0
ticker7bg := color.lime
else if ticker7momV < 0 and ticker7rsiV < 50 and ticker7mfiV < 50 and ticker7dmiPlus < 0 and ticker7macdLine < 0
ticker7bg := color.red
else
ticker7bg := color.aqua
ticker7mombg = color.aqua
if ticker7momV > 0
ticker7mombg := color.lime
else if ticker7momV < 0
ticker7mombg := color.red
else
ticker7mombg := color.aqua
ticker7rsibg = color.aqua
if ticker7rsiV > 50
ticker7rsibg := color.lime
else if ticker7rsiV < 50
ticker7rsibg := color.red
else
ticker7rsibg := color.aqua
ticker7mfibg = color.aqua
if ticker7mfiV > 50
ticker7mfibg := color.lime
else if ticker7mfiV < 50
ticker7mfibg := color.red
else
ticker7mfibg := color.aqua
ticker7dmibg = color.aqua
if ticker7dmiPlus > 0
ticker7dmibg := color.lime
else if ticker7dmiPlus < 0
ticker7dmibg := color.red
else
ticker7dmibg := color.aqua
ticker7macdbg = color.aqua
if ticker7macdLine > 0
ticker7macdbg := color.lime
else if ticker7macdLine < 0
ticker7macdbg := color.red
else
ticker7macdbg := color.aqua
//Ticker 8
ticker8 = input.symbol("COINBASE:LINKUSD", title="Ticker #8", group="Tickers To Scan")
ticker8momV = request.security(ticker8, "", momValue)
ticker8rsiV = request.security(ticker8, "", rsiValue)
ticker8mfiV = request.security(ticker8, "", mfiValue)
ticker8dmiPlus = request.security(ticker8, "", dmiPlus - dmiMinus)
ticker8macdLine = request.security(ticker8, "", macdHistLine)
ticker8text = str.tostring(ticker8)
ticker8mom = str.tostring(ticker8momV, format.mintick)
ticker8rsi = str.tostring(ticker8rsiV, format.mintick)
ticker8mfi = str.tostring(ticker8mfiV, format.mintick)
ticker8dmi = str.tostring(ticker8dmiPlus, format.mintick)
ticker8macd = str.tostring(ticker8macdLine, format.mintick)
ticker8bg = color.aqua
if ticker8momV > 0 and ticker8rsiV > 50 and ticker8mfiV > 50 and ticker8dmiPlus > 0 and ticker8macdLine > 0
ticker8bg := color.lime
else if ticker8momV < 0 and ticker8rsiV < 50 and ticker8mfiV < 50 and ticker8dmiPlus < 0 and ticker8macdLine < 0
ticker8bg := color.red
else
ticker8bg := color.aqua
ticker8mombg = color.aqua
if ticker8momV > 0
ticker8mombg := color.lime
else if ticker8momV < 0
ticker8mombg := color.red
else
ticker8mombg := color.aqua
ticker8rsibg = color.aqua
if ticker8rsiV > 50
ticker8rsibg := color.lime
else if ticker8rsiV < 50
ticker8rsibg := color.red
else
ticker8rsibg := color.aqua
ticker8mfibg = color.aqua
if ticker8mfiV > 50
ticker8mfibg := color.lime
else if ticker8mfiV < 50
ticker8mfibg := color.red
else
ticker8mfibg := color.aqua
ticker8dmibg = color.aqua
if ticker8dmiPlus > 0
ticker8dmibg := color.lime
else if ticker8dmiPlus < 0
ticker8dmibg := color.red
else
ticker8dmibg := color.aqua
ticker8macdbg = color.aqua
if ticker8macdLine > 0
ticker8macdbg := color.lime
else if ticker8macdLine < 0
ticker8macdbg := color.red
else
ticker8macdbg := color.aqua
//Alerts
allGreenAlert = false
if ticker1bg == color.lime and ticker2bg == color.lime and ticker3bg == color.lime and ticker4bg == color.lime and ticker5bg == color.lime and ticker6bg == color.lime and
ticker7bg == color.lime and ticker8bg == color.lime
allGreenAlert := true
allRedAlert = false
if ticker1bg == color.red and ticker2bg == color.red and ticker3bg == color.red and ticker4bg == color.red and ticker5bg == color.red and ticker6bg == color.red and
ticker7bg == color.red and ticker8bg == color.red
allRedAlert := true
alertcondition(allGreenAlert, "All Bullish Scanner", "Entire Market Scanner Is Bullish")
alertcondition(allRedAlert, "All Bearish Scanner", "Entire Market Scanner Is Bearish")
alertcondition(ticker1bg == color.lime, "Ticker 1 Is All Bullish", "Ticker 1 Scanner All Bullish")
alertcondition(ticker2bg == color.lime, "Ticker 2 Is All Bullish", "Ticker 2 Scanner All Bullish")
alertcondition(ticker3bg == color.lime, "Ticker 3 Is All Bullish", "Ticker 3 Scanner All Bullish")
alertcondition(ticker4bg == color.lime, "Ticker 4 Is All Bullish", "Ticker 4 Scanner All Bullish")
alertcondition(ticker5bg == color.lime, "Ticker 5 Is All Bullish", "Ticker 5 Scanner All Bullish")
alertcondition(ticker6bg == color.lime, "Ticker 6 Is All Bullish", "Ticker 6 Scanner All Bullish")
alertcondition(ticker7bg == color.lime, "Ticker 7 Is All Bullish", "Ticker 7 Scanner All Bullish")
alertcondition(ticker8bg == color.lime, "Ticker 8 Is All Bullish", "Ticker 8 Scanner All Bullish")
alertcondition(ticker1bg == color.red, "Ticker 1 Is All Bearish", "Ticker 1 Scanner All Bearish")
alertcondition(ticker2bg == color.red, "Ticker 2 Is All Bearish", "Ticker 2 Scanner All Bearish")
alertcondition(ticker3bg == color.red, "Ticker 3 Is All Bearish", "Ticker 3 Scanner All Bearish")
alertcondition(ticker4bg == color.red, "Ticker 4 Is All Bearish", "Ticker 4 Scanner All Bearish")
alertcondition(ticker5bg == color.red, "Ticker 5 Is All Bearish", "Ticker 5 Scanner All Bearish")
alertcondition(ticker6bg == color.red, "Ticker 6 Is All Bearish", "Ticker 6 Scanner All Bearish")
alertcondition(ticker7bg == color.red, "Ticker 7 Is All Bearish", "Ticker 7 Scanner All Bearish")
alertcondition(ticker8bg == color.red, "Ticker 8 Is All Bearish", "Ticker 8 Scanner All Bearish")
//Plot Scanner Table
dataTable = table.new(tablePosition, columns=6, rows=11, border_color=color.white, border_width=1)
if tableOn and barstate.islast
table.cell(table_id=dataTable, column=0, row=0, text="TICKER", height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=color.blue)
table.cell(table_id=dataTable, column=1, row=0, text="MOM", height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=color.blue)
table.cell(table_id=dataTable, column=2, row=0, text="RSI", height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=color.blue)
table.cell(table_id=dataTable, column=3, row=0, text="MFI", height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=color.blue)
table.cell(table_id=dataTable, column=4, row=0, text="DMI", height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=color.blue)
table.cell(table_id=dataTable, column=5, row=0, text="MACD", height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=color.blue)
table.cell(table_id=dataTable, column=0, row=1, text=ticker1text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker1bg)
table.cell(table_id=dataTable, column=1, row=1, text=ticker1mom, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker1mombg)
table.cell(table_id=dataTable, column=2, row=1, text=ticker1rsi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker1rsibg)
table.cell(table_id=dataTable, column=3, row=1, text=ticker1mfi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker1mfibg)
table.cell(table_id=dataTable, column=4, row=1, text=ticker1dmi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker1dmibg)
table.cell(table_id=dataTable, column=5, row=1, text=ticker1macd, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker1macdbg)
table.cell(table_id=dataTable, column=0, row=2, text=ticker2text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker2bg)
table.cell(table_id=dataTable, column=1, row=2, text=ticker2mom, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker2mombg)
table.cell(table_id=dataTable, column=2, row=2, text=ticker2rsi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker2rsibg)
table.cell(table_id=dataTable, column=3, row=2, text=ticker2mfi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker2mfibg)
table.cell(table_id=dataTable, column=4, row=2, text=ticker2dmi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker2dmibg)
table.cell(table_id=dataTable, column=5, row=2, text=ticker2macd, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker2macdbg)
table.cell(table_id=dataTable, column=0, row=3, text=ticker3text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker3bg)
table.cell(table_id=dataTable, column=1, row=3, text=ticker3mom, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker3mombg)
table.cell(table_id=dataTable, column=2, row=3, text=ticker3rsi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker3rsibg)
table.cell(table_id=dataTable, column=3, row=3, text=ticker3mfi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker3mfibg)
table.cell(table_id=dataTable, column=4, row=3, text=ticker3dmi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker3dmibg)
table.cell(table_id=dataTable, column=5, row=3, text=ticker3macd, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker3macdbg)
table.cell(table_id=dataTable, column=0, row=4, text=ticker4text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker4bg)
table.cell(table_id=dataTable, column=1, row=4, text=ticker4mom, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker4mombg)
table.cell(table_id=dataTable, column=2, row=4, text=ticker4rsi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker4rsibg)
table.cell(table_id=dataTable, column=3, row=4, text=ticker4mfi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker4mfibg)
table.cell(table_id=dataTable, column=4, row=4, text=ticker4dmi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker4dmibg)
table.cell(table_id=dataTable, column=5, row=4, text=ticker4macd, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker4macdbg)
table.cell(table_id=dataTable, column=0, row=5, text=ticker5text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker5bg)
table.cell(table_id=dataTable, column=1, row=5, text=ticker5mom, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker5mombg)
table.cell(table_id=dataTable, column=2, row=5, text=ticker5rsi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker5rsibg)
table.cell(table_id=dataTable, column=3, row=5, text=ticker5mfi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker5mfibg)
table.cell(table_id=dataTable, column=4, row=5, text=ticker5dmi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker5dmibg)
table.cell(table_id=dataTable, column=5, row=5, text=ticker5macd, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker5macdbg)
table.cell(table_id=dataTable, column=0, row=6, text=ticker6text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker6bg)
table.cell(table_id=dataTable, column=1, row=6, text=ticker6mom, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker6mombg)
table.cell(table_id=dataTable, column=2, row=6, text=ticker6rsi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker6rsibg)
table.cell(table_id=dataTable, column=3, row=6, text=ticker6mfi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker6mfibg)
table.cell(table_id=dataTable, column=4, row=6, text=ticker6dmi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker6dmibg)
table.cell(table_id=dataTable, column=5, row=6, text=ticker6macd, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker6macdbg)
table.cell(table_id=dataTable, column=0, row=7, text=ticker7text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker7bg)
table.cell(table_id=dataTable, column=1, row=7, text=ticker7mom, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker7mombg)
table.cell(table_id=dataTable, column=2, row=7, text=ticker7rsi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker7rsibg)
table.cell(table_id=dataTable, column=3, row=7, text=ticker7mfi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker7mfibg)
table.cell(table_id=dataTable, column=4, row=7, text=ticker7dmi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker7dmibg)
table.cell(table_id=dataTable, column=5, row=7, text=ticker7macd, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker7macdbg)
table.cell(table_id=dataTable, column=0, row=8, text=ticker8text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker8bg)
table.cell(table_id=dataTable, column=1, row=8, text=ticker8mom, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker8mombg)
table.cell(table_id=dataTable, column=2, row=8, text=ticker8rsi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker8rsibg)
table.cell(table_id=dataTable, column=3, row=8, text=ticker8mfi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker8mfibg)
table.cell(table_id=dataTable, column=4, row=8, text=ticker8dmi, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker8dmibg)
table.cell(table_id=dataTable, column=5, row=8, text=ticker8macd, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker8macdbg)
|
SRJ RSI Outperformer | https://www.tradingview.com/script/MjtqoE1o-SRJ-RSI-Outperformer/ | Sapt_Jash | https://www.tradingview.com/u/Sapt_Jash/ | 47 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sapt_Jash
//@version=5
indicator(title="SRJ RSI Outperformer ", shorttitle="SRJ RSI Outperformer")
srcperiod1 = input.int(14, minval=1, title="Length Of Fast RSI")
srcperiod2 = input.int(28, minval=1, title="Length Of Slow RSI")
srcperiod3 = input.int(14, minval=1, title="Length Of Moving Average")
rsi1 = ta.rsi(close, srcperiod1)
rsi2 = ta.rsi(close, srcperiod2)
divergence1 = (rsi2/rsi1)
divergence2 = (rsi1/divergence1)
ma1 = ta.sma(rsi1, srcperiod3)
ma2 = ta.sma(divergence2, srcperiod3)
plot(ma1, title='Fast RSI Moving Average', color=color.new(color.yellow, 0), linewidth=1, style=plot.style_line, offset=0, trackprice=true)
plot(ma2, title='RSI Outperformer Moving Average', color=color.new(#00ffaa, 0), linewidth=1, style=plot.style_line, offset=0, trackprice=true)
hline(80, title='Upper Level', color=color.new(#00ffaa, 0), linestyle=hline.style_solid, linewidth=1)
hline(20, title='Lower Level', color=color.new(#00ffaa, 0), linestyle=hline.style_solid, linewidth=1)
|
Wick Strategy | https://www.tradingview.com/script/Euhdk1cH-Wick-Strategy/ | Kawol268 | https://www.tradingview.com/u/Kawol268/ | 21 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kawol268
//@version=4
study("Myscript")
cumTimeFrame = input("D", type=input.resolution)
is_new_day = change(time(cumTimeFrame)) != 0 ? 1 : 0
cnt_new_day = barssince(is_new_day)
highwick=high-close
lowwick=low-open
Body=close-open
//Green Candle
if (close>open)
highwick:=abs(high-close)
lowwick:=abs(low-open)
Body:=abs(close-open)*1
//Red candle
else
highwick:=abs(high-open)
lowwick:=abs(close-low)
Body:=abs(close-open)*-1
//lowwick bullish, high wick bearish
output =lowwick- highwick+Body
plot(output, color=color.white, transp = 80)
// Accumulation
var cvol = 0.0
cvol :=output + (is_new_day ? 0 : cvol)
A=cum(cvol)
plot(cvol, color=color.red)
|
intraday_bonds | https://www.tradingview.com/script/ILfrvuHD-intraday-bonds/ | voided | https://www.tradingview.com/u/voided/ | 62 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © voided
//@version=5
indicator("intraday_bonds", overlay = true)
stdevs = input(2.0, "stdevs")
half_hour = 6.0
one_hour = 2.0 * half_hour
one_day = 23.0 * one_hour
one_year = 252.0 * one_day
zt_c = request.security("ZT1!", "5", close)
zf_c = request.security("ZF1!", "5", close)
zn_c = request.security("ZN1!", "5", close)
zb_c = request.security("ZB1!", "5", close)
zt_h = request.security("ZT1!", "5", high)
zf_h = request.security("ZF1!", "5", high)
zn_h = request.security("ZN1!", "5", high)
zb_h = request.security("ZB1!", "5", high)
zt_l = request.security("ZT1!", "5", low)
zf_l = request.security("ZF1!", "5", low)
zn_l = request.security("ZN1!", "5", low)
zb_l = request.security("ZB1!", "5", low)
var float[] zt_rvs = array.new_float()
var float[] zf_rvs = array.new_float()
var float[] zn_rvs = array.new_float()
var float[] zb_rvs = array.new_float()
rv(sym) =>
squared_returns = math.pow(math.log(sym / sym[1]), 2.0)
smoothed_returns = ta.ema(squared_returns, int(one_hour))
math.sqrt(smoothed_returns * one_year)
hour_ticks(rv, c, h, l) =>
rv_hour = c * stdevs * rv * math.sqrt(one_hour / one_year)
atr_hour = ta.highest(h, int(one_hour)) - ta.lowest(l, int(one_hour))
[ rv_hour, atr_hour ]
zt_rv = rv(zt_c)
zf_rv = rv(zf_c)
zn_rv = rv(zn_c)
zb_rv = rv(zb_c)
array.push(zt_rvs, zt_rv)
array.push(zf_rvs, zf_rv)
array.push(zn_rvs, zn_rv)
array.push(zb_rvs, zb_rv)
[ zt_rv_hour, zt_atr_hour ] = hour_ticks(zt_rv, zt_c, zt_h, zt_l)
[ zf_rv_hour, zf_atr_hour ] = hour_ticks(zf_rv, zf_c, zf_h, zf_l)
[ zn_rv_hour, zn_atr_hour ] = hour_ticks(zn_rv, zn_c, zn_h, zn_l)
[ zb_rv_hour, zb_atr_hour ] = hour_ticks(zb_rv, zb_c, zb_h, zb_l)
zt_d = zt_c - zt_c[1]
zf_d = zf_c - zf_c[1]
zn_d = zn_c - zn_c[1]
zb_d = zb_c - zb_c[1]
zt_zf = ta.correlation(zt_d, zf_d, int(one_day))
zt_zn = ta.correlation(zt_d, zn_d, int(one_day))
zt_zb = ta.correlation(zt_d, zb_d, int(one_day))
zf_zt = ta.correlation(zf_d, zt_d, int(one_day))
zf_zn = ta.correlation(zf_d, zn_d, int(one_day))
zf_zb = ta.correlation(zf_d, zb_d, int(one_day))
zn_zt = ta.correlation(zn_d, zt_d, int(one_day))
zn_zf = ta.correlation(zn_d, zf_d, int(one_day))
zn_zb = ta.correlation(zn_d, zb_d, int(one_day))
zb_zt = ta.correlation(zb_d, zt_d, int(one_day))
zb_zf = ta.correlation(zb_d, zf_d, int(one_day))
zb_zn = ta.correlation(zb_d, zn_d, int(one_day))
if barstate.islast
zt_rv_z = (zt_rv - array.avg(zt_rvs)) / array.stdev(zt_rvs)
zf_rv_z = (zf_rv - array.avg(zf_rvs)) / array.stdev(zf_rvs)
zn_rv_z = (zn_rv - array.avg(zn_rvs)) / array.stdev(zn_rvs)
zb_rv_z = (zb_rv - array.avg(zb_rvs)) / array.stdev(zb_rvs)
fmt = "#.##"
t = table.new(position.top_right, 5, 11)
table.cell(t, 0, 0)
table.cell(t, 0, 1, "zt", text_color = color.white)
table.cell(t, 0, 2, "zf", text_color = color.white)
table.cell(t, 0, 3, "zn", text_color = color.white)
table.cell(t, 0, 4, "zb", text_color = color.white)
table.cell(t, 1, 0, "rv", text_color = color.white)
table.cell(t, 2, 0, "z(rv) ", text_color = color.white)
table.cell(t, 3, 0, "vol rng", text_color = color.white)
table.cell(t, 4, 0, "atr rng", text_color = color.white)
table.cell(t, 1, 1, str.tostring(zt_rv * 100, fmt) + "%", text_color = color.white)
table.cell(t, 1, 2, str.tostring(zf_rv * 100, fmt) + "%", text_color = color.white)
table.cell(t, 1, 3, str.tostring(zn_rv * 100, fmt) + "%", text_color = color.white)
table.cell(t, 1, 4, str.tostring(zb_rv * 100, fmt) + "%", text_color = color.white)
table.cell(t, 2, 1, str.tostring(zt_rv_z, fmt), text_color = color.white)
table.cell(t, 2, 2, str.tostring(zf_rv_z, fmt), text_color = color.white)
table.cell(t, 2, 3, str.tostring(zn_rv_z, fmt), text_color = color.white)
table.cell(t, 2, 4, str.tostring(zb_rv_z, fmt), text_color = color.white)
table.cell(t, 3, 1, str.tostring(math.ceil(zt_rv_hour * 256.0)), text_color = color.white)
table.cell(t, 3, 2, str.tostring(math.ceil(zf_rv_hour * 128.0)), text_color = color.white)
table.cell(t, 3, 3, str.tostring(math.ceil(zn_rv_hour * 64.0)), text_color = color.white)
table.cell(t, 3, 4, str.tostring(math.ceil(zb_rv_hour * 32.0)), text_color = color.white)
table.cell(t, 4, 1, str.tostring(math.ceil(zt_atr_hour * 256.0)), text_color = color.white)
table.cell(t, 4, 2, str.tostring(math.ceil(zf_atr_hour * 128.0)), text_color = color.white)
table.cell(t, 4, 3, str.tostring(math.ceil(zn_atr_hour * 64.0)), text_color = color.white)
table.cell(t, 4, 4, str.tostring(math.ceil(zb_atr_hour * 32.0)), text_color = color.white)
table.cell(t, 0, 5)
table.cell(t, 1, 5)
table.cell(t, 2, 5)
table.cell(t, 3, 5)
table.cell(t, 4, 5)
table.cell(t, 0, 6)
table.cell(t, 1, 6, "zt", text_color = color.white)
table.cell(t, 2, 6, "zf", text_color = color.white)
table.cell(t, 3, 6, "zn", text_color = color.white)
table.cell(t, 4, 6, "zb", text_color = color.white)
table.cell(t, 0, 7, "zt", text_color = color.white)
table.cell(t, 0, 8, "zf", text_color = color.white)
table.cell(t, 0, 9, "zn", text_color = color.white)
table.cell(t, 0, 10, "zb", text_color = color.white)
table.cell(t, 1, 7, "1", text_color = color.white)
table.cell(t, 1, 8, str.tostring(zt_zf, fmt), text_color = color.white)
table.cell(t, 1, 9, str.tostring(zt_zn, fmt), text_color = color.white)
table.cell(t, 1, 10, str.tostring(zt_zb, fmt), text_color = color.white)
table.cell(t, 2, 7, str.tostring(zf_zt, fmt), text_color = color.white)
table.cell(t, 2, 8, "1", text_color = color.white)
table.cell(t, 2, 9, str.tostring(zf_zn, fmt), text_color = color.white)
table.cell(t, 2, 10, str.tostring(zf_zb, fmt), text_color = color.white)
table.cell(t, 3, 7, str.tostring(zn_zt, fmt), text_color = color.white)
table.cell(t, 3, 8, str.tostring(zn_zf, fmt), text_color = color.white)
table.cell(t, 3, 9, "1", text_color = color.white)
table.cell(t, 3, 10, str.tostring(zn_zb, fmt), text_color = color.white)
table.cell(t, 4, 7, str.tostring(zb_zt, fmt), text_color = color.white)
table.cell(t, 4, 8, str.tostring(zb_zf, fmt), text_color = color.white)
table.cell(t, 4, 9, str.tostring(zb_zn, fmt), text_color = color.white)
table.cell(t, 4, 10, "1", text_color = color.white) |
10-2 Year Treasury Yield Spread by zdmre | https://www.tradingview.com/script/JN82lVEA-10-2-Year-Treasury-Yield-Spread-by-zdmre/ | zdmre | https://www.tradingview.com/u/zdmre/ | 83 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © zdmre
//@version=5
indicator("US TSY Yield Curves by zdmre", overlay=false)
us02y = request.security("TVC:US02Y", "D", close)
us03y = request.security("TVC:US03Y", "D", close)
us05y = request.security("TVC:US05Y", "D", close)
us10y = request.security("TVC:US10Y", "D", close)
us30y = request.security("TVC:US30Y", "D", close)
diff = us10y - us02y
diff30_5 = us30y - us05y
diff10_3 = us10y - us03y
diff10_5 = us10y - us05y
diff30_2 = us30y - us02y
bearish = ta.cross(diff, 0) == 1 and diff < 0
bullish = ta.cross(diff, 2.6) == 1 and diff > 2.6
plot(bearish ? diff : na ,title='Recession Risk', style=plot.style_circles, color=color.new(color.red, 0), linewidth=5)
plot(bullish ? diff : na ,title='Recovery Plan ', style=plot.style_circles, color=color.new(color.green, 0), linewidth=5)
if bearish
label1 = label.new(bar_index, 0 , text='|\n'+ str.format("{0,date, y\nMMM-d}", time), style=label.style_label_up, color=color.new(color.red,100))
label.set_size(label1, size.small)
label.set_textcolor(label1, color.red)
if bullish
label2 = label.new(bar_index, 2.6 , text=str.format("{0,date, y\nMMM-d\n}", time)+'|', style=label.style_label_down, color=color.new(color.green,100))
label.set_size(label2, size.small)
label.set_textcolor(label2, color.green)
uband = hline(2.6, "Upper Band", color=#787B86)
mband = hline(1.3, "Mid-Band", color=color.new(color.yellow, 50))
lband = hline(0, "Lower Band", color=#787B86)
var tbis = table.new(position.middle_right, 2, 6, frame_color=color.black, frame_width=0, border_width=1, border_color=color.black)
table.cell(tbis, 0, 1, '10Y-2Y', bgcolor = color.new(#fff407, 0), text_size=size.normal, text_color=color.black)
table.cell(tbis, 0, 2, '10Y-3Y', bgcolor = color.new(#0765ff, 0), text_size=size.normal, text_color=color.white)
table.cell(tbis, 0, 3, '10Y-5Y', bgcolor = color.new(#34ff07, 0), text_size=size.normal, text_color=color.black)
table.cell(tbis, 0, 4, '30Y-2Y', bgcolor = color.new(#07f4ff, 0), text_size=size.normal, text_color=color.black)
table.cell(tbis, 0, 5, '30Y-5Y', bgcolor = color.new(#ff6807, 0), text_size=size.normal, text_color=color.black)
table.cell(tbis, 1, 1, str.tostring(diff[0]), text_color=color.white, text_size=size.normal, bgcolor=(diff[0] <= 0 ? color.red: diff[0] >= 2.6 ? color.lime : color.black))
table.cell(tbis, 1, 2, str.tostring(diff10_3[0]), text_color=color.white, text_size=size.normal, bgcolor= (diff10_3[0] <= 0 ? color.red: diff10_3[0] >= 2.6 ? color.lime : color.black))
table.cell(tbis, 1, 3, str.tostring(diff10_5[0]), text_color=color.white, text_size=size.normal, bgcolor= (diff10_5[0] <= 0 ? color.red: diff10_5[0] >= 2.6 ? color.lime : color.black))
table.cell(tbis, 1, 4, str.tostring(diff30_2[0]), text_color=color.white, text_size=size.normal, bgcolor= (diff30_2[0] <= 0 ? color.red: diff30_2[0] >= 2.6 ? color.lime : color.black))
table.cell(tbis, 1, 5, str.tostring(diff30_5[0]), text_color=color.white, text_size=size.normal, bgcolor= (diff30_5[0] <= 0 ? color.red: diff30_5[0] >= 2.6 ? color.lime : color.black))
fill(lband, uband, color=color.rgb(126, 87, 194, 90), title="Background")
plot(diff, title="10Y-2Y", color=color.new(#fff407, 0))
plot(diff10_3, title="10Y-3Y", color=color.new(#0765ff, 0), display=display.none)
plot(diff10_5, title="10Y-5Y", color=color.new(#34ff07, 0), display=display.none)
plot(diff30_2, title="30Y-2Y", color=color.new(#07f4ff, 0), display=display.none)
plot(diff30_5, title="30Y-5Y", color=color.new(#ff6807, 0), display=display.none) |
Rainbow Oscillator | https://www.tradingview.com/script/vWEFMXGf-Rainbow-Oscillator/ | businessduck | https://www.tradingview.com/u/businessduck/ | 180 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © businessduck
//@version=5
indicator("Rainbow Oscillator")
bool trendFilter = input.bool(true, 'Use trend filter')
bool useLSRatio = input.bool(false, 'Use long/hort instead of ticker price')
string long = input.symbol ('BITFINEX:BTCUSDLONGS', 'Margined Long Symbol')
string short = input.symbol ('BITFINEX:BTCUSDSHORTS', 'Margined Short Symbol')
float w1 = input.float(0.33, 'RSI Weight', 0, 1, 0.01)
float w2 = input.float(0.33, 'CCI Weight', 0, 1, 0.01)
float w3 = input.float(0.33, 'Stoch Weight', 0, 1, 0.01)
int fastPeriod = input.int(16, 'Ocillograph Fast Period', 4, 60, 1)
int slowPeriod = input.int(22, 'Ocillograph Slow Period', 4, 60, 1)
int oscillographSamplePeriod = input.int(8, 'Oscillograph Samples Period', 1, 30, 1)
int oscillographSamplesCount = input.int(2, 'Oscillograph Samples Count', 0, 4, 1)
string oscillographMAType = input.string("RMA", "Oscillograph Samples Type", options = ["EMA", "SMA", "RMA", "WMA"])
int levelPeriod = input.int(26, 'Level Period', 2, 100)
int levelOffset = input.int(0, 'Level Offset', 0, 200, 10)
float redunant = input.float(0.5, 'Level Redunant', 0, 1, 0.01)
int levelSampleCount = input.int(2, 'Level Smooth Samples', 0, 4, 1)
string levelType = input.string("RMA", "Level MA type", options = ["EMA", "SMA", "RMA", "WMA"])
[longsHigh, longsLow, longsClose] = request.security(long, timeframe.period, [high, low, close])
[shortsHigh, shortsLow, shortsClose] = request.security(short, timeframe.period, [high, low, close])
lsRatioClose = longsClose / shortsClose
lsRatioHigh = longsHigh / shortsHigh
lsRatioLow = longsLow / shortsLow
perc(current, prev) => ((current - prev) / prev) * 100
smooth(value, type, period) =>
float ma = switch type
"EMA" => ta.ema(value, period)
"SMA" => ta.sma(value, period)
"RMA" => ta.rma(value, period)
"WMA" => ta.wma(value, period)
=>
runtime.error("No matching MA type found.")
float(na)
getSample(value, samples, type, period) =>
float ma = switch samples
0 => value
1 => smooth(value, type, period)
2 => smooth(smooth(value, type, period), type, period)
3 => smooth(smooth(smooth(value, type, period), type, period), type, period)
4 => smooth(smooth(smooth(smooth(value, type, period), type, period), type, period), type, period)
float sourceClose = useLSRatio ? lsRatioClose : close
float sourceHigh = useLSRatio ? lsRatioHigh : high
float sourceLow = useLSRatio ? lsRatioLow : low
float takeProfit = input.float(7.5, "% Take profit", 0.8, 100, step = 0.1)
float stopLoss = input.float(3.5, "% Stop Loss", 0.8, 100, step = 0.1)
float magicFast = w2 * ta.cci(sourceClose, fastPeriod) + w1 * (ta.rsi(sourceClose, fastPeriod) - 50) + w3 * (ta.stoch(sourceClose, sourceHigh, sourceLow, fastPeriod) - 50)
float magicSlow = w2 * ta.cci(sourceClose, slowPeriod) + w1 * (ta.rsi(sourceClose, slowPeriod) - 50) + w3 * (ta.stoch(sourceClose, sourceHigh, sourceLow, slowPeriod) - 50)
float sampledMagicFast = getSample(magicFast, oscillographSamplesCount, oscillographMAType, oscillographSamplePeriod)
float sampledMagicSlow = getSample(magicSlow, oscillographSamplesCount, oscillographMAType, oscillographSamplePeriod)
float lastUpperValue = 0
float lastLowerValue = 0
if (magicFast > 0)
lastUpperValue := math.max(magicFast, magicFast[1])
else
lastUpperValue := math.max(0, lastUpperValue[1]) * redunant
if (magicFast <= 0)
lastLowerValue := math.min(magicFast, magicFast[1])
else
lastLowerValue := math.min(0, lastLowerValue[1]) * redunant
float level1up = getSample( (magicFast >= 0 ? magicFast : lastUpperValue) / 4, levelSampleCount, levelType, levelPeriod) + levelOffset
float level2up = getSample( (magicFast >= 0 ? magicFast : lastUpperValue) / 2, levelSampleCount, levelType, levelPeriod) + levelOffset
float level3up = getSample( magicFast >= 0 ? magicFast : lastUpperValue, levelSampleCount, levelType, levelPeriod) + levelOffset
float level4up = getSample( (magicFast >= 0 ? magicFast : lastUpperValue) * 2, levelSampleCount, levelType, levelPeriod) + levelOffset
float level1low = getSample( (magicFast <= 0 ? magicFast : lastLowerValue) / 4, levelSampleCount, levelType, levelPeriod) - levelOffset
float level2low = getSample( (magicFast <= 0 ? magicFast : lastLowerValue) / 2, levelSampleCount, levelType, levelPeriod) - levelOffset
float level3low = getSample( magicFast <= 0 ? magicFast : lastLowerValue, levelSampleCount, levelType, levelPeriod) - levelOffset
float level4low = getSample( (magicFast <= 0 ? magicFast : lastLowerValue) * 2, levelSampleCount, levelType, levelPeriod) - levelOffset
var transparent = color.new(color.white, 100)
var overbough4Color = color.new(color.red, 75)
var overbough3Color = color.new(color.orange, 75)
var overbough2Color = color.new(color.yellow, 75)
var oversold4Color = color.new(color.teal, 75)
var oversold3Color = color.new(color.blue, 75)
var oversold2Color = color.new(color.aqua, 85)
upperPlotId1 = plot(level1up, 'Upper1', transparent)
upperPlotId2 = plot(level2up, 'Upper2', transparent)
upperPlotId3 = plot(level3up, 'Upper3', transparent)
upperPlotId4 = plot(level4up, 'Upper4', transparent)
fastColor = color.new(color.teal, 60)
slowColor = color.new(color.red, 60)
fastPlotId = plot(sampledMagicFast, 'fast', color = fastColor)
slowPlotId = plot(sampledMagicSlow, 'slow', color = slowColor)
lowerPlotId1 = plot(level1low, 'Lower1', transparent)
lowerPlotId2 = plot(level2low, 'Lower2', transparent)
lowerPlotId3 = plot(level3low, 'Lower3', transparent)
lowerPlotId4 = plot(level4low, 'Lower4', transparent)
fill(upperPlotId4, upperPlotId3, overbough4Color)
fill(upperPlotId3, upperPlotId2, overbough3Color)
fill(upperPlotId2, upperPlotId1, overbough2Color)
fill(lowerPlotId4, lowerPlotId3, oversold4Color)
fill(lowerPlotId3, lowerPlotId2, oversold3Color)
fill(lowerPlotId2, lowerPlotId1, oversold2Color)
upTrend = sampledMagicFast > sampledMagicFast[1]
buySignal = ((upTrend or not trendFilter) and ta.crossunder(sampledMagicSlow, sampledMagicFast)) ? sampledMagicSlow : na
sellSignal = ((not upTrend or not trendFilter) and ta.crossover(sampledMagicSlow, sampledMagicFast)) ? sampledMagicSlow : na
diff = sampledMagicSlow - sampledMagicFast
fill(fastPlotId, slowPlotId, upTrend ? fastColor : slowColor)
plot(buySignal, color = color.aqua, style = plot.style_circles, linewidth = 4)
plot(sellSignal, color = color.red, style = plot.style_circles, linewidth = 4)
alertcondition(buySignal, title='Buy', message='RBow: Buy')
alertcondition(sellSignal, title='Sell', message='RBow: Sell')
alertcondition(upTrend != upTrend[1], title='Trend Change', message='RBow: Trend changed')
|
Rolling VWAP | https://www.tradingview.com/script/ZU2UUu9T-Rolling-VWAP/ | TradingView | https://www.tradingview.com/u/TradingView/ | 2,955 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradingView
//@version=5
indicator("Rolling VWAP", "RVWAP", true)
// Rolling VWAP
// v3, 2022.07.24
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
import PineCoders/ConditionalAverages/1 as pc
// ———————————————————— Constants and Inputs {
// ————— Constants
int MS_IN_MIN = 60 * 1000
int MS_IN_HOUR = MS_IN_MIN * 60
int MS_IN_DAY = MS_IN_HOUR * 24
string TT_SRC = "The source used to calculate the VWAP. The default is the average of the high, low and close prices."
string TT_WINDOW = "By default, the time period used to calculate the RVWAP automatically adjusts with the chart's timeframe.
Check this to use a fixed-size time period instead, which you define with the following three values."
string TT_MINBARS = "The minimum number of last values to keep in the moving window, even if these values are outside the time period.
This avoids situations where a large time gap between two bars would cause the time window to be empty."
string TT_STDEV = "The multiplier for the standard deviation bands offset above and below the RVWAP. Example: 1.0 is 100% of the offset value.
\n\nNOTE: A value of 0.0 will hide the bands."
string TT_TABLE = "Displays the time period of the rolling window."
// ————— Inputs
float srcInput = input.source(hlc3, "Source", tooltip = TT_SRC)
string GRP2 = '═══════════ Time Period ═══════════'
bool fixedTfInput = input.bool(false, "Use a fixed time period", group = GRP2, tooltip = TT_WINDOW)
int daysInput = input.int(1, "Days", group = GRP2, minval = 0, maxval = 90) * MS_IN_DAY
int hoursInput = input.int(0, "Hours", group = GRP2, minval = 0, maxval = 23) * MS_IN_HOUR
int minsInput = input.int(0, "Minutes", group = GRP2, minval = 0, maxval = 59) * MS_IN_MIN
bool showInfoBoxInput = input.bool(true, "Show time period", group = GRP2)
string infoBoxSizeInput = input.string("small", "Size ", inline = "21", group = GRP2, options = ["tiny", "small", "normal", "large", "huge", "auto"])
string infoBoxYPosInput = input.string("bottom", "↕", inline = "21", group = GRP2, options = ["top", "middle", "bottom"])
string infoBoxXPosInput = input.string("left", "↔", inline = "21", group = GRP2, options = ["left", "center", "right"])
color infoBoxColorInput = input.color(color.gray, "", inline = "21", group = GRP2)
color infoBoxTxtColorInput = input.color(color.white, "T", inline = "21", group = GRP2)
string GRP3 = '═════════ Deviation Bands ═════════'
float stdevMult1 = input.float(0.0, "Bands Multiplier 1", group = GRP3, inline = "31", minval = 0.0, step = 0.5, tooltip = TT_STDEV)
float stdevMult2 = input.float(0.0, "Bands Multiplier 2", group = GRP3, inline = "32", minval = 0.0, step = 0.5, tooltip = TT_STDEV)
float stdevMult3 = input.float(0.0, "Bands Multiplier 3", group = GRP3, inline = "33", minval = 0.0, step = 0.5, tooltip = TT_STDEV)
color stdevColor1 = input.color(color.green, "", group = GRP3, inline = "31")
color stdevColor2 = input.color(color.yellow, "", group = GRP3, inline = "32")
color stdevColor3 = input.color(color.red, "", group = GRP3, inline = "33")
string GRP4 = '════════ Minimum Window Size ════════'
int minBarsInput = input.int(10, "Bars", group = GRP4, tooltip = TT_MINBARS)
// }
// ———————————————————— Functions {
// @function Determines a time period from the chart's timeframe.
// @returns (int) A value of time in milliseconds that is appropriate for the current chart timeframe. To be used in the RVWAP calculation.
timeStep() =>
int tfInMs = timeframe.in_seconds() * 1000
float step =
switch
tfInMs <= MS_IN_MIN => MS_IN_HOUR
tfInMs <= MS_IN_MIN * 5 => MS_IN_HOUR * 4
tfInMs <= MS_IN_HOUR => MS_IN_DAY * 1
tfInMs <= MS_IN_HOUR * 4 => MS_IN_DAY * 3
tfInMs <= MS_IN_HOUR * 12 => MS_IN_DAY * 7
tfInMs <= MS_IN_DAY => MS_IN_DAY * 30.4375
tfInMs <= MS_IN_DAY * 7 => MS_IN_DAY * 90
=> MS_IN_DAY * 365
int result = int(step)
// @function Produces a string corresponding to the input time in days, hours, and minutes.
// @param (series int) A time value in milliseconds to be converted to a string variable.
// @returns (string) A string variable reflecting the amount of time from the input time.
tfString(int timeInMs) =>
int s = timeInMs / 1000
int m = s / 60
int h = m / 60
int tm = math.floor(m % 60)
int th = math.floor(h % 24)
int d = math.floor(h / 24)
string result =
switch
d == 30 and th == 10 and tm == 30 => "1M"
d == 7 and th == 0 and tm == 0 => "1W"
=>
string dStr = d ? str.tostring(d) + "D " : ""
string hStr = th ? str.tostring(th) + "H " : ""
string mStr = tm ? str.tostring(tm) + "min" : ""
dStr + hStr + mStr
// }
// ———————————————————— Calculations and Plots {
// Stop the indicator on charts with no volume.
if barstate.islast and ta.cum(nz(volume)) == 0
runtime.error("No volume is provided by the data vendor.")
// RVWAP + stdev bands
int timeInMs = fixedTfInput ? minsInput + hoursInput + daysInput : timeStep()
float sumSrcVol = pc.totalForTimeWhen(srcInput * volume, timeInMs, true, minBarsInput)
float sumVol = pc.totalForTimeWhen(volume, timeInMs, true, minBarsInput)
float sumSrcSrcVol = pc.totalForTimeWhen(volume * math.pow(srcInput, 2), timeInMs, true, minBarsInput)
float rollingVWAP = sumSrcVol / sumVol
float variance = sumSrcSrcVol / sumVol - math.pow(rollingVWAP, 2)
variance := math.max(0, variance)
float stDev = math.sqrt(variance)
float upperBand1 = rollingVWAP + stDev * stdevMult1
float lowerBand1 = rollingVWAP - stDev * stdevMult1
float upperBand2 = rollingVWAP + stDev * stdevMult2
float lowerBand2 = rollingVWAP - stDev * stdevMult2
float upperBand3 = rollingVWAP + stDev * stdevMult3
float lowerBand3 = rollingVWAP - stDev * stdevMult3
plot(rollingVWAP, "Rolling VWAP", color.orange)
p1 = plot(stdevMult1 != 0 ? upperBand1 : na, "Upper Band 1", stdevColor1)
p2 = plot(stdevMult1 != 0 ? lowerBand1 : na, "Lower Band 1", stdevColor1)
p3 = plot(stdevMult2 != 0 ? upperBand2 : na, "Upper Band 2", stdevColor2)
p4 = plot(stdevMult2 != 0 ? lowerBand2 : na, "Lower Band 2", stdevColor2)
p5 = plot(stdevMult3 != 0 ? upperBand3 : na, "Upper Band 3", stdevColor3)
p6 = plot(stdevMult3 != 0 ? lowerBand3 : na, "Lower Band 3", stdevColor3)
fill(p1, p2, color.new(color.green, 95), "Bands Fill")
fill(p3, p4, color.new(color.green, 95), "Bands Fill")
fill(p5, p6, color.new(color.green, 95), "Bands Fill")
// Display of time period.
var table tfDisplay = table.new(infoBoxYPosInput + "_" + infoBoxXPosInput, 1, 1)
if showInfoBoxInput and barstate.islastconfirmedhistory
table.cell(tfDisplay, 0, 0, tfString(timeInMs), bgcolor = infoBoxColorInput, text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput)
// } |
High Volume Bars | https://www.tradingview.com/script/ElfsaJiR-High-Volume-Bars/ | crypto_rife | https://www.tradingview.com/u/crypto_rife/ | 306 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © crypto_rife
//@version=5
indicator("High Volume Bars", overlay=true)
length = input(200, title="Loopback")
mult = input(1.0, title="Multiplier")
upColor = color.white
dnColor = color.black
upHighVolColor = color.blue
dnHighVolColor = color.red
volumeStDev = ta.stdev(volume, length)
var bg = dnColor
highVol = volume - volume[1] > volumeStDev*mult
if (close > open)
bg := highVol ? upHighVolColor : upColor
if (close < open)
bg := highVol ? dnHighVolColor : dnColor
barcolor(bg) |
RSI by zdmre | https://www.tradingview.com/script/sAM0DYGR-RSI-by-zdmre/ | zdmre | https://www.tradingview.com/u/zdmre/ | 85 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © zdmre
//@version=5
indicator("RSI by zdmre", overlay=false)
len = input.int(14, minval=1, title='Length')
src = input(close, 'Source')
up = ta.rma(math.max(ta.change(src), 0), len)
down = ta.rma(-math.min(ta.change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
plot(rsi, 'RSI', color=color.new(#7E57C2, 0))
band1 = hline(70, "Upper Band", color=#787B86)
bandm = hline(50, "Middle Band", color=color.new(#787B86, 50))
band0 = hline(30, "Lower Band", color=#787B86)
fill(band1, band0, color=color.rgb(126, 87, 194, 90), title="Background")
ob= ta.cross(rsi, 70) == 1 and rsi >= 70
os = ta.cross(rsi, 30) == 1 and rsi <= 30
plot(ob ? rsi : na ,title='Overbought', style=plot.style_circles, color=color.new(color.red, 0), linewidth=5)
plot(os ? rsi : na ,title='Oversold ', style=plot.style_circles, color=color.new(color.green, 0), linewidth=5)
if ob
label1 = label.new(bar_index, rsi , text=str.format("{0,date, y\nMMM-d\n}", time)+'|', style=label.style_label_down, color=color.new(color.red,100))
label.set_size(label1, size.small)
label.set_textcolor(label1, color.red)
if os
label2 = label.new(bar_index, rsi , text='|\n'+ str.format("{0,date, y\nMMM-d}", time), style=label.style_label_up, color=color.new(color.green,100))
label.set_size(label2, size.small)
label.set_textcolor(label2, color.green) |
Money Maykah -- DC-ATR , Stochastic RSI signals v.1-89 -- | https://www.tradingview.com/script/NZ5a0Fzx-Money-Maykah-DC-ATR-Stochastic-RSI-signals-v-1-89/ | mrchiller505 | https://www.tradingview.com/u/mrchiller505/ | 60 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mrchiller505
//@version=5
indicator("DC Stoch-RSI signal v.1-89", overlay = true)
// ---- Stoch RSI -----
var int smoothK = 3
var int smoothD = 3
lengthRSI = input.int(title='RSI Length',defval=21,minval=2)
lengthStoch = input.int(title='Stoch Length',defval=21,minval=2)
src_SRSI = close
rsi1 = ta.rsi(src_SRSI, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK) // ploted as blue line
d = ta.sma(k, smoothD) // ploted at orange line
// ---- DC ----
DClen = input.int(20, minval=1)
lower = ta.lowest(DClen)
upper = ta.highest(DClen)
ATR_factor = input.float(0.5, minval=0.1)
ATR_length = input.int(14, minval=1)
ATR_sma_length = input.int(10, minval=1)
LLATR = lower - ta.sma(ATR_factor*ta.atr(ATR_length),ATR_sma_length)
LHATR = lower + ta.sma(ATR_factor*ta.atr(ATR_length),ATR_sma_length)
HHATR = upper + ta.sma(ATR_factor*ta.atr(ATR_length),ATR_sma_length)
HLATR = upper - ta.sma(ATR_factor*ta.atr(ATR_length),ATR_sma_length)
basis = math.avg(upper, lower)
plot(basis, "Basis", color=#f19f7e)
u = plot(upper, "Upper", color=#7ed3f1)
plot(HHATR, "HH ATR", color=#c32ad0)
plot(HLATR, "HL ATR", color=#c32ad0)
l = plot(lower, "Lower", color=#7ed3f1)
plot(LLATR, "LL ATR", color=#c32ad0)
plot(LHATR, "LH ATR", color=#c32ad0)
fill(u, l, color=color.rgb(33, 150, 243, 95), title="Background")
// ---- Boolean check signals ----
sell_signal = input.int(title='Sell limit',defval=80,minval=50)
buy_signal = input.int(title='Buy limit',defval=20,maxval=50)
top_boolA = (d > sell_signal) and d>k and (hl2 > basis)
ttop_boolA = ta.crossunder(d,sell_signal) and (hl2 > basis)
btop_boolA = (d < buy_signal) and (hl2 > basis)
above_HL = high > HLATR
below_LH = low < LHATR
plotshape(top_boolA,title='d>sell,candle>basis',style=shape.triangleup, location=location.abovebar, color=above_HL?#ff4500:color.orange, size = size.tiny)
plotshape(ttop_boolA,title='crossunder',style=shape.xcross, location=location.abovebar, color=#eb9694 , size = size.tiny)
plotshape(btop_boolA,title='d<buy,candle>basis',style=shape.triangledown, location=location.belowbar, color=#eb8d68, size = size.tiny)
btm_boolA = (d < buy_signal) and d<k and (hl2 < basis)
bbtm_boolA = ta.crossover(d,buy_signal) and (hl2 < basis)
tbtm_boolA = (d > sell_signal) and (hl2 < basis)
plotshape(btm_boolA,title='d<buy,candle<basis',style=shape.triangledown, location=location.belowbar, color=below_LH?#6268e7:#7dbfe3, size = size.tiny)
plotshape(bbtm_boolA,title='crossover',style=shape.xcross, location=location.belowbar, color=#8ed1fc, size = size.tiny)
plotshape(tbtm_boolA,title='d>sell,candle<basis',style=shape.triangleup, location=location.abovebar, color=#bc68eb, size = size.tiny)
|
Adaptive Average Vortex Index [lastguru] | https://www.tradingview.com/script/UMb5cjVk-Adaptive-Average-Vortex-Index-lastguru/ | lastguru | https://www.tradingview.com/u/lastguru/ | 33 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © lastguru
//@version=5
indicator("Adaptive Average Vortex Index by lastguru", "AAVX [lastguru]", precision=2)
import lastguru/CommonFilters/1 as cf
import lastguru/NormalizedOscillators/2 as co
import lastguru/LengthAdaptation/1 as la
import lastguru/DominantCycle/1 as dc
// Internal smoothing algorithm selection
_smooth(type, src, len, default) =>
cf.doMA(type == "Default" or type == "Fast Default" ? default : type, src, type == "Fast Default" ? math.round(len/2) :len)
_avx(len, smooth) =>
default = "RMA"
plusVM = math.sum(math.abs( high - low[1]), len)
minusVM = math.sum(math.abs( low - high[1]), len)
str = math.sum(ta.tr, len)
plus = plusVM / str
minus = minusVM / str
sum = plus + minus
adx = _smooth(smooth, math.abs(plus - minus) / (sum == 0 ? 1 : sum), len, default)
[4 * adx - 1, plus - 1, minus - 1]
////////////
// Inputs //
////////////
src = input(close, title="Source")
Dynamic = input.string(title="Adaptation", options=["None", "VIDYA", "VIDYA-RS", "Kaufman Efficiency Scaling", "Fractal Adaptation", "MESA MAMA Cycle", "Pearson Autocorrelation", "DFT Cycle", "Phase Accumulation"], defval="None", inline="30")
DynamicHP = input.bool(true, "HP", inline="30")
DynamicSS = input.bool(true, "SS", inline="30")
DynamicHW = input.bool(false, "HW", inline="30")
DynamicLow = input.int(title="Bound From", defval=8, inline="31")
DynamicHigh = input.int(title="To", defval=50, inline="31")
OscWindow = input.string(title="Window", options=["Default", "Fast Default", "SMA", "Triangle Window", "Hamming Window", "Hann Window"], defval="Fast Default", group="Average Vortex Index")
OscLength = input.int(title="Length", defval=14, inline="11", group="Average Vortex Index")
OscCycle = input.float(title="Cycle", defval=0.5, step=0.1, inline="11", group="Average Vortex Index")
OutMAType = input.string(title='Filter/MA', options=["None", "SMA", "RMA", "EMA", "HMA", "VWMA", "2-pole Super Smoother", "3-pole Super Smoother", "Filt11", "Triangle Window", "Hamming Window", "Hann Window", "Lowpass", "DSSS"], defval="None", inline="12", group="Average Vortex Index")
OutMALength = input.float(title="Length", defval=9, inline="12", group="Average Vortex Index")
PostType = input.string(title='Postfilter', options=["None", "Stochastic", "Super Smooth Stochastic", "Inverse Fisher Transform", "Noise Elimination Technology", "Momentum"], defval="None", inline="13", group="Average Vortex Index")
PostLength = input.int(title="Length", defval=0, inline="13", group="Average Vortex Index")
////////////////////
// Dynamic Length //
////////////////////
dynLength = 0
dynLengthRaw = 0.0
dynLengthLim = 0.0
switch Dynamic
"None" =>
dynLength := OscLength
"Pearson Autocorrelation" =>
nl = dc.paPeriod(src, DynamicLow, DynamicHigh, DynamicHP, DynamicSS, DynamicHW)
dynLengthRaw := nl
dynLengthLim := math.max(math.min(nl, DynamicHigh), DynamicLow)
dynLength := math.round(dynLengthLim * OscCycle)
"DFT Cycle" =>
nl = dc.dftPeriod(src, DynamicLow, DynamicHigh, DynamicHP, DynamicSS, DynamicHW)
dynLengthRaw := nl
dynLengthLim := math.max(math.min(nl, DynamicHigh), DynamicLow)
dynLength := math.round(dynLengthLim * OscCycle)
"Phase Accumulation" =>
nl = dc.phasePeriod(src, DynamicLow, DynamicHigh, DynamicHP, DynamicSS, DynamicHW)
dynLengthRaw := nl
dynLengthLim := math.max(math.min(nl, DynamicHigh), DynamicLow)
dynLength := math.round(dynLengthLim * OscCycle)
=>
nl = dc.doAdapt(Dynamic, src, OscLength, DynamicLow, DynamicHigh)
dynLengthRaw := nl
dynLengthLim := math.max(math.min(nl, DynamicHigh), DynamicLow)
dynLength := math.round(dynLengthLim * OscCycle)
plotchar(dynLengthRaw, "Raw calculated length", "", location.top)
plotchar(dynLength, "Calculated length", "", location.top)
/////////////////
// Oscillators //
/////////////////
[osc, plus, minus] = _avx(math.max(dynLength, 1), OscWindow)
malen = OutMALength < 2 ? math.round(math.max(dynLength, 1) * OutMALength) : math.round(OutMALength)
float newosc = la.doMA(OutMAType, osc, malen)
float signal = co.doPostfilter(PostType, newosc, PostLength == 0 ? math.max(dynLength, 1) : PostLength)
//////////////
// Plotting //
//////////////
plot(osc, "Without smoothing", color.gray)
plot(signal, "Oscillator", color.white)
plot(plus, title="VI +", color=#2442BF)
plot(minus, title="VI -", color=#991643)
hline(0.0, "Zero", color.gray)
uBand = hline(0.6, "80%", color.gray)
lBand = hline(-0.6, "20%", color.gray)
fill(uBand, lBand, color=color.rgb(126, 87, 194, 90), title="Background Fill")
hline(1.0, "Upper", color.gray)
hline(-1.0, "Lower", color.gray) |
Inflation Rate of Change | https://www.tradingview.com/script/K4xgMDmp-Inflation-Rate-of-Change/ | TradeAutomation | https://www.tradingview.com/u/TradeAutomation/ | 39 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version = 5
// Author = TradeAutomation
indicator("Inflation Rate of Change", shorttitle="CPI Inflation ROC", overlay=false)
//Selects Consumer Price Index Data Source
CPISourceInput = input.string(title="Data Source", defval="All Items", options=["All Items", "Food", "Housing", "Energy", "Medical", "Apparel"])
//Maps Selection to Data Source
CPISource = CPISourceInput== "All Items" ? "FRED:CPIAUCSL" : CPISourceInput== "Food" ? "FRED:CPIUFDNS" : CPISourceInput== "Housing" ? "FRED:CPIHOSNS" : CPISourceInput== "Energy" ? "FRED:CPIENGSL" : CPISourceInput== "Medical" ? "FRED:CPIMEDSL" : CPISourceInput== "Apparel" ? "FRED:CPIAPPSL" : "All Items"
//Pulls in Consumer Price Index Data
CPI = request.security(CPISource, "D", close)
ROCBarsBack = input.int(253, "Comparing to CPI # of Bars Back", tooltip = "To compare CPI change year over year, you would put 253 here if on any typical market DAY chart, or 12 if on a MONTH chart.")
CPIROC = 100*(CPI-CPI[ROCBarsBack])/CPI
//Plots
plot(CPIROC, color = color.red)
|
MTF Pivots Zones [tanayroy] | https://www.tradingview.com/script/TxuQrsK6-MTF-Pivots-Zones-tanayroy/ | tanayroy | https://www.tradingview.com/u/tanayroy/ | 166 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tanayroy
//@version=5
indicator("MTF Pivots Zones [tanayroy]",shorttitle='MTF Pivots', overlay=true)
// Array to store pivots levels
dPivot = array.new_float(13)
wPivot = array.new_float(13)
mPivot = array.new_float(13)
qPivot = array.new_float(13)
yPivot = array.new_float(13)
// Array to store Pivot Name
dPivotName = array.new_string(13)
wPivotName = array.new_string(13)
mPivotName = array.new_string(13)
qPivotName = array.new_string(13)
yPivotName = array.new_string(13)
// Array to store display option
dPivotDisplay = array.new_bool(13)
wPivotDisplay = array.new_bool(13)
mPivotDisplay = array.new_bool(13)
qPivotDisplay = array.new_bool(13)
yPivotDisplay = array.new_bool(13)
// Function to calculate pivot
CalculatePivot(_o,dailyHigh,dailyLow,dailyClose)=>
pivot = (dailyHigh+dailyLow+dailyClose)/3
abc = (dailyHigh+dailyLow)/2
atc = (pivot-abc)+pivot
tc = abc>=atc?abc:atc
bc = abc>=atc?atc:abc
r1 = (2*pivot)-dailyLow
r2 = pivot+(dailyHigh-dailyLow)
r3 = r1+(dailyHigh-dailyLow)
r4 = r3+(r2-r1)
s1 = (2*pivot)-dailyHigh
s2 = pivot-(dailyHigh-dailyLow)
s3 = s1-(dailyHigh-dailyLow)
s4 = s3-(s1-s2)
[s1,s2,s3,s4,bc,pivot,tc,r1,r2,r3,r4,dailyHigh,dailyLow]
// Inputs
higherTF = input.timeframe ("12M", title='Your Choice for Pivot',tooltip="This will replace yearly pivot")
inputMultiplyer = input.float(0.5,'ATR Multiplyer', minval=0.01)
//MTF pivots
[s1,s2,s3,s4,bc,pivot,tc,r1,r2,r3,r4,dH,dL] = request.security(syminfo.tickerid, 'D', CalculatePivot(open[1],high[1],low[1],close[1]), lookahead=barmerge.lookahead_on)
[ws1,ws2,ws3,ws4,wbc,wvpivot,wtc,wr1,wr2,wr3,wr4,wH,wL] = request.security(syminfo.tickerid, 'W', CalculatePivot(open[1],high[1],low[1],close[1]), lookahead=barmerge.lookahead_on)
[ms1,ms2,ms3,ms4,mbc,mvpivot,mtc,mr1,mr2,mr3,mr4,mH,mL] = request.security(syminfo.tickerid, '1M', CalculatePivot(open[1],high[1],low[1],close[1]), lookahead=barmerge.lookahead_on)
[qs1,qs2,qs3,qs4,qbc,qvpivot,qtc,qr1,qr2,qr3,qr4,qH,qL] = request.security(syminfo.tickerid, '3M', CalculatePivot(open[1],high[1],low[1],close[1]), lookahead=barmerge.lookahead_on)
[ys1,ys2,ys3,ys4,ybc,yvpivot,ytc,yr1,yr2,yr3,yr4,yH,yL] = request.security(syminfo.tickerid, higherTF, CalculatePivot(open[1],high[1],low[1],close[1]), lookahead=barmerge.lookahead_on)
//Daily ATR
atr14 = request.security(syminfo.tickerid, 'D', ta.atr(14), lookahead=barmerge.lookahead_on)
//Display levels
displayOptionHigh = close+atr14*inputMultiplyer
displayOptionLow = close-atr14*inputMultiplyer
//Function to insert array
insertInArray(arrayName,arrayPlaceName,arrayDisplay,s1,s2,s3,s4,bc,pivot,tc,r1,r2,r3,r4,h,l)=>
array.set(arrayName,0,s1)
array.set(arrayPlaceName,0,'S1')
if displayOptionHigh>=s1 and s1>=displayOptionLow
array.set(arrayDisplay,0,true)
else
array.set(arrayDisplay,0,false)
array.set(arrayName,1,s2)
array.set(arrayPlaceName,1,'S2')
if displayOptionHigh>=s2 and s2>=displayOptionLow
array.set(arrayDisplay,1,true)
else
array.set(arrayDisplay,1,false)
array.set(arrayName,2,s3)
array.set(arrayPlaceName,2,'S3')
if displayOptionHigh>=s3 and s3>=displayOptionLow
array.set(arrayDisplay,2,true)
else
array.set(arrayDisplay,2,false)
array.set(arrayName,3,s4)
array.set(arrayPlaceName,3,'S4')
if displayOptionHigh>=s4 and s4>=displayOptionLow
array.set(arrayDisplay,3,true)
else
array.set(arrayDisplay,3,false)
array.set(arrayName,4,bc)
array.set(arrayPlaceName,4,'BC')
if displayOptionHigh>=bc and bc>=displayOptionLow
array.set(arrayDisplay,4,true)
else
array.set(arrayDisplay,4,false)
array.set(arrayName,5,pivot)
array.set(arrayPlaceName,5,'P')
if displayOptionHigh>=pivot and pivot>=displayOptionLow
array.set(arrayDisplay,5,true)
else
array.set(arrayDisplay,5,false)
array.set(arrayName,6,tc)
array.set(arrayPlaceName,6,'TC')
if displayOptionHigh>=tc and tc>=displayOptionLow
array.set(arrayDisplay,6,true)
else
array.set(arrayDisplay,6,false)
array.set(arrayName,7,r1)
array.set(arrayPlaceName,7,'R1')
if displayOptionHigh>=r1 and r1>=displayOptionLow
array.set(arrayDisplay,7,true)
else
array.set(arrayDisplay,7,false)
array.set(arrayName,8,r2)
array.set(arrayPlaceName,8,'R2')
if displayOptionHigh>=r2 and r2>=displayOptionLow
array.set(arrayDisplay,8,true)
else
array.set(arrayDisplay,8,false)
array.set(arrayName,9,r3)
array.set(arrayPlaceName,9,'R3')
if displayOptionHigh>=r3 and r3>=displayOptionLow
array.set(arrayDisplay,9,true)
else
array.set(arrayDisplay,9,false)
array.set(arrayName,10,r4)
array.set(arrayPlaceName,10,'R4')
if displayOptionHigh>=r4 and r4>=displayOptionLow
array.set(arrayDisplay,10,true)
else
array.set(arrayDisplay,10,false)
array.set(arrayName,11,h)
array.set(arrayPlaceName,11,'H')
if displayOptionHigh>=h and h>=displayOptionLow
array.set(arrayDisplay,11,true)
else
array.set(arrayDisplay,11,false)
array.set(arrayName,12,l)
array.set(arrayPlaceName,12,'L')
if displayOptionHigh>=l and l>=displayOptionLow
array.set(arrayDisplay,12,true)
else
array.set(arrayDisplay,12,false)
insertInArray(dPivot,dPivotName,dPivotDisplay,s1,s2,s3,s4,bc,pivot,tc,r1,r2,r3,r4,dH,dL)
insertInArray(wPivot,wPivotName,wPivotDisplay,ws1,ws2,ws3,ws4,wbc,wvpivot,wtc,wr1,wr2,wr3,wr4,wH,wL)
insertInArray(mPivot,mPivotName,mPivotDisplay,ms1,ms2,ms3,ms4,mbc,mvpivot,mtc,mr1,mr2,mr3,mr4,mH,mL)
insertInArray(qPivot,qPivotName,qPivotDisplay,qs1,qs2,qs3,qs4,qbc,qvpivot,qtc,qr1,qr2,qr3,qr4,qH,qL)
insertInArray(yPivot,yPivotName,yPivotDisplay,ys1,ys2,ys3,ys4,ybc,yvpivot,ytc,yr1,yr2,yr3,yr4,yH,yL)
//Display Pivots.
isNewPeriod = ta.change(time('D'))
tickp = syminfo.mintick*10
var box pivotBox = na
var prevBarIndex = bar_index
leftBody = prevBarIndex
rightBody = barstate.islast ? bar_index : bar_index[1]
if isNewPeriod
prevBarIndex := bar_index
for a=0 to array.size(dPivot)-1
if array.get(dPivotDisplay,a)
box.new(leftBody,array.get(dPivot,a),rightBody,array.get(dPivot,a),border_color=close>array.get(dPivot,a)?color.lime:color.maroon,bgcolor=close>array.get(dPivot,a)?color.lime:color.maroon)
label.new(leftBody,array.get(dPivot,a),text='D '+array.get(dPivotName,a),style= label.style_none,textcolor=close>array.get(dPivot,a)?color.lime:color.maroon)
for a=0 to array.size(wPivot)-1
if array.get(wPivotDisplay,a)
box.new(leftBody,array.get(wPivot,a),rightBody,array.get(wPivot,a),border_color=close>array.get(wPivot,a)?color.lime:color.maroon,bgcolor=close>array.get(wPivot,a)?color.lime:color.maroon)
label.new(leftBody,array.get(wPivot,a),text='W '+array.get(wPivotName,a),style= label.style_none,textcolor=close>array.get(wPivot,a)?color.lime:color.maroon)
for a=0 to array.size(mPivot)-1
if array.get(mPivotDisplay,a)
box.new(leftBody,array.get(mPivot,a),rightBody,array.get(mPivot,a),border_color=close>array.get(mPivot,a)?color.lime:color.maroon,bgcolor=close>array.get(mPivot,a)?color.lime:color.maroon)
label.new(leftBody,array.get(mPivot,a),text='M '+array.get(mPivotName,a),style= label.style_none,textcolor=close>array.get(mPivot,a)?color.lime:color.maroon)
for a=0 to array.size(qPivot)-1
if array.get(qPivotDisplay,a)
box.new(leftBody,array.get(qPivot,a),rightBody,array.get(qPivot,a),border_color=close>array.get(qPivot,a)?color.lime:color.maroon,bgcolor=close>array.get(qPivot,a)?color.lime:color.maroon)
label.new(leftBody,array.get(qPivot,a),text='Q '+array.get(qPivotName,a),style= label.style_none,textcolor=close>array.get(qPivot,a)?color.lime:color.maroon)
for a=0 to array.size(yPivot)-1
if array.get(yPivotDisplay,a)
box.new(leftBody,array.get(yPivot,a),rightBody,array.get(yPivot,a),border_color=close>array.get(yPivot,a)?color.lime:color.maroon,bgcolor=close>array.get(yPivot,a)?color.lime:color.maroon)
label.new(leftBody,array.get(yPivot,a),text='Y '+array.get(yPivotName,a),style= label.style_none,textcolor=close>array.get(yPivot,a)?color.lime:color.maroon)
|
Bogdan Ciocoiu - Sniper Entry | https://www.tradingview.com/script/GtjP7b5B-Bogdan-Ciocoiu-Sniper-Entry/ | BogdanCiocoiu | https://www.tradingview.com/u/BogdanCiocoiu/ | 200 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BogdanCiocoiu
//@version=5
// What is Sniper Entry
// Sniper Entry is a set indicator that encapsulates a collection of pre-configured scripts using specific variables that enable users to extract signals by interpreting market behaviour quickly, suitable for 1-3min scalping. This instrument is a tool that acts as a confluence for traders to make decisions concerning current market conditions. This indicator does not apply solely to an asset.
//
// What Sniper Entry is not
// Sniper Entry is not interpreting fundamental analysis and will also not be providing out of box market signals. Instead, it will provide a collection of integrated and significantly improved open-source subscripts designed to help traders speculate on market trends. Traders must apply their strategies and configure Sniper Entry accordingly to maximise the script's output.
//
// Originality and usefulness
// The collection of subscripts encapsulated in this tool makes it unique in the Trading View ecosystem. This indicator enables traders to consider entry positions or exit positions by comparing similar algorithms at once.
//
// Its usefulness also emerges from the unique configurations embedded in the indicator's settings, which are different from those of the original scripts.
//
// This indicator's originality is also reflected in how its modules are integrated, including the integration of the settings.
//
// Open-source reuse
// I used the following open-source resources, which I simplified significantly and pre-configured for short term scalping. The source codes for the below are already in the public domain, including the following links listed below.
//
// https://www.tradingview.com/scripts/rangefilter/ (open source)
// https://www.tradingview.com/script/mS0vb7DA-DH-True-Price-DOTS-for-Heikin-Ashi/ (open source and generic algorithm)
// https://www.tradingview.com/scripts/chandelier/ (open source)
// https://www.tradingview.com/script/hg92pFwS-Hull-Suite/ (open source)
// https://www.tradingview.com/script/whJATyGU-UT-Bot/ (open source)
// https://www.tradingview.com/ideas/movingaverage/ (generic MA algorithm and open source)
// https://www.tradingview.com/script/WwiSR6vK-VWAP-Standard-Deviation/ (generic VWAP algorithm and open source)
indicator("Bogdan Ciocoiu - Sniper Entry", shorttitle="BC - Sniper Entry", format=format.price, precision=2, timeframe="", timeframe_gaps=true, explicit_plot_zorder=true, overlay=true)
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// Range filter -- inputs
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_rf_1_source = input(defval=hl2, title="RF1", inline="RF1", group="Range filters")
_rf_1_period = input(30, title="Period", inline="RF1", group="Range filters")
_rf_1_multiplier = input(2.6, title="Multiplier", inline="RF1", group="Range filters")
_rf_2_source = input(defval=ohlc4, title="RF2", inline="RF2", group="Range filters")
_rf_2_period = input(48, title="Period", inline="RF2", group="Range filters")
_rf_2_multiplier = input(3.4, title="Multiplier", inline="RF2", group="Range filters")
_rf_transparency = input(50, title="Transp", inline="RF", group="Range filters")
_rf_border = input(2, title="Width", inline="RF", group="Range filters")
_rf_show_label = input(true, "Label", inline="RF", group="Range filters")
_rf_show_shape = input(true, "Shape", inline="RF", group="Range filters")
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// Range filter -- delivery
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_rf_smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x[1]), t)
smoothrng = ta.ema(avrng, wper) * m
smoothrng
_rf_1_smrng = _rf_smoothrng(_rf_1_source, _rf_1_period, _rf_1_multiplier)
_rf_2_smrng = _rf_smoothrng(_rf_2_source, _rf_2_period, _rf_2_multiplier)
_rf_rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r :
x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
_rf_1_filt = _rf_rngfilt(_rf_1_source, _rf_1_smrng)
_rf_2_filt = _rf_rngfilt(_rf_2_source, _rf_2_smrng)
_rf_1_upward = 0.0
_rf_1_upward := _rf_1_filt > _rf_1_filt[1] ? nz(_rf_1_upward[1]) + 1 : _rf_1_filt < _rf_1_filt[1] ? 0 : nz(_rf_1_upward[1])
_rf_1_downward = 0.0
_rf_1_downward := _rf_1_filt < _rf_1_filt[1] ? nz(_rf_1_downward[1]) + 1 : _rf_1_filt > _rf_1_filt[1] ? 0 : nz(_rf_1_downward[1])
_rf_2_upward = 0.0
_rf_2_upward := _rf_2_filt > _rf_2_filt[1] ? nz(_rf_2_upward[1]) + 1 : _rf_1_filt < _rf_1_filt[1] ? 0 : nz(_rf_2_upward[1])
_rf_2_downward = 0.0
_rf_2_downward := _rf_2_filt < _rf_2_filt[1] ? nz(_rf_2_downward[1]) + 1 : _rf_1_filt > _rf_1_filt[1] ? 0 : nz(_rf_2_downward[1])
_rf_1_plot_colour = (_rf_1_upward > 0) ? color.green : (_rf_1_downward > 0) ? color.red : color.yellow
_rf_2_plot_colour = (_rf_2_upward > 0) ? color.green : (_rf_2_downward > 0) ? color.red : color.yellow
_rf_bands_colour = (_rf_1_upward > 0 and _rf_2_upward > 0) ? color.green : (_rf_1_downward > 0 and _rf_2_downward > 0) ? color.red : color.yellow
_rf_1_band_plot = plot(_rf_1_filt, color=(_rf_show_shape) ? color.new(_rf_1_plot_colour, _rf_transparency) : na, title="RF 1 line", linewidth=_rf_border)
_rf_2_band_plot = plot(_rf_2_filt, color=(_rf_show_shape) ? color.new(_rf_2_plot_colour, _rf_transparency) : na, title="RF 2 line", linewidth=_rf_border)
_rf_1_long_cond = bool(na)
_rf_1_short_cond = bool(na)
_rf_1_long_cond := _rf_1_source > _rf_1_filt and _rf_1_source > _rf_1_source[1] and _rf_1_upward > 0 or _rf_1_source > _rf_1_filt and _rf_1_source < _rf_1_source[1] and _rf_1_upward > 0
_rf_1_short_cond := _rf_1_source < _rf_1_filt and _rf_1_source < _rf_1_source[1] and _rf_1_downward > 0 or _rf_1_source < _rf_1_filt and _rf_1_source > _rf_1_source[1] and _rf_1_downward > 0
_rf_1_cond_initiate = 0
_rf_1_cond_initiate := _rf_1_long_cond ? 1 : _rf_1_short_cond ? -1 : _rf_1_cond_initiate[1]
_rf_1_long_condition = _rf_1_long_cond and _rf_1_cond_initiate[1] == -1
_rf_1_short_condition = _rf_1_short_cond and _rf_1_cond_initiate[1] == 1
plotshape(_rf_1_long_condition and _rf_show_label, title="RF 1 buy signal", text="RF", textcolor=color.white, style=shape.labelup, location=location.belowbar, color=color.green)
plotshape(_rf_1_short_condition and _rf_show_label, title="RF 1 sell signal", text="RF", textcolor=color.white, style=shape.labeldown, location=location.abovebar, color=color.red)
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// HeikinAshiDot -- inputs
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_real_close_show = input(true, "", inline="Close dot", group="Close price dot")
_real_close_source = input.source(close, title="", inline="Close dot", group="Close price dot")
_real_close_colour = input.color(color.white, title="Color", inline="Close dot", group="Close price dot")
_real_close_size = input.int(3, title="Size", inline="Close dot", group="Close price dot")
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// HeikinAshiDot -- delivery
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_real_close = ticker.new(syminfo.prefix, syminfo.ticker)
_real_close_request = request.security(_real_close, timeframe.period, _real_close_source)
plot(_real_close_request, "Close price", style=plot.style_circles, linewidth=_real_close_size, color= (_real_close_show) ? _real_close_colour : na)
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// Chandelier exit -- inputs
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_ce_show = input(true, title="", inline="CE", group="Chandelier Exit")
_ce_period = input(1, title="ATR period", inline="CE", group="Chandelier Exit")
_ce_multiplier = input(0.6, title="ATR multiplier", inline="CE", group="Chandelier Exit")
_ce_use_close = input(true, title="Close", inline="CE", group="Chandelier Exit")
_ce_atr = _ce_multiplier * ta.atr(_ce_period)
_ce_long = (_ce_use_close ? ta.highest(close, _ce_period) : ta.highest(_ce_period)) - _ce_atr
_ce_long_previous = nz(_ce_long[1], _ce_long)
_ce_long := close[1] > _ce_long_previous ? math.max(_ce_long, _ce_long_previous) : _ce_long
_ce_short = (_ce_use_close ? ta.lowest(close, _ce_period) : ta.lowest(_ce_period)) + _ce_atr
_ce_short_previous = nz(_ce_short[1], _ce_short)
_ce_short := close[1] < _ce_short_previous ? math.min(_ce_short, _ce_short_previous) : _ce_short
var int _ce_direction = 1
_ce_direction := close > _ce_short_previous ? 1 : close < _ce_long_previous ? -1 : _ce_direction
_ce_signal_buy = _ce_direction == 1 and _ce_direction[1] == -1
_ce_signal_sell = _ce_direction == -1 and _ce_direction[1] == 1
_ce_change_condition = _ce_direction != _ce_direction[1]
plotshape(_ce_signal_buy and _ce_show ? _ce_long : na, title="CE buy signal", text="CE", location=location.belowbar, style=shape.labelup, color=color.green, textcolor=color.white)
plotshape(_ce_signal_sell and _ce_show ? _ce_short : na, title="CE sell signal", text="CE", location=location.abovebar, style=shape.labeldown, color=color.red, textcolor=color.white)
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// Hull Suite -- inputs
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_hull_suite_visual = input(true, title="", inline="Hull suite", group="Hull suite")
_hull_suite_source = input(close, title="", inline="Hull suite", group="Hull suite")
_hull_suite_switch = input.string("Hma", title="", options=["Hma", "Thma", "Ehma"], inline="Hull suite", group="Hull suite")
_hull_suite_length = input(55, title="Length", inline="Hull suite", group="Hull suite")
_hull_suite_multiplier = input(1.0, title="Multiplier", inline="Hull suite", group="Hull suite")
_hull_suite_transparency = input(50, title="Transp", inline="Hull suite", group="Hull suite")
_hull_suite_higher_tf = input(false, title="HTF", inline="Hull suite", group="Hull suite")
_hull_suite_higher_value = input.string("240", title="", inline="Hull suite", group="Hull suite")
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// Hull Suite -- delivery
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_hull_suite_HMA(_src, _length) => ta.wma(2 * ta.wma(_src, _length / 2) - ta.wma(_src, _length), math.round(math.sqrt(_length)))
_hull_suite_EHMA(_src, _length) => ta.ema(2 * ta.ema(_src, _length / 2) - ta.ema(_src, _length), math.round(math.sqrt(_length)))
_hull_suite_THMA(_src, _length) => ta.wma(ta.wma(_src,_length / 3) * 3 - ta.wma(_src, _length / 2) - ta.wma(_src, _length), _length)
_hull_suite_mode(_hull_suite_switch, src, len) =>
_hull_suite_switch == "Hma" ? _hull_suite_HMA(src, len) :
_hull_suite_switch == "Ehma" ? _hull_suite_EHMA(src, len) :
_hull_suite_switch == "Thma" ? _hull_suite_THMA(src, len/2) : na
_hull_suite_pre_security = _hull_suite_mode(_hull_suite_switch, _hull_suite_source, int(_hull_suite_length * _hull_suite_multiplier))
_hull_suite_line_sources = _hull_suite_higher_tf ? request.security(syminfo.ticker, _hull_suite_higher_value, _hull_suite_pre_security) : _hull_suite_pre_security
_hull_suite_line_m = _hull_suite_line_sources[0]
_hull_suite_line_s = _hull_suite_line_sources[2]
_hull_suite_color = _hull_suite_line_sources > _hull_suite_line_sources[2] ? color.new(color.green, _hull_suite_transparency) : color.new(color.red, _hull_suite_transparency)
_hull_suite_line_1 = plot(_hull_suite_visual ? _hull_suite_line_m : na, title="Hull 1 line", color=_hull_suite_color)
_hull_suite_line_2 = plot(_hull_suite_visual ? _hull_suite_line_s : na, title="Hull 2 line", color=_hull_suite_color)
fill(_hull_suite_line_1, _hull_suite_line_2, title="Hull band filler", color=_hull_suite_color)
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// UT bot -- inputs
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_ut_src = close
_ut_key_show_label = input(true, "", inline="UT", group="UT bot")
_ut_key_show_trailing_stop = input(true, "Trail", inline="UT", group="UT bot")
_ut_key_value = input.float(1, title = "Sensitivity", step = .5, inline="UT", group="UT bot")
_ut_atr_period = input(10, title="ATR period", inline="UT", group="UT bot")
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// UT bot -- delivery
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_ut_bot_atr = ta.atr(_ut_atr_period)
_ut_loss = _ut_key_value * _ut_bot_atr
_ut_atr_trailing_stop = 0.0
_ut_atr_trailing_stop := (_ut_src > nz(_ut_atr_trailing_stop[1], 0) and _ut_src[1] > nz(_ut_atr_trailing_stop[1], 0)) ? (math.max(nz(_ut_atr_trailing_stop[1]), _ut_src - _ut_loss)) : (_ut_src < nz(_ut_atr_trailing_stop[1], 0) and _ut_src[1] < nz(_ut_atr_trailing_stop[1], 0)) ? ( math.min(nz(_ut_atr_trailing_stop[1]), _ut_src + _ut_loss)) : (_ut_src > nz(_ut_atr_trailing_stop[1], 0)) ? (_ut_src - _ut_loss) : (_ut_src + _ut_loss)
_ut_pos = 0
_ut_pos := (_ut_src[1] < nz(_ut_atr_trailing_stop[1], 0) and _ut_src > nz(_ut_atr_trailing_stop[1], 0)) ? 1 : (_ut_src[1] > nz(_ut_atr_trailing_stop[1], 0) and _ut_src < nz(_ut_atr_trailing_stop[1], 0)) ? -1 : nz(_ut_pos[1], 0)
_ut_xcolor = _ut_pos == -1 ? color.red: _ut_pos == 1 ? color.green : color.blue
plot(_ut_atr_trailing_stop, color=_ut_key_show_trailing_stop ? _ut_xcolor : na, title="UT trailing stop")
_ut_buy = ta.crossover(_ut_src, _ut_atr_trailing_stop)
_ut_sell = ta.crossunder(_ut_src, _ut_atr_trailing_stop)
plotshape(_ut_key_show_label ? _ut_buy : na, title="UT buy signal", text="UT", style=shape.labelup, location=location.belowbar, color=color.green, textcolor=color.white)
plotshape(_ut_key_show_label ? _ut_sell : na, title="UT sell signal", text="UT", style=shape.labeldown, location=location.abovebar, color=color.red, textcolor=color.white)
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// MA -- inputs
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_ma_1_on = input(false, "1", inline="MA switch", group="MA")
_ma_2_on = input(false, "2", inline="MA switch", group="MA")
_ma_3_on = input(false, "3", inline="MA switch", group="MA")
_ma_4_on = input(false, "4", inline="MA switch", group="MA")
_ma_5_on = input(false, "5", inline="MA switch", group="MA")
_ma_6_on = input(false, "6", inline="MA switch", group="MA")
_ma_7_on = input(false, "7", inline="MA switch", group="MA")
_ma_8_on = input(false, "8", inline="MA switch", group="MA")
_ma_9_on = input(false, "9", inline="MA switch", group="MA")
_ma_10_on = input(false, "10", inline="MA switch", group="MA")
_ma_1_source = input.source(close, "", inline="MA1", group="MA")
_ma_1_length = input(5, "", inline="MA1", group="MA")
_ma_1_type = input.string("EMA", title="", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], inline="MA1", group="MA")
_ma_1_color = input.color(color.white, "", inline="MA1", group="MA")
_ma_2_source = input.source(close, "", inline="MA2", group="MA")
_ma_2_length = input(21, "", inline="MA2", group="MA")
_ma_2_type = input.string("EMA", title="", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], inline="MA2", group="MA")
_ma_2_color = input.color(color.silver, "", inline="MA2", group="MA")
_ma_3_source = input.source(close, "", inline="MA3", group="MA")
_ma_3_length = input(63, "", inline="MA3", group="MA")
_ma_3_type = input.string("EMA", title="", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], inline="MA3", group="MA")
_ma_3_color = input.color(color.teal, "", inline="MA3", group="MA")
_ma_4_source = input.source(close, "", inline="MA4", group="MA")
_ma_4_length = input(144, "", inline="MA4", group="MA")
_ma_4_type = input.string("EMA", title="", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], inline="MA4", group="MA")
_ma_4_color = input.color(color.white, "", inline="MA4", group="MA")
_ma_5_source = input.source(close, "", inline="MA5", group="MA")
_ma_5_length = input(200, "", inline="MA5", group="MA")
_ma_5_type = input.string("SMA", title="", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], inline="MA5", group="MA")
_ma_5_color = input.color(color.orange, "", inline="MA5", group="MA")
_ma_6_source = input.source(close, "", inline="MA6", group="MA")
_ma_6_length = input(18, "", inline="MA6", group="MA")
_ma_6_type = input.string("SMA", title="", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], inline="MA6", group="MA")
_ma_6_color = input.color(color.olive, "", inline="MA6", group="MA")
_ma_7_source = input.source(close, "", inline="MA7", group="MA")
_ma_7_length = input(8, "", inline="MA7", group="MA")
_ma_7_type = input.string("EMA", title="", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], inline="MA7", group="MA")
_ma_7_color = input.color(color.teal, "", inline="MA7", group="MA")
_ma_8_source = input.source(close, "", inline="MA8", group="MA")
_ma_8_length = input(10, "", inline="MA8", group="MA")
_ma_8_type = input.string("SMMA", title="", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], inline="MA8", group="MA")
_ma_8_color = input.color(color.purple, "", inline="MA8", group="MA")
_ma_9_source = input.source(close, "", inline="MA9", group="MA")
_ma_9_length = input(144, "", inline="MA9", group="MA")
_ma_9_type = input.string("SMA", title="", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], inline="MA9", group="MA")
_ma_9_color = input.color(color.silver, "", inline="MA9", group="MA")
_ma_10_source = input.source(close, "", inline="MA10", group="MA")
_ma_10_length = input(200, "", inline="MA10", group="MA")
_ma_10_type = input.string("EMA", title="", options=["SMA", "EMA", "WMA", "VWMA", "SMMA"], inline="MA10", group="MA")
_ma_10_color = input.color(color.lime, "", inline="MA10", group="MA")
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// MA -- delivery
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_ma (_src, _len, _type) =>
switch _type
"SMA" => ta.sma(_src, _len)
"EMA" => ta.ema(_src, _len)
"WMA" => ta.wma(_src, _len)
"VWMA" => ta.vwma(_src, _len)
"SMMA" =>
_ma = ta.sma ( _src, _len )
_ma_final = 0.0
_ma_final := na ( _ma_final[1] ) ? _ma : ( _ma_final[1] * ( _len - 1 ) + _src ) / _len
_ma_1_output = _ma(_ma_1_source, _ma_1_length, _ma_1_type)
_ma_2_output = _ma(_ma_2_source, _ma_2_length, _ma_2_type)
_ma_3_output = _ma(_ma_3_source, _ma_3_length, _ma_3_type)
_ma_4_output = _ma(_ma_4_source, _ma_4_length, _ma_4_type)
_ma_5_output = _ma(_ma_5_source, _ma_5_length, _ma_5_type)
_ma_6_output = _ma(_ma_6_source, _ma_6_length, _ma_6_type)
_ma_7_output = _ma(_ma_7_source, _ma_7_length, _ma_7_type)
_ma_8_output = _ma(_ma_8_source, _ma_8_length, _ma_8_type)
_ma_9_output = _ma(_ma_9_source, _ma_9_length, _ma_9_type)
_ma_10_output = _ma(_ma_10_source, _ma_10_length, _ma_10_type)
_ma_1_line = plot(_ma_1_on ? _ma_1_output : na, "MA 1 line", color=_ma_1_color)
_ma_2_line = plot(_ma_2_on ? _ma_2_output : na, "MA 2 line", color=_ma_2_color)
_ma_3_line = plot(_ma_3_on ? _ma_3_output : na, "MA 3 line", color=_ma_3_color)
_ma_4_line = plot(_ma_4_on ? _ma_4_output : na, "MA 4 line", color=_ma_4_color)
_ma_5_line = plot(_ma_5_on ? _ma_5_output : na, "MA 5 line", color=_ma_5_color)
_ma_6_line = plot(_ma_6_on ? _ma_6_output : na, "MA 6 line", color=_ma_6_color)
_ma_7_line = plot(_ma_7_on ? _ma_7_output : na, "MA 7 line", color=_ma_7_color)
_ma_8_line = plot(_ma_8_on ? _ma_8_output : na, "MA 8 line", color=_ma_8_color)
_ma_9_line = plot(_ma_9_on ? _ma_9_output : na, "MA 9 line", color=_ma_9_color)
_ma_10_line = plot(_ma_10_on ? _ma_10_output : na, "MA 10 line", color=_ma_10_color)
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// Trendfill -- inputs
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_trend_fill_show = input(false, "", inline="Trend fill", group="Trend fill")
_trend_fill_items = input.string("3", title="Trend across first", options=["2", "3", "4", "5"], inline="Trend fill", group="Trend fill")
_trend_fill_transparency = input.int(90, "Transparency", inline="Trend fill", group="Trend fill")
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// Trendfill -- delivery
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_trend_fill_color = _trend_fill_show ? color.new(color.white, 100) : na
if _trend_fill_items=="2"
if _ma_1_output>_ma_2_output
_trend_fill_color := color.new(color.green, _trend_fill_transparency)
if _ma_1_output<_ma_2_output
_trend_fill_color := color.new(color.red, _trend_fill_transparency)
if _trend_fill_items=="3"
if _ma_1_output>_ma_2_output and _ma_2_output>_ma_3_output
_trend_fill_color := color.new(color.green, _trend_fill_transparency)
if _ma_1_output<_ma_2_output and _ma_2_output<_ma_3_output
_trend_fill_color := color.new(color.red, _trend_fill_transparency)
if _trend_fill_items=="4"
if _ma_1_output>_ma_2_output and _ma_2_output>_ma_3_output and _ma_3_output>_ma_4_output
_trend_fill_color := color.new(color.green, _trend_fill_transparency)
if _ma_1_output<_ma_2_output and _ma_2_output<_ma_3_output and _ma_3_output<_ma_4_output
_trend_fill_color := color.new(color.red, _trend_fill_transparency)
if _trend_fill_items=="5"
if _ma_1_output>_ma_2_output and _ma_2_output>_ma_3_output and _ma_3_output>_ma_4_output and _ma_4_output>_ma_5_output
_trend_fill_color := color.new(color.green, _trend_fill_transparency)
if _ma_1_output<_ma_2_output and _ma_2_output<_ma_3_output and _ma_3_output<_ma_4_output and _ma_4_output<_ma_5_output
_trend_fill_color := color.new(color.red, _trend_fill_transparency)
fill(_ma_1_line, _ma_2_line, _trend_fill_items=="2" and _trend_fill_show ? _trend_fill_color : na, fillgaps=false)
fill(_ma_1_line, _ma_3_line, _trend_fill_items=="3" and _trend_fill_show ? _trend_fill_color : na, fillgaps=false)
fill(_ma_1_line, _ma_4_line, _trend_fill_items=="4" and _trend_fill_show ? _trend_fill_color : na, fillgaps=false)
fill(_ma_1_line, _ma_5_line, _trend_fill_items=="5" and _trend_fill_show ? _trend_fill_color : na, fillgaps=false)
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// Vwap standard deviations -- inputs
// -----------------------------------------------------------------------------------------------------------------------------------------------------------
_vsd_color_0 = input.color(color.yellow, "", inline="Vwap standard deviations", group="Vwap standard deviations")
_vsd_set_0 = input(true, "", inline="Vwap standard deviations", group="Vwap standard deviations")
_vsd_color_1 = input.color(color.orange, "", inline="Vwap standard deviations", group="Vwap standard deviations")
_vsd_set_1 = input(true, "", inline="Vwap standard deviations", group="Vwap standard deviations")
_vsd_color_2 = input.color(color.red, "", inline="Vwap standard deviations", group="Vwap standard deviations")
_vsd_set_2 = input(true, "", inline="Vwap standard deviations", group="Vwap standard deviations")
_vsd_color_3 = input.color(color.blue, "", inline="Vwap standard deviations", group="Vwap standard deviations")
_vsd_set_3 = input(true, "", inline="Vwap standard deviations", group="Vwap standard deviations")
_vsd_color_4 = input.color(color.green, "", inline="Vwap standard deviations", group="Vwap standard deviations")
_vsd_set_4 = input(true, "", inline="Vwap standard deviations", group="Vwap standard deviations")
_vsd_src = input(hlc3, "", inline="Vwap standard deviations settings", group="Vwap standard deviations")
_vsd_vwap_func(_vsd_src, _vsd_is_new_period) =>
var float _vsd_sum_src_vol = na
var float _vsd_sum_vol = na
var float _vsd_sum_src_src_vol = na
_vsd_sum_src_vol := _vsd_is_new_period ? _vsd_src * volume : _vsd_src * volume + _vsd_sum_src_vol[1]
_vsd_sum_vol := _vsd_is_new_period ? volume : volume + _vsd_sum_vol[1]
_vsd_sum_src_src_vol := _vsd_is_new_period ? volume * math.pow(_vsd_src, 2) : volume * math.pow(_vsd_src, 2) + _vsd_sum_src_src_vol[1]
_vsd_vwap = _vsd_sum_src_vol / _vsd_sum_vol
_vsd_variance = _vsd_sum_src_src_vol / _vsd_sum_vol - math.pow(_vsd_vwap, 2)
_vsd_variance := _vsd_variance < 0 ? 0 : _vsd_variance
_vsd_deviation = math.sqrt(_vsd_variance)
_vsd_lower_1 = _vsd_vwap - _vsd_deviation
_vsd_upper_1 = _vsd_vwap + _vsd_deviation
_vsd_lower_2 = _vsd_vwap - _vsd_deviation * 2
_vsd_upper_2 = _vsd_vwap + _vsd_deviation * 2
_vsd_lower_3 = _vsd_vwap - _vsd_deviation * 3
_vsd_upper_3 = _vsd_vwap + _vsd_deviation * 3
_vsd_lower_4 = _vsd_vwap - _vsd_deviation * 4
_vsd_upper_4 = _vsd_vwap + _vsd_deviation * 4
[_vsd_vwap, _vsd_lower_1, _vsd_upper_1, _vsd_lower_2, _vsd_upper_2, _vsd_lower_3, _vsd_upper_3, _vsd_lower_4, _vsd_upper_4]
_vsd_anchor = "Session"
_vsd_is_new_period = switch _vsd_anchor
"Session" => ta.change(time("D"))
=> false
isEsdAnchor = _vsd_anchor == "Earnings" or _vsd_anchor == "Dividends" or _vsd_anchor == "Splits"
if na(_vsd_src[1]) and not isEsdAnchor
_vsd_is_new_period := true
[_vsd_vwap, _vsd_bot_1, _vsd_top_1, _vsd_bot_2, _vsd_top_2, _vsd_bot_3, _vsd_top_3, _vsd_bot_4, _vsd_top_4] = _vsd_vwap_func(_vsd_src, _vsd_is_new_period)
plot(_vsd_set_0 ? _vsd_vwap : na, title="VWAP", color=_vsd_color_0)
plot(_vsd_set_1 ? _vsd_top_1 : na, title="VWAP x2 upper band", color=_vsd_color_1)
plot(_vsd_set_1 ? _vsd_bot_1 : na, title="VWAP x2 lower band", color=_vsd_color_1)
plot(_vsd_set_2 ? _vsd_top_2 : na, title="VWAP x2 upper band", color=_vsd_color_2)
plot(_vsd_set_2 ? _vsd_bot_2 : na, title="VWAP x2 lower band", color=_vsd_color_2)
plot(_vsd_set_3 ? _vsd_top_3 : na, title="VWAP x2 upper band", color=_vsd_color_3)
plot(_vsd_set_3 ? _vsd_bot_3 : na, title="VWAP x2 lower band", color=_vsd_color_3)
plot(_vsd_set_4 ? _vsd_top_4 : na, title="VWAP x2 upper band", color=_vsd_color_4)
plot(_vsd_set_4 ? _vsd_bot_4 : na, title="VWAP x2 lower band", color=_vsd_color_4)
|
Fading Moving Average | https://www.tradingview.com/script/aujMAaGB-Fading-Moving-Average/ | barnabygraham | https://www.tradingview.com/u/barnabygraham/ | 15 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © barnabygraham
//@version=5
indicator("Fading Moving Average",overlay=true)
length = input.int(50,'Length')
colour = input.color(color.new(color.yellow,0),'Color')
plot(ta.sma(close,length),color=color.new(colour,(100/length)*(last_bar_index - bar_index))) |
Short & Long Relative Strength | https://www.tradingview.com/script/3b8f95Pd-Short-Long-Relative-Strength/ | RS-Magic | https://www.tradingview.com/u/RS-Magic/ | 129 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RS-Magic
//@version=5
indicator('Short & Long Relative Strength', shorttitle='Short & Long RS')
source = input(title='Source', defval=close)
comparativeTickerId = input.symbol('NSE:NIFTY', title='Comparative Symbol')
showShortRS = input(defval=true, title='Show Short RS')
ShortLength = input.int(65, minval=1, title='Short RS Time Period')
showLongRS = input(defval=true, title='Show Long RS')
LongLength = input.int(123, minval=1, title='Long RS Time Period')
showZeroLine = input(defval=true, title='Show Zero Line')
baseSymbol = request.security(syminfo.tickerid, timeframe.period, source)
comparativeSymbol = request.security(comparativeTickerId, timeframe.period, source)
plot(showZeroLine ? 0 : na, title='Zero Line', linewidth=1, color=color.new(color.black, 0))
LongRS = baseSymbol / baseSymbol[LongLength] / (comparativeSymbol / comparativeSymbol[LongLength]) - 1
ShortRS = baseSymbol / baseSymbol[ShortLength] / (comparativeSymbol / comparativeSymbol[ShortLength]) - 1
plot(showShortRS ? ShortRS : na, title='Short RS', linewidth=2, color=color.new(color.black, 0))
plot(showLongRS ? LongRS : na, title='Long RS', linewidth=3)
|
Study forloop Star Diamond | https://www.tradingview.com/script/Vxm3vtIc-Study-forloop-Star-Diamond/ | hapharmonic | https://www.tradingview.com/u/hapharmonic/ | 14 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hapharmonic
//@version=5
//'Study forloop' pinescript Program to print star Diamond
//------Output------
// * |
// * * |
// * * * |
// * * * * |
// * * * * * |
// * * * * * * |
// * * * * * |
// * * * * |
// * * * |
// * * |
// * |
//------------------
indicator("Study forloop Star Diamond",overlay=true)
rows = input.int(15,'Enter number of rows:',maxval=35) //The number of rows displayed
i_tablePosition = input.string(title="Position", defval=position.middle_center, group="Table", options=[position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right])
in_ = array.new_string(1)
//define a function to print star shape
star_pattern4(n) =>
textin = ""
for i = 0 to n-1 //Use outer for loop for rows
for k=0 to i
textin := textin+'* ' //Store each star in the variable "textin"
textin := textin+'\n' //At the end of the forloop, start a new line. End of line after each row
////////Assemble the footer//////////
for i = 0 to n
for k=0 to n-i
textin := textin+'* '
textin := textin+'\n'
////////////////////////////////////
array.set(in_,0,textin)
star_pattern4(rows)
////==show label format==
// l1 = label.new(bar_index+5,close,text=array.get(in_,0),color=color.new(color.red,100),textcolor=color.white)
// label.delete(l1[1])
//Show data within an array.
for i = 0 to 1
var table tdSetupTable = table.new(i_tablePosition, 1, 2, border_width=0)
if i == 0
table.cell(tdSetupTable, 0, 0, array.get(in_,0), text_color = color.white,text_valign=text.align_center)
else
T = "'Study forloop' pinescript Program to print star Diamond"
table.cell(tdSetupTable, 0, 1, T, text_color = color.yellow,text_valign=text.align_center,text_size=size.large)
|
Backtesting- Indicator | https://www.tradingview.com/script/VGMYX0bJ-Backtesting-Indicator/ | Thumpyr | https://www.tradingview.com/u/Thumpyr/ | 188 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Thumpyr
//@version=5
/////////////////////////////////////////////////////////////////////////////////////////////
// Comment out Strategy Line and remove // from Indicator line to turn into Indicator //////
// Do same for alertConidction at bottom //////
/////////////////////////////////////////////////////////////////////////////////////////////
//strategy("Backtesting-Strategy", shorttitle="Backtesting- Strategy", overlay=true, margin_long=100, margin_short=100, default_qty_type=strategy.percent_of_equity,default_qty_value=90, commission_type=strategy.commission.percent, commission_value=.075)
indicator(title="Backtesting- Indicator", shorttitle="Backtesting - Indicator", overlay=true)//
openBalance =input.float(3000, minval=0, title="Opening Balance:", group="Back Test")
pctAllocated =input.float(.9, minval=0, title="Allocated % (90% = .9):", group="Back Test")
commission =input.float(.075, minval=0, title="Commission%", group="Back Test")
sellLow=input.float(.035, minval=0, title="Stop Loss Loss: 1% = .01", group="Sell Settings")
trailStopArm=input.float(.0065, minval=0, title="Trailing Stop Arm: 1%=.01", group="Sell Settings")
trailStopPct=input.float(.003, minval=0, title="Trailing Stop Trigger: 1%=.01 ", group="Sell Settings")
/////////////////////////////////////////////////
// Indicators //
/////////////////////////////////////////////////
ema1Len = input.int(14, minval=1, title=" ema 1 Length", group="Trend Line Settings")
ema1Src = input(close, title="ema 1 Source", group="Trend Line Settings")
ema1 = ta.ema(ema1Src, ema1Len)
plot(ema1, title="EMA", color=color.blue)
ema2Len = input.int(22, minval=1, title=" ema 2 Length", group="Trend Line Settings")
ema2Src = input(close, title="ema 2 Source", group="Trend Line Settings")
ema2 = ta.ema(ema2Src, ema2Len)
plot(ema2, title="EMA", color=color.orange)
ema3Len = input.int(200, minval=1, title=" ema 3 Length", group="Trend Line Settings")
ema3Src = input(close, title="ema 2 Source", group="Trend Line Settings")
ema3 = ta.ema(ema3Src, ema3Len)
plot(ema3, title="EMA", color=color.gray)
/////////////////////////////
//// Buy Conditions ////
/////////////////////////////
alertBuy = ta.crossover(ema1,ema2) and close>ema3
////////////////////////////////////////////////////////////////////
//// Filter redundant Buy Signals if Sell has not happened ////
////////////////////////////////////////////////////////////////////
var lastsignal = 0
showAlertBuy = 0
if(alertBuy and lastsignal != 1)
showAlertBuy := 1
lastsignal := 1
buyAlert= showAlertBuy > 0
var buyActive = 0
if buyAlert
buyActive :=1
//////////////////////////////////////////////////////////////////
//// Track Conditions at buy Signal ////
//////////////////////////////////////////////////////////////////
alertBuyValue = ta.valuewhen(buyAlert, close,0)
alertSellValueLow = alertBuyValue - (alertBuyValue*sellLow)
////////////////////////////////////////////////////////////
///// Trailing Stop /////
////////////////////////////////////////////////////////////
var TSLActive = 0 //Check to see if TSL has been activated
var TSLTriggerValue = 0.0 //Initial and climbing value of TSL
var TSLStop = 0.0 //Sell Trigger
var TSLRunning = 0 //Continuously check each bar to raise TSL or not
// Check if a Buy has been triggered and set initial value for TSL //
if buyAlert
TSLTriggerValue := alertBuyValue+(alertBuyValue*trailStopArm)
TSLActive := 0
TSLRunning := 1
TSLStop := TSLTriggerValue - (TSLTriggerValue*trailStopPct)
// Check that Buy has triggered and if Close has reached initial TSL//
// Keeps from setting Sell Signal before TSL has been armed w/TSLActive//
beginTrail=TSLRunning==1 and TSLActive==0 and close>alertBuyValue+(alertBuyValue*trailStopArm) and ta.crossover(close,TSLTriggerValue)
if beginTrail
TSLTriggerValue :=close
TSLActive :=1
TSLStop :=TSLTriggerValue - (TSLTriggerValue*trailStopPct)
// Continuously check if TSL needs to increase and set new value //
runTrail= TSLActive==1 and (ta.crossover(close,TSLTriggerValue) or close>=TSLTriggerValue)
if runTrail
TSLTriggerValue :=close
TSLStop :=TSLTriggerValue - (TSLTriggerValue*trailStopPct)
// Verify that TSL is active and trigger when close cross below TSL Stop//
TSL=TSLActive==1 and (ta.crossunder(close,TSLStop) or (close[1]>TSLStop and close<TSLStop))
// Plot point of inital arming of TSL//
TSLTrigger=TSLActive==1 and TSLActive[1]==0
plotshape(TSLTrigger, title='TSL Armed', location=location.abovebar, color=color.new(color.blue, 0), size=size.small, style=shape.cross, text='TSL Armed')
////////////////////////////////////////////////////////////
///// Sell Conditions ///////
////////////////////////////////////////////////////////////
Sell1 = TSL
Sell2 = ta.crossunder(close,alertSellValueLow)
alertSell = Sell1 or Sell2
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//// Remove Redundant Signals ////
////////////////////////////////////////////////////////////
showAlertSell = 0
if(alertSell and lastsignal != -1)
showAlertSell := 1
lastsignal := -1
sellAlert= showAlertSell > 0
if sellAlert
TSLActive :=0
TSLRunning :=0
buyActive :=0
/////////////////////////////////////////
// Plot Buy and Sell Shapes on Chart //
/////////////////////////////////////////
plotshape(buyAlert, title='Buy' , location=location.belowbar , color=color.new(color.green, 0), size=size.small , style=shape.triangleup , text='Buy')
plotshape(sellAlert, title='Sell', location=location.abovebar , color=color.new(color.red, 0) , size=size.small , style=shape.triangledown , text='Sell')
/////////////////////////////////////////////////////////////////////////////////////////////
// Remove // on alertCondition to enable Alerts //
/////////////////////////////////////////////////////////////////////////////////////////////
//Alerts
alertcondition(title='Buy Alert', condition=buyAlert, message='Buy Conditions are Met')
alertcondition(title='Sell Alert', condition=sellAlert, message='Sell Conditions are Met')
/////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//// Comment out this section if setup as Indicator ////
////////////////////////////////////////////////////////////
//longCondition = buyAlert
//if (longCondition)
// strategy.entry("Buy", strategy.long)
// alert(message='Buy', freq=alert.freq_once_per_bar_close)
//shortCondition = sellAlert
//if (shortCondition)
// strategy.close_all(sellAlert,"Sell")
// alert(message='Sell', freq=alert.freq_once_per_bar_close)
/////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// BackTesting ////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Table for Backtesting results. This is mostly Self-Contained. There are 2 variables above this area you will need //
// AlertBuyValue and buyActive are above in the remove Redundant Signals Section and Track Conditions at Buy Signal section //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
show_table = input.bool(true, title="Show table")
sellValue = ta.valuewhen(sellAlert,close,0)
currentPrice=close
var buyAlertCount = 0
var sellAlertCount = 0
var goodTradeCount = 0
var runningBalance = openBalance
var sharePurchaseAmt = 0.0
var actualPurchasePower = 0.0
var buyCommission = 0.0
var sharesPurchased = 0.0
var gross = 0.0
var net = 0.0
var sellCommission = 0.0
var totalCommission = 0.0
var tradeProfit = 0.0
var gain = 0.0
var closingBalance = 0.0
var profitLoss = 0.0
if buyAlert
sharePurchaseAmt := runningBalance * pctAllocated
buyCommission := (sharePurchaseAmt / 100) * commission
actualPurchasePower := sharePurchaseAmt - buyCommission
sharesPurchased := actualPurchasePower / alertBuyValue
buyAlertCount += 1
if sellAlert
gross := sharesPurchased * sellValue
net := gross - actualPurchasePower
sellCommission := (gross / 100) * commission
totalCommission := buyCommission + sellCommission
tradeProfit := net - totalCommission
gain := tradeProfit / actualPurchasePower
closingBalance := runningBalance + tradeProfit
runningBalance := closingBalance
profitLoss := ((runningBalance - openBalance) / openBalance) * 100
sellAlertCount += 1
if sellValue>alertBuyValue
goodTradeCount +=1
if show_table and buyActive==1
Table = table.new(position.bottom_right, columns = 2, rows = 9, border_width = 1, bgcolor = color.black, border_color = color.gray)
table.cell(table_id = Table, column = 0, row = 0, text = "Backtest Results:", text_size = size.normal, text_color=color.white)
table.cell(table_id = Table, column = 1, row = 0, text = "Value:", text_size = size.normal, text_color=color.white)
table.cell(table_id = Table, column = 0, row = 1, text = "Starting Balance:", text_size = size.normal, text_color=color.silver, text_halign=text.align_left)
table.cell(table_id = Table, column = 1, row = 1, text = str.tostring(openBalance,"###,###.##"), text_size = size.normal, text_color=color.white, text_halign=text.align_right)
table.cell(table_id = Table, column = 0, row = 2, text = "Closing Balance:", text_size = size.normal,text_color=color.silver, text_halign=text.align_left)
table.cell(table_id = Table, column = 1, row = 2, text = str.tostring(runningBalance,"###,###.##"), text_size = size.normal, text_color= runningBalance>=openBalance?color.green:color.red, text_halign=text.align_right)
table.cell(table_id = Table, column = 0, row = 3, text = "Profit/Loss%", text_size = size.normal, text_color=color.silver, text_halign=text.align_left)
table.cell(table_id = Table, column = 1, row = 3, text = str.tostring(profitLoss,format.percent), text_size = size.normal, text_color=runningBalance>=openBalance?color.green:color.red, text_halign=text.align_right)
table.cell(table_id = Table, column = 0, row = 4, text = "Profit/Loss Value", text_size = size.normal, text_color=color.silver, text_halign=text.align_left)
table.cell(table_id = Table, column = 1, row = 4, text = str.tostring(runningBalance-openBalance,"###,###.##"), text_size = size.normal, text_color=runningBalance-openBalance>=0?color.green:color.red, text_halign=text.align_right)
table.cell(table_id = Table, column = 0, row = 5, text = "Buy Alert Count:", text_size = size.normal, text_color=color.silver, text_halign=text.align_left)
table.cell(table_id = Table, column = 1, row = 5, text = str.tostring(buyAlertCount,"###,###.##"), text_size = size.normal, text_color=color.silver, text_halign=text.align_right)
table.cell(table_id = Table, column = 0, row = 6, text = "Sell Alert Count:", text_size = size.normal, text_color=color.silver, text_halign=text.align_left)
table.cell(table_id = Table, column = 1, row = 6, text = str.tostring(sellAlertCount,"###,###.##"), text_size = size.normal, text_color=color.silver, text_halign=text.align_right)
table.cell(table_id = Table, column = 0, row = 7, text = "Profitable Trade Count", text_size = size.normal, text_color=color.silver, text_halign=text.align_left)
table.cell(table_id = Table, column = 1, row = 7, text = str.tostring(goodTradeCount,"###,###.##"), text_size = size.normal, text_color=color.silver, text_halign=text.align_right)
table.cell(table_id = Table, column = 0, row = 8, text = "% Profitable Trades:", text_size = size.normal, text_color=color.silver, text_halign=text.align_left)
table.cell(table_id = Table, column = 1, row = 8, text = str.tostring((goodTradeCount/sellAlertCount)*100,format.percent), text_size = size.normal, text_color=color.white, text_halign=text.align_right)
|
Auto Order Block by D. Brigaglia | https://www.tradingview.com/script/i3BKmxdj/ | dadoesploso | https://www.tradingview.com/u/dadoesploso/ | 974 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dadoesploso
//@version=4
study(title="Volatility Expansion Levels", shorttitle = "VEL",overlay=true)
atrc = input(defval=0.9, title="ATR Multiplier (of Trapped Trend Bar minimum absolute close-to-open distance). Default is 0.9. Higher values make the indicator picky.")
atrct = input(defval=2.0, title="Trapping Trend Bar Close-Open Minimum value (relative to Trapped Trend Bar absolute close-to-open distance). Default is 2. Higher values make the indicator picky.")
lenght = input(title="Rectangle Lenght", type=input.integer, defval=350)
//Bullish VEL
if (open[1] - close[1]) > atrc*atr(10) and close - open > atrct*(open[1] - close[1])
box.new(left=bar_index[1], top=open[1], right=bar_index + lenght, bottom=lowest(low,1),
border_color=color.blue, border_width=3, bgcolor=na)
alert("Bullish OB", alert.freq_once_per_bar_close)
//Bearish VEL
if (close[1] - open[1]) > atrc*atr(10) and open - close > atrct*(close[1] - open[1])
box.new(left=bar_index[1], top=highest(high,1), right=bar_index + lenght, bottom=open[1],
border_color=color.red, border_width=3, bgcolor=na)
alert("Bearish OB", alert.freq_once_per_bar_close) |
Bar Chart | https://www.tradingview.com/script/NKes9ZrH-bar-chart/ | Full_Trade | https://www.tradingview.com/u/Full_Trade/ | 27 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Full_Trade
//@version=5
indicator("Bar Chart")
colorh = if (high>high[1]) and (low<low[1])
color.blue
else if (high<high[1]) and (low>low[1])
color.black
else if (high>high[1]) and (low>low[1])
color.green
else
color.red
plotbar(low, low, low, high, color=colorh)
plotbar(high, high, high, low, color=colorh)
plot(close, color=color.red, style = plot.style_circles) |
Risk On Risk Off | https://www.tradingview.com/script/S6tyWt7z-Risk-On-Risk-Off/ | xloexs | https://www.tradingview.com/u/xloexs/ | 80 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © xloexs
//@version=5
indicator("Risk On Risk Off")
//Theory:
//Indicator to determine if the current economic environment is either Risk On or Risk Off
//Parameters:
//Risk On when: 60 Day Cumulative Return of BND is Above BIL
//Risk Off when: 60 Day Cumulative Return of BND is Below BIL
//Calculation:
//60 Day Cumulative Return of BND
//BND Current Price
bndc = request.security("BND", "D", close)
//plot(bndc, "BND Current Price", color.yellow, 2)
//BND 60 Day Price
bndo = request.security("BND", "60D", close)
//plot(bndo, "BND 60D Price", color.green, 2)
//Calculation of Cumulative Return
//((Current price)-(Original price))/Original price
cumpbnd = (bndc - bndo)/bndo
plot(cumpbnd, "BND 60 Day Cumulative Price Return", color.green, 2)
//60 Day Cumulative Return of BIL
//BIL Current Price
bilc = request.security("BIL", "D", close)
//plot(bilc, "BIL Current Price", color.yellow, 2)
//BIL 60 Day Price
bilo= request.security("BIL", "60D", close)
//plot(bilo, "BIL 60 Day Price", color.green, 2)
//Calculation of Cumulative Return
//((Current price)-(Original price))/Original price
cumpbil = (bilc - bilo)/bilo
plot(cumpbil, "BIL 60 Day Cumulative Price Return", color.yellow, 2) |
Deviation from Average | https://www.tradingview.com/script/Ytkv8KtG/ | xlpguckerx | https://www.tradingview.com/u/xlpguckerx/ | 8 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © xlpguckerx
//@version=4
study("Deviation from Average",overlay=false)
a=sma(close,20)
b=a-close
c=b/a
plot(-c*100) |
Fibonacci Grid [LuxAlgo] | https://www.tradingview.com/script/FhuOxgN9-Fibonacci-Grid-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,404 | study | 5 | CC-BY-NC-SA-4.0 | // 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/
// © LuxAlgo
//@version=5
indicator('Fibonacci Grid [LuxAlgo]', 'LuxAlgo - Fibonacci Grid', overlay = true, max_bars_back = 2000, max_lines_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
N = input.int(4, 'Resolution', maxval=10)
fib = input(true, 'Use Fibonacci Ratios')
src = input(close)
//Style
upCss = input.color(#2157f3, 'Lines Colors', group = 'Style', inline='lcol')
midCss = input.color(#ff5d00, '', group = 'Style', inline='lcol')
dnCss = input.color(#ff1100, '', group = 'Style', inline='lcol')
showArea = input.bool(true, 'Evaluation Area',group='Style', inline='area')
uptrendCss = input.color(color.new(#2157f3, 80), '',group='Style', inline='area')
dntrendCss = input.color(color.new(#ff1100, 80), '',group='Style', inline='area')
ext = input(true, 'Extend Diagonal Lines')
x1 = input.time(0, confirm = true)
x2 = input.time(0, confirm = true)
//-----------------------------------------------------------------------------}
//Function
//-----------------------------------------------------------------------------{
Line(l, x1, y1, x2, y2, css, extend) =>
line.set_xy1(l, x1, y1)
line.set_xy2(l, x2, y2)
line.set_color(l, css)
line.set_extend(l, extend)
l
//-----------------------------------------------------------------------------}
//Calculations
//-----------------------------------------------------------------------------{
var ratios = array.from(0.236, 0.382, 0.5, 0.618, 0.786, 1.)
var float max = na
var float min = na
var X1 = 0
var X2 = 0
n = bar_index
if time == x1
max := src
min := src
X1 := n
else if time <= x2
max := math.max(src, max)
min := math.min(src, min)
X2 := n
//-----------------------------------------------------------------------------}
//Display lines
//-----------------------------------------------------------------------------{
if time == x2
length = X2 - X1
css = src > math.avg(max, min) ? uptrendCss : dntrendCss
if showArea
box.new(x1, max, x2, min, na, xloc = xloc.bar_time, bgcolor = color.new(css, 80))
k = 0.
size = fib ? array.size(ratios) : N
//Loops trough ratios
for i = 0 to size - 1
if fib
k := array.get(ratios, i)
else
k += 1 / N
upcol = color.from_gradient(i, 0, size-1, midCss, upCss)
dncol = color.from_gradient(i, 0, size-1, midCss, dnCss)
//Set upward lines
line.new(X2 - int(k * length), min, X2, k * max + (1 - k) * min
, color = color.from_gradient(i, 0, size-1, upCss, midCss)
, extend = ext ? extend.right : extend.none)
line.new(X1 + int(k * length), max, X1, k * min + (1 - k) * max
, color = color.from_gradient(i, 0, size-1, upCss, midCss)
, extend = ext ? extend.left : extend.none)
//Set downward lines
line.new(X2 - int(k * length), max, X2, k * min + (1 - k) * max
, color = color.from_gradient(i, 0, size-1, dnCss, midCss)
, extend = ext ? extend.right : extend.none)
line.new(X1 + int(k * length), min, X1, k * max + (1 - k) * min
, color = color.from_gradient(i, 0, size-1, dnCss, midCss)
, extend = ext ? extend.left : extend.none)
//-----------------------------------------------------------------------------} |
Trendelicious | https://www.tradingview.com/script/pfzWRRRV-Trendelicious/ | levieux | https://www.tradingview.com/u/levieux/ | 131 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © levieux
//@version=5
indicator("Trendelicious", overlay=true)
length=input(defval=30)
price=input(defval=hl2, title="Price Source")
aggressiveMode=input(defval=false,title="Aggressive Mode")
isUptrend(price,length,aggressiveMode) =>
uptrend= false
PP= (ta.highest(price,length)+ta.lowest(price,length))/2
ppChange= ta.change(PP,1)
ppFlat= ppChange==0
priceOverPP=ta.crossover(price,PP)
priceUnderPP=ta.crossunder(price,PP)
risingPrice= ta.rising(price,5)
risingPP= ta.rising(PP,5)
fallingPrice= ta.falling(price,5)
fallingPP= ta.falling(PP,5)
uptrendCondition1= price>PP and (ppChange>0 or (ppChange==0 and aggressiveMode)) and (ppChange[1]>0 or (ppChange[1]==0 and aggressiveMode)) and ppChange[2]>=0 and ppChange[3]>=0
uptrendCondition2= (priceOverPP or risingPrice) and ppFlat and aggressiveMode
uptrendCondition3= risingPrice and fallingPP and aggressiveMode
downtrendCondition1= price < PP and (ppChange<0 or (ppChange==0 and aggressiveMode)) and (ppChange[1]<0 or (ppChange[1]==0 and aggressiveMode)) and ppChange[2]<=0 and ppChange[3]<=0
downtrendCondition2= (priceUnderPP or fallingPrice) and ppFlat and aggressiveMode
downtrendCondition3= fallingPrice and risingPP and aggressiveMode
if uptrendCondition1 or uptrendCondition2 or uptrendCondition3
uptrend:= true
else if downtrendCondition1 or downtrendCondition2 or downtrendCondition3
uptrend:= false
else
uptrend:= uptrend[1]
[PP,uptrend]
[trendline,uptrend]= isUptrend(price,length,aggressiveMode)
baseLinePlot = plot((open + close) / 2, display=display.none)
upTrendPlot = plot(uptrend ? trendline : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrendPlot = plot(not uptrend ? trendline : na, "Down Trend", color = color.red, style=plot.style_linebr)
fill(baseLinePlot, upTrendPlot, color.new(color.green, 90), fillgaps=false)
fill(baseLinePlot, downTrendPlot, color.new(color.red, 90), fillgaps=false) |
Head-on-Correlation | https://www.tradingview.com/script/CYtZZHme-Head-on-Correlation/ | CubanEmissary | https://www.tradingview.com/u/CubanEmissary/ | 17 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CubanEmissary
//@version=5
indicator("HoC", format=format.price, precision=2, overlay=false)
//In case it times out
rsec = input.bool(title="Tick/Untick Box to Reload Indicator", defval=true)
//Manually configure incoming data source, calculation, and select series output
src0 = input.source(close, title="Line-In Source")
src1 = input.string(title="Source Calculation", defval="Close", options=["Close", "Line-In", "TSI", "RSI", "MFI", "SMA", "HMA", "H-L", "BBW", "WAD"])
src2 = input.string(title="Line-Out", defval="None", options=["None","1-ShortestTF","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40-LongestTF"])
//Set starting length size and incremental increase
step0 = input.int(2, title="Start Length", minval=2)
step1 = input.int(1, title="Step Size")
//Display Line Levels and customize colors
haw = input.bool(title="Show Line Levels", defval=false)
color1 = input.color(color.new(color.red, 30), title="Color1")
color2 = input.color(color.new(color.orange, 30), title="Color2")
color3 = input.color(color.new(color.yellow, 30), title="Color3")
color4 = input.color(color.new(color.green, 30), title="Color4")
color5 = input.color(color.new(color.blue, 30), title="Color5")
color6 = input.color(color.new(color.purple, 30), title="Color6")
color7 = input.color(color.new(color.fuchsia, 30), title="Color7")
color8 = input.color(color.new(color.white, 30), title="Color8")
//Switch assignment for Calculation dropdown
float org = switch src1
"Close" => close
"Line-In" => src0
"TSI" => ta.tsi(src0, step0, step1)
"RSI" => ta.rsi(src0, step0)
"MFI" => ta.mfi(src0, step0)
"SMA" => ta.sma(src0, step0)
"HMA" => ta.hma(src0, step0)
"H-L" => (ta.barssince(ta.highest(src0,step0)))-(ta.barssince(ta.lowest(src0,step0)))
"BBW" => ta.bbw(src0, step0, step1)
"WAD" => ta.wad
=>
float(na)
//Simple reference function and assignment calls left for you to customize
somefuncybusiness(_org, _step0, _step1) =>
ta.sma(_org, (_step0+_step1))
ss1 = somefuncybusiness(org, step0, 0*step1)
ss2 = somefuncybusiness(org, step0, 1*step1)
ss3 = somefuncybusiness(org, step0, 2*step1)
ss4 = somefuncybusiness(org, step0, 3*step1)
ss5 = somefuncybusiness(org, step0, 4*step1)
ss6 = somefuncybusiness(org, step0, 5*step1)
ss7 = somefuncybusiness(org, step0, 6*step1)
ss8 = somefuncybusiness(org, step0, 7*step1)
ss9 = somefuncybusiness(org, step0, 8*step1)
ss10 = somefuncybusiness(org, step0, 9*step1)
ss11 = somefuncybusiness(org, step0, 10*step1)
ss12 = somefuncybusiness(org, step0, 11*step1)
ss13 = somefuncybusiness(org, step0, 12*step1)
ss14 = somefuncybusiness(org, step0, 13*step1)
ss15 = somefuncybusiness(org, step0, 14*step1)
ss16 = somefuncybusiness(org, step0, 15*step1)
ss17 = somefuncybusiness(org, step0, 16*step1)
ss18 = somefuncybusiness(org, step0, 17*step1)
ss19 = somefuncybusiness(org, step0, 18*step1)
ss20 = somefuncybusiness(org, step0, 19*step1)
ss21 = somefuncybusiness(org, step0, 20*step1)
ss22 = somefuncybusiness(org, step0, 21*step1)
ss23 = somefuncybusiness(org, step0, 22*step1)
ss24 = somefuncybusiness(org, step0, 23*step1)
ss25 = somefuncybusiness(org, step0, 24*step1)
ss26 = somefuncybusiness(org, step0, 25*step1)
ss27 = somefuncybusiness(org, step0, 26*step1)
ss28 = somefuncybusiness(org, step0, 27*step1)
ss29 = somefuncybusiness(org, step0, 28*step1)
ss30 = somefuncybusiness(org, step0, 29*step1)
ss31 = somefuncybusiness(org, step0, 30*step1)
ss32 = somefuncybusiness(org, step0, 31*step1)
ss33 = somefuncybusiness(org, step0, 32*step1)
ss34 = somefuncybusiness(org, step0, 33*step1)
ss35 = somefuncybusiness(org, step0, 34*step1)
ss36 = somefuncybusiness(org, step0, 35*step1)
ss37 = somefuncybusiness(org, step0, 36*step1)
ss38 = somefuncybusiness(org, step0, 37*step1)
ss39 = somefuncybusiness(org, step0, 38*step1)
ss40 = somefuncybusiness(org, step0, 39*step1)
//Horizontal line displays for chart anchoring and value approximation
h2 = hline((haw == false) ? na : 75, title="Higher", color=color.new(color.silver, 95))
h3 = hline((haw == false) ? na : 50, title="Middle", color=color.new(color.silver, 95))
h4 = hline((haw == false) ? na : 25, title="Lower", color=color.new(color.silver, 95))
//Line displays with deletes on every new bar
l40 = line.new(bar_index-39, ss40[0], bar_index-40, ss40[0], color=color8, width=4)
l39 = line.new(bar_index-38, ss39[0], bar_index-39, ss39[0], color=color8, width=4)
l38 = line.new(bar_index-37, ss38[0], bar_index-38, ss38[0], color=color8, width=4)
l37 = line.new(bar_index-36, ss37[0], bar_index-37, ss37[0], color=color8, width=4)
l36 = line.new(bar_index-35, ss36[0], bar_index-36, ss36[0], color=color8, width=4)
line.delete(l40[1])
line.delete(l39[1])
line.delete(l38[1])
line.delete(l37[1])
line.delete(l36[1])
l35 = line.new(bar_index-34, ss35[0], bar_index-35, ss35[0], color=color7, width=4)
l34 = line.new(bar_index-33, ss34[0], bar_index-34, ss34[0], color=color7, width=4)
l33 = line.new(bar_index-32, ss33[0], bar_index-33, ss33[0], color=color7, width=4)
l32 = line.new(bar_index-31, ss32[0], bar_index-32, ss32[0], color=color7, width=4)
l31 = line.new(bar_index-30, ss31[0], bar_index-31, ss31[0], color=color7, width=4)
line.delete(l35[1])
line.delete(l34[1])
line.delete(l33[1])
line.delete(l32[1])
line.delete(l31[1])
l30 = line.new(bar_index-29, ss30[0], bar_index-30, ss30[0], color=color6, width=4)
l29 = line.new(bar_index-28, ss29[0], bar_index-29, ss29[0], color=color6, width=4)
l28 = line.new(bar_index-27, ss28[0], bar_index-28, ss28[0], color=color6, width=4)
l27 = line.new(bar_index-26, ss27[0], bar_index-27, ss27[0], color=color6, width=4)
l26 = line.new(bar_index-25, ss26[0], bar_index-26, ss26[0], color=color6, width=4)
line.delete(l30[1])
line.delete(l29[1])
line.delete(l28[1])
line.delete(l27[1])
line.delete(l26[1])
l25 = line.new(bar_index-24, ss25[0], bar_index-25, ss25[0], color=color5, width=4)
l24 = line.new(bar_index-23, ss24[0], bar_index-24, ss24[0], color=color5, width=4)
l23 = line.new(bar_index-22, ss23[0], bar_index-23, ss23[0], color=color5, width=4)
l22 = line.new(bar_index-21, ss22[0], bar_index-22, ss22[0], color=color5, width=4)
l21 = line.new(bar_index-20, ss21[0], bar_index-21, ss21[0], color=color5, width=4)
line.delete(l25[1])
line.delete(l24[1])
line.delete(l23[1])
line.delete(l22[1])
line.delete(l21[1])
l20 = line.new(bar_index-19, ss20[0], bar_index-20, ss20[0], color=color4, width=4)
l19 = line.new(bar_index-18, ss19[0], bar_index-19, ss19[0], color=color4, width=4)
l18 = line.new(bar_index-17, ss18[0], bar_index-18, ss18[0], color=color4, width=4)
l17 = line.new(bar_index-16, ss17[0], bar_index-17, ss17[0], color=color4, width=4)
l16 = line.new(bar_index-15, ss16[0], bar_index-16, ss16[0], color=color4, width=4)
line.delete(l20[1])
line.delete(l19[1])
line.delete(l18[1])
line.delete(l17[1])
line.delete(l16[1])
l15 = line.new(bar_index-14, ss15[0], bar_index-15, ss15[0], color=color3, width=4)
l14 = line.new(bar_index-13, ss14[0], bar_index-14, ss14[0], color=color3, width=4)
l13 = line.new(bar_index-12, ss13[0], bar_index-13, ss13[0], color=color3, width=4)
l12 = line.new(bar_index-11, ss12[0], bar_index-12, ss12[0], color=color3, width=4)
l11 = line.new(bar_index-10, ss11[0], bar_index-11, ss11[0], color=color3, width=4)
line.delete(l15[1])
line.delete(l14[1])
line.delete(l13[1])
line.delete(l12[1])
line.delete(l11[1])
l10 = line.new(bar_index-9, ss10[0], bar_index-10, ss10[0], color=color2, width=4)
l9 = line.new(bar_index-8, ss9[0], bar_index-9, ss9[0], color=color2, width=4)
l8 = line.new(bar_index-7, ss8[0], bar_index-8, ss8[0], color=color2, width=4)
l7 = line.new(bar_index-6, ss7[0], bar_index-7, ss7[0], color=color2, width=4)
l6 = line.new(bar_index-5, ss6[0], bar_index-6, ss6[0], color=color2, width=4)
line.delete(l10[1])
line.delete(l9[1])
line.delete(l8[1])
line.delete(l7[1])
line.delete(l6[1])
l5 = line.new(bar_index-4, ss5[0], bar_index-5, ss5[0], color=color1, width=4)
l4 = line.new(bar_index-3, ss4[0], bar_index-4, ss4[0], color=color1, width=4)
l3 = line.new(bar_index-2, ss3[0], bar_index-3, ss3[0], color=color1, width=4)
l2 = line.new(bar_index-1, ss2[0], bar_index-2, ss2[0], color=color1, width=4)
l1 = line.new(bar_index, ss1[0], bar_index-1, ss1[0], color=color1, width=4)
line.delete(l5[1])
line.delete(l4[1])
line.delete(l3[1])
line.delete(l2[1])
line.delete(l1[1])
//Line-Out switch and plot; display suppressed
float lineout = switch src2
"1-ShortestTF" => ss1
"2" => ss2
"3" => ss3
"4" => ss4
"5" => ss5
"6" => ss6
"7" => ss7
"8" => ss8
"9" => ss9
"10" => ss10
"11" => ss11
"12" => ss12
"13" => ss13
"14" => ss14
"15" => ss15
"16" => ss16
"17" => ss17
"18" => ss18
"19" => ss19
"20" => ss20
"21" => ss21
"22" => ss22
"23" => ss23
"24" => ss24
"25" => ss25
"26" => ss26
"27" => ss27
"28" => ss28
"29" => ss29
"30" => ss30
"31" => ss31
"32" => ss32
"33" => ss33
"34" => ss34
"35" => ss35
"36" => ss36
"37" => ss37
"38" => ss38
"39" => ss39
"40-LongestTF" => ss40
=>
float(na)
p1 = plot(lineout, "Line-Out", color=color.new(color.black, 100), display=display.none) |
Fed Funds Rate Indicator | https://www.tradingview.com/script/eFQOfrt5-Fed-Funds-Rate-Indicator/ | TradeAutomation | https://www.tradingview.com/u/TradeAutomation/ | 51 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version = 5
// Author = TradeAutomation
indicator("Fed Funds Rate", shorttitle="Fed Funds Rate", overlay=false)
//Selects Data Source
Rate = input.string(title="Data Source", defval="FRED:EFFR", options=["FRED:FEDFUNDS", "FRED:EFFR"], tooltip="FEDFUNDS Updates Monthly instead of daily, but has decades of additional historical data.")
//Pulls in Fed Rate Data
Resolution = input.timeframe(title="Resolution", defval="D")
FedRate = request.security(Rate, Resolution, close)
//Plots the Indicator
plot(FedRate, color = color.purple)
|
Plot futures volumes with index | https://www.tradingview.com/script/q4635s3N-Plot-futures-volumes-with-index/ | traderprb | https://www.tradingview.com/u/traderprb/ | 29 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © traderprb
//@version=5
indicator('FS vol', overlay=true, precision=0, scale=scale.none)
fs = input.symbol(title='Select futures symbol', defval='NSE:BANKNIFTY1!')
bullish = input.color(title='Color for bullish volume bar', defval=color.green)
bearish = input.color(title='Color for bullish volume bar', defval=color.red)
transp = input.int(title='Transparency of volumes', defval=70, minval=25, maxval=95)
f() => [open, high, low, close]
[o, h, l, c] = request.security(fs, timeframe.period, f())
//plotcandle(o, h, l, c, color=o > c ? color.red : color.green)
Volume(symbol) => request.security(symbol,timeframe.period,volume)
plot(Volume(fs), style=plot.style_columns, color=o > c ? color.new(bearish, transp) : color.new(bullish, transp), editable=false) |
Future Timevalue | https://www.tradingview.com/script/m5cOdJK3-Future-Timevalue/ | kajermail | https://www.tradingview.com/u/kajermail/ | 36 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © deejay
//@version=4
study("Future Timevalue", shorttitle="Future Timevalue", format=format.inherit, precision=4, overlay=false)
// Add the script's inputs
symbolFut= syminfo.tickerid + "1!"
maDuration = input(title="Moving Average", type=input.integer, defval=50)
gapFut = (security(symbolFut, '1', close))-(security(syminfo.tickerid, '1', close))
ma = sma(gapFut, maDuration)
hline(price=0, title="Median", color=color.white, linestyle=hline.style_dashed, linewidth=0)
// Plot a line
plot(series=gapFut, title="Timeval", color=color.red, style=plot.style_columns,linewidth=3)
plot(series=ma, color=color.blue,title="Timeval MA", style=plot.style_columns,linewidth=2)
|
R-Smart - Relative Strength | https://www.tradingview.com/script/FjGcOdGh-R-Smart-Relative-Strength/ | VebhaInvesting | https://www.tradingview.com/u/VebhaInvesting/ | 73 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Vebhainvest
//@version=4
//https://invest.webspacio.com, location to track screened stocks
study("R-Smart", shorttitle="R-SMART")
[macdLine, signalLine, histLine] = macd(close, 12, 26, 9)
[diplus,diminus,adx] = dmi(14,14)
// Calculating
adxRSI = rsi(adx,21) > 50 and adx > sma(adx,21) ? 1: -1
macdRSI = rsi(macdLine,21) > 50 ? 1: -1
//Input
source = input(title="Source", type=input.source, defval=close)
comparativeTickerId = input("NSE:NIFTY", type=input.symbol, title="Comparative Symbol")
length = input(63, type=input.integer, minval=1, title="Daily Period") //one quarter period
wLength = input(21, type=input.integer, minval=1, title="Wkly Period") //one quarter period
maRS = input(defval=5,type=input.integer,minval=1, title="Rel. Avg")
if timeframe.isweekly
length := wLength
//Set up
baseSymbol = security(syminfo.tickerid, timeframe.period, source)
comparativeSymbol = security(comparativeTickerId, timeframe.period, source)
//Calculations
res = 100*((baseSymbol/baseSymbol[length])/(comparativeSymbol/comparativeSymbol[length]) - 1)
resColor = res > 0 ? color.green : color.orange
maLine = sma(res,maRS)
//conditions to plot graph
// if RSI value of macdRSI and adxRSI > 0 then it's bullish signal else bearish signal
strongBull = (adxRSI > 0 and macdRSI > 0 and maLine > 0) ? 1 : -1 // green
weakBull = (adxRSI < 0 or macdRSI < 0) and maLine > 0 ? 1 : -1 // blue
strongBear = adxRSI < 0 and macdRSI < 0 and maLine < 0 ? 1 : -1 // red
weakBear = (adxRSI > 0 or macdRSI > 0) and maLine < 0 ? 1 : -1 // orange
strengthColor = if strongBull > 0
color.green
else if weakBull > 0
color.blue
else if strongBear > 0
color.red
else if weakBear > 0
color.orange
//Plot
plot(0, linewidth=2, color=color.gray, title="Zero Line")
plot(res, title="Relative Strength", linewidth=2, color= resColor,display=0)
plot(maLine, color= strengthColor , title="Relative Average", linewidth=2,style=plot.style_histogram)
|
Candle Classifier | https://www.tradingview.com/script/r0koywCm-Candle-Classifier/ | SamRecio | https://www.tradingview.com/u/SamRecio/ | 76 | study | 5 | MPL-2.0 | // 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("Candle Classifier", shorttitle = "🕯",overlay = true)
high_wick_per = input.float(20,minval = 0,title = "High Wick %", group = "Candle Classification")
body_per = input.float(60,minval = 0,title = "Body %", group = "Candle Classification")
low_wick_per = input.float(20,minval = 0,title = "Low Wick %", group = "Candle Classification")
variance = input.float(10,minval = 0, title = "Variance <->", group = "Candle Classification")
candle_color = input.string("All", title = "Candle Color", options = ["All","Green","Red"])
tl1 = input.string("bottom", title = "Table Location", options = ["top", "middle", "bottom"], group = "Display Settings", inline = "1")
tl2 = input.string("right", title = "", options = ["left", "center", "right"], group = "Display Settings", inline = "1")
def_color = input.color(color.white, title = "Default Display Color", group = "Display Settings", inline = "2")
tsize = input.string("normal", title = "Size", options = ["small", "normal", "large", "huge"], group = "Display Settings", inline = "2")
tab_loc = tl1+"_"+tl2
c_range = (high - low)
c_high = (high - math.max(open,close))/c_range * 100
c_body = (math.max(open,close) - math.min(open,close))/c_range * 100
c_low = (math.min(open,close) - low)/c_range * 100
c_color = math.max(open,close) == close?1:0
var_check(_src,_lvl) =>
var bool output = na
if variance > 0
output := _src > (_lvl - variance) and _src < (_lvl + variance)?true:false
else
output := _src == _lvl?true:false
color_check(_c) =>
_c == "All"?true:
_c == "Green" and c_color == 1?true:
_c == "Red" and c_color == 0? true:
false
high_check = var_check(c_high,high_wick_per)
body_check = var_check(c_body,body_per)
low_check = var_check(c_low,low_wick_per)
fire = high_check and body_check and low_check and color_check(candle_color)
o_color = candle_color == "All" ? def_color:candle_color == "Green"?color.green:candle_color == "Red"?color.red:na
plotshape(fire, style = shape.diamond,size = size.small, color = color.new(def_color,20), editable = false)
plot(c_high, color = color.new(def_color,100), editable = false)
plot(c_body, color = color.new(def_color,100), editable = false)
plot(c_low, color = color.new(def_color,100), editable = false)
t1 = table.new(tab_loc,2,1)
if variance > 0
table.cell(t1,0,0,text =
"|\n" +
"█\n" +
"|\n"
, text_color = o_color, text_size = tsize, text_halign = text.align_center)
table.cell(t1,1,0,text =
str.tostring(high_wick_per - variance < 0?0:high_wick_per - variance) + "% - " + str.tostring(high_wick_per + variance) + "%\n" +
str.tostring(body_per - variance < 0?0:body_per - variance) + "% - " + str.tostring(body_per + variance) + "%\n" +
str.tostring(low_wick_per - variance < 0?0:low_wick_per - variance) + "% - " + str.tostring(low_wick_per + variance) + "%"
, text_color = o_color, text_size = tsize, text_halign = text.align_left)
if variance == 0
table.cell(t1,0,0,text =
"|\n" +
"█\n" +
"|\n"
, text_color = o_color, text_size = tsize, text_halign = text.align_center)
table.cell(t1,1,0,text =
str.tostring(high_wick_per) + "%\n" +
str.tostring(body_per) + "%\n" +
str.tostring(low_wick_per) + "%"
, text_color = o_color, text_size = tsize, text_halign = text.align_left)
alertcondition(fire, title = "Candle Found", message = "Candle Found!") |
Study forloop Star Triangle | https://www.tradingview.com/script/09qMWBw9-Study-forloop-Star-Triangle/ | hapharmonic | https://www.tradingview.com/u/hapharmonic/ | 12 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hapharmonic
//@version=5
//'Study forloop' pinescript Program to print star Triangle
//------Output------
// * |
// * * |
// * * * |
// * * * * |
// * * * * * |
//------------------
indicator("Study forloop Star Triangle",overlay=true)
rows = input.int(15,'Enter number of rows:',maxval=51) //The number of rows displayed
i_tablePosition = input.string(title="Position", defval=position.middle_center, group="Table", options=[position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right])
in_ = array.new_string(1)
//define a function to print star shape
star_pattern4(n) =>
textin = ""
for i = 0 to n-1 //Use outer for loop for rows
for k=0 to i
textin := textin+'* ' //Store each star in the variable "textin"
textin := textin+'\n' //At the end of the forloop, start a new line. End of line after each row
array.set(in_,0,textin) //The function sets the value of the element at the specified index. to store the characters
star_pattern4(rows)
////==show label format==
// l1 = label.new(bar_index+5,close,text=array.get(in_,0),color=color.new(color.red,100),textcolor=color.white)
// label.delete(l1[1])
//Show data within an array.
for i = 0 to 1
var table tdSetupTable = table.new(i_tablePosition, 1, 2, border_width=0)
if i == 0
table.cell(tdSetupTable, 0, 0, array.get(in_,0), text_color = color.white,text_valign=text.align_center)
else
T = "'Study forloop' pinescript Program to print star Triangle"
table.cell(tdSetupTable, 0, 1, T, text_color = color.yellow,text_valign=text.align_center,text_size=size.large)
|
BTC HASHRATE DROP: Onchain | https://www.tradingview.com/script/Ybgr2nFz-BTC-HASHRATE-DROP-Onchain/ | cryptoonchain | https://www.tradingview.com/u/cryptoonchain/ | 63 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MJShahsavar
//@version=5
indicator("BTC HASHRATE DROP: Onchain", timeframe = "D")
//@version=5
R = input.symbol("BTC_HASHRATE", "Symbol")
r = request.security(R, 'D', close)
D = ta.sma(r, 50)
M = ta.rsi(D, 14)
h1=hline (80)
h2= hline (20)
h3= hline (50)
h4= hline (120)
h5 = hline (140)
hashColor = M >= 80 ? color.blue : M <= 20 ? color.red : color.maroon
fill (h5, h4, hashColor)
plot (M, "hashColor" , M >= 80 ? color.blue : M <= 20 ? color.red : color.maroon, linewidth=1)
|
Candle relative power | https://www.tradingview.com/script/FgLj3neN-Candle-relative-power/ | AliSignals | https://www.tradingview.com/u/AliSignals/ | 38 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AliSignals
//@version=5
indicator("Candle relative power", timeframe="")
Length = input.int(1)
Shadowindex = input.float(0.5, title= "Shadow index")
AverageCriteria = input.int(24, title= "Average Criteria")
// Calculating Close, Open, High and Low of the integrated candles
CO = close-open[Length]
H = ta.highest(high,Length)
L = ta.lowest(low,Length)
// Calculating Highest and Lowest of closes and opens of the integrated candles
maxC = ta.highest(close,Length)
maxO = ta.highest(open,Length)
minC = ta.lowest(close,Length)
minO = ta.lowest(open,Length)
maxCO = math.max(maxC,maxO)
minCO = math.min(minC,minO)
//calculating TR of of the integrated candles
HL = H-L
HC = math.abs(H-close[Length])
LC = math.abs(L-close[Length])
TR = math.max(HL,HC,LC)
ATR = ta.sma(TR,AverageCriteria*Length)
// Calculating shadows
TSH = H-maxCO
BSH = minCO-L
// Calculating candle power
CP = (CO+BSH-TSH)/ATR
V = math.sum(volume,Length)
VP = CP*V/ta.sma(V,AverageCriteria*Length)
plot(CP, title= "CP")
plot(VP, color=color.yellow, title= "VP")
hline(3)
hline(-3)
|
Kasper index | https://www.tradingview.com/script/fUqLBwyf-Kasper-index/ | mr2j | https://www.tradingview.com/u/mr2j/ | 5 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mr2j
//@version=5
indicator("Kasper index")
period = input(title="Period", defval=14)
smooth = input(title="Smooth", defval=3)
crv_close = request.security(symbol="BINANCE:CRVUSDT", timeframe=timeframe.period, expression=close)
ada_close = request.security(symbol="BINANCE:ADAUSDT", timeframe=timeframe.period, expression=close)
dash_close = request.security(symbol="BINANCE:DASHUSDT", timeframe=timeframe.period, expression=close)
sol_close = request.security(symbol="BINANCE:SOLUSDT", timeframe=timeframe.period, expression=close)
doge_close = request.security(symbol="BINANCE:DOGEUSDT", timeframe=timeframe.period, expression=close)
xtz_close = request.security(symbol="BINANCE:XTZUSDT", timeframe=timeframe.period, expression=close)
crv_rsi = ta.rsi(crv_close, period)
ada_rsi = ta.rsi(ada_close, period)
dash_rsi = ta.rsi(dash_close, period)
sol_rsi = ta.rsi(sol_close, period)
doge_rsi = ta.rsi(doge_close, period)
xtz_rsi = ta.rsi(xtz_close, period)
index = (crv_rsi + ada_rsi + dash_rsi + sol_rsi + doge_rsi + xtz_rsi) / 6
plot(ta.sma(crv_rsi, smooth), title='CRV', color=color.new(color.red, 50))
plot(ta.sma(ada_rsi, smooth), title='ADA', color=color.new(color.blue, 50))
plot(ta.sma(dash_rsi, smooth), title='DASH', color=color.new(color.green, 50))
plot(ta.sma(sol_rsi, smooth), title='SOL', color=color.new(color.yellow, 50))
plot(ta.sma(doge_rsi, smooth), title='DOGE', color=color.new(color.orange, 50))
plot(ta.sma(xtz_rsi, smooth), title='XTZ', color=color.new(color.white, 50))
plot(ta.sma(index, smooth), title='INDEX', color=color.new(color.lime, 0), linewidth=3)
|
KINSKI Multi Trend Oscillator | https://www.tradingview.com/script/fdJ6Zhhr/ | KINSKI | https://www.tradingview.com/u/KINSKI/ | 169 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KINSKI
//@version=5
indicator('KINSKI Multi Trend Oscillator', shorttitle='Multi Trend Oscillator', format=format.price, precision=2, overlay=false)
//************ Colors
color valColorsUpTrendHistogram = #007007, color valColorsUpTrendStrongHistogram = #00FF11, color valColorsUpWeakHistogram = #007a08, color valColorsUpTrendStrongHintHistogram = #e8be00
color valColorsDownTrendHistogram = #8A0002, color valColorsDownTrendStrongHistogram = #FF0004, color valColorsDownTrendWeakHistogram = #750001
color valColorsUpTrend = #003307, color valColorsUpTrendStrong = #00610d, color valColorsUpTrendStrongHint = #615100
color valColorsDownTrend = #330000, color valColorsDownTrendStrong = #610000
color valColorsNeutral = #4f4f4f, color valColorMA = #9900FF
//********** Functions
_funcPercent(_val, _different) =>
100 * _val / _different
// Calculate Uptrend/Downtrend Volume
_funcRate(_cond, _cwT, _cwB, _cwBody) =>
_tmp = 0.5 * (_cwT + _cwB + (_cond ? 2 * _cwBody : 0)) / (_cwT + _cwB + _cwBody)
na(_tmp) ? 0.5 : _tmp
// Calculate Regression Slope for Uptrend/Downtrend Volumes
_funcTrend(_len, _cwT, _cwB, _cwBody) =>
_tmpUp = volume * _funcRate(open <= close, _cwT, _cwB, _cwBody)
_tmpDown = volume * _funcRate(open > close, _cwT, _cwB, _cwBody)
volumeUp = ta.linreg(_tmpUp, _len, 0) - ta.linreg(_tmpUp, _len, 1)
volumeDown = ta.linreg(_tmpDown, _len, 0) - ta.linreg(_tmpDown, _len, 1)
[volumeUp, volumeDown]
_funcGetBuySell(_val, _levelOverBought, _levelOverSold) =>
tmpIsUptrend = _val > _val[1]
tmpRuleBuy = (ta.crossover(_val, _levelOverBought) or (_val < _levelOverSold or _val < _levelOverBought)) and (tmpIsUptrend)
tmpRuleSell = (ta.crossunder(_val, _levelOverBought) or (_val >= _levelOverBought)) and not tmpIsUptrend
[tmpRuleBuy, tmpRuleSell, tmpIsUptrend]
_funcCalcHistogramColor(_val) =>
conditionColors_1 = _val > nz(_val[1]) ? valColorsUpTrendStrongHistogram : valColorsUpTrendHistogram
conditionColors_2 = _val < nz(_val[1]) ? valColorsDownTrendStrongHistogram : valColorsDownTrendHistogram
(_val == -0.00 or _val == 0.00) ? valColorsNeutral : _val > 0 ? conditionColors_1 : conditionColors_2
_funcCalcRating(_buy, _sell) =>
int tmpRating = 0
color tmpRatingColorTable = valColorsNeutral
string tmpRatingStatus = "Neutral"
if _buy
tmpRating := 1
tmpRatingStatus := "Uptrend"
tmpRatingColorTable := valColorsUpTrend
else if _sell
tmpRating := 0
tmpRatingStatus := "Downtrend"
tmpRatingColorTable := valColorsDownTrend
[tmpRating, tmpRatingStatus, tmpRatingColorTable]
_funcCalcRatingTotalCompare(_ratingMaxCount, _ratingThresholdSellStrong, _ratingThresholdNeutralStart, _ratingThresholdNeutralEnd, _ratingThresholdBuyStrong) =>
_tmpCompareSellStrong = _ratingMaxCount * _ratingThresholdSellStrong
_tmpCompareMidStart = _ratingMaxCount * _ratingThresholdNeutralStart
_tmpCompareMidEnd = _ratingMaxCount * _ratingThresholdNeutralEnd
_tmpCompareBuyStrong = _ratingMaxCount * _ratingThresholdBuyStrong
[_tmpCompareSellStrong, _tmpCompareMidStart, _tmpCompareMidEnd, _tmpCompareBuyStrong]
_funcCalcRatingTotalStatus(_rating, _ratingMaxCount, _histogram, _ratingThresholdSellStrong, _ratingThresholdNeutralStart, _ratingThresholdNeutralEnd, _ratingThresholdBuyStrong) =>
[_tmpCompareSellStrong, _tmpCompareMidStart, _tmpCompareMidEnd, _tmpCompareBuyStrong] = _funcCalcRatingTotalCompare(_ratingMaxCount, _ratingThresholdSellStrong, _ratingThresholdNeutralStart, _ratingThresholdNeutralEnd, _ratingThresholdBuyStrong)
color tmpRatingColor = valColorsNeutral
color tmpRatingColorTable = valColorsNeutral
string tmpRatingStatus = "Neutral"
float prevRating = nz(_rating[1])
bool isInNeutralRange = _rating >= _tmpCompareMidStart and _rating <= _tmpCompareMidEnd
if isInNeutralRange
tmpRatingStatus := tmpRatingStatus
tmpRatingColorTable := tmpRatingColorTable
tmpRatingColor := tmpRatingColor
else if _rating >= _tmpCompareBuyStrong and _rating > _tmpCompareMidEnd
tmpPrevSame = prevRating >= _tmpCompareBuyStrong
tmpRatingStatus := tmpPrevSame ? "Strong Uptrend\nBut Downtrend coming" : "Strong Uptrend"
tmpRatingColorTable := tmpPrevSame ? valColorsUpTrendStrongHint : valColorsUpTrendStrong
tmpRatingColor := tmpPrevSame ? valColorsUpTrendStrongHintHistogram : valColorsUpTrendStrongHistogram
else if _rating < _tmpCompareBuyStrong and _rating > _tmpCompareMidEnd
tmpRatingStatus := "Uptrend"
tmpRatingColorTable := valColorsUpTrend
tmpRatingColor := valColorsUpTrendHistogram
else if _rating <= _tmpCompareSellStrong and _rating < _tmpCompareMidStart
tmpRatingStatus := "Strong Downtrend"
tmpRatingColorTable := valColorsDownTrendStrong
tmpRatingColor := valColorsDownTrendStrongHistogram
else if _rating > _tmpCompareSellStrong and _rating < _tmpCompareMidStart
tmpRatingStatus := "Downtrend"
tmpRatingColorTable := valColorsDownTrend
tmpRatingColor := valColorsDownTrendHistogram
[tmpRatingColor, tmpRatingColorTable, tmpRatingStatus]
// Smoothed Moving Average (SMMA)
_funcSMMA(_src, _len) =>
tmpSMA = ta.sma(_src, _len)
tmpVal = 0.0
na(tmpVal[1]) ? tmpSMA : (tmpVal[1] * (_len - 1) + _src) / _len
// Triple EMA (TEMA)
_funcTEMA(_src, _len) =>
ema1 = ta.ema(_src, _len)
ema2 = ta.ema(ema1, _len)
ema3 = ta.ema(ema2, _len)
3 * (ema1 - ema2) + ema3
// Double Expotential Moving Average (DEMA)
_funcDEMA(_src, _len) =>
2 * ta.ema(_src, _len) - ta.ema(ta.ema(_src, _len), _len)
// Exponential Hull Moving Average (EHMA)
_funcEHMA(_src, _len) =>
tmpVal = math.max(2, _len)
ta.ema(2 * ta.ema(_src, tmpVal / 2) - ta.ema(_src, tmpVal), math.round(math.sqrt(tmpVal)))
// Kaufman's Adaptive Moving Average (KAMA)
_funcKAMA(_src, _len) =>
tmpVal = 0.0
sum_1 = math.sum(math.abs(_src - _src[1]), _len)
sum_2 = math.sum(math.abs(_src - _src[1]), _len)
nz(tmpVal[1]) + math.pow((sum_1 != 0 ? math.abs(_src - _src[_len]) / sum_2 : 0) * (0.666 - 0.0645) + 0.0645, 2) * (_src - nz(tmpVal[1]))
// Variable Index Dynamic Average (VIDYA)
_funcVIDYA(_src, _len) =>
_diff = ta.change(_src)
_uppperSum = math.sum(_diff > 0 ? math.abs(_diff) : 0, _len)
_lowerSum = math.sum(_diff < 0 ? math.abs(_diff) : 0, _len)
_chandeMomentumOscillator = (_uppperSum - _lowerSum) / (_uppperSum + _lowerSum)
_factor = 2 / (_len + 1)
tmpVal = 0.0
_src * _factor * math.abs(_chandeMomentumOscillator) + nz(tmpVal[1]) * (1 - _factor * math.abs(_chandeMomentumOscillator))
// Coefficient of Variation Weighted Moving Average (COVWMA)
_funcCOVWMA(_src, _len) =>
_coefficientOfVariation = ta.stdev(_src, _len) / ta.sma(_src, _len)
_cw = _src * _coefficientOfVariation
math.sum(_cw, _len) / math.sum(_coefficientOfVariation, _len)
// Fractal Adaptive Moving Average (FRAMA)
_funcFRAMA(_src, _len) =>
_coefficient = -4.6
_n3 = (ta.highest(high, _len) - ta.lowest(low, _len)) / _len
_hd2 = ta.highest(high, _len / 2)
_ld2 = ta.lowest(low, _len / 2)
_n2 = (_hd2 - _ld2) / (_len / 2)
_n1 = (_hd2[_len / 2] - _ld2[_len / 2]) / (_len / 2)
_dim = _n1 > 0 and _n2 > 0 and _n3 > 0 ? (math.log(_n1 + _n2) - math.log(_n3)) / math.log(2) : 0
_alpha = math.exp(_coefficient * (_dim - 1))
_sc = _alpha < 0.01 ? 0.01 : _alpha > 1 ? 1 : _alpha
ta.cum(1) <= 2 * _len ? _src : _src * _sc + nz(_src[1]) * (1 - _sc)
// Karobein
_funcKarobein(_src, _len) =>
tmpMA = ta.ema(_src, _len)
tmpUpper = ta.ema(tmpMA < tmpMA[1] ? tmpMA/tmpMA[1] : 0, _len)
tmpLower = ta.ema(tmpMA > tmpMA[1] ? tmpMA/tmpMA[1] : 0, _len)
tmpRescaleResult = (tmpMA/tmpMA[1]) / (tmpMA/tmpMA[1] + tmpLower)
(2*((tmpMA/tmpMA[1]) / (tmpMA/tmpMA[1] + tmpRescaleResult * tmpUpper)) - 1) * 100
// RSX based Noise Remover based Noise Remover
_funcRemoveNoise(_src, _len) =>
f8 = 100 * _src
f10 = nz(f8[1])
v8 = f8 - f10
f18 = 3 / (_len + 2)
f20 = 1 - f18
f28 = 0.0
f28 := f20 * nz(f28[1]) + f18 * v8
f30 = 0.0
f30 := f18 * f28 + f20 * nz(f30[1])
vC = f28 * 1.5 - f30 * 0.5
f38 = 0.0
f38 := f20 * nz(f38[1]) + f18 * vC
f40 = 0.0
f40 := f18 * f38 + f20 * nz(f40[1])
v10 = f38 * 1.5 - f40 * 0.5
f48 = 0.0
f48 := f20 * nz(f48[1]) + f18 * v10
f50 = 0.0
f50 := f18 * f48 + f20 * nz(f50[1])
v14 = f48 * 1.5 - f50 * 0.5
f58 = 0.0
f58 := f20 * nz(f58[1]) + f18 * math.abs(v8)
f60 = 0.0
f60 := f18 * f58 + f20 * nz(f60[1])
v18 = f58 * 1.5 - f60 * 0.5
f68 = 0.0
f68 := f20 * nz(f68[1]) + f18 * v18
f70 = 0.0
f70 := f18 * f68 + f20 * nz(f70[1])
v1C = f68 * 1.5 - f70 * 0.5
f78 = 0.0
f78 := f20 * nz(f78[1]) + f18 * v1C
f80 = 0.0
f80 := f18 * f78 + f20 * nz(f80[1])
v20 = f78 * 1.5 - f80 * 0.5
f88_ = 0.0
f90_ = 0.0
f88 = 0.0
f90_ := nz(f90_[1]) == 0 ? 1 : nz(f88[1]) <= nz(f90_[1]) ? nz(f88[1]) + 1 : nz(f90_[1]) + 1
f88 := nz(f90_[1]) == 0 and _len - 1 >= 5 ? _len - 1 : 5
f0 = f88 >= f90_ and f8 != f10 ? 1 : 0
f90 = f88 == f90_ and f0 == 0 ? 0 : f90_
v4_ = f88 < f90 and v20 > 0 ? (v14 / v20 + 1) * 50 : 50
v4_ > 100 ? 100 : v4_ < 0 ? 0 : v4_
// calculate the moving average with the transferred settings
_funcCalcMA(_type, _src, _len) =>
float ma = switch _type
"COVWMA" => _funcCOVWMA(_src, _len)
"DEMA" => _funcDEMA(_src, _len)
"EMA" => ta.ema(_src, _len)
"EHMA" => _funcEHMA(_src, _len)
"HMA" => ta.hma(_src, _len)
"KAMA" => _funcKAMA(_src, _len)
"RMA" => ta.rma(_src, _len)
"RSX based Noise Remover" => _funcRemoveNoise(_src, _len)
"SMA" => ta.sma(_src, _len)
"SMMA" => _funcSMMA(_src, _len)
"TEMA" => _funcTEMA(_src, _len)
"FRAMA" => _funcFRAMA(_src, _len)
"VWMA" => ta.vwma(_src, _len)
"VIDYA" => _funcVIDYA(_src, _len)
"WMA" => ta.wma(_src, _len)
"Karobein" => _funcKarobein(_src, _len)
=>
float(na)
_funcGetVal(_val, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased) =>
tmpVal = _enableStochasticBased ? ta.sma(ta.stoch(_val, _val, _val, _len), 3) : _val
tmpValAlternative = _smoothingType != 'DISABLED' ? _funcCalcMA(_smoothingType, tmpVal, _smoothingPeriod) : tmpVal
_smoothingType != 'DISABLED' ? tmpValAlternative : tmpVal
_funcGetFinalVal(_src, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold) =>
tmpValFinal = _funcGetVal(_src, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased)
[tmpRuleBuy, tmpRuleSell, tmpIsUptrend] = _funcGetBuySell(tmpValFinal, levelOverBought, levelOverSold)
[tmpRating, tmpRatingStatus, tmpRatingColorTable] = _funcCalcRating(tmpRuleBuy, tmpRuleSell)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable]
_funcGetFinalValNullLine(_src, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased) =>
tmpValFinal = _funcGetVal(_src, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased)
tmpIsUptrend = tmpValFinal > tmpValFinal[1]
tmpRuleBuy = tmpIsUptrend and (ta.crossover(tmpValFinal, 0) or (tmpValFinal >= 0))
tmpRuleSell = not tmpIsUptrend and (ta.crossunder(tmpValFinal, 0) or (tmpValFinal < 0))
[tmpRating, tmpRatingStatus, tmpRatingColorTable] = _funcCalcRating(tmpRuleBuy, tmpRuleSell)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable]
// Average Directional Index (ADX)
_funcADX(_len, _smoothingType, _smoothingPeriod, _enableStochasticBased) =>
float adxValue = na, float adxPlus = na, float adxMinus = na
[plus, minus, value] = ta.dmi(_len, _len)
adxValue := value
adxPlus := plus
adxMinus := minus
tmpTA = math.abs(adxPlus - adxMinus) / (adxValue == 0 ? 1 : adxValue)
tmpValFinal = 100 * _funcGetVal(tmpTA, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased)
tmpIsUptrend = tmpValFinal > tmpValFinal[1]
tmpRuleBuy = tmpIsUptrend and (tmpValFinal > 20 and adxPlus[1] < adxMinus[1] and adxPlus > adxMinus)
tmpRuleSell = not tmpIsUptrend and (tmpValFinal > 20 and adxPlus[1] > adxMinus[1] and adxPlus < adxMinus)
[tmpRating, tmpRatingStatus, tmpRatingColorTable] = _funcCalcRating(tmpRuleBuy, tmpRuleSell)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable]
// Awesome Oscillator
_funcAwesomeOscillator(_src, _lenFast, _lenSlow, _smoothingType, _smoothingPeriod, _enableStochasticBased) =>
tmpTA = ta.sma(_src, _lenFast) - ta.sma(_src, _lenSlow)
tmpValFinal = _funcGetVal(tmpTA, _lenFast, _smoothingType, _smoothingPeriod, _enableStochasticBased)
tmpIsUptrend = tmpValFinal > tmpValFinal[1]
tmpRuleBuy = ta.crossover(tmpValFinal, 0) or (tmpValFinal > 0 and tmpValFinal[1] > 0 and tmpValFinal > tmpValFinal[1] and tmpValFinal[2] > tmpValFinal[1])
tmpRuleSell = ta.crossunder(tmpValFinal, 0) or (tmpValFinal < 0 and tmpValFinal[1] < 0 and tmpValFinal < tmpValFinal[1] and tmpValFinal[2] < tmpValFinal[1])
[tmpRating, tmpRatingStatus, tmpRatingColorTable] = _funcCalcRating(tmpRuleBuy, tmpRuleSell)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable]
// Ultimate Oscillator
_funcUltimateOscillator(_src, _lenShort, _lenMid, _lenLong, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold) =>
tmpNewSrc = _src[1] < low ? _src[1]: low
tmpVal1 = math.sum(ta.tr, _lenShort)
tmpVal2 = math.sum(ta.tr, _lenMid)
tmpVal3 = math.sum(ta.tr, _lenLong)
tmpVal4 = math.sum(_src - tmpNewSrc, _lenShort)
tmpVal5 = math.sum(_src - tmpNewSrc, _lenMid)
tmpVal6 = math.sum(_src - tmpNewSrc, _lenLong)
float tmpTA = na
if tmpVal1 != 0 and tmpVal2 != 0 and tmpVal3 != 0
var0 = _lenLong / _lenShort
var1 = _lenLong / _lenMid
tmpVal7 = (tmpVal4 / tmpVal1) * (var0)
tmpVal8 = (tmpVal5 / tmpVal2) * (var1)
tmpVal9 = (tmpVal6 / tmpVal3)
tmpTA := (tmpVal7 + tmpVal8 + tmpVal9) / (var0 + var1 + 1)
tmpTA := tmpTA * 100
tmpValFinal = _funcGetVal(tmpTA, _lenShort, _smoothingType, _smoothingPeriod, _enableStochasticBased)
[tmpRuleBuy, tmpRuleSell, tmpIsUptrend] = _funcGetBuySell(tmpValFinal, levelOverBought, levelOverSold)
[tmpRating, tmpRatingStatus, tmpRatingColorTable] = _funcCalcRating(tmpRuleBuy, tmpRuleSell)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable]
// Volume Regression Trend (VRT)
_funcVRT(_src, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased) =>
// determine the price of the regression slope
slopePrice = ta.linreg(_src, _len, 0) - ta.linreg(_src, _len, 1)
slopePriceFinal = _smoothingType == 'DISABLED' ? slopePrice : _funcCalcMA(_smoothingType, slopePrice, _smoothingPeriod)
// get sizes of the candles
candleWidthTop = high - math.max(open, close)
candleWidthBottom = math.min(open, close) - low
candleWidthBody = math.abs(close - open)
// determine upward and downward movement of the regression slope
[volumeUp, volumeDown] = _funcTrend(_len, candleWidthTop, candleWidthBottom, candleWidthBody)
// alternative histogram color
color tmpRatingColorHistogram = slopePriceFinal > 0 ? volumeUp > 0 ? volumeUp > volumeDown ? valColorsUpTrendStrongHistogram : valColorsUpTrendHistogram : valColorsUpWeakHistogram : slopePriceFinal < 0 ? volumeDown > 0 ? volumeUp < volumeDown ? valColorsDownTrendStrongHistogram : valColorsDownTrendHistogram : valColorsDownTrendWeakHistogram : valColorsNeutral
tmpTA = slopePriceFinal * _len
tmpValFinal = _funcGetVal(tmpTA, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased)
tmpIsUptrend = tmpValFinal > tmpValFinal[1]
tmpRuleBuy = tmpIsUptrend and (slopePriceFinal > 0 and volumeUp > 0 and volumeUp > volumeDown)
tmpRuleSell = not tmpIsUptrend and (slopePriceFinal < 0 and volumeDown > 0 and volumeUp < volumeDown)
[tmpRating, tmpRatingStatus, tmpRatingColorTable] = _funcCalcRating(tmpRuleBuy, tmpRuleSell)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable, tmpRatingColorHistogram]
_funcControl(_src, _timeframe, _type, _period) =>
tmpValFinal = request.security(syminfo.tickerid, _timeframe, _funcCalcMA(_type, _src, _period))
tmpIsUptrend = (tmpValFinal > tmpValFinal[1]) and (_src > tmpValFinal)
[tmpRating, tmpRatingStatus, tmpRatingColorTable] = _funcCalcRating(tmpIsUptrend, (not tmpIsUptrend))
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable]
// Williams Percent Range
_funcWPR(_len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold) =>
tmpTA = ta.wpr(_len)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable] = _funcGetFinalVal(tmpTA, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold)
_funcMomentum(_src, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased) =>
tmpTA = ta.mom(_src, _len)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable] = _funcGetFinalValNullLine(tmpTA, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased)
// Detrended Price Oscillator (DPO)
_funcDPO(_src, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased) =>
tmpLookBarsBack = _len / 2 + 1
tmpSMA = ta.sma(_src, _len)
tmpTA = _src - tmpSMA[tmpLookBarsBack]
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable] = _funcGetFinalValNullLine(tmpTA, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased)
// Klinger Oscillator
_funcKlinger(_src, _lenFast, _lenSlow, _smoothingType, _smoothingPeriod, _enableStochasticBased) =>
tmpVolumeForce = ta.change(_src) >= 0 ? volume : -volume
tmpTA = ta.ema(tmpVolumeForce, _lenFast) - ta.ema(tmpVolumeForce, _lenSlow)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable] = _funcGetFinalValNullLine(tmpTA, _lenFast, _smoothingType, _smoothingPeriod, _enableStochasticBased)
// Chaikin Oscillator (CO)
_funcCO(_src, _lenFast, _lenSlow, _smoothingType, _smoothingPeriod, _enableStochasticBased) =>
tmpTA = ta.ema(ta.accdist, _lenFast) - ta.ema(ta.accdist, _lenSlow)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable] = _funcGetFinalValNullLine(tmpTA, _lenFast, _smoothingType, _smoothingPeriod, _enableStochasticBased)
// Chande Momentum Oscillator (CMO)
_funcCMO(_src, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold) =>
_diff = ta.change(_src)
m1 = _diff >= 0.0 ? _diff : 0.0
m2 = _diff >= 0.0 ? 0.0 : -_diff
sm1 = math.sum(m1, _len)
sm2 = math.sum(m2, _len)
tmpTA = _funcPercent(sm1-sm2, sm1+sm2)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable] = _funcGetFinalVal(tmpTA, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold)
_funcRSI(_src, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold) =>
tmpTA = ta.rsi(_src, _len)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable] = _funcGetFinalVal(tmpTA, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold)
_funcRSX(_src, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold) =>
tmpTA = _funcRemoveNoise(_src, _len)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable] = _funcGetFinalVal(tmpTA, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold)
// Money Flow Index (MFI)
_funcMFI(_src, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold) =>
tmpChange = ta.change(_src)
tmpMoneyFlowRatio = math.sum(volume * (tmpChange <= 0 ? 0 : _src), _len)
tmpMoneyFlowIndex = math.sum(volume * (tmpChange >= 0 ? 0 : _src), _len)
tmpTA = 100.0 - 100.0 / (1.0 + tmpMoneyFlowRatio / tmpMoneyFlowIndex)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable] = _funcGetFinalVal(tmpTA, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold)
// Commodity Channel Index (CCI)
_funcCCI(_src, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold) =>
tmpTA = ta.cci(_src, _len)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable] = _funcGetFinalVal(tmpTA, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold)
_funcLaguerreFilter(_src, _len, _gammaFactor, _smoothingFactor, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold) =>
_tmpGamma = 1 - _gammaFactor
_tmpFilter_0 = 0.0
_tmpFilter_0 := ((1 - _tmpGamma) * _src) + (_tmpGamma * nz(_tmpFilter_0[1]))
_tmpFilter_1 = 0.0
_tmpFilter_1 := (-_tmpGamma * _tmpFilter_0) + nz(_tmpFilter_0[1]) + (_tmpGamma * nz(_tmpFilter_1[1]))
_tmpFilter_2 = 0.0
_tmpFilter_2 := (-_tmpGamma * _tmpFilter_1) + nz(_tmpFilter_1[1]) + (_tmpGamma * nz(_tmpFilter_2[1]))
_tmpFilter_3 = 0.0
_tmpFilter_3 := (-_tmpGamma * _tmpFilter_2) + nz(_tmpFilter_2[1]) + (_tmpGamma * nz(_tmpFilter_3[1]))
_tmpFilterUpTrend = (_tmpFilter_0 > _tmpFilter_1 ? _tmpFilter_0 - _tmpFilter_1 : 0) + (_tmpFilter_1 > _tmpFilter_2 ? _tmpFilter_1 - _tmpFilter_2 : 0) + (_tmpFilter_2 > _tmpFilter_3 ? _tmpFilter_2 - _tmpFilter_3 : 0)
_tmpFilterDownTrend = (_tmpFilter_0 < _tmpFilter_1 ? _tmpFilter_1 - _tmpFilter_0 : 0) + (_tmpFilter_1 < _tmpFilter_2 ? _tmpFilter_2 - _tmpFilter_1 : 0) + (_tmpFilter_2 < _tmpFilter_3 ? _tmpFilter_3 - _tmpFilter_2 : 0)
_tmpFilterTemp = (_tmpFilterUpTrend + _tmpFilterDownTrend == 0) ? -1 : (_tmpFilterUpTrend + _tmpFilterDownTrend)
_tmpFilterSmoothed = _smoothingFactor > 1 ? ta.ema(_tmpFilterTemp, _smoothingFactor) : _tmpFilterTemp
_tmpFilterVal = _tmpFilterSmoothed == -1 ? 0 : (_tmpFilterUpTrend / _tmpFilterSmoothed)
tmpTA = (100 * _tmpFilterVal)
[tmpValFinal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable] = _funcGetFinalVal(tmpTA, _len, _smoothingType, _smoothingPeriod, _enableStochasticBased, levelOverBought, levelOverSold)
_funcHistogramMACD(_src, _fastType, _fastPeriod, _slowType, _slowPeriod, _signalType, _signalPeriod, _enableStochasticBased) =>
tmpFastMA = _funcCalcMA(_fastType, _src, _fastPeriod)
tmpSlowMA = _funcCalcMA(_slowType, _src, _slowPeriod)
tmpMACD = tmpFastMA - tmpSlowMA
tmpTA = _funcCalcMA(_signalType, tmpMACD, _signalPeriod)
tmpHistogramSignal = _enableStochasticBased ? ta.sma(ta.stoch(tmpTA, tmpTA, tmpTA, _signalPeriod), 3) : tmpTA
tmpIsUptrend = tmpHistogramSignal > tmpHistogramSignal[1]
tmpHistogram = tmpMACD - tmpHistogramSignal
tmpRuleBuy = tmpIsUptrend and (tmpMACD > tmpHistogramSignal)
tmpRuleSell = not tmpIsUptrend and (tmpMACD < tmpHistogramSignal)
[tmpRating, tmpRatingStatus, tmpRatingColorTable] = _funcCalcRating(tmpRuleBuy, tmpRuleSell)
tmpAdvancedRatingColor = _funcCalcHistogramColor(tmpHistogram)
[tmpHistogramSignal, tmpRating, tmpRatingStatus, tmpIsUptrend, tmpRatingColorTable, tmpHistogram, tmpAdvancedRatingColor]
_funcHistogramRatingTotal(_type, _len, _rating, _ratingMaxCount, _ratingThresholdSellStrong, _ratingThresholdNeutralStart, _ratingThresholdNeutralEnd, _ratingThresholdBuyStrong) =>
tmpHistogramSignal = _funcCalcMA(_type, _rating, _len)
tmpHistogram = _rating - tmpHistogramSignal
[tmpAdvancedRatingColor, tmpAdvancedRatingColorTable, tmpAdvancedRatingStatus] = _funcCalcRatingTotalStatus(_rating, _ratingMaxCount, tmpHistogram, _ratingThresholdSellStrong, _ratingThresholdNeutralStart, _ratingThresholdNeutralEnd, _ratingThresholdBuyStrong)
[tmpHistogram, tmpAdvancedRatingColor, tmpAdvancedRatingColorTable, tmpAdvancedRatingStatus]
_funcHistogram(_type, _src, _len) =>
tmpHistogramSignal = _funcCalcMA(_type, _src, _len)
tmpHistogram = _src - tmpHistogramSignal
tmpAdvancedRatingColor = _funcCalcHistogramColor(tmpHistogram)
[tmpHistogram, tmpAdvancedRatingColor]
_funcFillTableCell(_table, _column, _row, _showValues, _showLabelShort, _label, _labelShort, _color, _transparency, _trend, _value, _valueRating, _isUptrend, _showTotalOnly, _valueWeighting) =>
tmpTextSize = _showTotalOnly ? size.normal : size.small
tmpValue = _showValues ? ':' + '\n' + str.tostring(_value, '0.00') + '\n' + (_isUptrend ? 'Uptrend' : 'Downtrend') + '\n' + _trend + ': ' + str.tostring(_valueRating) + ' Point' : '\n' + _trend
if str.tostring(_valueRating) != '0' and _valueWeighting > 0
tmpValue := tmpValue + ' + ' + str.tostring(_valueWeighting) + ' (Weighting)'
if _label == 'TOTAL RATING'
tmpValue := _showValues ? ':' + '\n' + str.tostring(_valueRating) + '\n' + _trend : '\n' + _trend
_cellText = (_showLabelShort ? _labelShort : _label) + tmpValue
table.cell(_table, _column, _row, _cellText, bgcolor=color.new(_color, _transparency), text_color=color.silver, text_size=tmpTextSize)
if _label == 'TOTAL RATING'
table.merge_cells(_table, _column, _row, _column, _row+1)
//********** Inputs
inputCalculationSource = input(title='Calculation Source', group='Global Settings', defval=close)
// Rating Threshold
float inputRatingThresholdSellStrong = input.float(title="Downtrend Strong", group='Rating Threshold', defval=0.30, minval=0.10, maxval=0.90, step=0.10)
float inputRatingThresholdNeutralRangeStart = input.float(title="Neutral: Start", group='Rating Threshold', defval=0.45, minval=0.10, maxval=0.90, step=0.05)
float inputRatingThresholdNeutralRangeEnd = input.float(title="Neutral: End", group='Rating Threshold', defval=0.55, minval=0.10, maxval=0.90, step=0.05)
float inputRatingThresholdBuyStrong = input.float(title="Uptrend Strong", group='Rating Threshold', defval=0.70, minval=0.10, maxval=0.90, step=0.10)
// Total
bool inputPanelShowTotalOnly = input.bool(title='Show Total Only', group='Panel', defval=true)
bool inputPanelShowValues = input.bool(title='Show Details', group='Panel', defval=true)
bool inputPanelShowLabelShort = input.bool(title='Show Short Labels', group='Panel', defval=true)
string inputPanelYposInput = input.string("middle", "Position:", inline="11", options = ["top", "middle", "bottom"], group='Panel')
string inputPanelXposInput = input.string("right", "", inline="11", options = ["left", "center", "right"], group='Panel')
int inputPanelTransparency = input.int(title='Transparency:', group="Panel", defval=0, minval=0, maxval=100, step=5)
// Histogram
string inputHistogramVariant = input.string(title='Show:', group='Histogram', defval='Total Rating (Summary of all Oscillator)', options=['DISABLED', 'Total Rating (Summary of all Oscillator)', 'Awesome Oscillator', 'ADX', 'CCI', 'Chande Momentum Oscillator', 'Chaikin Oscillator', 'Control Primary', 'Control Secondary', 'Detrended Price Oscillator', 'Klinger', 'MFI', 'MACD', 'Momentum', 'RSI', 'RSI Laguerre', 'RSX', 'Ultimate Oscillator', 'Volume Regression Trend', 'Williams Percent Range'])
string inputHistogramType = input.string(title='Smoothing:', group='Histogram', defval='SMA', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputHistogramLength = input.int(title='Period:', group='Histogram', defval=8, maxval=100)
int inputHistogramTransparency = input.int(title='Transparency:', group="Histogram", defval=5, minval=0, maxval=100, step=5)
// Total Rating
string inputTotalRatingSmoothingType = input.string(title='MA Line: Type', group='Total Rating', defval='RMA', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputTotalRatingSmoothingPeriod = input.int(title='MA Line: Smoothing Period', group='Total Rating', minval=1, defval=5)
// Relative Strength Index (RSI)
bool inputRsiEnableVolumeBased = input.bool(title='Volume Based Calculation On/Off', group='Relative Strength Index (RSI)', defval=false)
bool inputRsiEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Relative Strength Index (RSI)', defval=false)
int inputRsiWeighting = input.int(title='Weighting', group='Relative Strength Index (RSI)', minval=0, maxval=3, defval=3)
int inputRsiLength = input.int(title='Period', group='Relative Strength Index (RSI)', minval=1, defval=14)
string inputRsiSmoothingType = input.string(title='Smoothing Type', group='Relative Strength Index (RSI)', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputRsiSmoothingPeriod = input.int(title='Smoothing Period', group='Relative Strength Index (RSI)', minval=1, defval=5)
int inputRsiLevelOverBought = input(title='Level Overbought', group='Relative Strength Index (RSI)', defval=75)
int inputRsiLevelOverSold = input(title='Level Oversold', group='Relative Strength Index (RSI)', defval=25)
// Noise free Relative Strength Index (RSX)
bool inputRsxEnableVolumeBased = input.bool(title='Volume Based Calculation On/Off', group='Noise free Relative Strength Index (RSX)', defval=false)
bool inputRsxEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Noise free Relative Strength Index (RSX)', defval=false)
int inputRsxWeighting = input.int(title='Weighting', group='Noise free Relative Strength Index (RSX)', minval=0, maxval=3, defval=0)
int inputRsxLength = input.int(title='Period', group='Noise free Relative Strength Index (RSX)', minval=1, defval=14)
string inputRsxSmoothingType = input.string(title='Smoothing Type', group='Noise free Relative Strength Index (RSX)', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputRsxSmoothingPeriod = input.int(title='Smoothing Period', group='Noise free Relative Strength Index (RSX)', minval=1, defval=5)
int inputRsxLevelOverBought = input(title='Level Overbought', group='Noise free Relative Strength Index (RSX)', defval=75)
int inputRsxLevelOverSold = input(title='Level Oversold', group='Noise free Relative Strength Index (RSX)', defval=25)
// Relative Strength Index Laguerre (RSI-L)
bool inputLaguerreEnableVolumeBased = input.bool(title='Volume Based Calculation On/Off', group='Relative Strength Index Laguerre (RSI-L)', defval=false)
bool inputLaguerreEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Relative Strength Index Laguerre (RSI-L)', defval=false)
int inputLaguerreWeighting = input.int(title='Weighting', group='Relative Strength Index Laguerre (RSI-L)', minval=0, maxval=3, defval=0)
int inputLaguerreLength = input.int(title='Period', group='Relative Strength Index Laguerre (RSI-L)', minval=1, defval=14)
int inputLaguerreFilterSmoothingFactor = input.int(title="Smoothing Factor", group='Relative Strength Index Laguerre (RSI-L)', minval=1, maxval=100, defval=1)
float inputLaguerreFilterGamma = input.float(title="Gamma Factor", group='Relative Strength Index Laguerre (RSI-L)', defval=0.20, minval=0.01, step=0.001)
string inputLaguerreSmoothingType = input.string(title='Smoothing Type', group='Relative Strength Index Laguerre (RSI-L)', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputLaguerreSmoothingPeriod = input.int(title='Smoothing Period', group='Relative Strength Index Laguerre (RSI-L)', minval=1, defval=5)
int inputLaguerreLevelOverBought = input(title='Level Overbought', group='Relative Strength Index Laguerre (RSI-L)', defval=95)
int inputLaguerreLevelOverSold = input(title='Level Oversold', group='Relative Strength Index Laguerre (RSI-L)', defval=5)
// Money Flow Index (MFI)
bool inputMfiEnableVolumeBased = input.bool(title='Volume Based Calculation On/Off', group='Money Flow Index (MFI)', defval=false)
bool inputMfiEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Money Flow Index (MFI)', defval=false)
int inputMfiWeighting = input.int(title='Weighting', group='Money Flow Index (MFI)', minval=0, maxval=3, defval=0)
int inputMfiLength = input.int(title='Period', group='Money Flow Index (MFI)', minval=1, defval=14)
string inputMfiSmoothingType = input.string(title='Smoothing Type', group='Money Flow Index (MFI)', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputMfiSmoothingPeriod = input.int(title='Smoothing Period', group='Money Flow Index (MFI)', minval=1, defval=5)
int inputMfiLevelOverBought = input(title='Level Overbought', group='Money Flow Index (MFI)', defval=80)
int inputMfiLevelOverSold = input(title='Level Oversold', group='Money Flow Index (MFI)', defval=20)
// Commodity Channel Index (CCI)
bool inputCciEnableVolumeBased = input.bool(title='Volume Based Calculation On/Off', group='Commodity Channel Index (CCI)', defval=false)
bool inputCciEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Commodity Channel Index (CCI)', defval=false)
int inputCciWeighting = input.int(title='Weighting', group='Commodity Channel Index (CCI)', minval=0, maxval=3, defval=0)
int inputCciLength = input.int(title='Period', group='Commodity Channel Index (CCI)', minval=1, defval=20)
string inputCciSmoothingType = input.string(title='Smoothing Type', group='Commodity Channel Index (CCI)', defval='HMA', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputCciSmoothingPeriod = input.int(title='Smoothing Period', group='Commodity Channel Index (CCI)', minval=1, defval=5)
int inputCciLevelOverBought = input(title='Level Overbought', group='Commodity Channel Index (CCI)', defval=100)
int inputCciLevelOverSold = input(title='Level Oversold', group='Commodity Channel Index (CCI)', defval=-100)
// Moving Average Convergence/Divergence (MACD)
bool inputMacdEnableVolumeBased = input.bool(title='Volume Based Calculation On/Off', group='Moving Average Convergence/Divergence (MACD)', defval=false)
bool inputMacdEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Moving Average Convergence/Divergence (MACD)', defval=false)
int inputMacdWeighting = input.int(title='Weighting', group='Moving Average Convergence/Divergence (MACD)', minval=0, maxval=3, defval=3)
string inputMacdFastSmoothingType = input.string(title='Fast: Smoothing Type', group='Moving Average Convergence/Divergence (MACD)', defval='EMA', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputMacdFastPeriod = input.int(title='Fast: Period', group='Moving Average Convergence/Divergence (MACD)', defval=13, minval=1)
string inputMacdSlowSmoothingType = input.string(title='Slow: Smoothing Type', group='Moving Average Convergence/Divergence (MACD)', defval='EMA', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputMacdSlowPeriod = input.int(title='Slow: Period', group='Moving Average Convergence/Divergence (MACD)', defval=21, minval=1)
// Klinger
bool inputKlingerEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Klinger', defval=false)
int inputKlingerWeighting = input.int(title='Weighting', group='Klinger', minval=0, maxval=3, defval=0)
int inputKlingerPeriodFast = input.int(title='Period Fast', group='Klinger', minval=1, defval=34)
int inputKlingerPeriodSlow = input.int(title='Period Slow', group='Klinger', minval=1, defval=55)
string inputKlingerSmoothingType = input.string(title='Smoothing Type', group='Klinger', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputKlingerSmoothingPeriod = input.int(title='Smoothing Period', group='Klinger', minval=1, defval=5)
// Average Directional Index (ADX)
bool inputAdxEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Average Directional Index (ADX)', defval=false)
int inputAdxWeighting = input.int(title='Weighting', group='Average Directional Index (ADX)', minval=0, maxval=3, defval=3)
int inputAdxLength = input.int(title='Period', group='Average Directional Index (ADX)', minval=1, defval=14)
string inputAdxSmoothingType = input.string(title='Smoothing Type', group='Average Directional Index (ADX)', defval='RMA', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputAdxSmoothingPeriod = input.int(title='Smoothing Period', group='Average Directional Index (ADX)', minval=1, defval=14)
// Awesome Oscillator
bool inputAoEnableVolumeBased = input.bool(title='Volume Based Calculation On/Off', group='Awesome Oscillator', defval=false)
bool inputAoEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Awesome Oscillator', defval=false)
int inputAoWeighting = input.int(title='Weighting', group='Awesome Oscillator', minval=0, maxval=3, defval=3)
int inputAoLengthShort = input.int(title='Period Short', group='Awesome Oscillator', minval=1, defval=5)
int inputAoLengthLong = input.int(title='Period Long', group='Awesome Oscillator', minval=1, defval=34)
string inputAoSmoothingType = input.string(title='Smoothing Type', group='Awesome Oscillator', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputAoSmoothingPeriod = input.int(title='Smoothing Period', group='Awesome Oscillator', minval=1, defval=5)
// Williams Percent Range
bool inputWprEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Williams Percent Range', defval=false)
int inputWprWeighting = input.int(title='Weighting', group='Williams Percent Range', minval=0, maxval=3, defval=0)
int inputWprLength = input.int(title='Period', group='Williams Percent Range', minval=1, defval=14)
string inputWprSmoothingType = input.string(title='Smoothing Type', group='Williams Percent Range', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'WPR based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputWprSmoothingPeriod = input.int(title='Smoothing Period', group='Williams Percent Range', minval=1, defval=5)
int inputWprLevelOverBought = input(title='Level Overbought', group='Williams Percent Range', defval=-20)
int inputWprLevelOverSold = input(title='Level Oversold', group='Williams Percent Range', defval=-80)
// Ultimate Oscillator
bool inputUoEnableVolumeBased = input.bool(title='Volume Based Calculation On/Off', group='Ultimate Oscillator', defval=false)
bool inputUoEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Ultimate Oscillator', defval=false)
int inputUoWeighting = input.int(title='Weighting', group='Ultimate Oscillator', minval=0, maxval=3, defval=0)
int inputUoShortLength = input.int(title='Period Short', group='Ultimate Oscillator', minval=1, defval=7)
int inputUoMidLength = input.int(title='Period Middle', group='Ultimate Oscillator', minval=1, defval=14)
int inputUoLongLength = input.int(title='Period Long', group='Ultimate Oscillator', minval=1, defval=28)
string inputUoSmoothingType = input.string(title='Smoothing Type', group='Ultimate Oscillator', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputUoSmoothingPeriod = input.int(title='Smoothing Period', group='Ultimate Oscillator', minval=1, defval=5)
int inputUoLevelOverBought = input(title='Level Overbought', group='Ultimate Oscillator', defval=70)
int inputUoLevelOverSold = input(title='Level Oversold', group='Ultimate Oscillator', defval=30)
// Momentum
bool inputMomentumEnableVolumeBased = input.bool(title='Volume Based Calculation On/Off', group='Momentum', defval=false)
bool inputMomentumEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Momentum', defval=false)
int inputMomentumWeighting = input.int(title='Weighting', group='Momentum', minval=0, maxval=3, defval=0)
int inputMomentumLength = input.int(title='Period', group='Momentum', minval=1, defval=10)
string inputMomentumSmoothingType = input.string(title='Smoothing Type', group='Momentum', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputMomentumSmoothingPeriod = input.int(title='Smoothing Period', group='Momentum', minval=1, defval=5)
// Volume Regression Trend (VRT)
bool inputVrtEnableVolumeBased = input.bool(title='Volume Based Calculation On/Off', group='Volume Regression Trend (VRT)', defval=false)
bool inputVrtEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Volume Regression Trend (VRT)', defval=false)
int inputVrtWeighting = input.int(title='Weighting', group='Volume Regression Trend (VRT)', minval=0, maxval=3, defval=3)
int inputVrtLength = input.int(title='Period', group='Volume Regression Trend (VRT)', minval=1, defval=4)
string inputVrtSmoothingType = input.string(title='Smoothing Type', group='Volume Regression Trend (VRT)', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputVrtSmoothingPeriod = input.int(title='Smoothing Period', group='Volume Regression Trend (VRT)', minval=1, defval=5)
// Chande Momentum Oscillator (CMO)
bool inputCmoEnableVolumeBased = input.bool(title='Volume Based Calculation On/Off', group='Chande Momentum Oscillator (CMO)', defval=false)
bool inputCmoEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Chande Momentum Oscillator (CMO)', defval=false)
int inputCmoWeighting = input.int(title='Weighting', group='Chande Momentum Oscillator (CMO)', minval=0, maxval=3, defval=0)
int inputCmoLength = input.int(title='Period', group='Chande Momentum Oscillator (CMO)', minval=1, defval=9)
string inputCmoSmoothingType = input.string(title='Smoothing Type', group='Chande Momentum Oscillator (CMO)', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputCmoSmoothingPeriod = input.int(title='Smoothing Period', group='Chande Momentum Oscillator (CMO)', minval=1, defval=5)
int inputCmoLevelOverBought = input(title='Level Overbought', group='Chande Momentum Oscillator (CMO)', defval=75)
int inputCmoLevelOverSold = input(title='Level Oversold', group='Chande Momentum Oscillator (CMO)', defval=25)
// Detrended Price Oscillator (DPO)
bool inputDpoEnableVolumeBased = input.bool(title='Volume Based Calculation On/Off', group='Detrended Price Oscillator (DPO)', defval=false)
bool inputDpoEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Detrended Price Oscillator (DPO)', defval=false)
int inputDpoWeighting = input.int(title='Weighting', group='Detrended Price Oscillator (DPO)', minval=0, maxval=3, defval=0)
int inputDpoLength = input.int(title='Period', group='Detrended Price Oscillator (DPO)', minval=1, defval=21)
string inputDpoSmoothingType = input.string(title='Smoothing Type', group='Detrended Price Oscillator (DPO)', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputDpoSmoothingPeriod = input.int(title='Smoothing Period', group='Detrended Price Oscillator (DPO)', minval=1, defval=5)
// Chaikin Oscillator (CO)
bool inputCoEnableStochasticBased = input.bool(title='Stochastic Based Calculation On/Off', group='Chaikin Oscillator (CO)', defval=false)
int inputCoWeighting = input.int(title='Weighting', group='Chaikin Oscillator (CO)', minval=0, maxval=3, defval=0)
int inputCoPeriodFast = input.int(title='Period Fast', group='Chaikin Oscillator (CO)', minval=1, defval=3)
int inputCoPeriodSlow = input.int(title='Period Slow', group='Chaikin Oscillator (CO)', minval=1, defval=10)
string inputCoSmoothingType = input.string(title='Smoothing Type', group='Chaikin Oscillator (CO)', defval='DISABLED', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputCoSmoothingPeriod = input.int(title='Smoothing Period', group='Chaikin Oscillator (CO)', minval=1, defval=5)
// Control Primary
inputControlPrimaryTimeframe = input.timeframe("", "Resolution:", group="Control Primary Line")
string inputControlPrimaryType = input.string(title='Type:', group='Control Primary Line', defval='EHMA', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputControlPrimaryLength = input.int(title='Period:', group='Control Primary Line', defval=21, maxval=1000)
int inputControlPrimaryWeighting = input.int(title='Weighting', group='Control Primary Line', minval=0, maxval=100, defval=0)
// Control Secondary
inputControlSecondaryTimeframe = input.timeframe("", "Resolution:", group="Control Secondary Line")
string inputControlSecondaryType = input.string(title='Type:', group='Control Secondary Line', defval='EHMA', options=['DISABLED', 'COVWMA', 'DEMA', 'EMA', 'EHMA', 'FRAMA', 'HMA', 'KAMA', 'Karobein', 'RMA', 'RSX based Noise Remover', 'SMA', 'SMMA', 'TEMA', 'VIDYA', 'VWMA', 'WMA'])
int inputControlSecondaryLength = input.int(title='Period:', group='Control Secondary Line', defval=34, maxval=1000)
int inputControlSecondaryWeighting = input.int(title='Weighting', group='Control Secondary Line', minval=0, maxval=100, defval=0)
//********** Calculation
float volumeBased = ta.cum(ta.change(inputCalculationSource) * volume)
// Relative Strength Index (RSI)
float inputCalculationSourceRsi = inputRsiEnableVolumeBased ? volumeBased : inputCalculationSource
[valRsi, valRsiRating, valRsiRatingStatus, valRsiIsUptrend, valRsiRatingStatusTable] = _funcRSI(inputCalculationSourceRsi, inputRsiLength, inputRsiSmoothingType, inputRsiSmoothingPeriod, inputRsiEnableStochasticBased, inputRsiLevelOverBought, inputRsiLevelOverSold)
// Relative Strength Index (RSI) Laguerre
float inputCalculationSourceLaguerre = inputLaguerreEnableVolumeBased ? volumeBased : inputCalculationSource
[valRsiLaguerre, valRsiLaguerreRating, valRsiLaguerreRatingStatus, valRsiLaguerreIsUptrend, valRsiLaguerreRatingStatusTable] = _funcLaguerreFilter(inputCalculationSourceLaguerre, inputLaguerreLength, inputLaguerreFilterGamma, inputLaguerreFilterSmoothingFactor, inputLaguerreSmoothingType, inputLaguerreSmoothingPeriod, inputLaguerreEnableStochasticBased, inputLaguerreLevelOverBought, inputLaguerreLevelOverSold)
// Noise free Relative Strength Index (RSX)
float inputCalculationSourceRsx = inputRsxEnableVolumeBased ? volumeBased : inputCalculationSource
[valRsx, valRsxRating, valRsxRatingStatus, valRsxIsUptrend, valRsxRatingStatusTable] = _funcRSX(inputCalculationSourceRsx, inputRsxLength, inputRsxSmoothingType, inputRsxSmoothingPeriod, inputRsxEnableStochasticBased, inputRsxLevelOverBought, inputRsxLevelOverSold)
// Money Flow Index (MFI)
float inputCalculationSourceMfi = inputMfiEnableVolumeBased ? volumeBased : inputCalculationSource
[valMfi, valMfiRating, valMfiRatingStatus, valMfiIsUptrend, valMfiRatingStatusTable] = _funcMFI(inputCalculationSourceMfi, inputMfiLength, inputMfiSmoothingType, inputMfiSmoothingPeriod, inputMfiEnableStochasticBased, inputMfiLevelOverBought, inputMfiLevelOverSold)
// Commodity Channel Index (CCI)
float inputCalculationSourceCci = inputCciEnableVolumeBased ? volumeBased : inputCalculationSource
[valCci, valCciRating, valCciRatingStatus, valCciIsUptrend, valCciRatingStatusTable] = _funcCCI(inputCalculationSourceCci, inputCciLength, inputCciSmoothingType, inputCciSmoothingPeriod, inputCciEnableStochasticBased, inputCciLevelOverBought, inputCciLevelOverSold)
// Klinger
[valKlinger, valKlingerRating, valKlingerRatingStatus, valKlingerIsUptrend, valKlingerRatingStatusTable] = _funcKlinger(inputCalculationSource, inputKlingerPeriodFast, inputKlingerPeriodSlow, inputKlingerSmoothingType, inputKlingerSmoothingPeriod, inputKlingerEnableStochasticBased)
// Moving Average Convergence/Divergence (MACD)
float inputCalculationSourceMacd = inputMacdEnableVolumeBased ? volumeBased : inputCalculationSource
[valMACD, valMACDRating, valMACDRatingStatus, valMACDIsUptrend, valMACDRatingStatusTable, macdHistogram, macdHistogramColor] = _funcHistogramMACD(inputCalculationSourceMacd, inputMacdFastSmoothingType, inputMacdFastPeriod, inputMacdSlowSmoothingType, inputMacdSlowPeriod, inputHistogramType, inputHistogramLength, inputMacdEnableStochasticBased)
// Average Directional Index (ADX)
[valAdx, valAdxRating, valAdxRatingStatus, valAdxIsUptrend, valAdxRatingStatusTable] = _funcADX(inputAdxLength, inputAdxSmoothingType, inputAdxSmoothingPeriod, inputAdxEnableStochasticBased)
// Awesome Oscillator
float inputCalculationSourceAo = inputAoEnableVolumeBased ? volumeBased : inputCalculationSource
[valAo, valAoRating, valAoRatingStatus, valAoIsUptrend, valAoRatingStatusTable] = _funcAwesomeOscillator(inputCalculationSourceAo, inputAoLengthShort, inputAoLengthLong, inputAoSmoothingType, inputAoSmoothingPeriod, inputAoEnableStochasticBased)
// Williams Percent Range
[valWpr, valWprRating, valWprRatingStatus, valWprIsUptrend, valWprRatingStatusTable] = _funcWPR(inputWprLength, inputWprSmoothingType, inputWprSmoothingPeriod, inputWprEnableStochasticBased, inputWprLevelOverBought, inputWprLevelOverSold)
// Ultimate Oscillator
float inputCalculationSourceUo = inputUoEnableVolumeBased ? volumeBased : inputCalculationSource
[valUo, valUoRating, valUoRatingStatus, valUoIsUptrend, valUoRatingStatusTable] = _funcUltimateOscillator(inputCalculationSourceUo, inputUoShortLength, inputUoMidLength, inputUoLongLength, inputUoSmoothingType, inputUoSmoothingPeriod, inputUoEnableStochasticBased, inputUoLevelOverBought, inputUoLevelOverSold)
// Momentum
float inputCalculationSourceMomentum = inputMomentumEnableVolumeBased ? volumeBased : inputCalculationSource
[valMomentum, valMomentumRating, valMomentumRatingStatus, valMomentumIsUptrend, valMomentumRatingStatusTable] = _funcMomentum(inputCalculationSourceMomentum, inputMomentumLength, inputMomentumSmoothingType, inputMomentumSmoothingPeriod, inputMomentumEnableStochasticBased)
// Volume Regression Trend (VRT)
float inputCalculationSourceVrt = inputVrtEnableVolumeBased ? volumeBased : inputCalculationSource
[valVrt, valVrtRating, valVrtRatingStatus, valVrtIsUptrend, valVrtRatingStatusTable, valVrtRatingColorHistogram] = _funcVRT(inputCalculationSourceVrt, inputVrtLength, inputVrtSmoothingType, inputVrtSmoothingPeriod, inputVrtEnableStochasticBased)
// Chande Momentum Oscillator (CMO)
float inputCalculationSourceCmo = inputCmoEnableVolumeBased ? volumeBased : inputCalculationSource
[valCmo, valCmoRating, valCmoRatingStatus, valCmoIsUptrend, valCmoRatingStatusTable] = _funcCMO(inputCalculationSourceCmo, inputCmoLength, inputCmoSmoothingType, inputCmoSmoothingPeriod, inputCmoEnableStochasticBased, inputCmoLevelOverBought, inputCmoLevelOverSold)
// Detrended Price Oscillator (DPO)
float inputCalculationSourceDpo = inputDpoEnableVolumeBased ? volumeBased : inputCalculationSource
[valDpo, valDpoRating, valDpoRatingStatus, valDpoIsUptrend, valDpoRatingStatusTable] = _funcDPO(inputCalculationSourceDpo, inputDpoLength, inputDpoSmoothingType, inputDpoSmoothingPeriod, inputDpoEnableStochasticBased)
// Chaikin Oscillator (CO)
[valCo, valCoRating, valCoRatingStatus, valCoIsUptrend, valCoRatingStatusTable] = _funcCO(inputCalculationSource, inputCoPeriodFast, inputCoPeriodSlow, inputCoSmoothingType, inputCoSmoothingPeriod, inputCoEnableStochasticBased)
// Control Primary
[valControlPrimary, valControlPrimaryRating, valControlPrimaryRatingStatus, valControlPrimaryIsUptrend, valControlPrimaryRatingStatusTable] = _funcControl(inputCalculationSource, inputControlPrimaryTimeframe, inputControlPrimaryType, inputControlPrimaryLength)
// Control Secondary
[valControlSecondary, valControlSecondaryRating, valControlSecondaryRatingStatus, valControlSecondaryIsUptrend, valControlSecondaryRatingStatusTable] = _funcControl(inputCalculationSource, inputControlSecondaryTimeframe, inputControlSecondaryType, inputControlSecondaryLength)
// Rating Total
float ratingTotal = 0
float ratingTotalMaxCount = 0
if not(na(valRsiRating) or na(valRsiRating[1]))
ratingTotal := ratingTotal
if valRsiRating > 0
ratingTotal := ratingTotal + valRsiRating + inputRsiWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputRsiWeighting
if not(na(valRsiLaguerreRating) or na(valRsiLaguerreRating[1]))
ratingTotal := ratingTotal
if valRsiLaguerreRating > 0
ratingTotal := ratingTotal + valRsiLaguerreRating + inputLaguerreWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputLaguerreWeighting
if not(na(valRsxRating) or na(valRsxRating[1]))
ratingTotal := ratingTotal
if valRsxRating > 0
ratingTotal := ratingTotal + valRsxRating + inputRsxWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputRsxWeighting
if not(na(valMfiRating) or na(valMfiRating[1]))
ratingTotal := ratingTotal
if valMfiRating > 0
ratingTotal := ratingTotal + valMfiRating + inputMfiWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputMfiWeighting
if not(na(valCciRating) or na(valCciRating[1]))
ratingTotal := ratingTotal
if valCciRating > 0
ratingTotal := ratingTotal + valCciRating + inputCciWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputCciWeighting
if not(na(valKlingerRating) or na(valKlingerRating[1]))
ratingTotal := ratingTotal
if valKlingerRating > 0
ratingTotal := ratingTotal + valKlingerRating + inputKlingerWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputKlingerWeighting
if not(na(valMACDRating) or na(valMACDRating[1]))
ratingTotal := ratingTotal
if valMACDRating > 0
ratingTotal := ratingTotal + valMACDRating + inputMacdWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputMacdWeighting
if not(na(valAdxRating) or na(valAdxRating[1]))
ratingTotal := ratingTotal
if valAdxRating > 0
ratingTotal := ratingTotal + valAdxRating + inputAdxWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputAdxWeighting
if not(na(valAoRating) or na(valAoRating[1]))
ratingTotal := ratingTotal
if valAoRating > 0
ratingTotal := ratingTotal + valAoRating + inputAoWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputAoWeighting
if not(na(valWprRating) or na(valWprRating[1]))
ratingTotal := ratingTotal
if valWprRating > 0
ratingTotal := ratingTotal + valWprRating + inputWprWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputWprWeighting
if not(na(valUoRating) or na(valUoRating[1]))
ratingTotal := ratingTotal
if valUoRating > 0
ratingTotal := ratingTotal + valUoRating + inputUoWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputUoWeighting
if not(na(valMomentumRating) or na(valMomentumRating[1]))
ratingTotal := ratingTotal
if valMomentumRating > 0
ratingTotal := ratingTotal + valMomentumRating + inputMomentumWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputMomentumWeighting
if not(na(valVrt) or na(valVrt[1]))
ratingTotal := ratingTotal
if valVrtRating > 0
ratingTotal := ratingTotal + valVrtRating + inputVrtWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputVrtWeighting
if not(na(valCmo) or na(valCmo[1]))
ratingTotal := ratingTotal
if valCmoRating > 0
ratingTotal := ratingTotal + valCmoRating + inputCmoWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputCmoWeighting
if not(na(valDpo) or na(valDpo[1]))
ratingTotal := ratingTotal
if valDpoRating > 0
ratingTotal := ratingTotal + valDpoRating + inputDpoWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputDpoWeighting
if not(na(valCo) or na(valCo[1]))
ratingTotal := ratingTotal
if valCoRating > 0
ratingTotal := ratingTotal + valCoRating + inputCoWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputCoWeighting
if inputControlPrimaryType != 'DISABLED' and not(na(valControlPrimaryRating) or na(valControlPrimaryRating[1]))
ratingTotal := ratingTotal
if valControlPrimaryRating > 0
ratingTotal := ratingTotal + valControlPrimaryRating + inputControlPrimaryWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputControlPrimaryWeighting
if inputControlSecondaryType != 'DISABLED' and not(na(valControlSecondaryRating) or na(valControlSecondaryRating[1]))
ratingTotal := ratingTotal
if valControlSecondaryRating > 0
ratingTotal := ratingTotal + valControlSecondaryRating + inputControlSecondaryWeighting
ratingTotalMaxCount := ratingTotalMaxCount + 1 + inputControlSecondaryWeighting
[valPlotHistogramRatingTotal, valPlotHistogramRatingTotalColor, valPlotHistogramRatingTotalColorTable, valPlotHistogramRatingTotalTrend] = _funcHistogramRatingTotal(inputHistogramType, inputHistogramLength, ratingTotal, ratingTotalMaxCount, inputRatingThresholdSellStrong, inputRatingThresholdNeutralRangeStart, inputRatingThresholdNeutralRangeEnd, inputRatingThresholdBuyStrong)
//************ Plotting
// Histogram
float valPlotHistogram = na
color valPlotHistogramColor = valColorsNeutral
if inputHistogramVariant != 'DISABLED' and inputHistogramVariant != 'MACD' and inputHistogramVariant != 'Volume Regression Trend'
float valHistogramSource = switch inputHistogramVariant
"RSI" => valRsi
"RSX" => valRsx
"RSI Laguerre" => valRsiLaguerre
"MFI" => valMfi
"CCI" => valCci
"Control Primary" => valControlPrimary
"Control Secondary" => valControlSecondary
"Klinger" => valKlinger
"ADX" => valAdx
"Awesome Oscillator" => valAo
"Williams Percent Range" => valWpr
"Ultimate Oscillator" => valUo
"Momentum" => valMomentum
"Chande Momentum Oscillator" => valCmo
"Detrended Price Oscillator" => valDpo
"Chaikin Oscillator" => valCo
=>
float(na)
[tmpValPlotHistogram, tmpValPlotHistogramColor] = _funcHistogram(inputHistogramType, valHistogramSource, inputHistogramLength)
valPlotHistogram := tmpValPlotHistogram
valPlotHistogramColor := tmpValPlotHistogramColor
plot((ratingTotal and inputHistogramVariant != 'DISABLED' and inputHistogramVariant == 'Total Rating (Summary of all Oscillator)') ? ratingTotal : na, title='Histogram Total Rating', style=plot.style_columns, color=color.new(valPlotHistogramRatingTotalColor, inputHistogramTransparency), linewidth=2)
plot((valPlotHistogram and inputHistogramVariant != 'DISABLED' and inputHistogramVariant != 'MACD' and inputHistogramVariant != 'Total Rating (Summary of all Oscillator)' and inputHistogramVariant != 'Volume Regression Trend') ? valPlotHistogram : na, title='Histogram Default', style=plot.style_columns, color=color.new(valPlotHistogramColor, inputHistogramTransparency), linewidth=2)
plot((valVrt and inputHistogramVariant == 'Volume Regression Trend') ? valVrt : na, title='Histogram Volume Regression Trend', style=plot.style_columns, color=color.new(valVrtRatingColorHistogram, inputHistogramTransparency), linewidth=2)
plot((macdHistogram and inputHistogramVariant == 'MACD') ? macdHistogram : na, title='Histogram MACD', style=plot.style_columns, color=color.new(macdHistogramColor, inputHistogramTransparency), linewidth=2)
// Plotting MA
float plottingMA = switch inputHistogramVariant
"Total Rating (Summary of all Oscillator)" =>
if inputTotalRatingSmoothingType != 'DISABLED'
_funcCalcMA(inputTotalRatingSmoothingType, ratingTotal, inputTotalRatingSmoothingPeriod)
else
na
"Williams Percent Range" => (valWpr + 50)
"Ultimate Oscillator" => (valUo - 50)
"Awesome Oscillator" => valAo
"ADX" => (valAdx - 50)
"RSI" => (valRsi - 50)
"RSI Laguerre" => (valRsiLaguerre - 50)
"RSX" => (valRsx - 50)
"MFI" => (valMfi - 50)
"CCI" => valCci
// "Control Primary" => valControlPrimary
// "Control Secondary" => valControlSecondary
"MACD" => valMACD
"Klinger" => valKlinger
"Momentum" => valMomentum
"Chande Momentum Oscillator" => valCmo
"Detrended Price Oscillator" => valDpo
"Chaikin Oscillator" => valCo
=>
float(na)
plot(plottingMA, title='MA Line', color=color.new(valColorMA, 0), linewidth=2, style=plot.style_line)
// Table
string labelRatingTotal = str.tostring(ratingTotal) + ' of ' + str.tostring(ratingTotalMaxCount) + ' Points'
var table perfTable = table.new(inputPanelYposInput + "_" + inputPanelXposInput, 10, 2, border_width=3)
if barstate.islast
if not inputPanelShowTotalOnly
_funcFillTableCell(perfTable, 0, 0, inputPanelShowValues, inputPanelShowLabelShort, 'Relative Strength Index', 'RSI', valRsiRatingStatusTable, inputPanelTransparency, valRsiRatingStatus, valRsi, valRsiRating, valRsiIsUptrend, inputPanelShowTotalOnly, inputRsiWeighting)
_funcFillTableCell(perfTable, 1, 0, inputPanelShowValues, inputPanelShowLabelShort, 'Relative Strength Index Laguerre', 'RSI-L', valRsiLaguerreRatingStatusTable, inputPanelTransparency, valRsiLaguerreRatingStatus, valRsiLaguerre, valRsiLaguerreRating, valRsiLaguerreIsUptrend, inputPanelShowTotalOnly, inputLaguerreWeighting)
_funcFillTableCell(perfTable, 2, 0, inputPanelShowValues, inputPanelShowLabelShort, 'Relative Strength Index (Noise free)', 'RSX', valRsxRatingStatusTable, inputPanelTransparency, valRsxRatingStatus, valRsx, valRsxRating, valRsxIsUptrend, inputPanelShowTotalOnly, inputRsxWeighting)
_funcFillTableCell(perfTable, 3, 0, inputPanelShowValues, inputPanelShowLabelShort, 'Money Flow Index', 'MFI', valMfiRatingStatusTable, inputPanelTransparency, valMfiRatingStatus, valMfi, valMfiRating, valMfiIsUptrend, inputPanelShowTotalOnly, inputMfiWeighting)
_funcFillTableCell(perfTable, 4, 0, inputPanelShowValues, inputPanelShowLabelShort, 'Williams Percent Range', 'WPR', valWprRatingStatusTable, inputPanelTransparency, valWprRatingStatus, valWpr, valWprRating, valWprIsUptrend, inputPanelShowTotalOnly, inputWprWeighting)
_funcFillTableCell(perfTable, 5, 0, inputPanelShowValues, inputPanelShowLabelShort, 'Momentum', 'MOM', valMomentumRatingStatusTable, inputPanelTransparency, valMomentumRatingStatus, valMomentum, valMomentumRating, valMomentumIsUptrend, inputPanelShowTotalOnly, inputMomentumWeighting)
_funcFillTableCell(perfTable, 6, 0, inputPanelShowValues, inputPanelShowLabelShort, 'Volume Regression Trend', 'VRT', valVrtRatingStatusTable, inputPanelTransparency, valVrtRatingStatus, valVrt, valVrtRating, valVrtIsUptrend, inputPanelShowTotalOnly, inputVrtWeighting)
_funcFillTableCell(perfTable, 7, 0, inputPanelShowValues, inputPanelShowLabelShort, 'Detrended Price Oscillator', 'DPO', valDpoRatingStatusTable, inputPanelTransparency, valDpoRatingStatus, valDpo, valDpoRating, valDpoIsUptrend, inputPanelShowTotalOnly, inputDpoWeighting)
_funcFillTableCell(perfTable, 8, 0, inputPanelShowValues, inputPanelShowLabelShort, 'Control Primary', 'Control P', valControlPrimaryRatingStatusTable, inputPanelTransparency, valControlPrimaryRatingStatus, valControlPrimary, valControlPrimaryRating, valControlPrimaryIsUptrend, inputPanelShowTotalOnly, inputControlPrimaryWeighting)
_funcFillTableCell(perfTable, 9, 0, inputPanelShowValues, inputPanelShowLabelShort, 'TOTAL RATING', 'TOTAL RATING', valPlotHistogramRatingTotalColorTable, inputPanelTransparency, valPlotHistogramRatingTotalTrend, valPlotHistogramRatingTotal, labelRatingTotal, false, inputPanelShowTotalOnly, 0)
if not inputPanelShowTotalOnly
_funcFillTableCell(perfTable, 0, 1, inputPanelShowValues, inputPanelShowLabelShort, 'Commodity Channel Index', 'CCI', valCciRatingStatusTable, inputPanelTransparency, valCciRatingStatus, valCci, valCciRating, valCciIsUptrend, inputPanelShowTotalOnly, inputCciWeighting)
_funcFillTableCell(perfTable, 1, 1, inputPanelShowValues, inputPanelShowLabelShort, 'Moving Average Convergence/Divergence', 'MACD', valMACDRatingStatusTable, inputPanelTransparency, valMACDRatingStatus, valMACD, valMACDRating, valMACDIsUptrend, inputPanelShowTotalOnly, inputMacdWeighting)
_funcFillTableCell(perfTable, 2, 1, inputPanelShowValues, inputPanelShowLabelShort, 'Klinger', 'KLG', valKlingerRatingStatusTable, inputPanelTransparency, valKlingerRatingStatus, valKlinger, valKlingerRating, valKlingerIsUptrend, inputPanelShowTotalOnly, inputKlingerWeighting)
_funcFillTableCell(perfTable, 3, 1, inputPanelShowValues, inputPanelShowLabelShort, 'Average Directional Index', 'ADX', valAdxRatingStatusTable, inputPanelTransparency, valAdxRatingStatus, valAdx, valAdxRating, valAdxIsUptrend, inputPanelShowTotalOnly, inputAdxWeighting)
_funcFillTableCell(perfTable, 4, 1, inputPanelShowValues, inputPanelShowLabelShort, 'Awesome Oscillator', 'AO', valAoRatingStatusTable, inputPanelTransparency, valAoRatingStatus, valAo, valAoRating, valAoIsUptrend, inputPanelShowTotalOnly, inputAoWeighting)
_funcFillTableCell(perfTable, 5, 1, inputPanelShowValues, inputPanelShowLabelShort, 'Ultimate Oscillator', 'UO', valUoRatingStatusTable, inputPanelTransparency, valUoRatingStatus, valUo, valUoRating, valUoIsUptrend, inputPanelShowTotalOnly, inputUoWeighting)
_funcFillTableCell(perfTable, 6, 1, inputPanelShowValues, inputPanelShowLabelShort, 'Chande Momentum Oscillator', 'CMO', valCmoRatingStatusTable, inputPanelTransparency, valCmoRatingStatus, valCmo, valCmoRating, valCmoIsUptrend, inputPanelShowTotalOnly, inputCmoWeighting)
_funcFillTableCell(perfTable, 7, 1, inputPanelShowValues, inputPanelShowLabelShort, 'Chaikin Oscillator', 'CO', valCoRatingStatusTable, inputPanelTransparency, valCoRatingStatus, valCo, valCoRating, valCoIsUptrend, inputPanelShowTotalOnly, inputCoWeighting)
_funcFillTableCell(perfTable, 8, 1, inputPanelShowValues, inputPanelShowLabelShort, 'Control Secondary', 'Control S', valControlSecondaryRatingStatusTable, inputPanelTransparency, valControlSecondaryRatingStatus, valControlSecondary, valControlSecondaryRating, valControlSecondaryIsUptrend, inputPanelShowTotalOnly, inputControlSecondaryWeighting)
//************ Alerting
// Neutral
alertcondition((valPlotHistogramRatingTotalTrend == "Neutral"), "Neutral", "Multi Trend Oscillator: Neutral")
// Downtrend
alertcondition((valPlotHistogramRatingTotalTrend == "Downtrend"), "Downtrend", "Multi Trend Oscillator: Downtrend")
alertcondition((valPlotHistogramRatingTotalTrend == "Strong Downtrend"), "Strong Downtrend", "Multi Trend Oscillator: Downtrend")
// Uptrend
alertcondition((valPlotHistogramRatingTotalTrend == "Uptrend"), "Uptrend", "Multi Trend Oscillator: Uptrend")
alertcondition((valPlotHistogramRatingTotalTrend == "Strong Uptrend"), "Strong Uptrend", "Multi Trend Oscillator: Strong Uptrend")
alertcondition((valPlotHistogramRatingTotalTrend == "Strong Uptrend\nBut Downtrend coming"), "Strong Uptrend - But Downtrend coming", "Multi Trend Oscillator: Strong Uptrend - But Downtrend coming")
|
ATK multiple EMA | https://www.tradingview.com/script/LK9eq8MU-ATK-multiple-EMA/ | TKMOR | https://www.tradingview.com/u/TKMOR/ | 2 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TKMOR
//@version=5
indicator("ATK multiple EMA ", overlay=true)
opensar = input(false, title="Show Parabolic SAR")
openshort=input(true, title="Show EMA 9")
openshorter=input(true, title="Show EMA 50")
openlong=input(true, title="Show EMA 99")
openlonger=input(true, title="Show EMA 200")
opensrc=input(false, title="Show Close Line")
src = input(close, title="Source")
shortline = ta.ema(src,input.int(9, minval=1))
shorterline = ta.ema(src,input.int(50, minval=1))
longline = ta.ema(src,input.int(99, minval=1))
longerline = ta.ema(src,input.int(200, minval=1))
plot(openshort?shortline:na, color = color.new(color.red,0),linewidth=2)
plot(openshorter?shorterline:na, color = color.new(color.orange,0),linewidth=2)
plot(openlong?longline:na, color = color.new(color.aqua,0),linewidth=2)
plot(openlonger?longerline:na, color = color.new(color.green,0),linewidth=2)
//plot(opensrc?src:na)
ShowFib = input(false, title="Open Auto Fib")
Fibs = input.string('Plot Fibs based on Lookback', options=['Plot Fibs based on Lookback', 'Plot Fibs based on Price Input'], title='Fibonacci Plot Type')
FIBS = Fibs == 'Plot Fibs based on Lookback' ? 1 : Fibs == 'Plot Fibs based on Price Input' ? 2 : na
Foption = input.string(defval='1. Candles', title='Fibonacci Plot Lookback Type', options=['2. Days', '1. Candles'])
FP = input(defval=100, title='Days/Candles to Lookback')
Reverse = input(defval=false, title='Reverse Fibonacci Levels?')
ExtraFibs = input(true, 'Show 0.886 and 1.113 Fibs')
Note = input(true, '════ 𝗙𝗶𝗯𝘀 𝗯𝗮𝘀𝗲𝗱 𝗼𝗻 𝗣𝗿𝗶𝗰𝗲 𝗜𝗻𝗽𝘂𝘁 ════')
High = input.float(0., minval=0, title='High - Enter Value')
Low = input.float(-1., minval=-1, title='Low - Enter Value')
Note2 = input(true, '══════ 𝗙𝗶𝗯 𝗟𝗶𝗻𝗲/𝗟𝗮𝗯𝗲𝗹 𝗦𝘁𝘆𝗹𝗲 ══════')
Bull_Color = input(#f23645, title='Support Fibs Color')
Bear_Color = input(#42bda8, title='Resistance Fibs Color')
CurrentFib = input(false, 'Show Fib Level of Current Price')
Current_Color = input(color.orange, title='Current Fib Label Color')
LineStyle = input.string('Solid', options=['Dotted', 'Solid'], title='Fib Line Style')
LineWidth = input.int(1, minval=1, maxval=3, title='Fib Line Width')
Ext = input(false, 'Extend Lines Left')
// Transparency = input("Low", options = ["High", "Medium", "Low"], title="Fib Line Transparency")
BullColor = Bull_Color //Transparency == "High"?color.new(#20B2AA,75):Transparency == "Medium"?color.new(#20B2AA,50):Bull_Color
BearColor = Bear_Color //Transparency == "High"?color.new(#C70039,75):Transparency == "Medium"?color.new(#C70039,50):Bear_Color
FPeriod = timeframe.isintraday and Foption == '2. Days' ? 1440 / timeframe.multiplier * FP : timeframe.isdaily and Foption == '2. Days' ? FP / timeframe.multiplier : timeframe.isweekly and Foption == '2. Days' ? FP / (7 * timeframe.multiplier) : timeframe.ismonthly and Foption == '2. Days' ? FP / (28 * timeframe.multiplier) : Foption == '1. Candles' ? FP : 100
Fhigh = FIBS == 1 ? ta.highest(FPeriod) : FIBS == 2 and High == 0 ? ta.highest(high, 100) : FIBS == 2 and High != 0 ? High : na
Flow = FIBS == 1 ? ta.lowest(FPeriod) : FIBS == 2 and Low == -1 ? ta.lowest(low, 100) : FIBS == 2 and High != -1 ? Low : na
FH = FIBS == 1 ? ta.highestbars(high, FPeriod) : 1
FL = FIBS == 1 ? ta.lowestbars(low, FPeriod) : 2
revfibs = not Reverse ? FL > FH : FL < FH
Fib_x(n) =>
revfibs ? (Fhigh - Flow) * n + Flow : Fhigh - (Fhigh - Flow) * n
Current = revfibs ? (close - Flow) / (Fhigh - Flow) : (Fhigh - close) / (Fhigh - Flow)
var label Current_Fib_Label = na
label.delete(Current_Fib_Label)
if CurrentFib and barstate.islast
Current_Fib_Label := label.new(bar_index, close, str.tostring(Current, '##.##'), textcolor=Current_Color, color=color.new(#000000, 100), style=label.style_label_left, yloc=yloc.price)
Current_Fib_Label
EXTEND = Ext ? extend.left : extend.none
STYLE = LineStyle == 'Dotted' ? line.style_dotted : line.style_solid
WIDTH = LineWidth
BB = FIBS == 1 ? FL < FH ? bar_index[-FL] : bar_index[-FH] : FIBS == 2 ? bar_index[50] : bar_index[50]
Fib_line(x) =>
var line ln = na
line.delete(ln)
ln := line.new(BB, x, bar_index, x, color=close > x ? BullColor : BearColor, extend=EXTEND, style=STYLE, width=WIDTH)
ln
Fib_label(x, _txt) =>
var label lbl = na
label.delete(lbl)
lbl := label.new(bar_index, x, _txt + str.tostring(x, '##.########') + ' )', textcolor=close > x ? BullColor : BearColor, color=color.new(#000000, 100), style=label.style_label_left, yloc=yloc.price)
lbl
if ShowFib == true
Fib0 = Fib_line(Fib_x(0))
Fib236 = Fib_line(Fib_x(0.236))
Fib382 = Fib_line(Fib_x(0.382))
Fib500 = Fib_line(Fib_x(0.500))
Fib618 = Fib_line(Fib_x(0.618))
Fib786 = Fib_line(Fib_x(0.786))
Fib1000 = Fib_line(Fib_x(1.000))
Fib886 = ExtraFibs ? Fib_line(Fib_x(0.886)) : na
if FIBS == 2
Fib1113 = ExtraFibs ? Fib_line(Fib_x(1.113)) : na
Fib1272 = Fib_line(Fib_x(1.272))
Fib1618 = Fib_line(Fib_x(1.618))
Fib2000 = Fib_line(Fib_x(2.000))
Fib2236 = Fib_line(Fib_x(2.236))
Fib2618 = Fib_line(Fib_x(2.618))
Fib3236 = Fib_line(Fib_x(3.236))
Fib3618 = Fib_line(Fib_x(3.618))
Fib4236 = Fib_line(Fib_x(4.236))
Fib4618 = Fib_line(Fib_x(4.618))
Fib4618
// if ShowFib == true
LFib0 = Fib_label(Fib_x(0), '0 ( ')
LFib236 = Fib_label(Fib_x(0.236), '0.236 ( ')
LFib382 = Fib_label(Fib_x(0.382), '0.382 ( ')
LFib500 = Fib_label(Fib_x(0.500), '0.500 ( ')
LFib618 = Fib_label(Fib_x(0.618), '0.618 ( ')
LFib786 = Fib_label(Fib_x(0.786), '0.786 ( ')
LFib1000 = Fib_label(Fib_x(1.000), '1.000 ( ')
LFib886 = ExtraFibs ? Fib_label(Fib_x(0.886), '0.886 ( ') : na
if FIBS == 2
LFib1113 = ExtraFibs ? Fib_label(Fib_x(1.113), '1.113 ( ') : na
LFib1272 = Fib_label(Fib_x(1.272), '1.272 ( ')
LFib1618 = Fib_label(Fib_x(1.618), '1.618 ( ')
LFib2000 = Fib_label(Fib_x(2.000), '2.000 ( ')
LFib2236 = Fib_label(Fib_x(2.236), '2.236 ( ')
LFib2618 = Fib_label(Fib_x(2.618), '2.618 ( ')
LFib3236 = Fib_label(Fib_x(3.236), '3.236 ( ')
LFib3618 = Fib_label(Fib_x(3.618), '3.618 ( ')
LFib4236 = Fib_label(Fib_x(4.236), '4.236 ( ')
LFib4618 = Fib_label(Fib_x(4.618), '4.618 ( ')
LFib4618
start = input(0.02)
increment = input(0.02)
maximum = input(0.2, "Max Value")
out = ta.sar(start, increment, maximum)
plot(opensar?out:na, "ParabolicSAR", style=plot.style_cross, color=#2962FF) |
HODL LINE [AstrideUnicorn] | https://www.tradingview.com/script/TEm8g89B-HODL-LINE-AstrideUnicorn/ | AstrideUnicorn | https://www.tradingview.com/u/AstrideUnicorn/ | 158 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AstrideUnicorn
// Asymmetrical Trend Filter aka HODL Line
//@version=5
indicator("HODL LINE", overlay=true)
// initialize indicator period parameter and the asymmetry paramter
length = 300
asymmetry = 0.05 //input.float(defval=0.05,step=0.01, minval=0.01, maxval=0.3)
// script inputs
sensitivity = input.string(defval="Hold Medium Term", title="Sensitivity", options=['Super Sensitive','Hold Short Term', 'Hold Medium Term', 'Hold Long Term'])
use_smoothing = input.bool(defval=false, title="Use Smoothing")
// Set the indicator period based on the choosen sensitivity
if sensitivity == 'Super Sensitive'
length:=50
if sensitivity == 'Hold Short Term'
length:=100
if sensitivity == 'Hold Medium Term'
length:=300
if sensitivity == 'Hold Long Term'
length:=500
// Calculate HODL Line - an assymetric trend filter
HODL_line = (ta.highest(close,length) + ta.lowest(close,length))/(2.0 + asymmetry)
// Calculate smoothed price time series
smoothed_price = ta.hma(close,50)
// Use closing price or smoothed price based on the choosen option for smoothing
price_model = use_smoothing ? smoothed_price : close
// Define conditional color for the HODL Line
hodl_line_color = price_model >= HODL_line ? color.green : color.red
// define the HODL Line crossing conditions
crossing_condition_bull = ta.crossover(price_model, HODL_line)
crossing_condition_bear = ta.crossunder(price_model, HODL_line)
// plotting
plot(HODL_line, color = hodl_line_color, linewidth = 2)
plot(crossing_condition_bull?HODL_line:na, color = color.new(color.green,40), style= plot.style_circles, linewidth = 20)
plot(crossing_condition_bear?HODL_line:na, color = color.new(color.red,40), style= plot.style_circles, linewidth = 20)
bgcolor(color.new(hodl_line_color,80))
plot(use_smoothing?price_model:na, color=color.purple, linewidth=2)
|
crypto futures hourly scalping with ma & rsi - ogcheckers | https://www.tradingview.com/script/uhWOTxDi-crypto-futures-hourly-scalping-with-ma-rsi-ogcheckers/ | ogcheckers | https://www.tradingview.com/u/ogcheckers/ | 113 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ogcheckers
//@version=5
indicator("ogcheckers_1hr_scalp_ema_sma_rsi","ogcheckers_1hr_scalp_ema_sma_rsi_chartbank_follower",overlay=true,timeframe="",timeframe_gaps=true)
ma1 = input(title="moving average length 1 ( default = 3 )", defval=3, group="moving_average_settings")
ma2 = input(title="moving average length 2 ( default = 5 )", defval=5, group="moving_average_settings")
ma3 = input(title="moving average length 3 ( default = 7 )", defval=7, group="moving_average_settings")
ma_source = input(title="moving_average_source ( default = close ) (_close_&_low_are_good_)", defval=close, group="moving_average_settings")
rsi_source = input(title="rsi_source ( default = open ) - (_open_&_low_are_good_)", defval=open, group="rsi_settings [ please set the same in multiple rsi indicator ]")
rsi_length = input.int(title="rsi_length ( default = 14 )", defval=14, group="rsi_settings [ please set the same in multiple rsi indicator ]", options=[7,14,26])
rsi_upper = input(title="rsi_upper_limit ( default = 75 )", defval=75, group="rsi_settings [ please set the same in multiple rsi indicator ]")
rsi_lower = input(title="rsi_lower_limit ( default = 25 )", defval=25, group="rsi_settings [ please set the same in multiple rsi indicator ]")
rsi_buffer = input(title="rsi_buffer ( -10 to +10 ) ( default = 5 )", defval=5, group="rsi_additional_lower = rsi_lower_limit + rsi_buffer")
rsi_additional_lower = rsi_lower + rsi_buffer
rsi_additional_upper = rsi_upper + rsi_buffer
e3=ta.ema(ma_source,ma1)
e5=ta.ema(ma_source,ma2)
e7=ta.ema(ma_source,ma3)
s3=ta.sma(ma_source,ma1)
s5=ta.sma(ma_source,ma2)
s7=ta.sma(ma_source,ma3)
plot(e3, title="ema1 (moving average length 1)", color=color.white, linewidth=2)
plot(e5, title="ema2 (moving average length 2)", color=color.green, linewidth=2)
plot(e7, title="ema3 (moving average length 3)", color=color.blue, linewidth=2)
plot(s3, title="sma1 (moving average length 1)", color=color.black, linewidth=2)
plot(s5, title="sma2 (moving average length 2)", color=color.red, linewidth=2)
plot(s7, title="sma3 (moving average length 3)", color=color.yellow, linewidth=2)
r7=ta.rsi(rsi_source,7)
r14=ta.rsi(rsi_source,14)
r26=ta.rsi(rsi_source,26)
r7low = r7<=rsi_lower ? 1:0
r7high = r7>=rsi_upper ? 1:0
r14low = r14<=rsi_lower ? 1:0
r14high = r14>=rsi_upper ? 1:0
r26low = r26<=rsi_lower ? 1:0
r26high = r26>=rsi_upper ? 1:0
plotshape(r14low, title="rsi <= rsi_lower_limit (default_rsi_length=14)", style=shape.circle, size=size.tiny, location=location.belowbar, color=color.new(color.white,70))
plotshape(r14high, title="rsi >= rsi_upper_limit (default_rsi_length=14)", style=shape.circle, size=size.tiny, location=location.abovebar, color=color.new(color.black,70))
plotshape(r26<=rsi_additional_lower and r14low, title="Rsi_26_<=_rsi_additional_lower and Rsi_14_<=_rsi_lower_limit", style=shape.cross, size=size.large, location=location.belowbar, color=color.new(color.red,70))
//plotshape(r26>=rsi_upper and r14high, title="Rsi_26_>=_rsi_upper and Rsi_14_>=_rsi_upper_limit", style=shape.cross, size=size.large, location=location.abovebar, color=color.new(color.red,70))
de3 = request.security(syminfo.tickerid, 'D', e3)
de5 = request.security(syminfo.tickerid, 'D', e5)
ds3 = request.security(syminfo.tickerid, 'D', s3)
ds5 = request.security(syminfo.tickerid, 'D', s5)
plot(de3, title="day ema1 (moving average length 1)", color=color.white, linewidth=3)
plot(de5, title="day ema2 (moving average length 2)", color=color.green, linewidth=3)
plot(ds3, title="day sma1 (moving average length 1)", color=color.black, linewidth=3)
plot(ds5, title="day sma2 (moving average length 2)", color=color.red, linewidth=3)
es3 = e3>s3 ? 1:0
es5 = e5>s5 ? 1:0
es7 = e7>s7 ? 1:0
des3 = ta.crossover(de3,ds3) ? 1:0
plotshape(es3 and r14low==1 and r14<=rsi_additional_lower and close>close[1], title="long_reference => rsi=14 entry)", style=shape.triangleup, size=size.tiny, location=location.belowbar, color=color.new(color.orange,70), text="rsi14_entry", textcolor=color.new(color.orange,70))
plotshape(es3 and r14low==0 and r7<=rsi_additional_lower and close>close[1], title="long_reference => rsi=7 entry)", style=shape.triangleup, size=size.small, location=location.belowbar, color=color.new(color.green,70), text="rsi7_entry", textcolor=color.new(color.green,70))
dr7 = request.security(syminfo.tickerid, 'D', r7)
dr14 = request.security(syminfo.tickerid, 'D', r14)
dr26 = request.security(syminfo.tickerid, 'D', r26)
dr7low = dr7<=rsi_lower ? 1:0
dr7high = dr7>=rsi_upper ? 1:0
dr14low = dr14<=rsi_lower ? 1:0
dr14high = dr14>=rsi_upper ? 1:0
dr26low = dr26<=rsi_lower ? 1:0
dr26high = dr26>=rsi_upper ? 1:0
plotshape(dr7low and des3, title="day_emasma_crossover @ day_rsi_7_<=_rsi_lower", style=shape.triangleup, size=size.large, location=location.belowbar, color=color.new(color.purple,70))
plotshape(dr7<=rsi_additional_lower, title="day_rsi_7 <= rsi_additional_lower", style=shape.triangleup, size=size.huge, location=location.belowbar, color=color.new(color.white,70))
//plotshape(r7low and dr7low, title="rsi_7 & day_rsi_7 <= rsi_lower", style=shape.arrowup, size=size.huge, location=location.belowbar, color=color.new(color.white,70))
o1c1 = open[1]>=close[1] ? 1:0
oc1 = open>=close[1] ? 1:0
co = close>=open ? 1:0
cc1 = close>=close[1] ? 1:0
co1 = close>=open[1] ? 1:0
plotshape(o1c1 and oc1 and co and cc1 and r14<=rsi_lower, title="long_reference => BLC1 = bullish candles 1 @_rsi_14_<=_rsi_lower_limit", style=shape.triangleup, size=size.normal, location=location.belowbar, color=color.new(color.blue,70), text="BLC1", textcolor=color.new(color.blue,70))
plotshape(o1c1 and oc1 and co and cc1 and r14<=rsi_additional_lower, title="long_reference => BLC2 = bullish candles 2 @_rsi_14_<=_rsi_additional_lower", style=shape.cross, size=size.large, location=location.belowbar, color=color.new(color.blue,70), text="BLC2", textcolor=color.new(color.blue,70))
se5 = s5>e5 ? 1:0
se7 = s7>e7 ? 1:0
dse3 = ta.crossover(ds3,de3) ? 1:0
c1o1 = close[1]>=open[1]
c1o = close[1]>=open
oc = open>=close
c1c = close[1]>=close
o1c = open[1]>=close
plotshape(c1o1 and c1o and oc and c1c and r7>=rsi_upper, title="short_reference => BRC1 = bearish candles 1 @_rsi_7_>=_rsi_upper_limit", style=shape.triangledown, size=size.normal, location=location.abovebar, color=color.new(color.yellow,70), text="BRC1", textcolor=color.new(color.yellow,70))
plotshape(c1o1 and c1o and oc and c1c and r7>=rsi_additional_upper, title="short_reference => BRC2 = bearish candles 2 @_rsi_7_>=_rsi_additional_upper", style=shape.cross, size=size.large, location=location.abovebar, color=color.new(color.yellow,70), text="BRC2", textcolor=color.new(color.yellow,70))
|
FTX spot/perp 24h volume ratio | https://www.tradingview.com/script/FfxzDMw4-FTX-spot-perp-24h-volume-ratio/ | Thojdid | https://www.tradingview.com/u/Thojdid/ | 29 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Thojdid
//This indicator gives the ratio between the 24h volume on the spot instrument versus the perpetual contract on FTX.
//Works on intraday timeframes only (minutes and hourly)
//@version=4
study("FTX spot/perp 24h volume ratio", overlay=false)
coin = input("BTC", title='coin')
vp1 = security("FTX:"+coin+"PERP","",volume)
vs1 = security("FTX:"+coin+"USD","",volume)
cum_vp1 = 0.0
cum_vs1 = 0.0
period = 1440/tonumber(timeframe.period)
for i = 0 to period
cum_vp1 := cum_vp1 + vp1[i]
cum_vs1 := cum_vs1 + vs1[i]
plot(cum_vs1/cum_vp1, color=color.green) |
BTC NVM Ratio - Onchain Analysis | https://www.tradingview.com/script/hZooNg6z-BTC-NVM-Ratio-Onchain-Analysis/ | cryptoonchain | https://www.tradingview.com/u/cryptoonchain/ | 37 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MJShahsavar
//@version=5
indicator("NVM Ratio", timeframe = "W")
R = input.symbol("BTC_MARKETCAP", "Symbol")
r = request.security(R, 'D', close)
S=input.symbol("BTC_ACTIVEADDRESSES", "Symbol")
s = request.security(S, 'D', close)
A= math.log10 (r)
b= s*s
B= math.log10 (b)
C= A/B
D = ta.sma(C, 7)
E= ta.sma(C, 100)
plot (D, color = D>= E ? color.red : color.blue, linewidth=1)
plot (E, color = D >= E ? color.red : color.blue, linewidth=3)
|
SuperJump Turn Back Bollinger Band | https://www.tradingview.com/script/9KNKhgYa/ | SuperJump | https://www.tradingview.com/u/SuperJump/ | 453 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@SuperJump
//@version=5
indicator(shorttitle="SuperJump TBBB", title="SuperJump Turn Back Bollinger Band", overlay=true, timeframe="", timeframe_gaps=true)
length = input.int(60, minval=1, group="Bollinger", inline='1')
src = input(close, title="Source", group="Bollinger", inline='1')
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev", group="Bollinger", inline='1')
b_mult = input.float(2.5, minval=0.001, maxval=50, title="Wide StdDev", group="Bollinger", inline='1')
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
b_dev = b_mult * ta.stdev(src, length)
b_upper = basis + b_dev
b_lower = basis - b_dev
atrlength = input.int(title="ATR Length", defval=14, minval=1,group="ATR" ,inline='2')
smoothing = input.string(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"],group="ATR", inline='2')
SLAtr = input.float(title="Stop Loss ATR Ratio", defval=1.0, minval=1,group="ATR" ,inline='2')
ma_function(source, length) =>
switch smoothing
"RMA" => ta.rma(source, length)
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
=> ta.wma(source, length)
atr = ma_function(ta.tr(true), atrlength)
LongSig = ta.crossunder(lower,src) and close > open
ShortSig = ta.crossover(upper,src) and close < open
WLongSig = ta.crossunder(b_lower,src) and close > open
WShortSig = ta.crossover(b_upper,src) and close < open
//Plots
plot(basis, "Basis", color=#FF6D00)
plot(upper, "Upper", color=#2962FF)
plot(lower, "Lower", color=#2962FF)
plot(b_upper, "Wide Upper", color=#2962FF)
plot(b_lower, "Wide Lower", color=#2962FF)
plot(b_upper + atr*SLAtr, "SL Upper", color=color.red)
plot(b_lower - atr*SLAtr, "SL Lower", color=color.red)
plotchar(ShortSig and WShortSig == false ? src : na, location = location.abovebar, char= "▼", size = size.tiny, color = color.white )
plotchar(LongSig and WLongSig == false ? src : na, location = location.belowbar, char= "▲", size = size.tiny, color = color.white)
plotchar(WShortSig ? src : na, location = location.abovebar, char= "▼", size = size.tiny, color = color.yellow )
plotchar(WLongSig ? src : na, location = location.belowbar, char= "▲", size = size.tiny, color = color.yellow)
alertcondition(LongSig and WLongSig == false, title='Bollinger Band Long', message='Bollinger Band Long Price is {{close}}, SL :{{plot_4}}')
alertcondition(ShortSig and WShortSig == false, title='Bollinger Band Short', message='Bollinger Band Short Price is {{close}},SL :{{plot_3}} ')
alertcondition(WLongSig, title='Wide Bollinger Band Long', message='Wide Bollinger Band Long Price is {{close}}, SL :{{plot_4}}')
alertcondition(WShortSig, title='Wide Bollinger Band Short', message='Wide Bollinger Band Short Price is {{close}},SL :{{plot_3}} ')
|
Anlik Trade Merkezi MA v2 | https://www.tradingview.com/script/nhgKRmLt-Anlik-Trade-Merkezi-MA-v2/ | hakanar | https://www.tradingview.com/u/hakanar/ | 9 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hakanar
//@version=5
indicator("Anlik Trade Merkezi MA v2", overlay=true)
InputSource = input.source(close, "Source", group="Moving Average")
InputSignalMA = input.int(9, minval=1, maxval=500, title="MA Signal Line", group="Moving Average")
InputMA01 = input.int(20, minval=1, maxval=500, title="MA Line 1", group="Moving Average")
InputMA02 = input.int(50, minval=1, maxval=500, title="MA Line 2", group="Moving Average")
InputMA03 = input.int(55, minval=1, maxval=500, title="MA Line 3", group="Moving Average")
InputMA04 = input.int(100, minval=1, maxval=500, title="MA Line 4", group="Moving Average")
InputMA05 = input.int(200, minval=1, maxval=500, title="MA Line 5", group="Moving Average")
InputShowMALines = input.bool(true, "Show MA Lines", group="MA Lines")
InputMATimeframe = input.timeframe("", "MA Line Resolution", group="MA Lines")
InputMATimeframe_Security = request.security(syminfo.tickerid, InputMATimeframe, InputSource)
InputMATimeframe_signal = ta.sma(InputMATimeframe_Security, InputSignalMA)
InputMATimeframe_MA01 = ta.ema(InputMATimeframe_Security, InputMA01)
InputMATimeframe_MA02 = ta.sma(InputMATimeframe_Security, InputMA02)
InputMATimeframe_MA03 = ta.sma(InputMATimeframe_Security, InputMA03)
InputMATimeframe_MA04 = ta.sma(InputMATimeframe_Security, InputMA04)
InputMATimeframe_MA05 = ta.sma(InputMATimeframe_Security, InputMA05)
plot(InputShowMALines ? InputMATimeframe_signal : na, color=color.new(color.white, 0), linewidth=2, title='MASignal')
plot(InputShowMALines ? InputMATimeframe_MA01 : na, color=color.new(color.blue, 40), linewidth=2, title='MA01')
plot(InputShowMALines ? InputMATimeframe_MA02 : na, color=color.new(color.green, 40), linewidth=2, title='MA03')
plot(InputShowMALines ? InputMATimeframe_MA03 : na, color=color.new(color.green, 40), linewidth=2, title='MA03')
plot(InputShowMALines ? InputMATimeframe_MA04 : na, color=color.new(color.red, 40), linewidth=2, title='MA04')
plot(InputShowMALines ? InputMATimeframe_MA05 : na, color=color.new(color.orange, 40), linewidth=2, title='MA05')
|
Squeeze + ADX + RSI + Stochastic RSI [Bybit en Español] | https://www.tradingview.com/script/VUeORbv7-Squeeze-ADX-RSI-Stochastic-RSI-Bybit-en-Espa%C3%B1ol/ | futura_matt | https://www.tradingview.com/u/futura_matt/ | 109 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Bybit Embajador de la Comunidad en Español: matetaronna
//@version=4
study(title="Squeeze + ADX + RSI + Stochastic RSI + MFI [Matt]", shorttitle="[All-In-One Indicator]", overlay=false)
//***************************************************************************************************************************************************************************************//
// Colors
colorRed = #ff0000
colorPurple = #e600e6
colorGreen = #3fff00
colorOrange = #e2a400
colorYellow = #ffe500
colorWhite = #ffffff
colorPink = #ff00f0
colorBluelight = #31c0ff
//***************************************************************************************************************************************************************************************//
//RSI
show_RSI = input(true, title="----------- Mostrar RSI-StochRSI-BB -----------", group="RSI-StochRSI-BB")
int rsiLengthInput = input(5, title="RSI Longitud", minval=1, step=1, group="RSI")
rsiSourceInput = input(close, title="RSI Fuente", type=input.source, group="RSI")
up = rma(max(change(rsiSourceInput), 0), rsiLengthInput)
down = rma(-min(change(rsiSourceInput), 0), rsiLengthInput)
rsi_x = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
//plot(rsi, "RSI", color=#7E57C2)
//STOCH RSI
smoothK = 3
smoothD = 3
lengthRSI = 14
lengthStoch = 14
rsi1 = rsi(close, lengthRSI)
k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(k, smoothD)
//BB
lengthBB = input(20, minval=1)
srcBB = input(close, title="Source", group="BB")
multBB = input(2.0, minval=0.001, maxval=50, title="StdDev", group="BB")
basisBB = sma(srcBB, lengthBB)
devBB = multBB * stdev(srcBB, lengthBB)
upperBB = basisBB + devBB
lowerBB = basisBB - devBB
//RSI + MFI
rsiMFIShow0 = input(true, title = "----------- Mostrar RSI-MFI (Barra) -----------", type = input.bool, group="RSI-MFI")
rsiMFIShow = input(true, title = "----------- Mostrar RSI-MFI -----------", type = input.bool, group="RSI-MFI")
rsiMFIperiod = input(60,title = 'MFI Period', type = input.integer, group="RSI-MFI")
rsiMFIMultiplier = input(380, title = 'MFI Area multiplier', type = input.float, group="RSI-MFI")
rsiMFIPosY = input(2.5, title = 'MFI Area Y Pos', type = input.float, group="RSI-MFI")
f_rsimfi(_period, _multiplier, _tf) => security(syminfo.tickerid, _tf, sma(((close - open) / (high - low)) * _multiplier, _period) - rsiMFIPosY)
rsiMFI = f_rsimfi(rsiMFIperiod, rsiMFIMultiplier, timeframe.period)
rsiMFIColor = rsiMFI > 0 ? #3ee145 : #ff3d2e
//****************************************************************************************************************************************************************************************//
// Squeeze Momentum
show_Momen = input(true, title="----------- Mostrar Squeeze Momentum -----------", group="Squeeze Momentum")
int lengthM = input(20, title="MOM Longitud", minval=1, step=1, group="Squeeze Momentum")
srcM = input(close, title="MOM Fuente", type=input.source, group="Squeeze Momentum")
int length = input(20, title="SQZ Longitud", minval=1, step=1, group="Squeeze Momentum")
src = input(close, title="SQZ Fuente", type=input.source, group="Squeeze Momentum")
color_bool = input(false, title="----------- Colores Originales -----------", group="Squeeze Momentum")
// Momentum
sz = linreg(srcM - avg(avg(highest(high, lengthM), lowest(low, lengthM)), sma(close, lengthM)), lengthM, 0)
// Condiciones del momento para elegir el color
sc1 = sz >= 0
sc2 = sz < 0
sc3 = sz >= sz[1]
sc4 = sz < sz[1]
// Asignamos el color final
colorSQ1 = color_bool ? #008000 : #90caf9
colorSQ2 = color_bool ? #00ff00 : #0d47a1
colorSQ3 = color_bool ? #800000 : #90caf9
colorSQ4 = color_bool ? #ff0000 : #0d47a1
colorSQ2_ = #131722
clr = sc1 and sc3 ? colorSQ2 : sc1 and sc4 ? colorSQ1 : sc2 and sc4 ? colorSQ4 : sc2 and sc3 ? colorSQ3 : color.gray
// Calculate BB
multKC = 1.5
source = close
basis = sma(source, lengthM)
dev = multKC * stdev(source, lengthM)
//upperBB = basis + dev
//lowerBB = basis - dev
// Calculate KC
lengthKC=20
ma = sma(source, lengthKC)
range = tr
rangema = sma(range, lengthKC)
upperKC = ma + rangema * multKC
lowerKC = ma - rangema * multKC
sqzOn = (lowerBB > lowerKC) and (upperBB < upperKC)
sqzOff = (lowerBB < lowerKC) and (upperBB > upperKC)
noSqz = (sqzOn == false) and (sqzOff == false)
val = linreg(source - avg(avg(highest(high, lengthKC), lowest(low, lengthKC)),sma(close,lengthKC)), lengthKC,0)
bcolor = iff( val > 0, iff( val > nz(val[1]), color.lime, color.green), iff( val < nz(val[1]), color.red, color.maroon))
scolor = noSqz ? color.blue : sqzOn ? color.yellow : color.gray
show_SQZ = input(true, title="----------- Mostrar Compresion de Bandas -----------")
//Abreviamos en variables los colores que utilizamos
openLongC = bcolor == color.lime
closeLongC = bcolor == color.green and bcolor[1] == color.green
closeLongC1W = bcolor == color.green
openShortC = bcolor == color.red
closeShortC = bcolor == color.maroon and bcolor[1] == color.maroon
closeShortC1W = bcolor == color.maroon
//****************************************************************************************************************************************************************************************//
// ADX
// Variables extra
int scale = 75
useTrueRange = true
show_ADX = input(true, title="----------- Mostrar ADX -----------", group="ADX")
scaleADX = 2
int far = input(-3, title="Desfase del ADX", minval=-10, step=1, group="ADX")
int adxlen = input(14, title="ADX Longitud", minval=1, step=1, group="ADX")
int dilen = input(14, title="DI Longitud", minval=1, step=1, group="ADX")
keyLevel = input(23, title="Key Level", minval=1, step=1, group="ADX")
// Operaciones del ADX en si
dirmov(len) =>
up = change(high)
down = -change(low)
truerange = rma(tr, len)
plus = fixnan(100 * rma(up > down and up > 0 ? up : 0, len) / truerange)
minus = fixnan(100 * rma(down > up and down > 0 ? down : 0, len) / truerange)
[plus, minus]
adx(dilen, adxlen) =>
[plus, minus] = dirmov(dilen)
sum = plus + minus
adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
[adx, plus, minus]
// Valor final del ADX
[adxValue, diplus, diminus] = adx(dilen, adxlen)
// Calculamos el scale del ADX respecto a los otros indicadores
biggest(series) =>
max = 0.0
max := nz(max[1], series)
if series > max
max := series
max
ni = biggest(sz)
far1=far* ni/scale
adx_scale = (adxValue - keyLevel) * ni/scale
adx_scale2 = (adxValue - keyLevel+far) * ni/scale
//Variables de fuerza utilizadas en el calculo de las posiciones
adxForce = adxValue > adxValue[1] and adxValue < 35
adxNoForce = adxValue < adxValue[1] and adxValue[1] < adxValue[2]
adxNoForce1W = adxValue < adxValue[1]
//****************************************************************************************************************************************************************************************//
// Plot de todo
// RSI + MFI
// Barra de Abajo
zLine = plot(0, color = color.new(colorWhite, 100))
rsiMfiBarTopLine = plot(rsiMFIShow0 ? -55 * (ni/scale) : na, title = 'MFI Bar TOP Line', color = color.new(colorWhite, 100))
rsiMfiBarBottomLine = plot(rsiMFIShow0 ? -59 * (ni/scale) : na, title = 'MFI Bar BOTTOM Line', color = color.new(colorWhite, 100))
fill(rsiMfiBarTopLine, rsiMfiBarBottomLine, title = 'MFI Bar Colors', color = color.new(rsiMFIColor, 75))
// Ondas
rsiMFIplot = plot(rsiMFIShow ? rsiMFI * (ni/scale) : na, title = 'RSI+MFI Area', color = color.new(rsiMFIColor, 75))
fill(rsiMFIplot, zLine, color = color.new(rsiMFIColor, 70))
//ADX
plot(show_ADX ? far1 * scaleADX : na, color=color.white, title="KeyLevel", linewidth = 1)
p1 = plot(show_ADX ? adx_scale2 * scaleADX : show_ADX ? adx_scale * scaleADX : na, color = color.purple, title = "ADX", linewidth = 2)
// RSI + STOCHASTIC
plotchar(show_RSI and d < 30 and rsi_x < 30 and close < lowerBB and rsiMFI < 0 ? -40 * (ni/scale) : na, title = 'Buy circle', char='•', color = color.new(colorGreen, 50), location = location.absolute, size = size.small)
plotchar(show_RSI and d > 70 and rsi_x > 70 and close > upperBB and rsiMFI > 0 ? 40 * (ni/scale) : na, title = 'Sell circle', char='•', color = color.new(colorRed, 50), location = location.absolute, size = size.small)
// SQUEEZE
plot(show_Momen ? sz * 1.5 : na, title = "Momentum", color = color.new(clr, 0), style=plot.style_area, linewidth = 4)
plot(show_SQZ ? 0 : na, title = "Squeeze", color = color.new(scolor, 0), style=plot.style_circles, linewidth=1)
//****************************************************************************************************************************************************************************************//
// Divergencias
show_div=input(true,title="-------- Divergencias --------", group="Divergencias [Monitor]")
lbR = input(title="Pivot Lookback Right", defval=1, group="Divergencias [Monitor]")
lbL = input(title="Pivot Lookback Left", defval=1, group="Divergencias [Monitor]")
rangeUpper = input(title="Max of Lookback Range", defval=60, group="Divergencias [Monitor]")
rangeLower = input(title="Min of Lookback Range", defval=1, group="Divergencias [Monitor]")
plotBull = input(title="Plot Bullish", defval=true, group="Divergencias [Monitor]")
plotBear = input(title="Plot Bearish", defval=true, group="Divergencias [Monitor]")
bearColor = #ff0000
bullColor = #1bff00
hiddenBullColor = #a4ff99
hiddenBearColor = #ff9e9e
textColor = color.white
noneColor = color.new(color.white, 100)
// Funciones
plFound(osc) => na(pivotlow(osc, lbL, lbR)) ? false : true
phFound(osc) => na(pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
_findDivRB(osc)=>
// Osc: Higher Low
oscHL = osc[lbR] > valuewhen(plFound(osc), osc[lbR], 1) and _inRange(plFound(osc)[1])
// Price: Lower Low
priceLL = low[lbR] < valuewhen(plFound(osc), low[lbR], 1)
bullCond = plotBull and priceLL and oscHL and plFound(osc)
//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High
oscLH = osc[lbR] < valuewhen(phFound(osc), osc[lbR], 1) and _inRange(phFound(osc)[1])
// Price: Higher High
priceHH = high[lbR] > valuewhen(phFound(osc), high[lbR], 1)
bearCond = plotBear and priceHH and oscLH and phFound(osc)
[bullCond,bearCond]
[sz_bullCond,sz_bearCond]=_findDivRB(sz)
foundDivBSZ = plFound(sz) and show_Momen and show_div ? true : false
colordivBSZ = sz_bullCond ? bullColor : noneColor
foundDivBeSZ = phFound(sz) and show_Momen and show_div ? true : false
colordivBeSZ = sz_bearCond ? bearColor : noneColor
plot(
foundDivBSZ ? sz[lbR]* 1.5 : na,
offset=-lbR,
title="Regular Bullish",
linewidth=1,
color=colordivBSZ,
transp=0
)
plot(
foundDivBeSZ ? sz[lbR]* 1.5 : na,
offset=-lbR,
title="Regular Bullish",
linewidth=1,
color=colordivBeSZ,
transp=0
)
//****************************************************************************************************************************************************************************************//
// Informacion del Indicador
// Tendencia General
//Esta funcion nos permite llamar a security() sin problemas
f_secureSecurity(_symbol, _res, _src) => security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)
//Diferenciamos y marcamos una tendencia bien definida, nos enfocamos en los graficos mas a largo plazo
ema25 = ema(close, 25)
ema55 = ema(close, 55)
ema200 = ema(close, 200)
//RSI
rsiStory = f_secureSecurity(syminfo.tickerid, "D", close) > f_secureSecurity(syminfo.tickerid, "D", ema200) ? (f_secureSecurity(syminfo.tickerid, "D", rsi_x < 40) and f_secureSecurity(syminfo.tickerid, "240", rsi_x < 40) ? "RSI -> STRONG BUY [BULL]" : f_secureSecurity(syminfo.tickerid, "D", rsi_x > 75) and f_secureSecurity(syminfo.tickerid, "240", rsi_x > 75) ? "RSI -> STRONG SELL [BULL]" : "RSI --> NADA") : f_secureSecurity(syminfo.tickerid, "D", close) < f_secureSecurity(syminfo.tickerid, "D", ema200) ? (f_secureSecurity(syminfo.tickerid, "D", rsi_x < 25) and f_secureSecurity(syminfo.tickerid, "240", rsi_x < 25) ? "RSI -> STRONG BUY [BEAR]" : f_secureSecurity(syminfo.tickerid, "D", rsi_x > 60) and f_secureSecurity(syminfo.tickerid, "240", rsi_x > 60) ? "RSI -> STRONG SELL [BEAR]" : "RSI --> NADA") : "RSI --> NADA"
//BullTrend
//longTrend1W = f_secureSecurity(syminfo.tickerid, "1W", (closeShortC1W and adxNoForce1W) or openLongC)
longTrend1D = f_secureSecurity(syminfo.tickerid, "D", (closeShortC and (adxNoForce or adxValue < 23)) or (openLongC and adxForce))
longTrend4HR = f_secureSecurity(syminfo.tickerid, "240", close > ema25)
BullTrend = (longTrend1D and longTrend4HR)
//BearTrend
shortTrend1D = f_secureSecurity(syminfo.tickerid, "D", (closeLongC) or (openShortC and adxForce))
shortTrend4HR = f_secureSecurity(syminfo.tickerid, "240", low < ema55)
BearTrend = (shortTrend1D and shortTrend4HR)
//NeutralTrend
NeutralTrend = not BullTrend and not BearTrend
trend = BearTrend ? "BAJISTA" : BullTrend ? "ALCISTA" : NeutralTrend ? "NEUTRAL" : na
//ATR calculation for stoplosses
atrValue = rma(tr, 14)
stopLong = tostring(lowest(low, 14) - atrValue, "#.####")
stopShort = tostring(highest(high, 14) + atrValue, "#.####")
//Inputs
show_status = input(true, title = "----------- Mostrar Status ------------", group="General")
dist= input(10,title="Distancia del monitor", group="General")
dashColor = input(color.new(#696969, 90), "label Color", inline="Dash Line", group="General")
dashTextColor = input(color.new(#ffffff, 0), "Text Color", inline="Dash Line", group="General")
if(adxValue > adxValue[1] and adxValue > 23)
iadx='ADX con pendiente positiva por encima punto 23'
if(adxValue > adxValue[1] and adxValue < 23)
iadx='ADX con pendiente positiva por debajo punto 23'
if(adxValue < adxValue[1] and adxValue < 23)
iadx='ADX con pendiente negativa por debajo punto 23'
if(adxValue < adxValue[1] and adxValue > 23)
iadx='ADX con pendiente negativa por encima punto 23'
a1=adxValue >= 23
a2=adxValue < 23
a3=adxValue >= adxValue[1]
a4=adxValue < adxValue[1]
iAdx = a1 and a3 ? 'Pendiente positiva ↑ 23' : a1 and a4 ? 'Pendiente negativa ↑ 23' :
a2 and a4 ? 'Pendiente negativa ↓ 23' : a2 and a3 ? 'Pendiente positiva ↓ 23' : '-'
iMom = sc1 and sc3 ? 'Direccionalidad alcista' : sc1 and sc4 ? 'Direccionalidad bajista' :
sc2 and sc4 ? 'Direccionalidad bajista' : sc2 and sc3 ? 'Direccinalidad alcista' : '-'
igral = a1 and a3 and sc1 and sc3 ? 'Fuerte movimiento alcista' : a1 and a3 and sc1 and sc4 ? 'Monitor muestra rango-caida pero\nel movimiento tiene fuerza':
a1 and a3 and sc2 and sc4 ? 'Fuerte movimiento bajista' : a1 and a3 and sc2 and sc3 ? 'Monitor muestra rango-subida pero\nel movimiento tiene fuerza':
a1 and a4 and sc1 and sc3 ? 'Movimiento alcista sin fuerza' : a1 and a4 and sc1 and sc4 ? 'Monitor muestra rango-caida\n pendiente negativa en ADX ':
a1 and a4 and sc2 and sc4 ? 'Movimiento bajista sin fuerza' : a1 and a4 and sc2 and sc3 ? 'Monitor muestra rango-subida con \npendiente negativa en ADX ':
a2 and a4 and sc1 and sc3 ? 'Movimiento alcista sin fuerza' : a2 and a4 and sc1 and sc4 ? 'Monitor muestra rango-caida sin fuerza ':
a2 and a4 and sc2 and sc4 ? 'Movimiento bajista sin fuerza' : a2 and a4 and sc2 and sc3 ? 'Monitor muestra rango-subida sin fuerza ':
a2 and a3 and sc1 and sc3 ? 'Movimiento alcista que \n quiere agarrar fuerza' : a2 and a3 and sc1 and sc4 ? 'Monitor muestra rango-caida,\n el movimiento quiere agarrar fuerza':
a2 and a3 and sc2 and sc4 ? 'Movimiento bajista que \n quiere agarrar fuerza' : a2 and a3 and sc2 and sc3 ? 'Monitor muestra rango-subida,\n el movimiento quiere agarrar fuerza': '-'
scr_label='- ADX: '+iAdx+'\n- Monitor: '+iMom+'\n- Overal BIAS: '+igral+"\n"+rsiStory+"\n- SL para Long: "+stopLong+"\n- SL para Short: "+stopShort+"\n- Tendencia General: "+trend
if show_status
lab_l = label.new(
bar_index + dist, 0, scr_label,
color = dashColor,
textcolor = dashTextColor,
style = label.style_label_left,
yloc = yloc.price,
size = size.normal)
label.delete(lab_l[1])
//****************************************************************************************************************************************************************************************// |
Anlik Trade Merkezi Supertrend | https://www.tradingview.com/script/SlBR2iW7-Anlik-Trade-Merkezi-Supertrend/ | hakanar | https://www.tradingview.com/u/hakanar/ | 86 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hakanar
//@version=5
indicator("Anlik Trade Merkezi Supertrend", overlay=true, timeframe="", timeframe_gaps=true)
atrPeriod = input(10, "ATR Length")
factor = input.float(1.05, "Factor", step = 0.01)
vwmaLength = input.int(10, "vwma Length")
showsignals = input.bool(true, "Show Signals")
pine_vwma(x, y, volume) =>
ta.sma(x * volume, y) / ta.sma(volume, y)
//the same on pine
pine_atr(length) =>
trueRange = na(high[1])? high-low : math.max(math.max(high - low, math.abs(high - close[1])), math.abs(low - close[1]))
//true range can be also calculated with ta.tr(true)
ta.rma(trueRange, length)
// The same on Pine
pine_supertrend(factor, atrPeriod) =>
src = hl2
atr = pine_atr(atrPeriod)
vwma = pine_vwma(hl2, vwmaLength, volume)
newfactor = factor + (vwma[1] / vwma[18])
upperBand = src + newfactor * atr
lowerBand = src - newfactor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
vwmaclose_1 = close[1]
vwmaclose = close
lowerBand := lowerBand > prevLowerBand or vwmaclose_1 < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or vwmaclose_1 > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := vwmaclose > upperBand ? -1 : 1
else
direction := vwmaclose < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
[superTrend, direction]
[supertrend, direction] = pine_supertrend(factor, atrPeriod)
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
plotshape(ta.change(direction) < 0 and showsignals ? supertrend : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white)
plotshape(ta.change(direction) > 0 and showsignals ? supertrend : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white) |
EMA TREND CLOUD | https://www.tradingview.com/script/RuTYaSkt-EMA-TREND-CLOUD/ | rwestbrookjr | https://www.tradingview.com/u/rwestbrookjr/ | 83 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Ron Westbrook (discord: disturbinglymellow#4075)
// Date: 5/17/2021
// Description: Plots two exponential moving averages and places a colored cloud between to indicate trend direction. Default values of 9 and 20 periods have worked well for me, but inputs are available if you choose to change them. If you like my work and want to support more of it please consider leaving me a tip here. https://tinyurl.com/tipron
//@version=5
indicator(title='EMA TREND CLOUD', overlay=true)
fastLen = input(title='Fast EMA Length', defval=9)
slowLen = input(title='Slow EMA Length', defval=20)
useTextLabels = input.bool(true, title='Use Text-Based Crossover Labels?', group='Crossover Moving Averages')
fastEMA = ta.ema(close, fastLen)
slowEMA = ta.ema(close, slowLen)
fema = plot(fastEMA, title='FastEMA', color=color.new(color.green, 0), linewidth=1, style=plot.style_line)
sema = plot(slowEMA, title='SlowEMA', color=color.new(color.red, 0), linewidth=1, style=plot.style_line)
fill(fema, sema, color=fastEMA > slowEMA ? color.new(#417505, 50) : color.new(#890101, 50), title='Cloud')
// Bull and Bear Alerts
Bull = ta.crossover(fastEMA, slowEMA)
Bear = ta.crossunder(fastEMA, slowEMA)
plotshape(Bull, title='Calls Label', color=color.new(color.green, 25), textcolor=useTextLabels ? color.white : color.new(color.white, 100), style=useTextLabels ? shape.labelup : shape.triangleup, text='Calls', location=location.belowbar)
plotshape(Bear, title='Puts Label', color=color.new(color.red, 25), textcolor=useTextLabels ? color.white : color.new(color.white, 100), style=useTextLabels ? shape.labeldown : shape.triangledown, text='Puts', location=location.abovebar)
if Bull
alert('Calls Alert: 9ema crossed over 20ema', alert.freq_once_per_bar_close)
if Bear
alert('Puts Alert: 9ema crossed under 20ema', alert.freq_once_per_bar_close)
|
Quad-EMA | https://www.tradingview.com/script/jcNAvBzS-Quad-EMA/ | zobad16 | https://www.tradingview.com/u/zobad16/ | 10 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © zobad16
//@version=5
//Inputs
MA1 = input.int(10,"MA 1 Length")
MA1Color = input.color(color.blue , "MA 1 Color")
MA2 = input.int(50,"MA 2 Length")
MA2Color = input.color(color.green , "MA 2 Color")
MA3 = input.int(100,"MA 3 Length")
MA3Color = input.color(color.red , "MA 3 Color")
MA4 = input.int(200,"MA 4 Length")
MA4Color = input.color(color.purple , "MA 4 Color")
indicator("Tripple-EMA", overlay=true)
//Plot MA1
plot(ta.ema(close, MA1), color = MA1Color)
//Plot MA2
plot(ta.ema(close, MA2), color = MA2Color)
//Plot MA3
plot(ta.ema(close, MA3), color = MA3Color)
//Plot MA4
plot(ta.ema(close, MA4), color = MA4Color) |
Trend Day Indentification | https://www.tradingview.com/script/3tRKY7B0-Trend-Day-Indentification/ | Marcn5_ | https://www.tradingview.com/u/Marcn5_/ | 102 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Marcns_
//@version=4
study("Trend Day")
// a script that identifies trend days for the purpose of 1) counting how often they occur
// and 2) predicting intraday reversion regime the following day
// atr filter indicating that range expansion today is highest over previous 3 periods
r = atr(1)
RangeEx = 0.0
if r >= highest(r, 5)
RangeEx := 1.0
else
na
//definition of a trend day - opens in the upper or lower 15% of it's range.
// and closes in the opposite upper or lower 15% of its range
TrndExThreshold_Open = input(0.15)
TrndExThreshold_Close = input(0.15)
//#1 open within 15% of low
OpenAtLow = 0.0
if (close > open) and (open-low) / (high-low) < TrndExThreshold_Open
OpenAtLow := 1.0
else
na
//#2 close within 15% of high
CloseAtHigh = 0.0
if (close > open) and (high-close) / (high-low) < TrndExThreshold_Close
CloseAtHigh := 1.0
else
na
TrendDayUp = 0.0
if OpenAtLow + CloseAtHigh + RangeEx == 3.0
TrendDayUp := 1
else
na
plot(TrendDayUp, title = "TrdUp")
OpenAtHigh = 0.0
if (close < open) and (high-open) / (high-low) < TrndExThreshold_Open
OpenAtHigh := 1.0
else
na
//#2 close within 15% of high
CloseAtLow = 0.0
if (close < open) and (close-low) / (high-low) < TrndExThreshold_Close
CloseAtLow := 1.0
else
na
TrendDayDown = 0.0
if OpenAtHigh + CloseAtLow + RangeEx == 3.0
TrendDayDown := 1
else
na
plot(TrendDayDown, title = "TrdDn", color = color.red)
//
|
Trending Bollinger Bands by SiddWolf | https://www.tradingview.com/script/l0104d5M-Trending-Bollinger-Bands-by-SiddWolf/ | SiddWolf | https://www.tradingview.com/u/SiddWolf/ | 89 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SiddWolf
//@version=5
indicator(title="Trending Bollinger Bands by SiddWolf", shorttitle="TBB [SiddWolf]", overlay=true, timeframe="", timeframe_gaps=false)
calc_ma(source, length, type) =>
type == "SMA" ? ta.sma(source, length) :
type == "EMA" ? ta.ema(source, length) :
type == "SMMA (RMA)" ? ta.rma(source, length) :
type == "WMA" ? ta.wma(source, length) :
type == "VWMA" ? ta.vwma(source, length) :
type == "HMA" ? ta.hma(source, length) :
na
mee_ma_type = input.string(title="Moving Average: ", defval="SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], inline="MA")
mee_ma_length = input.int(title="Length", defval=50, minval=1, maxval=300, inline="MA")
mee_ma_src_basis = input.source(title="Basis Source", defval=hl2, inline="src")
mee_ma_src_band = input.string(title="Band Source", defval="Close", options=["Close", "High/Low"], inline="src")
mult_a = input.float(1.618, minval=0.001, maxval=50, title="StdDev Inner", inline="mult")
mult_b = input.float(2.618, minval=0.001, maxval=50, title="StdDev Outer", inline="mult")
basis = calc_ma(mee_ma_src_basis, mee_ma_length, mee_ma_type)
basis_top_for_aa = calc_ma(close , mee_ma_length, mee_ma_type)
basis_bottom_for_aa = calc_ma(close , mee_ma_length, mee_ma_type)
basis_top_for_bb = calc_ma(mee_ma_src_band == "Close" ? close : high , mee_ma_length, mee_ma_type)
basis_bottom_for_bb = calc_ma(mee_ma_src_band == "Close" ? close : low , mee_ma_length, mee_ma_type)
dev_a = mult_a * ta.stdev(close, mee_ma_length)
dev_b = mult_b * ta.stdev(close, mee_ma_length)
upper_a = basis_top_for_aa + dev_a
lower_a = basis_bottom_for_aa - dev_a
upper_b = basis_top_for_bb + dev_b
lower_b = basis_bottom_for_bb - dev_b
upper_b_plus_atr = upper_b + ta.atr(math.floor(mee_ma_length/2))
lower_b_plus_atr = lower_b - ta.atr(math.floor(mee_ma_length/2))
upper_a_minus_atr = upper_a - ta.atr(math.floor(mee_ma_length/2))
lower_a_minus_atr = lower_a + ta.atr(math.floor(mee_ma_length/2))
plot(basis, "Basis", color=#FF6D00)
p_upper_a_minus_atr = plot(upper_a_minus_atr, "Upper_AA", color=color.new(#0000ff, 50))
p_upper_b_plus_atr = plot(upper_b_plus_atr, "Upper_BB", color=color.new(#0000ff, 50))
p_lower_a_minus_atr = plot(lower_a_minus_atr, "Lower_AA", color=color.new(#0000ff, 50))
p_lower_b_plus_atr = plot(lower_b_plus_atr, "Lower_BB", color=color.new(#0000ff, 50))
p_upper_a = plot(upper_a, "Upper_aa", color=color.new(#2962FF, 90), display=display.none)
p_upper_b = plot(upper_b, "Upper_bb", color=color.new(#2962FF, 90), display=display.none)
p_lower_a = plot(lower_a, "Lower_aa", color=color.new(#2962FF, 90), display=display.none)
p_lower_b = plot(lower_b, "Lower_bb", color=color.new(#2962FF, 90), display=display.none)
fill(p_upper_a, p_upper_b, title = "Background Green Inner", color=color.new(#00ff00, 95))
fill(p_lower_a, p_lower_b, title = "Background Red Inner", color=color.new(#ff0000, 95))
fill(p_upper_a_minus_atr, p_upper_b_plus_atr, title = "Background Green Outer", color=color.new(#00ff00, 95))
fill(p_lower_a_minus_atr, p_lower_b_plus_atr, title = "Background Red Outer ", color=color.new(#ff0000, 95))
|
Earnings Price Move Cheat Sheet [KT] | https://www.tradingview.com/script/oKUj0d2n-Earnings-Price-Move-Cheat-Sheet-KT/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 559 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KioseffTrading
//@version=5
indicator("Earnings Price Move Cheat Sheet [Kioseff Trading]", overlay = true, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)
// ________________________________________________
// | |
// | --------------------------------- |
// | | K̲ i̲ o̲ s̲ e̲ f̲ f̲ T̲ r̲ a̲ d̲ i̲ n̲ g | |
// | | | |
// | | ƃ u ᴉ p ɐ ɹ ꓕ ⅎ ⅎ ǝ s o ᴉ ꓘ | |
// | -------------------------------- |
// | |
// |_______________________________________________|
// _______________________________________________________
//
// Free Parameters
// _______________________________________________________
len = input.int(title = "Calculation Period -- This Setting Defines the Calculated %Gain/Loss Period BEFORE and AFTER Earnings", defval = 10, minval = 1, maxval = 20, group = "Utility")
all = input.string(title = "Use All Historical Sessions for VaR Calculation? ([250 Sessions] Otherwise)", defval = "Yes", options = ["Yes", "No"])
conf = input.int(title = "VaR Confidence Level", defval = 95, maxval = 99, minval = 95, tooltip = 'Value at Risk (VaR) Is a Measure Which Attempts to Quantify the Risk of Potential Losses. There Are a Few Ways to Calculate the Metric; This Indicator Uses the Historical Method to Calculate VaR. A Confidence Level Is Assigned to the Calculation. Using the Historical Method, for This Script, All Return Values Are Appended to Array A. The Lowest Return Values (Greatest Losses), Based on the Assigned Confidence Level, Are Extracted and Appended to Array B. The Greatest Measurement in Array B Reflects the VaR Measurement at the Assigned Confidence Level. For Instance, if VaR Confidence Is Set to 95%, Returns are Categorized by the Lowest 5% Of Returns and the Greatest 95% Of Returns. The Highest Measure (Lowest Loss) In the 5th Percentile for Returns Is Considered the VaR Measure. Ideally, One Could Look at the VaR Measure (95% Confidence) and Proclaim (“I Am 95% Confident That Any One-Session Loss Over the Next [Month, Year, Quarter, Etc] Will Not Be Greater Than the VaR 95% Measure”.) Of Course, the Inevitable Black Swan Is an Incalculable Occurrence - Be Sure to Assess Results With This in Mind. ')
sfi = input.string("READ TOOLTIP", title = "Expected Shortfall (CVaR) Explanation", options = ["READ TOOLTIP", "⚫🦢 <= Keep In Mind!"], tooltip = "CVaR Is a Supplementary Risk Measure That Quantifies the Magnitude of Tail Risk. CVaR Averages Losses That Extend Beyond the VaR Threshold. Simply, CVaR Measures the Average Return (Loss) When the Return Is Less Than the VaR Measurement. For Instance, if VaR Incorporates a 95% Confidence Level and the Measure Is -2.43%, CVaR Calculates All Losses That Exceed -2.43% and Averages Them. For This Script, if a Losing Return Exceeds the VaR Measure the Return Is Appended to an Array. The Average Is Taken of All Values in the Array. If the CVaR (Expected Shortfall Measurement) Is - 3.12%, and the VaR Measurement Is -2.43%, It Means That When a Loss Is Greater Than -2.43%, on Average, That Loss Will Be -3.12%. This Is Generally Done Within the Context of Portfolio Management; However, This Only Script Uses Daily Asset Returns.")
lope = input.string(defval = "Off", title = "Use Linear Interploation Pine Function for VaR and Expected Shortfall?", options = ["Off", "On"])
// _______________________________________________________
//
// Display Setting
// _______________________________________________________
statLabel = input.string("On", title = "Show Fundamental Statistics Label?", options = ["On", "Off", "Half"], group = "Display")
tab = input.string("No", title = "Hide Table?", options = ["No", "Yes"])
Band = input.string("Off", title = "Show CVaR and VaR as Bands? ", options = ["Off", "On"])
sizE = input.string(defval = "Tiny", title = "Label Size", options = ["Tiny", "Small", "Auto"])
LLHHlabels = input.string(defval = "On", title = "Show Highest/High and Lowest Low Labels?", options = ["On", "Off"])
// _______________________________________________________
//
// Earnings Identifiers
// _______________________________________________________
earnings() => request.earnings(syminfo.tickerid, earnings.actual, ignore_invalid_symbol = true)
est() => request.earnings(syminfo.tickerid, earnings.estimate, ignore_invalid_symbol = true)
surp = ta.change(earnings()) and earnings() > est()
miss = ta.change(earnings()) and earnings() < est()
pScore = request.financial(syminfo.tickerid, "PIOTROSKI_F_SCORE", "FQ", currency = syminfo.currency, ignore_invalid_symbol = true)
zScore = request.financial(syminfo.tickerid, "ALTMAN_Z_SCORE", "FQ", currency = syminfo.currency, ignore_invalid_symbol = true)
qScore = request.financial(syminfo.tickerid, "QUICK_RATIO", "FQ", currency = syminfo.currency, ignore_invalid_symbol = true)
bScore = request.financial(syminfo.tickerid, "BENEISH_M_SCORE", "FQ", currency = syminfo.currency, ignore_invalid_symbol = true)
sScore = request.financial(syminfo.tickerid, "SLOAN_RATIO", "FQ", currency = syminfo.currency, ignore_invalid_symbol = true)
kScore = request.financial(syminfo.tickerid, "KZ_INDEX", "FY", currency = syminfo.currency, ignore_invalid_symbol = true)
dI = request.financial(syminfo.tickerid, "DAYS_INVENT", "FQ", currency = syminfo.currency, ignore_invalid_symbol = true)
dE = request.financial(syminfo.tickerid, "DEBT_TO_EBITDA", "FQ", currency = syminfo.currency, ignore_invalid_symbol = true)
hScore = request.financial(syminfo.tickerid, "FULMER_H_FACTOR", "FQ", currency = syminfo.currency, ignore_invalid_symbol = true)
gN = request.financial(syminfo.tickerid, "GRAHAM_NUMBERS", "FQ", currency = syminfo.currency, ignore_invalid_symbol = true)
nR = request.financial(syminfo.tickerid, "NCAVPS_RATIO", "FQ", currency = syminfo.currency, ignore_invalid_symbol = true)
PEG = request.financial(syminfo.tickerid, "PEG_RATIO", "FY", currency = syminfo.currency, ignore_invalid_symbol = true)
totalShort = request.security(syminfo.ticker + "_SHORT_VOLUME", "D", close, ignore_invalid_symbol = true)
// _______________________________________________________
//
// Array Creation
// _______________________________________________________
var float [] x = array.new_float()
var int [] y = array.new_int()
var float [] x2 = array.new_float()
var int [] y2 = array.new_int()
var float [] x3 = array.new_float()
var int [] y3 = array.new_int()
var float [] x4 = array.new_float()
var float [] x5 = array.new_float()
var float [] x6 = array.new_float()
var float [] x7 = array.new_float()
var float [] x8 = array.new_float()
var int [] y4 = array.new_int()
var float [] x9 = array.new_float()
var float [] x10 = array.new_float()
var float [] x11 = array.new_float()
var float [] q1 = array.new_float()
var float [] q2 = array.new_float()
var float [] q3 = array.new_float()
var float [] q4 = array.new_float()
var int [] q1count = array.new_int()
var int [] q2count = array.new_int()
var int [] q3count = array.new_int()
var int [] q4count = array.new_int()
var float [] track1 = array.new_float()
var float [] track2 = array.new_float()
var float [] track3 = array.new_float()
var float [] track4 = array.new_float()
var float [] zx = array.new_float()
var float [] zx1 = array.new_float()
var float [] zx2 = array.new_float()
var float [] zx3 = array.new_float()
var float [] zx4 = array.new_float()
var float [] zx5 = array.new_float()
var float [] zx6 = array.new_float()
var float [] zx7 = array.new_float()
var float date = na
var float date1 = na
var float date2 = na
var float date3 = na
var float date4 = na
var float date5 = na
var float date6 = na
var float date7 = na
var float date8 = na
var float date9 = na
var float date10 = na
var float date11 = na
// _______________________________________________________
//
// PnL Caclculation
// _______________________________________________________
pl(x, y) =>
((x / y) - 1) * 100
// _______________________________________________________
//
// Array Appending
// _______________________________________________________
if ta.change(earnings())
array.push(x, pl(close, close[len]))
array.push(y, 1)
array.push(y3, bar_index)
array.push(x4, close)
array.push(x5, high)
array.push(x6, ohlc4)
array.push(x7, volume)
array.push(x8, totalShort)
array.push(x9, pl(close, close[1]))
for i = 0 to len - 1
array.push(x10, volume[i])
array.push(x11, totalShort[i])
if totalShort > 0
array.push(y4, 1)
if month(time) >= 1 and month(time) <= 3
array.push(track1, earnings() - est())
array.push(zx, earnings())
array.push(zx1, est())
date := year(time)
date1 := month(time)
date2 := dayofmonth(time)
if month(time) >= 4 and month(time) <= 6
array.push(track2, earnings() - est())
array.push(zx2, earnings())
array.push(zx3, est())
date3 := year(time)
date4 := month(time)
date5 := dayofmonth(time)
if month(time) >= 7 and month(time) <= 9
array.push(track3, earnings() - est())
array.push(zx4, earnings())
array.push(zx5, est())
date6 := year(time)
date7 := month(time)
date8 := dayofmonth(time)
if month(time) >= 10 and month(time) <= 12
array.push(track4, earnings() - est())
array.push(zx6, earnings())
array.push(zx7, est())
date9 := year(time)
date10 := month(time)
date11 := dayofmonth(time)
if ta.barssince(ta.change(earnings())) == len
array.push(x2, pl(close, close[len]))
array.push(y2, 1)
array.push(x3, pl(close, close[20]))
if month(time) >= 1 and month(time) <= 3
array.push(q1, pl(close, close[len]))
array.push(q1count, 1)
if month(time) >= 4 and month(time) <= 6
array.push(q2, pl(close, close[len]))
array.push(q2count, 1)
if month(time) >= 7 and month(time) <= 9
array.push(q3, pl(close, close[len]))
array.push(q3count, 1)
if month(time) >= 10 and month(time) <= 12
array.push(q4, pl(close, close[len]))
array.push(q4count, 1)
// _______________________________________________________
//
// Average PnL Calculation
// _______________________________________________________
calc(j, z) =>
array.sum(j) / array.sum(z)
b4 = calc(x, y)
aftr = calc(x2, y2)
vol = calc(x7, y)
shortvol = calc(x8, y4)
q1x = calc(q1, q1count)
q2x = calc(q2, q2count)
q3x = calc(q3, q3count)
q4x = calc(q4, q4count)
sizeOption = sizE == "Tiny" ? size.tiny : sizE == "Small" ? size.small : size.auto
// _______________________________________________________
//
// Line/Label Arrays
// _______________________________________________________
var int counter = 0
var int counter1 = 0
var label [] f = array.new_label()
var line [] fx = array.new_line()
var line [] fxx = array.new_line()
var label [] f1 = array.new_label()
var line [] fx1 = array.new_line()
var label[] f2 = array.new_label()
var line [] f2x = array.new_line()
var line [] fxxx = array.new_line()
var label z1 = na
var label z2 = na
var label z3 = na
var line o = na
var line o1 = na
var label [] stats = array.new_label()
var line [] statsLine = array.new_line()
var line [] statsLine1 = array.new_line()
// _______________________________________________________
//
// HH/LL
// _______________________________________________________
llfix = ta.lowest(low, 20)
hh = ta.highest(array.size(y3) > 0 ? bar_index + 1 - array.get(y3, array.size(y3) - 1): 1)
ll = ta.lowest(array.size(y3) > 0 ? bar_index + 1 - array.get(y3, array.size(y3) - 1): 1)
difference(x,y) =>
j = math.abs(x) - math.abs(y)
n = j / ((x + y) / 2)
fin = n * 100
fin
difference1 = ta.barssince(hh != hh[1]) > ta.barssince(ll != ll[1]) ? ((ll / hh) - 1) * 100 : ((hh / ll) - 1) * 100
hls = difference1 < 0.0 ? "\n(HH to LL)" : "\n(LL to HH)"
hPlot = plot(hh, color = counter == 1 ? color.new(color.white, 50) : color(na))
lPlot = plot(ll, color = counter == 1 ? color.new(color.white, 50) : color(na))
fill(hPlot, lPlot, color = counter == 1 ? color.new(color.blue, 75) : na)
if counter[1] == 0 and counter == 1
o := line.new(bar_index, hh, bar_index, ll, color = color.new(color.white, 50))
if counter > 0
counter1 += 1
if counter == 0
counter1 := 0
// _______________________________________________________
//
// Line/Label Plots
// _______________________________________________________
if ta.change(earnings())
counter := 1
array.push(f,
label.new(
bar_index - len,
high * 1.04,
color = array.get(x, array.size(x) - 1) >= 0.0 ? color.new(color.green, 50) : color.new(color.red, 50),
textcolor = color.white,
text = str.tostring(len, "#") + "-Session Gain/Loss Prior to Earnings: " + str.tostring(array.get(x, array.size(x) - 1), format.percent) + "\nAverage " + str.tostring(len, "#") + "-Session Gain/Loss Prior to Earnings: "
+ str.tostring(b4, format.percent),
size = sizeOption
))
if year(time) > 2013
if statLabel == "Half"
array.push(stats, label.new(bar_index[len], llfix, text = "F-Score: " + str.tostring(pScore, "#") + "\nAltZ-Score: " + str.tostring(zScore, format.mintick) + "\nQuick Ratio: "
+ str.tostring(qScore, format.mintick) + "\n Beneish-M: " + str.tostring(bScore, format.mintick) + "\nSloan Ratio: " + str.tostring(sScore, format.mintick) +
"\n KZ Index: " + str.tostring(kScore, format.mintick)
, style = label.style_label_up, textcolor = color.white, color = color.new(color.blue, 75), size = sizeOption))
array.push(statsLine,
line.new(
bar_index[len],
high * 1.04,
bar_index[len],
llfix,
color = color.white,
style = line.style_dashed
))
if statLabel == "On"
array.push(stats, label.new(bar_index[len], llfix, text = "F-Score: " + str.tostring(pScore, "#") + "\nAltZ-Score: " + str.tostring(zScore, format.mintick) + "\nQuick Ratio: "
+ str.tostring(qScore, format.mintick) + "\n Beneish-M: " + str.tostring(bScore, format.mintick) + "\nSloan Ratio: " + str.tostring(sScore, format.mintick) +
"\n KZ Index: " + str.tostring(kScore, format.mintick) + "\n___________\nDays Inventory: " + str.tostring(dI, format.mintick) + "\nDebt to EBITDA: " + str.tostring(dE, format.mintick) +
"\nH-Factor: " + str.tostring(hScore, format.mintick) + "\nGraham: " + str.tostring(gN) + "\nNCAVPS Ratio: " + str.tostring(nR, format.mintick) + "\nPEG: " + str.tostring(PEG, format.mintick)
, style = label.style_label_up, textcolor = color.white, color = color.new(color.blue, 75), size = sizeOption))
array.push(statsLine,
line.new(
bar_index[len],
high * 1.04,
bar_index[len],
llfix,
color = color.white,
style = line.style_dashed
))
array.push(fx,
line.new(
bar_index,
high * 1.04,
bar_index,
high,
color = color.white,
style = line.style_dashed
))
if counter[1] == 1
line.delete(o[1])
o := line.new(bar_index, hh, bar_index, ll, color = color.new(color.white, 50))
array.push(f1,
label.new(
bar_index,
high * 1.04,
text = str.tostring(counter1, "#") + "-Session Gain/Loss After Earnings: " + str.tostring(close / array.get(x4, array.size(x4) - 1), format.percent),
color = array.get(x, array.size(x) - 1) >= 0.0 ? color.new(color.green, 50) : color.new(color.red, 50),
textcolor = color.white
))
if counter != 0 and LLHHlabels == "On"
label.delete(z1[1])
label.delete(z2[1])
label.delete(z3[1])
z1 := label.new(bar_index, hh, text = "Highest High: $" + str.tostring(hh, format.mintick), color = na, textcolor = color.white, size = sizE == "Tiny" ? size.auto : sizE == "Auto" ? size.auto : size.auto)
z2 := label.new(bar_index, ll, text = "Lowest Low: $" + str.tostring(ll, format.mintick), color = na, textcolor = color.white, size = sizE == "Tiny" ? size.auto : sizE == "Auto" ? size.auto : size.auto)
z3 := label.new(bar_index, math.avg(hh, ll), text = "High/Low Difference: " + str.tostring(difference(hh, ll), format.percent) + "\nPercent Change: " + str.tostring(difference1, format.percent) + hls, color = na, textcolor = color.white, size = sizE == "Tiny" ? size.auto : sizE == "Auto" ? size.auto : size.auto)
if counter[2] == 0
array.push(fx,
line.new(
array.get(y3, array.size(y3) - 1),
array.get(x5, array.size(x5) - 1) * 1.04,
array.get(y3, array.size(y3) - 1) - len,
array.get(x5, array.size(x5) - 1) * 1.04,
color = color.white,
style = line.style_dashed
))
array.push(fx1,
line.new(
array.get(y3, array.size(y3) - 1),
array.get(x5, array.size(x5) - 1),
bar_index,
high * 1.04,
style = line.style_dashed,
color = color.white
))
if array.size(f1) > 1
label.delete(array.shift(f1))
line.delete(array.shift(fx1))
if ta.barssince(counter[1] == 0 and counter == 1) == len
counter := 0
o := line.new(bar_index, hh, bar_index, ll, color = color.new(color.white, 50))
label.delete(array.shift(f1))
line.delete(array.shift(fx1))
array.push(f2,
label.new(
bar_index,
array.get(x2, array.size(x2) -1 ) > array.get(x, array.size(x) - 1) ? array.get(x5, array.size(x5) - 1) * 1.08 : array.get(x5, array.size(x5) - 1) * 1.04,
text = str.tostring(len, "#") + "-Session Gain/Loss After Earnings: " + str.tostring(array.get(x2, array.size(x2) - 1), format.percent) + "\nAverage " + str.tostring(len, "#") +
"-Session Gain/Loss After Earnings: " + str.tostring(aftr, format.percent),
textcolor = color.white,
color = array.get(x2, array.size(x2) - 1) >= 0.0 ? color.new(color.green, 50) : color.new(color.red, 50),
size = sizeOption
))
label.delete(array.get(f, array.size(f) - 1))
array.push(f,
label.new(
bar_index - (len * 2),
array.get(x2, array.size(x2) - 1) > array.get(x, array.size(x) - 1) ? array.get(x5, array.size(x5) - 1) * 1.04 : array.get(x5, array.size(x5) - 1) * 1.08,
color = array.get(x, array.size(x) - 1) >= 0.0 ? color.new(color.green, 50) : color.new(color.red, 50),
textcolor = color.white,
text = str.tostring(len, "#") + "-Session Gain/Loss Prior to Earnings: " + str.tostring(array.get(x, array.size(x) - 1), format.percent) + "\nAverage " + str.tostring(len, "#") + "-Session Gain/Loss Prior to Earnings: "
+ str.tostring(b4, format.percent),
size = sizeOption
))
if LLHHlabels == "On"
label.delete(z1[1])
label.delete(z2[1])
label.delete(z3[1])
z1 := label.new(bar_index, hh, text = "Highest High: $" + str.tostring(hh, format.mintick), color = na, textcolor = color.white, size = sizE == "Tiny" ? size.auto : sizE == "Auto" ? size.auto : size.auto)
z2 := label.new(bar_index, ll, text = "Lowest Low: $" + str.tostring(ll, format.mintick), color = na, textcolor = color.white, size = sizE == "Tiny" ? size.auto : sizE == "Auto" ? size.auto : size.auto)
z3 := label.new(bar_index, math.avg(hh, ll), text = "High/Low Difference: " + str.tostring(difference(hh, ll), format.percent) + "\nPercent Change: " + str.tostring(difference1, format.percent) +hls, color = na, textcolor = color.white, size = sizE == "Tiny" ? size.auto : sizE == "Auto" ? size.auto : size.auto)
array.push(fx,
line.new(
bar_index - len,
array.get(x2, array.size(x2) - 1) > array.get(x, array.size(x) - 1) ? array.get(x5, array.size(x5) - 1) * 1.04 : array.get(x5, array.size(x5) - 1) * 1.08,
bar_index - (len * 2),
label.get_y(array.get(f, array.size(f) - 1)),
color = color.white,
style = line.style_dashed))
array.push(fxx,
line.new(
bar_index - len,
array.get(x5, array.size(x5) - 1) * 1.08,
bar_index - len,
high[len],
color = color.white,
style = line.style_dashed
))
array.push(fxxx,
line.new(
bar_index - len,
array.get(x2, array.size(x2) - 1) > array.get(x, array.size(x) - 1) ? array.get(x5, array.size(x5) - 1) * 1.08 : array.get(x5, array.size(x5) - 1) * 1.04,
bar_index,
array.get(x2, array.size(x2) - 1) > array.get(x, array.size(x) - 1) ? array.get(x5, array.size(x5) - 1) * 1.08 : array.get(x5, array.size(x5) - 1) * 1.04,
color = color.white,
style = line.style_dashed
))
if year(time) > 2013
if statLabel == "On"
array.push(statsLine,
line.new(
bar_index[len],
array.get(x2, array.size(x2) - 1) > array.get(x, array.size(x) - 1) ? array.get(x5, array.size(x5) - 1) * 1.04 : array.get(x5, array.size(x5) - 1) * 1.08,
bar_index[len],
label.get_y(array.get(f, array.size(f) - 1)),
color = color.white,
style = line.style_dashed
))
array.push(statsLine1,
line.new(
bar_index[len * 2],
array.get(x2, array.size(x2) - 1) > array.get(x, array.size(x) - 1) ? array.get(x5, array.size(x5) - 1) * 1.04 : array.get(x5, array.size(x5) - 1) * 1.08,
bar_index[len * 2],
high[len] * 1.04,
color = color.white,
style = line.style_dashed
))
if array.size(fx) > 3
line.delete(array.get(fx, array.size(fx) - 3))
line.delete(array.get(fx, array.size(fx) - 2))
// _______________________________________________________
//
// VaR 95% and CVaR 95% Calculations
// _______________________________________________________
var float [] min = array.new_float(all == "Yes" ? bar_index : 250)
var float [] earnmin = array.new_float()
var float [] es = array.new_float()
if ta.change(bar_index)
array.push(min, pl(close, close[1]))
if all == "No" and array.size(min) > 250
array.shift(min)
fin = array.min(min, math.round(array.size(min) * ((100 - conf) / 100)))
if pl(close, close[1]) < fin
array.push(es, pl(close, close[1]))
if all == "No"
if ta.change(year(time))
array.shift(es)
altInterpolation = ta.percentile_linear_interpolation(pl(close, close[1]), all == "No" and bar_index > 250 ? 250 : all == "Yes" and bar_index > 5000 ? 5000 : all == "No" and bar_index < 250 ? bar_index + 1: all == "Yes" and bar_index < 5000 ? bar_index + 1: 1, (100 - conf))
// _______________________________________________________
//
// Average PnL Following EPS Surprise/Miss
// _______________________________________________________
var int earnCount = 0
var int surpriseCount = 0
var int missCount = 0
var float i = 0.0
var float i1 = 0.0
if ta.change(earnings())
earnCount += 1
if surp
surpriseCount += 1
if ta.barssince(surpriseCount != surpriseCount[1]) == len
i := pl(close, close[len])
i := i[1] + i
finsurp = i / surpriseCount
if miss
missCount += 1
if ta.barssince(missCount != missCount[1]) == len
i1 := pl(close, close[len])
i1 := i1[1] + i1
finmiss = i1 / missCount
var float alt1 = 0.0
var int altcount = 0
if pl(close, close[1]) < altInterpolation
alt1 := pl(close, close[1])
alt1 := alt1[1] + alt1
altcount += 1
finalt = alt1 / altcount
earn5(x) =>
if ta.change(earnCount[1])
array.push(earnmin, pl(close, close[1]))
round = array.size(earnmin) > 0 ? math.round(array.size(earnmin) * x) : na
fin2 = array.size(earnmin) > 10 ? array.min(earnmin, round) : array.min(earnmin, 0)
fin2
barChange = ta.change(bar_index)
n = plot(barstate.islast and lope == "Off" and Band == "Off" ? close[1] * (1 + (fin/100)) : barstate.islast and lope == "On" and Band == "Off"? close[1] * (1 + (altInterpolation/100)) :
barChange and lope == "Off" and Band == "On" ? close[1] * (1 + (fin/100)) : barChange and lope == "On" and Band == "On"? close[1] * (1 + (altInterpolation/100)) : na, style = Band == "Off" ? plot.style_stepline_diamond : plot.style_line, color = #00f6ff, linewidth = Band == "Off" ? 4 : 2)
n1 = plot(low, display = display.none)
n2 = plot(barstate.islast and lope == "Off" and Band == "Off" ? close[1] * (1 + (array.avg(es) / 100)) : barstate.islast and lope == "On" and Band == "Off" ? close[1] * (1 + (finalt/100)) :
barChange and lope == "Off" and Band == "On" ? close[1] * (1 + (array.avg(es) / 100)) : barChange and lope == "On" and Band == "On" ? close[1] * (1 + (finalt/100)) : na
, style = Band == "Off" ? plot.style_stepline_diamond : plot.style_line, color = color.red, linewidth = Band == "Off" ? 4 : 2)
var label [] VaRl = array.new_label()
var label [] CVaRl = array.new_label()
var line [] VaRlC = array.new_line()
var line [] CVaRlC = array.new_line()
if ta.change(bar_index)
array.push(VaRl, label.new(bar_index + 5, lope == "Off" ? close[1] * (1 + (fin/100)) : close[1] * (1 + (altInterpolation/100)), color = #00f6ff, style = label.style_label_left, text = lope == "Off" ? "Price Level VaR Measure (" + str.tostring(fin, format.percent) + " Less Than Last Close)" : "Price Level VaR Measure (" + str.tostring(altInterpolation, format.percent) + " Less Than Last Close)"))
array.push(VaRlC, line.new (bar_index + 5, lope == "Off" ? close[1] * (1 + (fin/100)) : close[1] * (1 + (altInterpolation/100)), bar_index, lope == "Off" ? close[1] * (1 + (fin/100)) : close[1] * (1 + (altInterpolation/100)), color = #00f6ff, width = 2))
array.push(CVaRl, label.new(bar_index + 5, lope == "Off" ? close[1] * (1 + (array.avg(es) / 100)) : close[1] * (1 + (finalt/100)), color = color.red, style = label.style_label_left, text = lope == "Off" ? "CVaR Measure (" + str.tostring(array.avg(es), format.percent) + " Less Than Last Close)" : "CVaR Measure (" + str.tostring(finalt, format.percent) + " Less Than Last Close)"))
array.push(CVaRlC, line.new (bar_index + 5, lope == "Off" ? close[1] * (1 + (array.avg(es) / 100)) : close[1] * (1 + (finalt/100)), bar_index, lope == "Off" ? close[1] * (1 + (array.avg(es) / 100)) : close[1] * (1 + (finalt/100)), color = color.red, width = 2))
if array.size(VaRl) > 1
label.delete(array.shift(VaRl))
line.delete (array.shift(VaRlC))
label.delete(array.shift(CVaRl))
line.delete (array.shift(CVaRlC))
// _______________________________________________________
//
// Table Plots
// _______________________________________________________
percstring = 100 - conf == 1 ? "st Percentile Loss Threshold Following \nan Earnings Release: " : 100 - conf == 2 ? "nd Percentile Loss Threshold Following \nan Earnings Release: " : 100 - conf == 3 ? "rd Percentile Loss Threshold Following \nan Earnings Release: " :
"th Percentile Loss Threshold Following \nan Earnings Release: "
percX = earn5((100 - conf) / 100)
avgVol = ta.sma(volume, 50)
t1 = table.new(position.bottom_right, 10, 10, bgcolor = color.new(color.white, 100), frame_color = color.white, frame_width = 1, border_color = color.white, border_width = 1)
t2 = table.new(position.top_right, 10, 10, bgcolor = color.new(color.white, 100))
if barstate.islast
if tab == "No"
table.cell(t1, 0, 0, text = str.tostring(syminfo.tickerid), text_color = #ff6d00, bgcolor = color.new(#ff6d00, 90))
table.cell(t1, 0, 1, text = "Earnings Price Moves", text_color = color.yellow, bgcolor = color.new(color.yellow, 90))
table.cell(t1, 0, 3, text = "Risk Measures", text_color = #fb5c5c, bgcolor = color.new(#fb5c5c, 90))
table.merge_cells(t1, 0, 0, 1, 0)
table.cell(t1, 1,1, text = "Number of EPS Beats: " + str.tostring(surpriseCount, "#") + "\nAverage " + str.tostring(len, "#") + "-Session Gain/Loss Following an EPS Beat: " + str.tostring(finsurp, format.percent) +
"\n\nNumber of EPS Misses: " + str.tostring(missCount, "#") + "\nAverage " + str.tostring(len, "#") + "-Session Gain/Loss Following an EPS Miss: " + str.tostring(finmiss, format.percent), text_color = color.white, bgcolor = color.new(color.white, 90))
if lope == "Off"
table.cell(t1, 1,3, text = "\nVaR " + str.tostring(conf, "#") + "% Confidence: " + str.tostring(fin, format.percent) + "\n\nExpected Shortfall: " + str.tostring(array.avg(es), format.percent) +
"\n\n" + str.tostring(100 - conf, "#") + percstring + str.tostring(percX, format.percent)+ "\n\nLargest Close to Close Gain After Earnings: " + str.tostring(array.max(x9), format.percent), text_color = color.white,bgcolor = color.new(color.white, 95))
else if lope == "On"
table.cell(t1, 1,3, text ="\nVaR " + str.tostring(conf, "#") + "% Confidence: " + str.tostring(altInterpolation, format.percent) + "\n\nExpected Shortfall: " + str.tostring(finalt, format.percent) +
"\n\n" + str.tostring(100 - conf, "#") + percstring + str.tostring(percX, format.percent) + "\n\nLargest Close to Close Gain After Earnings: " + str.tostring(array.max(x9), format.percent), text_color = color.white, bgcolor = color.new(color.white, 95))
table.cell(t1, 0,4, text ="Volume", text_color = color.blue, bgcolor = color.new(color.blue, 75))
table.cell(t1, 1,4, text ="50-Session Volume Average: " + str.tostring(avgVol, format.volume) + "\nAverage Volume on Earnings Day: " + str.tostring(vol, format.volume) +"\nAverage Short Volume on Earnings Day: " + str.tostring(shortvol, format.volume)
+"\n\nAverage " + str.tostring(len, "#") + "-Session Daily Volume Before Earnings: " + str.tostring(array.avg(x10), format.volume) + "\nAverage " + str.tostring(len, "#") + "-Session Daily Short Volume Before Earnings: " + str.tostring(array.avg(x11), format.volume), text_color = color.white, bgcolor = color.new(color.white, 90))
table.cell(t1, 1,2, text = " Average " + str.tostring(len, "#") + "-Session Gain/Loss Following Q1 Report: " + str.tostring(q1x, format.percent)
+ "\nAverage " + str.tostring(len, "#") + "-Session Gain/Loss Following Q2 Report: " + str.tostring(q2x, format.percent)
+ "\n Average " + str.tostring(len, "#") + "-Session Gain/Loss Following Q3 Report: " + str.tostring(q3x, format.percent)
+ "\nAverage " + str.tostring(len, "#") + "-Session Gain/Loss Following Q4 Report: " + str.tostring(q4x, format.percent)
, text_color = color.white, bgcolor = color.new(color.white, 95))
table.cell(t1, 0,2, text ="Quarterly Price Moves ", text_color = color.green, bgcolor = color.new(color.green, 90))
if barstate.islast
table.cell(t2, 0, 0, text = "Q1\n", text_size = size.huge, bgcolor = month(time) >= 1 and month(time) <= 3 ? color.new(color.blue, 75) : na, text_color = color.blue)
table.cell(t2, 1, 0, text = "Q2\n", text_size = size.huge, bgcolor = month(time) >= 4 and month(time) <= 6 ? color.new(color.green, 75) : na, text_color =color.green)
table.cell(t2, 2, 0, text = "Q3\n", text_size = size.huge, bgcolor = month(time) >= 7 and month(time) <= 9 ? color.new(color.red, 75) : na, text_color =color.red)
table.cell(t2, 3, 0, text = "Q4\n", text_size = size.huge, bgcolor = month(time) >= 10 and month(time) <= 12 ? color.new(color.yellow, 75) : na, text_color =color.yellow)
var float qString1 = 0.0
var int qStringa1 = 0
var float qString2 = 0.0
var int qStringa2 = 0
var float qString3 = 0.0
var int qStringa3 = 0
var float qString4 = 0.0
var int qStringa4 = 0
if ta.change(earnings())
qStringa1 := 1
if ta.change(earnings()) and qStringa1[1] == 1
qStringa2 := 1
if ta.change(earnings()) and qStringa2[1] == 1
qStringa3 := 1
if ta.change(earnings()) and qStringa3[1] == 1
qStringa4 := 1
if ta.change(year(time))
qStringa1 := 0
qStringa2 := 0
qStringa3 := 0
qStringa4 := 0
//
if array.size(track1) > 0 and qStringa1 == 1
qString1 := array.get(track1, array.size(track1) - 1)
else if qStringa1 == 0
qString1 := 0
else if array.size(track1) < 1
qString1 := 0
//
if array.size(track2) > 0 and qStringa2 == 1
qString2 := array.get(track2, array.size(track2) - 1)
else if qStringa2 == 0
qString2 := 0
else if array.size(track2) < 1
qString2 := 0
//
if array.size(track3) > 0 and qStringa3 == 1
qString3 := array.get(track3, array.size(track3) - 1)
else if qStringa2 == 0
qString3 := 0
else if array.size(track3) < 1
qString3 := 0
//
if array.size(track4) > 0 and qStringa4 == 1
qString4 := array.get(track4, array.size(track4) - 1)
else if qStringa2 == 0
qString4 := 0
else if array.size(track4) < 1
qString4 := 0
if barstate.islast
table.cell(t2, 0, 1, text = qString1 != 0 ? str.tostring(date, "#") + "/" + str.tostring(date1, "#") + "/" + str.tostring(date2, "#") + "\n__" : "--\n__", text_size = size.small, bgcolor = month(time) >= 1 and month(time) <= 3 ? color.new(color.blue, 75) : na, text_color = color.blue)
table.cell(t2, 1, 1, text = qString2 != 0 ? str.tostring(date3, "#") + "/" + str.tostring(date4, "#") + "/" + str.tostring(date5, "#") + "\n__" : "--\n__", text_size = size.small, bgcolor = month(time) >= 4 and month(time) <= 6 ? color.new(color.green, 75) : na, text_color =color.green)
table.cell(t2, 2, 1, text = qString3 != 0 ? str.tostring(date6, "#") + "/" + str.tostring(date7, "#") + "/" + str.tostring(date8, "#") + "\n__" : "--\n__", text_size = size.small, bgcolor = month(time) >= 7 and month(time) <= 9 ? color.new(color.red, 75) : na, text_color =color.red)
table.cell(t2, 3, 1, text = qString4 != 0 ? str.tostring(date9, "#") + "/" + str.tostring(date10, "#") + "/" + str.tostring(date11, "#") + "\n__" : "--\n__", text_size = size.small, bgcolor = month(time) >= 10 and month(time) <= 12 ? color.new(color.yellow, 75) : na, text_color =color.yellow)
if barstate.islast
if array.size(zx) > 1
table.cell(t2, 0, 2, text = qString1 > 0.000000 ? "Actual: " + str.tostring(array.get(zx, array.size(zx) - 1), format.mintick) + "\nEstimate: " + str.tostring(array.get(zx1, array.size(zx1) - 1), format.mintick) + "\nSurprise" : qString1 == 0 ? "--" : "Actual: " + str.tostring(array.get(zx, array.size(zx) - 1), format.mintick) + "\nEstimate: " + str.tostring(array.get(zx1, array.size(zx1) - 1), format.mintick)+ "\nMiss", text_size = size.small, text_color = color.blue)
if array.size(zx2) > 1
table.cell(t2, 1, 2, text = qString2 > 0.000000 ? "Actual: " + str.tostring(array.get(zx2, array.size(zx2) - 1), format.mintick) + "\nEstimate: " + str.tostring(array.get(zx3, array.size(zx3) - 1), format.mintick) + "\nSurprise" : qString2 == 0 ? "--" : "Actual: " + str.tostring(array.get(zx2, array.size(zx2) - 1), format.mintick) + "\nEstimate: " + str.tostring(array.get(zx3, array.size(zx3) - 1), format.mintick)+ "\nMiss", text_size = size.small, text_color = color.green)
if array.size(zx4) > 1
table.cell(t2, 2, 2, text = qString3 > 0.000000 ? "Actual: " + str.tostring(array.get(zx4, array.size(zx4) - 1), format.mintick) + "\nEstimate: " + str.tostring(array.get(zx5, array.size(zx5) - 1), format.mintick) + "\nSurprise" : qString3 == 0 ? "--" : "Actual: " + str.tostring(array.get(zx4, array.size(zx4) - 1), format.mintick) + "\nEstimate: " + str.tostring(array.get(zx5, array.size(zx5) - 1), format.mintick)+ "\nMiss", text_size = size.small, text_color = color.red)
if array.size(zx6) > 1
table.cell(t2, 3, 2, text = qString4 > 0.000000 ? "Actual: " + str.tostring(array.get(zx6, array.size(zx6) - 1), format.mintick) + "\nEstimate: " + str.tostring(array.get(zx7, array.size(zx7) - 1), format.mintick) + "\nSurprise" : qString4 == 0 ? "--" : "Actual: " + str.tostring(array.get(zx6, array.size(zx6) - 1), format.mintick) + "\nEstimate: " + str.tostring(array.get(zx7, array.size(zx7) - 1), format.mintick)+ "\nMiss", text_size = size.small, text_color = color.yellow)
var line [] tri = array.new_line()
var line [] tri1 = array.new_line()
var line [] tri2 = array.new_line()
if barstate.islast
table.cell(t2, 0, 3, text = qString1 == 0 ? "◠" : qString1 > 0.000000 ? "✔" : "╳" ,text_size = size.huge, text_color = color.blue)
table.cell(t2, 1, 3, text = qString2 == 0 ? "◠" : qString2 > 0.000000 ? "✔" : "╳" ,text_size = size.huge, text_color = color.green)
table.cell(t2, 2, 3, text = qString3 == 0 ? "◠" : qString3 > 0.000000 ? "✔" : "╳" ,text_size = size.huge, text_color = color.red)
table.cell(t2, 3, 3, text = qString4 == 0 ? "◠" : qString4 > 0.000000 ? "✔" : "╳" ,text_size = size.huge, text_color = color.yellow)
|
SFP Momentum | https://www.tradingview.com/script/72ifzLt4-SFP-Momentum/ | Austimize | https://www.tradingview.com/u/Austimize/ | 104 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Austimize
//Custom swing fail detector with levels, breakouts, and colored candles.
//Key: Arrow = pivot, x = anchor (major pivot), B = breakout, b = minor breakout, F = swing failure, f(rare) = minor swing failure, A = accumulation, D = distribution
//Blue line = last anchor (major pivot) level, gray = last pivot, green lines = last high anchor/pivot, red lines = last low anchor/pivot
//@version=5
indicator("Swing Fail Levels, Breakouts, Candles", "SF LBC", overlay = true)
lbL = input.int(4, "Left Lookback")
lbR = input.int(3, "Right Lookback")
useAccDist = input.bool(true, "Accumulation/Distribution?")
usePrevPivots = input.bool(true, "Plot Last Pivots?")
colorCandles = input.bool(true, "Color Candles?")
anchorR = math.round(lbR * 1.5)
anchorL = lbL * 2
get_lowest (source, num) =>
lowval = 99999999.9
for i = 1 to num
if source[i] < lowval
lowval := source[i]
lowval
get_highest (source, num) =>
highval = 0.0
for i = 1 to num
if source[i] > highval
highval := source[i]
highval
swingBull = 0 + close > open ? 1 : 0 + close > close[1] ? 1 : 0
swingBear = 0 + close > open ? 0 : 1 + close > close[1] ? 1 : 0
isHighAnchor = ta.pivothigh(high, anchorL, anchorR)
prevHighAnchor = ta.valuewhen(isHighAnchor > 0.0, isHighAnchor, 1)
isLowAnchor = ta.pivotlow(low, anchorL, anchorR)
prevLowAnchor = ta.valuewhen(isLowAnchor > 0.0, isLowAnchor, 1)
lastAnchor = 0
lastAnchor := isHighAnchor and not isLowAnchor ? 1 : isLowAnchor and not isHighAnchor ? -1 : lastAnchor[1]
swingBull += lastAnchor == -1 ? 1 : 0
swingBear += lastAnchor == 1 ? 1 : 0
plotshape(isHighAnchor, "High Anchor", style = shape.xcross, location = location.abovebar, color = color.green, offset = -anchorR)
plotshape(isLowAnchor, "Low Anchor", style = shape.xcross, location = location.belowbar, color = color.red, offset = -anchorR)
barsSinceHigh = 0
barsSinceLow = 0
barsSinceHigh := barsSinceHigh[1] + 1
barsSinceLow := barsSinceLow[1] + 1
lowSwing = low[barsSinceLow]
highSwing = high[barsSinceHigh]
pivotHigh = ta.pivothigh(high, lbL, lbR)
prevHighPivot = ta.valuewhen(pivotHigh > 0.0, pivotHigh, 1)
pivotLow = ta.pivotlow(low, lbL, lbR)
prevLowPivot = ta.valuewhen(pivotLow > 0.0, pivotLow, 1)
highSameSame = prevHighAnchor == prevHighPivot
lowSameSame = prevLowAnchor == prevLowPivot
prevHighColor = highSameSame ? color.new(color.green, 70) : color.new(color.green, 90)
prevLowColor = lowSameSame ? color.new(color.red, 70) : color.new(color.red, 90)
plot(usePrevPivots and highSameSame ? prevHighAnchor : na, color = prevHighColor, style=plot.style_stepline, linewidth = 3)
plot(usePrevPivots and lowSameSame ? prevLowAnchor : na, color = prevLowColor, style=plot.style_stepline, linewidth = 3)
plot(usePrevPivots and not highSameSame ? prevHighAnchor : na, color = prevHighColor, style=plot.style_stepline, linewidth = 2)
plot(usePrevPivots and not lowSameSame ? prevLowAnchor : na, color = prevLowColor, style=plot.style_stepline, linewidth = 2)
plot(usePrevPivots ? prevHighPivot : na, color = prevHighColor, style=plot.style_stepline, linewidth = 1)
plot(usePrevPivots ? prevLowPivot : na, color = prevLowColor, style=plot.style_stepline, linewidth = 1)
lastPivot = 0
lastPivot := pivotHigh and not pivotLow ? 1 : pivotLow and not pivotHigh ? -1 : lastPivot[1]
barsSinceHighPivot = 0
barsSinceLowPivot = 0
barsSinceHighPivot := barsSinceHighPivot[1] + 1
barsSinceLowPivot := barsSinceLowPivot[1] + 1
pivotHighline = high[barsSinceHighPivot]
pivotLowline = low[barsSinceLowPivot]
plot(pivotHighline, "Pivot High", color = color.new(color.white, 75))
plot(pivotLowline, "Pivot Low", color = color.new(color.white, 75))
swingBull += lastPivot == -1 ? 1 : 0
swingBear += lastPivot == 1 ? 1 : 0
plotshape(pivotHigh, "High Pivot", style = shape.arrowup, location = location.abovebar, color = color.green, offset = -lbR)
plotshape(pivotLow, "Low Pivot", style = shape.arrowdown, location = location.belowbar, color = color.red, offset = -lbR)
swingFailHigh = pivotHigh and close[lbR] < highSwing ? true : false
swingFailLow = pivotLow and close[lbR] > lowSwing ? true : false
swingFailHighMinor = pivotHigh and close[lbR] < pivotHighline ? true : false
swingFailLowMinor = pivotLow and close[lbR] > pivotLowline ? true : false
lastMinorFail = 0
lastMinorFail := swingFailHighMinor and not swingFailLowMinor ? 1 : swingFailLowMinor and not swingFailHighMinor ? -1 : lastMinorFail[1]
swingBull += lastMinorFail == -1 and lastPivot == -1 ? 2 : lastMinorFail == -1 ? 1 : 0
swingBear += lastMinorFail == 1 and lastPivot == 1 ? 2 : lastMinorFail == 1 ? 1 : 0
plotHighFail = swingFailHighMinor and not swingFailHigh
plotLowFail = swingFailLowMinor and not swingFailLow
plotchar(plotHighFail, "Minor Swing Fail", char = "f", location = location.belowbar, color = color.green, offset = -lbR)
plotchar(plotLowFail, "Minor Swing Fail", char = "f", location = location.abovebar, color = color.red, offset = -lbR)
lastFail = 0
lastFail := swingFailHigh and not swingFailLow ? 1 : swingFailLow and not swingFailHigh ? -1 : lastFail[1]
swingBull += lastFail == -1 and lastAnchor == -1 ? 2 : lastFail == -1 ? 1 : 0
swingBear += lastFail == 1 and lastAnchor == 1 ? 2 : lastFail == 1 ? 1 : 0
plotchar(swingFailHigh, "Swing Fail", char = "F", location = location.belowbar, color = color.green, offset = -lbR)
plotchar(swingFailLow, "Swing Fail", char = "F", location = location.abovebar, color = color.red, offset = -lbR)
highBreakout = close > highSwing and close > get_highest(close, anchorR - 1)
lowBreakout = close < lowSwing and close < get_lowest(close, anchorR - 1)
lastBreakout = 0
prevBreakout = lastBreakout[1]
lastBreakout := highBreakout ? 1 : lowBreakout? -1 : prevBreakout
lastBreakout := lastBreakout >= 1 and isHighAnchor ? -1 : lastBreakout
lastBreakout := lastBreakout <= 1 and isLowAnchor ? 1 : lastBreakout
minorHighBreakout = close > pivotHighline and close > get_highest(close, lbR - 1)
minorLowBreakout = close < pivotLowline and close < get_lowest(close, lbR - 1)
lastMinorBreakout = 0
prevMinorBreakout = lastMinorBreakout[1]
lastMinorBreakout := minorHighBreakout ? 1 : minorLowBreakout? -1 : prevMinorBreakout
lastMinorBreakout := lastMinorBreakout >= 1 and pivotHigh ? -1 : lastMinorBreakout
lastMinorBreakout := lastMinorBreakout <= 1 and pivotLow ? 1 : lastMinorBreakout
isMinorBreakHigh = minorHighBreakout and not highBreakout
isMinorBreakLow = minorLowBreakout and not lowBreakout
barsSinceHigh := isHighAnchor ? anchorR : barsSinceHigh
barsSinceLow := isLowAnchor ? anchorR : barsSinceLow
barsSinceHighPivot := pivotHigh ? lbR : barsSinceHighPivot
barsSinceLowPivot := pivotLow ? lbR : barsSinceLowPivot
swingBull += (lastBreakout == 1 ? 2 : 0) + (highBreakout and lastBreakout == 1 ? 3 : 0) + (lastMinorBreakout == 1 and (lastBreakout == 1 or lastMinorBreakout == 1) ? 2 : 0) + (lastMinorBreakout == 1 ? 1 : 0)
swingBear += (lastBreakout == -1 ? 2 : 0) + (lowBreakout and lastBreakout == -1 ? 3 : 0) + (lastMinorBreakout == -1 and (lastBreakout == -1 or lastMinorBreakout == -1) ? 2 : 0) + (lastMinorBreakout == -1 ? 1 : 0)
barsSinceHigh := isHighAnchor ? anchorR : barsSinceHigh
barsSinceLow := isLowAnchor ? anchorR : barsSinceLow
lowSwing := low[barsSinceLow]
highSwing := high[barsSinceHigh]
midSwing = (highSwing + lowSwing) / 2
lastCrossover = 0
lastCrossover := ta.crossover(close, lowSwing) or ta.crossover(close, midSwing) or ta.crossover(close, highSwing) ? 1 : lastCrossover[1]
lastCrossover := ta.crossunder(close, lowSwing) or ta.crossunder(close, midSwing) or ta.crossunder(close, highSwing) ? -1 : lastCrossover[1]
accum = highBreakout and prevBreakout == -1
dist = lowBreakout and prevBreakout == 1
accumM1 = minorHighBreakout and prevMinorBreakout == -1
distM1 = minorLowBreakout and prevMinorBreakout == 1
accumM2 = minorHighBreakout and prevBreakout == -1
distM2 = minorLowBreakout and prevBreakout == 1
accumM3 = highBreakout and prevMinorBreakout == -1
distM3 = lowBreakout and prevMinorBreakout == 1
isAccum = accum or accumM1 or accumM2 or accumM3
isDist = dist or distM1 or distM2 or distM3
currentAD = 0
lastAD = currentAD[1]
currentAD := isAccum ? 1 : isDist ? -1 : lastAD
plotchar(accum and useAccDist, "Accumulation", char = "A", location = location.top, color = color.green)
plotchar(dist and useAccDist, "Distribution", char = "D", location = location.bottom, color = color.red)
plotchar(isAccum and not accum and useAccDist, "Accumulation", char = "a", location = location.top, color = color.green)
plotchar(isDist and not dist and useAccDist, "Distribution", char = "d", location = location.bottom, color = color.red)
plotchar(highBreakout and not (isAccum and useAccDist), "High Breakout", char = "B", location = location.top, color = color.green)
plotchar(lowBreakout and not (isDist and useAccDist), "Low Breakout", char = "B", location = location.bottom, color = color.red)
plotchar(isMinorBreakHigh and not (isAccum and useAccDist), "Minor High Breakout", char = "b", location = location.top, color = color.green)
plotchar(isMinorBreakLow and not(isDist and useAccDist), "Minor Low Breakout", char = "b", location = location.bottom, color = color.red)
swingBull += (lastCrossover > 0 ? 2 : 0) + (close > midSwing ? 3 : 0) + (close > lowSwing and close < midSwing ? 1 : 0) + (currentAD == 1 ? 2 : 0) + (isAccum ? 2 : 0)
swingBear += (lastCrossover < 0 ? 2 : 0) + (close < midSwing ? 3 : 0) + (close < highSwing and close > midSwing? 1 : 0) + (currentAD == -1 ? 2 : 0) + (isDist ? 2 : 0)
plot(highSwing, "Anchored High")
plot(lowSwing, "Anchored Low")
plot(midSwing, "Midline", color = color.orange)
plotColor = color.orange
plotColor := swingBull > swingBear ? color.green : swingBear > swingBull ? color.red : swingBull[1] > swingBear[1] ? color.red : swingBear[1] > swingBull[1] ? color.green : plotColor[1]
barcolor(colorCandles ? plotColor : na, title = "Bar Color") |
Valuation Table | https://www.tradingview.com/script/qPj3QnlN-Valuation-Table/ | kenhuangsy2 | https://www.tradingview.com/u/kenhuangsy2/ | 163 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kenhuangsy2
//@version=4
study("Valuation Table", overlay=true)
_fin = input(true, "|| Financial Valuation ====================")
on_off = input(title="On/Off Panel?", type=input.bool, defval=true)
_select = input(title="Select Fiscal (ROA/ROE/ROIC/Current Ratio)", defval="FY", options=["FY", "FQ"])
CAGR = input(title="CAGR %", defval=20, minval=1, maxval=100)
//Financial ID-----------------------------------------------------------------------------------------
ROA = financial(syminfo.tickerid,"RETURN_ON_ASSETS", _select)
ROE = financial(syminfo.tickerid,"RETURN_ON_EQUITY", _select)
ROIC = financial(syminfo.tickerid,"RETURN_ON_INVESTED_CAPITAL", _select)
Current_Ratio = financial(syminfo.tickerid,"CURRENT_RATIO", _select)
EPS = financial(syminfo.tickerid, "EARNINGS_PER_SHARE", "TTM")
TSO = financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")
TR = financial(syminfo.tickerid, "TOTAL_REVENUE", "TTM")
GR = financial(syminfo.tickerid, "REVENUE_ONE_YEAR_GROWTH", "FY")
CA = financial(syminfo.tickerid, "TOTAL_CURRENT_ASSETS", "FY")/1000000
TL = financial(syminfo.tickerid, "TOTAL_LIABILITIES", "FY")/1000000
NI = financial(syminfo.tickerid, "NET_INCOME", "FY")/1000000
TA = financial(syminfo.tickerid, "TOTAL_ASSETS", "FY")/1000000
LT_Debt = financial(syminfo.tickerid, "LONG_TERM_DEBT", "FY")/1000000
Cash = financial(syminfo.tickerid, "FREE_CASH_FLOW", "FY")/1000000
CL = financial(syminfo.tickerid, "TOTAL_CURRENT_LIABILITIES", "FY")/1000000
DY = financial(syminfo.tickerid, "DIVIDENDS_YIELD", "FY")
DTE = financial(syminfo.tickerid, "DEBT_TO_EQUITY", "FY")
BVPS = financial(syminfo.tickerid, "BOOK_VALUE_PER_SHARE", "FY")
PEGratio = financial(syminfo.tickerid, "PEG_RATIO", "FY")
GM = financial(syminfo.tickerid, "GROSS_MARGIN", "FY")
PioFscore = financial(syminfo.tickerid, "PIOTROSKI_F_SCORE", "FY")
RevGrowth = financial(syminfo.tickerid, "REVENUE_ONE_YEAR_GROWTH", "FY")/100
EnterpriseValtoEBITDA = financial(syminfo.tickerid, "ENTERPRISE_VALUE_EBITDA", "FY")
EBITDA = financial(syminfo.tickerid, "EBITDA", "FY")
//Calculation-----------------------------------------------------------------------------------------
PriceEarningsRatio = close/EPS
MarketCap = TSO*close
PriceSalesRatio = MarketCap/TR
EV = EnterpriseValtoEBITDA*EBITDA
EVtoFCF = EV/(Cash*1000000)
FCF0 = (Cash*1000000)/TSO
FCF1 = (Cash[52.14] * 1000000)/TSO[52.14]
FCF2 = (Cash[104.28] * 1000000)/TSO[104.28]
FCF3 = (Cash[156.42] * 1000000)/TSO[156.42]
FCF4 = (Cash[208.56] * 1000000)/TSO[208.56]
FCF5 = (Cash[260.7] * 1000000)/TSO[260.7]
FCF6 = (Cash[312.84] * 1000000)/TSO[312.84]
AVGFCF = (FCF0 + FCF1 + FCF2 + FCF3 + FCF4 + FCF5 + FCF6)/7
EBITDA0 = EBITDA
EBITDA1 = EBITDA[52.14]
EBITDA2 = EBITDA[52.14*2]
EBITDA3 = EBITDA[52.14*3]
EBITDA4 = EBITDA[52.14*4]
GrowthE0 = (EBITDA3 - EBITDA4)/abs(EBITDA4)
GrowthE1 = (EBITDA2 - EBITDA3)/abs(EBITDA3)
GrowthE2 = (EBITDA1 - EBITDA2)/abs(EBITDA2)
GrowthE3 = (EBITDA0 - EBITDA1)/abs(EBITDA1)
AVGgrowthE = (GrowthE0 + GrowthE1 + GrowthE2 + GrowthE3)/4
DYFRR = ((AVGFCF/close) + AVGgrowthE)*100
//ROC% Joel Greenblatt Calculation
//get ebit
//get non current assets
EBIT = financial(syminfo.tickerid, "EBIT", "FQ")
noncur = financial(syminfo.tickerid, "TOTAL_NON_CURRENT_ASSETS", "FQ")
accrec = financial(syminfo.tickerid, "ACCOUNTS_RECEIVABLES_NET", "FQ")
tolinv = financial(syminfo.tickerid, "TOTAL_INVENTORY", "FQ")
accpay = financial(syminfo.tickerid, "ACCOUNTS_PAYABLE", "FQ")
othcurrass = financial(syminfo.tickerid, "OTHER_CURRENT_ASSETS_TOTAL", "FQ")
defrev = financial(syminfo.tickerid, "DEFERRED_INCOME_CURRENT", "FQ")
othcurrlia = financial(syminfo.tickerid, "OTHER_CURRENT_LIABILITIES", "FQ")
//NFA (might not work)
netproperty = financial(syminfo.tickerid, "PPE_TOTAL_NET", "FQ")
NFA = netproperty
//(Accounts Receivable + Total Inventories + Other Current Assets) - (Accounts Payable & Accrued Expense + Deferred Revenue + Other Current Liabilities)
NWC = (accrec + tolinv)-(accpay)
ROC = EBIT/((NFA + NWC)/2)
//PEG = close/EPS/CAGR
NetCashPS = (Cash*1000000)/TSO
RealStockPrice = close - NetCashPS
RealPriceEarningsRatio = RealStockPrice/EPS
OwnersEquity = TA-TL
BookValue = TA-TL
ShortMarketCap = MarketCap/1000000
PriceBookRatio = close/BVPS
//Truncate to Decimal---------------------------------------------------------------------------------
truncate(number, decimals) =>
factor = pow(10, decimals)
int(number * factor) / factor
Trunc_1 = truncate(ROA, 2)
Trunc_2 = truncate(ROE, 2)
Trunc_3 = truncate(ROIC, 2)
Trunc_4 = truncate(Current_Ratio, 2)
Trunc_5 = truncate(PriceEarningsRatio, 2)
Trunc_6 = truncate(PEGratio, 2)
Trunc_7 = truncate(PriceSalesRatio, 2)
Trunc_8 = truncate(LT_Debt, 2)
Trunc_9 = truncate(Cash, 2)
Trunc_10 = truncate(RealStockPrice, 2)
Trunc_11 = truncate(EVtoFCF, 2)
Trunc_12 = truncate(TA, 2)
Trunc_13 = truncate(TL, 2)
Trunc_14 = truncate(CA, 2)
Trunc_15 = truncate(CL, 2)
Trunc_16 = truncate(OwnersEquity, 2)
Trunc_17 = truncate(BookValue, 2)
Trunc_18 = truncate(ShortMarketCap, 2)
Trunc_19 = truncate(DY, 2)
Trunc_20 = truncate(DTE, 2)
Trunc_21 = truncate(PriceBookRatio, 2)
Trunc_22 = truncate(NetCashPS, 2)
Trunc_23 = truncate(ROC, 2)
Trunc_24 = truncate(DYFRR, 2)
//---------------------------------------------------------------------------------------------------------
draw_information_panel()=>
var label info_panel = na
info_1 = string(na)
info_2 = string(na)
info_3 = string(na)
info_4 = string(na)
info_5 = string(na)
info_6 = string(na)
info_7 = string(na)
info_8 = string(na)
info_9 = string (na)
info_10 = string (na)
info_11 = string (na)
info_12 = string (na)
info_13 = string (na)
info_14 = string (na)
info_panel_position_x = int(0)
info_panel_position_y = float(0.0)
info_panel_color = color(na)
label.delete(info_panel)
//colors
color greater = color.new(color.green, 50)
color lower = color.new(color.red, 50)
color neutral = color.new(color.blue, 50)
color credits = color.new(color.blue, 50)
//plotting
var table t = table.new(position.bottom_right, 2, 12, border_width = 1) // 22 elements + last 2 for by ken
table.cell(t, 0, 0, "ROA: " +tostring(Trunc_1), width = 13, text_color = color.white, bgcolor = (Trunc_1 < 1) ? lower:greater)
table.cell(t, 1, 0, "ROE: " +tostring(Trunc_2), width = 13, text_color = color.white, bgcolor = (Trunc_2 < 1) ? lower:greater)
table.cell(t, 0, 1, "ROIC: " +tostring(Trunc_3), width = 13, text_color = color.white, bgcolor = (Trunc_3 < 1) ? lower:greater)
table.cell(t, 1, 1, "CurrentRatio: " +tostring(Trunc_4), width = 13, text_color = color.white, bgcolor = (Trunc_4 < 2) ? lower:greater)
table.cell(t, 0, 2, "PE: " +tostring(Trunc_5), width = 13, text_color = color.white, bgcolor = (Trunc_5 > 15) ? lower:greater)
table.cell(t, 1, 2, "PEG: " +tostring(Trunc_6), width = 13, text_color = color.white, bgcolor = (Trunc_6 > 1) ? lower:greater)
table.cell(t, 0, 3, "PS: " +tostring(Trunc_7), width = 13, text_color = color.white, bgcolor = (Trunc_7 > 2) ? lower:greater)
table.cell(t, 1, 3, "DebtToEquity: " +tostring(Trunc_20), width = 13, text_color = color.white, bgcolor = (Trunc_20 > 1) ? lower:greater)
table.cell(t, 0, 4, "CashFlowYield: " +tostring(Trunc_11) + "%", width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 1, 4, "PriceToBookRatio: " +tostring(Trunc_21), width = 13, text_color = color.white, bgcolor = (Trunc_21 > 1.5) ? lower:greater)
table.cell(t, 0, 5, "NetCashPerShare: " +tostring(Trunc_22), width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 1, 5, "LongTermDebt: " +tostring(Trunc_8) + "M", width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 0, 6, "Cash: " +tostring(Trunc_9) + "M", width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 1, 6, "BookValue: " +tostring(Trunc_17) + "M", width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 0, 7, "MarketCap: " +tostring(Trunc_18) + "M", width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 1, 7, "DividendYield: " +tostring(Trunc_19), width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 0, 8, "TotalAssets: " +tostring(Trunc_12) + "M", width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 1, 8, "TotalLiabilities: " +tostring(Trunc_13) + "M", width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 0, 9, "CurrentAssets: " +tostring(Trunc_14) + "M", width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 1, 9, "CurrentLiabilities: " +tostring(Trunc_15) + "M", width = 14, text_color = color.white, bgcolor = neutral)
table.cell(t, 0, 10, "RealPrice: " +tostring(Trunc_10), width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 1, 10, "ROC%: " +tostring(Trunc_23*100) + "%", width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 0, 11, "Donald Yacktman: " +tostring(Trunc_24) + "%", width = 13, text_color = color.white, bgcolor = neutral)
table.cell(t, 1, 11, "Valuation Table", width = 13, text_color = color.white, bgcolor = credits)
|
Neo Matrix | https://www.tradingview.com/script/PJFTY5SV-Neo-Matrix/ | NeonMoney | https://www.tradingview.com/u/NeonMoney/ | 178 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © NeonMoney
//@version=5
indicator('', overlay=true)
TF = timeframe.period == '15S' ? '60' : timeframe.period == '1' ? '240' : timeframe.period == '3' ? 'D' : timeframe.period == '5' ? 'D' : timeframe.period == '15' ? 'W' : timeframe.period == '60' ? 'M' : timeframe.period == '240' ? '3M' : timeframe.period == 'D' ? '12M' : '12M'
timeflaga = timeframe.period == '1' ? true : false
timeflagb = timeframe.period == '3' ? true : false
timeflagc = timeframe.period == '15S' or timeframe.period == '15' ? true : false
timeflagd = timeframe.period == '60' ? true : false
timeflage = timeframe.period == '240' ? true : false
timeflagf = timeframe.period == 'D' ? true : false
out0 = ta.ema(close, 25 )
outa = timeflaga ? ta.ema(close, 125 ):na
outb = timeflaga ? ta.ema(close, 375 ):na
outc = timeflagb ? ta.ema(close, 125 ):na
outd = timeflagb ? ta.ema(close, 500 ):na
oute = timeflagc ? ta.ema(close, 100 ):na
outf = timeflagc ? ta.ema(close, 400 ):na
outg = timeflagd ? ta.ema(close, 100 ):na
outh = timeflagd ? ta.ema(close, 600 ):na
outi = timeflage ? ta.ema(close, 150 ):na
outj = timeflage ? ta.ema(close, 525 ):na
outk = timeflagf ? ta.ema(close, 175 ):na
outl = timeflagf ? ta.ema(close, 761 ):na
m=color.gray
n=75
plot(out0, color=m, transp=n)
plot(outa, color=m, transp=n)
plot(outb, color=m, transp=n)
plot(outc, color=m, transp=n)
plot(outd, color=m, transp=n)
plot(oute, color=m, transp=n)
plot(outf, color=m, transp=n)
plot(outg, color=m, transp=n)
plot(outh, color=m, transp=n)
plot(outi, color=m, transp=n)
plot(outj, color=m, transp=n)
plot(outk, color=m, transp=n)
plot(outl, color=m, transp=n)
//VWAP
timeflag = timeframe.period == '15S' or timeframe.period == '1' or timeframe.period == '3' or timeframe.period == '5' or timeframe.period == '15' or timeframe.period == '60' or timeframe.period == '240' or timeframe.period == 'D' ? true : false
src = hlc3
t = time(TF)
start = na(t[1]) or t > t[1]
sumSrc = src * volume
sumVol = volume
sumSrc := start ? sumSrc : sumSrc + sumSrc[1]
sumVol := start ? sumVol : sumVol + sumVol[1]
Value = timeflag ? sumSrc / sumVol : na
plot(Value, title="Vwap", style=plot.style_circles, linewidth=1, color=m, transp=n)
//Daily Pivot Plot
h = request.security(syminfo.tickerid, TF, high[1], barmerge.gaps_off, barmerge.lookahead_on)
l = request.security(syminfo.tickerid, TF, low[1], barmerge.gaps_off, barmerge.lookahead_on)
c = request.security(syminfo.tickerid, TF, close[1], barmerge.gaps_off, barmerge.lookahead_on)
p = (h + l + c) / 3.0
bc = (h + l) / 2.0
tc = p - bc + p
tcline = plot(timeflag ? tc : na, color=tc != tc[1] ? na : color.blue, linewidth=2, style=plot.style_line, display=display.none, transp=0)
bcline = plot(timeflag ? bc : na, color=bc != bc[1] ? na : color.blue, linewidth=2, style=plot.style_line, display=display.none, transp=0)
fill(tcline, bcline, color=tc != tc[1] and bc != bc[1] ? na : m, transp=92)
//Fib pivots
s1 = p - 0.236 * (h - l)
s2 = p - 0.382 * (h - l)
s3 = p - 0.618 * (h - l)
s4 = p - 0.786 * (h - l)
s5 = p - 1 * (h - l)
r1 = p + 0.236 * (h - l)
r2 = p + 0.382 * (h - l)
r3 = p + 0.618 * (h - l)
r4 = p + 0.786 * (h - l)
r5 = p + 1 * (h - l)
plot(timeflag ? p : na, linewidth=2, style=plot.style_line, color=p != p[1] ? na : m, transp=n)
plot(timeflag ? s1 : na, linewidth=1, style=plot.style_line, transp=n, color=s1 != s1[1] ? na : color.red)
plot(timeflag ? s2 : na, linewidth=1, style=plot.style_line, transp=n, color=s2 != s2[1] ? na : color.lime)
plot(timeflag ? s3 : na, linewidth=1, style=plot.style_line, transp=n, color=s3 != s3[1] ? na : color.aqua)
plot(timeflag ? s4 : na, linewidth=1, style=plot.style_line, transp=n, color=s4 != s4[1] ? na : color.orange)
plot(timeflag ? s5 : na, linewidth=1, style=plot.style_line, transp=n, color=s5 != s5[1] ? na : color.yellow)
plot(timeflag ? r1 : na, linewidth=1, style=plot.style_line, transp=n, color=r1 != r1[1] ? na : color.red)
plot(timeflag ? r2 : na, linewidth=1, style=plot.style_line, transp=n, color=r2 != r2[1] ? na : color.lime)
plot(timeflag ? r3 : na, linewidth=1, style=plot.style_line, transp=n, color=r3 != r3[1] ? na : color.aqua)
plot(timeflag ? r4 : na, linewidth=1, style=plot.style_line, transp=n, color=r4 != r4[1] ? na : color.orange)
plot(timeflag ? r5 : na, linewidth=1, style=plot.style_line, transp=n, color=r5 != r5[1] ? na : color.yellow)
//Table
var table t1 = table.new(position.bottom_center, 2, 7)
table.cell(t1, 1, 0, timeframe.period, text_color = color.new(m, n))
table.cell(t1, 0, 0, syminfo.ticker, text_color = color.new(m, n))
draw_line(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) =>
dline = line.new(x1=_x1, y1=_y1, x2=_x2, y2=_y2, xloc=_xloc, extend=_extend, color=_color, style=_style, width=_width)
line.delete(dline[1])
PreVal = 1
CurVal = 0
// Function outputs 1 when it's the first bar of the D/W/M/Y
is_newbar(tf) =>
is_nb = 0
t = time(tf)
is_nb := ta.change(t) != 0 ? 1 : 0
is_nb
[pd1_open, pd1_high, pd1_low, pd1_close] = request.security(syminfo.tickerid, TF, [open, high, low, close], lookahead=barmerge.lookahead_on)
var float pd_open = na
var float pd_high = na
var float pd_low = na
var float pd_close = na
if is_newbar(TF)
pd_open := pd1_open[1]
pd_high := pd1_high[1]
pd_low := pd1_low[1]
pd_close := pd1_close[1]
PP = (pd_high + pd_low + pd_close) / 3
S1 = PP - 0.236 * (pd_high - pd_low)
S2 = PP - 0.382 * (pd_high - pd_low)
S3 = PP - 0.618 * (pd_high - pd_low)
S4 = PP - 0.786 * (pd_high - pd_low)
S5 = PP - 1 * (pd_high - pd_low)
R1 = PP + 0.236 * (pd_high - pd_low)
R2 = PP + 0.382 * (pd_high - pd_low)
R3 = PP + 0.618 * (pd_high - pd_low)
R4 = PP + 0.786 * (pd_high - pd_low)
R5 = PP + 1 * (pd_high - pd_low)
pv_session = ta.barssince(is_newbar(TF) ? true : false)
pv_start_bar = bar_index - pv_session
pv_end_bar = pv_start_bar + 1
if true
draw_line(pv_start_bar, PP, pv_end_bar, PP, xloc.bar_index, extend.right, color.new(color.gray, n), line.style_solid, 1)
if true
draw_line(pv_start_bar, S1, pv_end_bar, S1, xloc.bar_index, extend.right, color.new(color.red, n), line.style_solid, 1)
if true
draw_line(pv_start_bar, S2, pv_end_bar, S2, xloc.bar_index, extend.right, color.new(color.lime, n), line.style_solid, 1)
if true
draw_line(pv_start_bar, S3, pv_end_bar, S3, xloc.bar_index, extend.right, color.new(color.aqua, n), line.style_solid, 1)
if true
draw_line(pv_start_bar, S4, pv_end_bar, S4, xloc.bar_index, extend.right, color.new(color.orange, n), line.style_solid, 1)
if true
draw_line(pv_start_bar, S5, pv_end_bar, S5, xloc.bar_index, extend.right, color.new(color.yellow, n), line.style_solid, 1)
if true
draw_line(pv_start_bar, R1, pv_end_bar, R1, xloc.bar_index, extend.right, color.new(color.red, n), line.style_solid, 1)
if true
draw_line(pv_start_bar, R2, pv_end_bar, R2, xloc.bar_index, extend.right, color.new(color.lime, n), line.style_solid, 1)
if true
draw_line(pv_start_bar, R3, pv_end_bar, R3, xloc.bar_index, extend.right, color.new(color.aqua, n), line.style_solid, 1)
if true
draw_line(pv_start_bar, R4, pv_end_bar, R4, xloc.bar_index, extend.right, color.new(color.orange, n), line.style_solid, 1)
if true
draw_line(pv_start_bar, R5, pv_end_bar, R5, xloc.bar_index, extend.right, color.new(color.yellow, n), line.style_solid, 1)
|
Educational LTF -> HTF volume delta | https://www.tradingview.com/script/SIQLVUAr-Educational-LTF-HTF-volume-delta/ | fikira | https://www.tradingview.com/u/fikira/ | 160 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © fikira
//@version=5
indicator("Educational LTF -> HTF volume delta", overlay=false, format=format.volume)
// This script is part of a collection of educational scripts
// If you want to return to the open source INDEX page, click the link in the comments:
// -> https://www.tradingview.com/script/TUeC9XDq-Education-INDEX/
// This script shows 1 of several technique to gather volume delta
// When there is an up-candle ('green') candle, the volume from that candle is added to an 'up-volume' variable
// When there is an down-candle ( 'red' ) candle, the volume from that candle is added to an 'down-volume' variable
// –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// | [ We are going to do this with lower timeframe candles data against 1 higher timeframe candle ] |
// –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// first, we set the lower timeframe:
i_ltf = input.timeframe('1', 'lower timeframe') // -> If the current chart timeframe is set to 60 minutes, then there will be 60 1-minute candles where we can calculate our up/down volume with
i_bar = input.string ('stack', 'Appearance', options=['stack', 'split', 'sell V -> column / buy V -> hist', 'buy V -> column / sell V -> hist'])
i_len = input.int (20 , 'length', tooltip='length of ema when \'split\'')
// Next, we save 2 kinds of data of lower tf in a 2 variables
// This will create 2 array's
// • array p which contains math.sign(close - open) of each ltf bar
// • array v which contains volume of each ltf bar
[p, v] = request.security_lower_tf(syminfo.tickerid, i_ltf, [math.sign(close - open), volume])
// What happens with that 'math.sign' thingy ?
// if data is below 0, it will return -1
// if data is above 0, it will return 1
// otherwise it will return 0
// So, in this care, we can easily check 'red'/'green' bars
// when 'open - close' < 0 ('red' bar) -> math.sign of this data will return -1
// when 'open - close' > 0 ('green' bar) -> math.sign of this data will return 1
// otherwise it will return 0
// Let's do something with that data
upV = 0.
ntV = 0.
dnV = 0.
// for each [index, data] in the array p
for [i, n] in p
// whatever fits first
switch n
-1 =>
dnV := dnV + array.get(v, i) // when 'red' bar -> add 'volume' of that bar to 'dnV'
1 =>
upV := upV + array.get(v, i) // when 'green' bar -> add 'volume' of that bar to 'upV'
=>
ntV := ntV + array.get(v, i) // when 'neutral' bar -> add 'volume' of that bar to 'ntV'
tt = ntV + dnV + upV // = total
// -> plotting
//plot(tt > 0 ? ntV : na, style=plot.style_columns, color=color.new(color.blue, 0), title='Neutral Volume')
//plot(tt > 0 ? ntV + dnV : na, style=plot.style_columns, color=color.new(color.red , 0), title='Sell Volume' )
//plot(tt > 0 ? ntV + dnV + upV : na, style=plot.style_columns, color=color.new(color.lime, 70), title='Buy Volume' )
//plot(volume , style=plot.style_columns, color=color.new(color.red , 80), title='Total Volume' )
// –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// | [ This can be written shorter ] |
// –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// Since the math.sign() can only have 3 possible values (-1, 0, 1), we can use this to direct immedeatily to a position in an array
a = array.from(0., 0., 0.)
// for each data (sign) in array
// • if -1 -> add volume at array index 0 (-1 + 1)
// • if 0 -> add volume at array index 1 ( 0 + 1)
// • if 1 -> add volume at array index 2 ( 1 + 1)
for [i, n] in p
array.set(a, math.round(n + 1), array.get(a, math.round(n + 1)) + array.get(v, i))
gDn = array.get(a, 0), gNt = array.get(a, 1), gUp = array.get(a, 2), tot = gDn + gNt + gUp
sUp = ta.ema(gUp, i_len), plot( sUp, color=color.lime)
sDn = ta.ema(gDn, i_len), plot(-sDn, color=color.red )
// -> plotting
plot(i_bar != 'split' ? tot > 0 ? gNt : na : na, style=plot.style_columns , color=color.new(color.blue , 0), title='Neutral Volume')
plot(i_bar == 'stack' and tot > 0 ? gNt + gDn : na, style=plot.style_columns , color=color.new(color.red , 0), title='Sell Volume' )
plot(i_bar == 'stack' and tot > 0 ? gNt + gDn + gUp : na, style=plot.style_columns , color=color.new(color.lime , 70), title='Buy Volume' )
plot(i_bar == 'buy V -> column / sell V -> hist' and tot > 0 ? gUp : na, style=plot.style_columns , color=color.new(color.lime , 60), title='Buy Volume' )
plot(i_bar == 'buy V -> column / sell V -> hist' and tot > 0 ? gDn : na, style=plot.style_histogram, color=color.new(color.red , 0), title='Sell Volume' , linewidth=5)
plot(i_bar == 'sell V -> column / buy V -> hist' and tot > 0 ? gDn : na, style=plot.style_columns , color=color.new(color.red , 60), title='Sell Volume' )
plot(i_bar == 'sell V -> column / buy V -> hist' and tot > 0 ? gUp : na, style=plot.style_histogram, color=color.new(color.lime , 0), title='Buy Volume' , linewidth=5)
plot(i_bar == 'split' and tot > 0 ? volume : na, style=plot.style_circles , color=
gUp > gDn ? color.new(color.lime, 60) : color.new(color.red, 60) , title='Total Volume', linewidth=2)
plot(i_bar == 'split' and tot > 0 ? -gDn : na, style=plot.style_columns , color=color.new(color.red , 50), title='Sell Volume' )
plot(i_bar == 'split' and tot > 0 ? gUp : na, style=plot.style_columns , color=color.new(color.lime , 50), title='Buy Volume' , linewidth=5)
plot(i_bar != 'split' ? volume : na, style=plot.style_columns, color= i_bar == 'stack' ? color.new(color.red , 80) : color.new(color.red , 90), title='Total Volume')
// –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// | [ Actually, this can be written even shorter (~Sharad_Gaikwad) ] |
// –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
[nV, sV, bV, tV] = request.security_lower_tf(syminfo.tickerid, '1', [close == open ? volume : 0, close < open ? volume : 0, close > open ? volume : 0, volume])
//plot(array.sum(nV) , style=plot.style_columns, color=color.new(color.lime, 50), title='Buy Volume' )
//plot(array.sum(nV) + array.sum(sV) , style=plot.style_columns, color=color.new(color.red , 50), title='Sell Volume' )
//plot(array.sum(nV) + array.sum(sV) + array.sum(bV) , style=plot.style_columns, color=color.new(color.red , 50), title='Sell Volume' )
//plot(array.sum(tV) , style=plot.style_columns, color=color.new(color.aqua, 50), title='Total Volume')
// –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// | [ Do mind: ] |
// –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// A maximum of 100,000 intrabars can be accessed by a call.
// This means not every bar will display ltf data, here this can be easily seen by columns which are only red, there only volume of current tf is shown
// –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// | [ Labels buy/sell Volume ] |
// –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
label.new(bar_index, tot, text= str.tostring(gUp, format.volume), style=label.style_label_down, textcolor=color.green, color=color.new(color.black, 100), size=size.small)
label.new(bar_index, 0 , text= str.tostring(gDn, format.volume), style=label.style_label_up , textcolor=color.red , color=color.new(color.black, 100), size=size.small)
|
CVD - Cumulative Volume Delta Candles | https://www.tradingview.com/script/NlM312nK-CVD-Cumulative-Volume-Delta-Candles/ | TradingView | https://www.tradingview.com/u/TradingView/ | 2,659 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradingView
//@version=5
indicator("CVD - Cumulative Volume Delta Candles", "CVD Candles", format = format.volume)
// CVD - Cumulative Volume Delta Candles
// v7, 2023.03.25
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
import PineCoders/Time/4 as PCtime
import PineCoders/lower_tf/4 as PCltf
import TradingView/ta/4 as TVta
//#region ———————————————————— Constants and Inputs
// ————— Constants
int MS_IN_MIN = 60 * 1000
int MS_IN_HOUR = MS_IN_MIN * 60
int MS_IN_DAY = MS_IN_HOUR * 24
// Default colors
color GRAY = #808080ff
color LIME = #00FF00ff
color MAROON = #800000ff
color ORANGE = #FF8000ff
color PINK = #FF0080ff
color TEAL = #008080ff
color BG_DIV = color.new(ORANGE, 90)
color BG_RESETS = color.new(GRAY, 90)
// Reset conditions
string RST1 = "None"
string RST2 = "On a stepped higher timeframe"
string RST3 = "On a fixed higher timeframe..."
string RST4 = "At a fixed time..."
string RST5 = "At the beginning of the regular session"
string RST6 = "At the first visible chart bar"
string RST7 = "On trend changes..."
// Trends
string TR01 = "Supertrend"
string TR02 = "Aroon"
string TR03 = "Parabolic SAR"
// Volume Delta calculation mode
string VD01 = "Volume Delta"
string VD02 = "Volume Delta Percent"
// Realtime calculation modes
string RT1 = "Intrabars (same as on historical bars)"
string RT2 = "Chart updates"
// Intrabar precisions
string LTF1 = "Covering most chart bars (least precise)"
string LTF2 = "Covering some chart bars (less precise)"
string LTF3 = "Covering less chart bars (more precise)"
string LTF4 = "Covering few chart bars (very precise)"
string LTF5 = "Covering the least chart bars (most precise)"
string LTF6 = "~12 intrabars per chart bar"
string LTF7 = "~24 intrabars per chart bar"
string LTF8 = "~50 intrabars per chart bar"
string LTF9 = "~100 intrabars per chart bar"
string LTF10 = "~250 intrabars per chart bar"
// Tooltips
string TT_RST = "This is where you specify how you want the cumulative volume delta to reset.
If you select one of the last three choices, you must also specify the relevant additional information below."
string TT_RST_HTF = "This value only matters when '" + RST3 +"' is selected."
string TT_RST_TIME = "Hour: 0-23\nMinute: 0-59\nThese values only matter when '" + RST4 +"' is selected.
A reset will occur when the time is greater or equal to the bar's open time, and less than its close time."
string TT_RST_TREND = "These values only matter when '" + RST7 +"' is selected.\n
For Supertrend, the first value is the length of ATR, the second is the factor. For Aroon, the first value is the lookback length."
string TT_TOTVOL = "Total volume can only be displayed when '" + VD01 +"' is selected as the Volume Delta Calculation mode.\n\n
The 'Bodies' value is the transparency of the total volume candle bodies. Zero is opaque, 100 is transparent."
string TT_LINE = "This plots a line at the `close` values of the CVD candles. You can use it instead of the CVD candles."
string TT_LTF = "Your selection here controls how many intrabars will be analyzed for each chart bar.
The more intrabars you analyze, the more precise the calculations will be,
but the less chart bars will be covered by the indicator's calculations because a maximum of 100K intrabars can be analyzed.\n\n
The first five choices determine the lower timeframe used for intrabars using how much chart coverage you want.
The last five choices allow you to select approximately how many intrabars you want analyzed per chart bar."
string TT_MA = "This plots the running average of CVD from its last reset. The 'Length' period only applies when CVD does not reset, i.e., the reset is 'None'."
// ————— Inputs
string resetInput = input.string(RST2, "CVD Resets", inline = "00", options = [RST1, RST2, RST5, RST6, RST3, RST4, RST7], tooltip = TT_RST)
string fixedTfInput = input.timeframe("D", " Fixed higher timeframe:", tooltip = TT_RST_HTF)
int hourInput = input.int(9, " Fixed time: Hour", inline = "01", minval = 0, maxval = 23)
int minuteInput = input.int(30, "Minute", inline = "01", minval = 0, maxval = 59, tooltip = TT_RST_TIME)
string trendInput = input.string(TR01, " Trend: ", inline = "02", options = [TR02, TR03, TR01])
int trendPeriodInput = input.int(14, " Length", inline = "02", minval = 2)
float trendValue2Input = input.float(3.0, "", inline = "02", minval = 0.25, step = 0.25, tooltip = TT_RST_TREND)
string ltfModeInput = input.string(LTF3, "Intrabar precision", inline = "03", options = [LTF1, LTF2, LTF3, LTF4, LTF5, LTF6, LTF7, LTF8, LTF9, LTF10], tooltip = TT_LTF)
string vdCalcModeInput = input.string(VD01, "Volume Delta Calculation", inline = "04", options = [VD01, VD02])
string GRP1 = "Visuals"
bool showCandlesInput = input.bool(true, "CVD candles", inline = "11", group = GRP1)
color upColorInput = input.color(LIME, " 🡑", inline = "11", group = GRP1)
color dnColorInput = input.color(PINK, "🡓", inline = "11", group = GRP1)
bool colorDivBodiesInput = input.bool(true, "Color CVD bodies on divergences ", inline = "12", group = GRP1)
color upDivColorInput = input.color(TEAL, "🡑", inline = "12", group = GRP1)
color dnDivColorInput = input.color(MAROON, "🡓", inline = "12", group = GRP1)
bool showTotVolInput = input.bool(false, "Total volume candle borders", inline = "13", group = GRP1)
color upTotVolColorInput = input.color(TEAL, "🡑", inline = "13", group = GRP1)
color dnTotVolColorInput = input.color(MAROON, "🡓", inline = "13", group = GRP1)
int totVolBodyTranspInput = input.int(80, "bodies", inline = "13", group = GRP1, minval = 0, maxval = 100, tooltip = TT_TOTVOL)
bool showLineInput = input.bool(false, "CVD line", inline = "14", group = GRP1)
color lineUpColorInput = input.color(LIME, " 🡑", inline = "14", group = GRP1)
color lineDnColorInput = input.color(PINK, "🡓", inline = "14", group = GRP1, tooltip = TT_LINE)
bool showMaInput = input.bool(false, "CVD MA", inline = "15", group = GRP1)
color maUpColorInput = input.color(TEAL, " 🡑", inline = "15", group = GRP1)
color maDnColorInput = input.color(MAROON, "🡓", inline = "15", group = GRP1)
int maPeriodInput = input.int(20, " Length", inline = "15", group = GRP1, minval = 2, tooltip = TT_MA)
bool bgDivInput = input.bool(false, "Color background on divergences ", inline = "16", group = GRP1)
color bgDivColorInput = input.color(BG_DIV, "", inline = "16", group = GRP1)
bool bgResetInput = input.bool(true, "Color background on resets ", inline = "17", group = GRP1)
color bgResetColorInput = input.color(BG_RESETS, "", inline = "17", group = GRP1)
bool showZeroLineInput = input.bool(true, "Zero line", inline = "18", group = GRP1)
bool showInfoBoxInput = input.bool(true, "Show information box ", group = GRP1)
string infoBoxSizeInput = input.string("small", "Size ", inline = "19", group = GRP1, options = ["tiny", "small", "normal", "large", "huge", "auto"])
string infoBoxYPosInput = input.string("bottom", "↕", inline = "19", group = GRP1, options = ["top", "middle", "bottom"])
string infoBoxXPosInput = input.string("left", "↔", inline = "19", group = GRP1, options = ["left", "center", "right"])
color infoBoxColorInput = input.color(color.gray, "", inline = "19", group = GRP1)
color infoBoxTxtColorInput = input.color(color.white, "T", inline = "19", group = GRP1)
//#endregion
//#region ———————————————————— Functions
// @function Determines if the volume for an intrabar is up or down.
// @returns ([float, float]) A tuple of two values, one of which contains the bar's volume. `upVol` is the volume of up bars. `dnVol` is the volume of down bars.
// Note that when this function is called with `request.security_lower_tf()` a tuple of float[] arrays will be returned by `request.security_lower_tf()`.
upDnIntrabarVolumes() =>
float upVol = 0.0
float dnVol = 0.0
switch
// Bar polarity can be determined.
close > open => upVol += volume
close < open => dnVol -= volume
// If not, use price movement since last bar.
close > nz(close[1]) => upVol += volume
close < nz(close[1]) => dnVol -= volume
// If not, use previously known polarity.
nz(upVol[1]) > 0 => upVol += volume
nz(dnVol[1]) < 0 => dnVol -= volume
[upVol, dnVol]
// @function Selects a HTF from the chart's TF.
// @returns (simple string) A timeframe string.
htfStep() =>
int tfInMs = timeframe.in_seconds() * 1000
string result =
switch
tfInMs <= MS_IN_MIN => "60"
tfInMs < MS_IN_HOUR * 3 => "D"
tfInMs <= MS_IN_HOUR * 12 => "W"
tfInMs < MS_IN_DAY * 7 => "M"
=> "12M"
// @function Determines when a bar opens at a given time.
// @param hours (series int) "Hour" part of the time we are looking for.
// @param minutes (series int) "Minute" part of the time we are looking for.
// @returns (series bool) `true` when the bar opens at `hours`:`minutes`, false otherwise.
timeReset(int hours, int minutes) =>
int openTime = timestamp(year, month, dayofmonth, hours, minutes, 0)
bool timeInBar = time <= openTime and time_close > openTime
bool result = timeframe.isintraday and not timeInBar[1] and timeInBar
//#endregion
//#region ———————————————————— Calculations
// Lower timeframe (LTF) used to mine intrabars.
var string ltfString = PCltf.ltf(ltfModeInput, LTF1, LTF2, LTF3, LTF4, LTF5, LTF6, LTF7, LTF8, LTF9, LTF10)
// Get two arrays, one each for up and dn volumes.
[upVolumes, dnVolumes] = request.security_lower_tf(syminfo.tickerid, ltfString, upDnIntrabarVolumes())
// Calculate the maximum volumes, total volume, and volume delta, and assign the result to the `barDelta` variable.
float totalUpVolume = nz(upVolumes.sum())
float totalDnVolume = nz(dnVolumes.sum())
float maxUpVolume = nz(upVolumes.max())
float maxDnVolume = nz(dnVolumes.min())
float totalVolume = totalUpVolume - totalDnVolume
float delta = totalUpVolume + totalDnVolume
float deltaPct = delta / totalVolume
// Track cumulative volume.
var float cvd = 0.0
[reset, trendIsUp, resetDescription] =
switch resetInput
RST1 => [false, na, "No resets"]
RST2 => [timeframe.change(htfStep()), na, "Resets every " + htfStep()]
RST3 => [timeframe.change(fixedTfInput), na, "Resets every " + fixedTfInput]
RST4 => [timeReset(hourInput, minuteInput), na, str.format("Resets at {0,number,00}:{1,number,00}", hourInput, minuteInput)]
RST5 => [session.isfirstbar_regular, na, "Resets at the beginning of the session"]
RST6 => [time == chart.left_visible_bar_time, na, "Resets at the beginning of visible bars"]
RST7 =>
switch trendInput
TR01 =>
[_, direction] = ta.supertrend(trendValue2Input, trendPeriodInput)
[ta.change(direction, 1) != 0, direction == -1, "Resets on Supertrend changes"]
TR02 =>
[up, dn] = TVta.aroon(trendPeriodInput)
[ta.cross(up, dn), ta.crossover(up, dn), "Resets on Aroon changes"]
TR03 =>
float psar = ta.sar(0.02, 0.02, 0.2)
[ta.cross(psar, close), ta.crossunder(psar, close), "Resets on PSAR changes"]
=> [na, na, na]
if reset
cvd := 0
// Build OHLC values for CVD candles.
bool useVdPct = vdCalcModeInput == VD02
float barDelta = useVdPct ? deltaPct : delta
float cvdO = cvd
float cvdC = cvdO + barDelta
float cvdH = useVdPct ? math.max(cvdO, cvdC) : cvdO + maxUpVolume
float cvdL = useVdPct ? math.min(cvdO, cvdC) : cvdO + maxDnVolume
cvd += barDelta
// MA of CVD
var float ma = cvd
var cvdValues = array.new<float>()
if resetInput == RST1
ma := ta.sma(cvdC, maPeriodInput)
else
if reset
cvdValues.clear()
cvdValues.push(cvd)
else
cvdValues.push(cvd)
ma := cvdValues.avg()
// Total volume level relative to CVD.
float totalVolumeLevel = cvdO + (totalVolume * math.sign(barDelta))
// ———— Intrabar stats
[intrabars, chartBarsCovered, avgIntrabars] = PCltf.ltfStats(upVolumes)
int chartBars = bar_index + 1
// Detect errors.
if resetInput == RST3 and timeframe.in_seconds(fixedTfInput) <= timeframe.in_seconds()
runtime.error("The higher timeframe for resets must be greater than the chart's timeframe.")
else if resetInput == RST4 and not timeframe.isintraday
runtime.error("Resets at a fixed time work on intraday charts only.")
else if ta.cum(totalVolume) == 0 and barstate.islast
runtime.error("No volume is provided by the data vendor.")
else if ta.cum(intrabars) == 0 and barstate.islast
runtime.error("No intrabar information exists at the '" + ltfString + "' timeframe.")
// Detect divergences between volume delta and the bar's polarity.
bool divergence = delta != 0 and math.sign(delta) != math.sign(close - open)
//#endregion
//#region ———————————————————— Visuals
color candleColor = delta > 0 ? colorDivBodiesInput and divergence ? upDivColorInput : upColorInput : colorDivBodiesInput and divergence ? dnDivColorInput : dnColorInput
color totVolCandleColor = delta > 0 ? upTotVolColorInput : dnTotVolColorInput
// Display key values in indicator values and Data Window.
displayLocation = display.data_window
plot(delta, "Volume delta for the bar", candleColor, display = displayLocation)
plot(totalUpVolume, "Up volume for the bar", upColorInput, display = displayLocation)
plot(totalDnVolume, "Dn volume for the bar", dnColorInput, display = displayLocation)
plot(totalVolume, "Total volume", display = displayLocation)
plot(na, "═════════════════", display = displayLocation)
plot(cvdO, "CVD before this bar", display = displayLocation)
plot(cvdC, "CVD after this bar", display = displayLocation)
plot(maxUpVolume, "Max intrabar up volume", upColorInput, display = displayLocation)
plot(maxDnVolume, "Max intrabar dn volume", dnColorInput, display = displayLocation)
plot(intrabars, "Intrabars in this bar", display = displayLocation)
plot(avgIntrabars, "Average intrabars", display = displayLocation)
plot(chartBarsCovered, "Chart bars covered", display = displayLocation)
plot(bar_index + 1, "Chart bars", display = displayLocation)
plot(na, "═════════════════", display = displayLocation)
// Total volume boxes.
[totalVolO, totalVolH, totalVolL, totalVolC] = if showTotVolInput and not useVdPct
[cvdO, math.max(cvdO, totalVolumeLevel), math.min(cvdO, totalVolumeLevel), totalVolumeLevel]
else
[na, na, na, na]
plotcandle(totalVolO, totalVolH, totalVolL, totalVolC, "CVD", color = color.new(totVolCandleColor, totVolBodyTranspInput), wickcolor = totVolCandleColor, bordercolor = totVolCandleColor)
// CVD candles.
plotcandle(showCandlesInput ? cvdO : na, cvdH, cvdL, cvdC, "CVD", color = candleColor, wickcolor = candleColor, bordercolor = candleColor)
// CVD line.
plot(showLineInput ? cvdC : na, "CVD line", cvdC > 0 ? lineUpColorInput : lineDnColorInput)
// CVD MA.
plot(showMaInput ? ma : na, "CVD MA", reset ? na : ma > 0 ? maUpColorInput : maDnColorInput)
// Zero line.
hline(showZeroLineInput ? 0 : na, "Zero", GRAY, hline.style_dotted)
// Up/Dn arrow used when resets occur on trend changes.
plotchar(reset and not na(trendIsUp) ? trendIsUp : na, "Up trend", "▲", location.top, upColorInput)
plotchar(reset and not na(trendIsUp) ? not trendIsUp : na, "Dn trend", "▼", location.top, dnColorInput)
// Background on resets and divergences.
bgcolor(bgResetInput and reset ? bgResetColorInput : bgDivInput and divergence ? bgDivColorInput : na)
// Display information box only once on the last historical bar, instead of on all realtime updates, as when `barstate.islast` is used.
if showInfoBoxInput and barstate.islastconfirmedhistory
var table infoBox = table.new(infoBoxYPosInput + "_" + infoBoxXPosInput, 1, 1)
color infoBoxBgColor = infoBoxColorInput
string txt = str.format("{0}\nUses intrabars at {1}\nAvg intrabars per chart bar: {2,number,#.##}\nChart bars covered: {3} / {4} ({5,number,percent})",
resetDescription, PCtime.formattedNoOfPeriods(timeframe.in_seconds(ltfString) * 1000),
avgIntrabars, chartBarsCovered, bar_index + 1, chartBarsCovered / (bar_index + 1))
if avgIntrabars < 5
txt += "\nThis quantity of intrabars is dangerously small.\nResults will not be as reliable with so few."
infoBoxBgColor := color.red
table.cell(infoBox, 0, 0, txt, text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput, bgcolor = infoBoxBgColor)
//#endregion
|
Trend Line Regression | https://www.tradingview.com/script/tf2TTN6c/ | dandrideng | https://www.tradingview.com/u/dandrideng/ | 603 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dandrideng
//@version=5
indicator(title="Trend Line Regression", shorttitle="TLR", overlay=true, max_bars_back=800, max_lines_count=400, max_labels_count=400)
import dandrideng/least_squares_regression/1 as lsr
//trend line regression
lookback_left = input.int(defval=5, title="Pivot Lookback Left", group="Trend Line Regression")
lookback_right = input.int(defval=5, title="Pivot Lookback Right", group="Trend Line Regression")
reg_forward = input.int(defval=20, title="Max Lookback Forward", group="Trend Line Regression")
min_length = input.int(defval=100, title="Min Regression Length", maxval=500, group="Trend Line Regression")
max_length = input.int(defval=200, title="Max Regression Length", maxval=500, group="Trend Line Regression")
length_step = input.int(defval=100, title="Regression Length Steps", group="Trend Line Regression")
max_iteration = input.int(defval=4, title="Max Iterations of Regression", group="Trend Line Regression")
max_points = input.int(defval=30, title="Max Point Numbers of Trend Line", group="Trend Line Regression")
min_points = input.int(defval=3, title="Min Point Numbers of Trend Line", group="Trend Line Regression")
min_reg_level = input.float(defval=4, title="Min Regression Level of Trend Line", group="Trend Line Regression")
std_offset = input.float(defval=0.5, title="Multiply Regression Std", group="Trend Line Regression")
top_line_color = input.color(defval=color.red, title="Color of Top Trend Line", group="Trend Line Regression")
bottom_line_color = input.color(defval=color.green, title="Color of Bottom Trend Line", group="Trend Line Regression")
extend_lines = input.bool(defval=true, title="Extend Lines", group="Trend Line Regression") ? extend.right : extend.none
draw_pivot = input.bool(defval=false, title="Draw Piovt High/Low", group="Trend Line Regression")
show_labels = input.bool(defval=false, title="Show Labels", group="Trend Line Regression")
pivot_high = ta.pivothigh(high, lookback_left, lookback_right)
pivot_low = ta.pivotlow(low, lookback_left, lookback_right)
plot(draw_pivot ? pivot_high : na, offset=-lookback_left)
plot(draw_pivot ? pivot_low : na, offset=-lookback_left)
//check regression (functional)
check_trend_line(start, end, type, a, b) =>
res = true
for i = start + 1 to end - 1
yi = a * i + b
yi_1 = a * (i - 1) + b
if type == "top" and (close[i] > yi and close[i - 1] > yi_1)
res := false
break
else if type == "bottom" and (close[i] < yi and close[i - 1] < yi_1)
res := false
break
res
//draw trend line regressions (functional)
draw_trend_line(forward, length, type) =>
pivot_src = type == "top" ? pivot_high : pivot_low
tick = array.new_int(max_points, 0)
price = array.new_float(max_points, 0)
num = 0
for i = 0 to length - 1
if not na(pivot_src[i + forward]) and num < max_points
array.set(tick, num, i + lookback_left + forward)
array.set(price, num, pivot_src[i + forward])
num := num + 1
if num > 0
[x2, x1, a, b, r, s, n] = lsr.trend_line_lsr(tick, price, num, type, max_iteration, min_points)
y1 = x1 * a + b
y2 = x2 * a + b
o = s * std_offset
if n > min_points and r > min_reg_level and check_trend_line(x1, x2, type, a, b)
var line mid_line = na
mid_line := line.new(x1=bar_index-x1, y1=y1, x2=bar_index-x2, y2=y2)
line.set_width(mid_line, 1)
line.set_color(mid_line, color.new(type == "top" ? top_line_color : bottom_line_color, 25))
line.set_extend(mid_line, extend_lines)
line.set_style(mid_line, line.style_dashed)
var line top_line = na
top_line := line.new(x1=bar_index-x1, y1=y1+o, x2=bar_index-x2, y2=y2+o)
line.set_width(top_line, 1)
line.set_color(top_line, color.new(type == "top" ? top_line_color : bottom_line_color, 25))
line.set_extend(top_line, extend_lines)
var line bottom_line = na
bottom_line := line.new(x1=bar_index-x1, y1=y1-o, x2=bar_index-x2, y2=y2-o)
line.set_width(bottom_line, 1)
line.set_color(bottom_line, color.new(type == "top" ? top_line_color : bottom_line_color, 25))
line.set_extend(bottom_line, extend_lines)
linefill.new(mid_line, top_line, color=color.new(type == "top" ? top_line_color : bottom_line_color, 90))
linefill.new(mid_line, bottom_line, color=color.new(type == "top" ? top_line_color : bottom_line_color, 90))
if show_labels
var label reg_label = na
reg_label := label.new(x=bar_index-x2, y=type == "top" ? y2+o : y2-o, textcolor=color.white)
label.set_color(reg_label, color.new(type == "top" ? top_line_color : bottom_line_color, 30))
label.set_text(reg_label, "Level: " + str.tostring(r, "#.###") + "\nPoints: " + str.tostring(n, "#"))
label.set_style(reg_label, type == "top" ? label.style_label_down : label.style_label_up)
//delete all lines
all_lines = line.all
if array.size(all_lines) > 0
for i = 0 to array.size(all_lines) - 1
line.delete(array.get(all_lines, i))
//delete all labels
all_labels = label.all
if array.size(all_labels) > 0
for i = 0 to array.size(all_labels) - 1
label.delete(array.get(all_labels, i))
//trend line
for l = min_length to max_length by length_step
draw_trend_line(reg_forward, l, "top")
draw_trend_line(reg_forward, l, "bottom")
//end of file |
Volume + Volatility | https://www.tradingview.com/script/6Q89OSQ8-Volume-Volatility/ | sueun123 | https://www.tradingview.com/u/sueun123/ | 95 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sueun123
// @version=5
indicator(title = "Volume + Volatility", shorttitle = "Vo & Va", overlay = false, format = format.inherit, precision = 2, scale = scale.right)
//---Input Section---
// Input H, L, C, O
h = input(high, title = "Line 1")
l = input(low, title = "Line 2")
c = input(close, title = "Line 3")
o = input(open, title = "Line 4")
// Input WMA
wma_length = input.int(defval = 7, minval = 1, title = "WMA Length")
wma_source = input(close, title = "WMA Source")
//---Calculation Section---
// Calculate H, L, C, O
hlco_formula = (h+l)/2
// Calculate WMA
wma_formula = ta.wma(2*ta.wma(wma_source, wma_length/2) - ta.wma(wma_source, wma_length), ((wma_length)))
// Calculate BB
multiply__BB = input(defval = 1.0, title = "BB Deviation")
upperbb_formula = ta.wma(c, wma_length)
lowerbb_formula = ta.wma(o, wma_length)
upper_stdev = multiply__BB * ta.stdev(h, wma_length)
lower_stdev = multiply__BB * ta.stdev(l, wma_length)
upperbb = upperbb_formula + upper_stdev
lowerbb = lowerbb_formula - lower_stdev
// Calculate CCI
cci = ta.cci(hlco_formula, wma_length)
cci_formula = ta.wma(cci, wma_length)
c1 = cci > upperbb
c2 = cci < upperbb and cci > cci_formula
c3 = cci > lowerbb and cci < cci_formula
c4 = cci < lowerbb
// Calculate WMA & BB Crosses
signal_1 = ta.crossover(c, upperbb) or ta.crossunder(c, upperbb)
signal_2 = ta.crossover(c, lowerbb) or ta.crossunder(c, lowerbb)
signal_3 = ta.crossunder(o, upperbb) or ta.crossunder(o, upperbb)
signal_4 = ta.crossunder(o, lowerbb) or ta.crossunder(o, lowerbb)
//---Plot Section---
// Plot H, L, C, O
p1 = plot(c, title = "Line 3", color = color.green, transp = 0, linewidth = 2, style = plot.style_line, linewidth = 2, display = display.all, editable = true) //Only Close
p2 = plot(o, title = "Line 4", color = color.blue, transp = 0, linewidth = 2, style = plot.style_line, linewidth = 2, display = display.all, editable = true) //Only Open
// Plot WMA & BB
plot(c, color = signal_1 ? color.red : na, style = plot.style_circles, title = "Line 3 outside Upper BB", linewidth = 3, display = display.none)
plot(c, color = signal_2 ? color.blue : na, style = plot.style_circles, title = "Line 3 outside Upper BB", linewidth = 3, display = display.none)
plot(o, color = signal_3 ? color.green : na, style = plot.style_circles, title = "Line 4 outside Upper BB", linewidth = 3, display = display.none)
plot(o, color = signal_4 ? color.orange : na, style = plot.style_circles, title = "Line 4 outside Lower BB", linewidth = 3, display = display.none)
// Plot BB
p3 = plot(upperbb, title = "Upper BB", color = color.yellow, transp = 45, linewidth = 1, editable = true)
p4 = plot(lowerbb, title = "Lower BB", color = color.yellow, transp = 45, linewidth = 1, editable = true)
//---Fill Section---
// Fill H, L, C, O
fillColor1 = c > upperbb ? color.new(color.yellow, transp = 45) : na
fill(p3, p1, fillColor1, title = "Line 3 Volatile Up")
fillColor2 = o > upperbb ? color.new(color.yellow, transp = 45) : na
fill(p3, p2, fillColor2, title = "Line 4 Volatile Up")
fillColor3 = c < lowerbb ? color.new(color.yellow, transp = 45) : na
fill(p4, p1, fillColor3, title = "Line 3 Volatile Down")
fillColor4 = o < lowerbb ? color.new(color.yellow, transp = 45) : na
fill(p4, p2, fillColor4, title = "Line 4 Volatile Down")
// Fill BB
fill_bb_color = c1 ? color.new(color.green, transp = 75) : c2 ? color.new(color.green, transp = 75) : c3 ? color.new(color.red, transp = 75) : color.new(color.red, transp = 75)
fill(p3, p4, color = fill_bb_color, title = "BB Fill")
//---END--- |
Comparative Relative Strength(CRS), ARS,SRS,Beta,Roc | https://www.tradingview.com/script/gK296lU7-Comparative-Relative-Strength-CRS-ARS-SRS-Beta-Roc/ | Mindsets | https://www.tradingview.com/u/Mindsets/ | 49 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Mindsets
//@version=5
indicator('Comparative Relative Strength', shorttitle='CRS', precision=3)
//Input
comparativeTicker = input.symbol('NIFTY', title='Comparative Symbol', group='RS Parameters')
ARSDate = input.time(defval=timestamp('18 Oct 2021'), title='ARS Date', group='RS Parameters')
SRSLength = input.int(123, minval=1, title='SRS Period', group='RS Parameters')
XRSLength = input.int(55, title='XRS Period',tooltip = "EXtra RS Parameter", group='RS Parameters')
toggleSRS = input.bool(defval=true, title='Toggle CRS color on SRS +ve/-ve', group='RS Parameters')
SRS_up = input.color(color.new(color.teal, 30), 'SRS +Ve', inline='Colors', group='RS Parameters')
SRS_down = input.color(color.new(color.red, 30), 'SRS -Ve', inline='Colors', group='RS Parameters')
togglelabelbox = input.bool(defval=true, title='Toggle Label Box color on ARS +ve/-ve', group='Display Choices')
color_text = input.color(color.new(color.white, 20), 'Info Text', inline='Colors', group='Display Choices')
showRefLine = input.bool(defval=true, title='Show ARS Reference Line', group='Display Choices')
showMA = input.bool(defval=false, title='Show EMA of CRS', group='Additional Info')
lengthMA = input.int(34, minval=1, title='EMA Length', group='Additional Info')
//Input End
//Function
isRefDayBar(testTime) =>
time[1] < testTime and testTime <= time
//Set up
var refTS = 0
var isRefDayOutOfRange = false
float maxCRS = 0.0
float bs_ref_c = 0.0
float cs_ref_c = 0.0
//Bar ahead refDay
isRefBar = isRefDayBar(ARSDate)
isBarAheadOfRef = time > ARSDate
isRefDayOutOfRange := bar_index == 0 and isBarAheadOfRef ? true : isRefDayOutOfRange[1]
refTS := isRefBar ? timestamp(syminfo.timezone, year(time), month(time), dayofmonth(time), hour(time), minute(time), second(time)) : refTS[1]
cs_c = request.security(comparativeTicker, timeframe.period, close)
crs = close / cs_c
//Ref CRS
bs_ref_c := isRefBar ? close : bs_ref_c[1]
cs_ref_c := isRefBar ? cs_c : cs_ref_c[1]
//CRS
refCRS = bs_ref_c / cs_ref_c
CRS_chng = (crs / refCRS - 1) * 100
//Price change from reference
price_chng = (close / bs_ref_c - 1) * 100
compTickerchng = (cs_c / cs_ref_c - 1) * 100
eq_price = cs_c * bs_ref_c / cs_ref_c
ARS = close / bs_ref_c / (cs_c / cs_ref_c) - 1
SRS = close / close[SRSLength] / (cs_c / cs_c[SRSLength]) - 1
XRS = close / close[XRSLength] / (cs_c / cs_c[XRSLength]) - 1
RoC = close / close[XRSLength] - 1
//Beta calculations RicardoSantos
return_percent(src) =>
ta.change(src) * 100 / src[1]
lengthx = 252
inst_return = return_percent(close)
bench_return = return_percent(cs_c)
avg_inst_return = ta.sma(inst_return, lengthx)
avg_bench_return = ta.sma(bench_return, lengthx)
sum = 0.0
for idx = lengthx to 0 by 1
inst_variance = inst_return[idx] - avg_inst_return
bench_variance = bench_return[idx] - avg_bench_return
sum += inst_variance * bench_variance
sum
covariance = sum / (lengthx - 1)
beta = covariance / ta.variance(bench_return, lengthx)
//----------------------------------------------------------------------------------------------------------------------
//Flip Color
CRSColor = toggleSRS ? SRS > 0 ? SRS_up : SRS_down : color.blue
labelboxColor = togglelabelbox ? ARS > 0 ? color.new(color.teal, 40) : color.new(color.red, 40) : color.new(color.blue, 40)
//SMA
CRS_MA = ta.ema(crs, lengthMA)
//Label Texts
refDateText = 'ARS Date: ' + str.tostring(dayofmonth(refTS), '#00') + '/' + str.tostring(month(refTS), '#00') + '/' + str.tostring(year(refTS)) + ' ' + str.tostring(hour(refTS), '#00') + ':' + str.tostring(minute(refTS), '#00')
labelText = isRefDayOutOfRange ? '\nSelected reference date not in view range.\nTry higher TF or more recent reference date\n' : refDateText + '\n' +
str.tostring(syminfo.ticker) + ' Chng = ' + str.tostring(price_chng, '#0.00') + '%' + '\n' + str.tostring(comparativeTicker) +
' Chng = ' + str.tostring(compTickerchng, '#0.00') + '%'
labelToolTipText = 'ARS= ' + str.tostring(ARS, '#0.000') + ' SRS= ' + str.tostring(SRS, '#0.000') + '\nXRS(' + str.tostring(XRSLength) + '): ' + str.tostring(XRS, '#0.00') + ' RoC: ' + str.tostring(RoC, '#0.000') + '\nβ: ' + str.tostring(beta, '#0.00')
//Label
changePercentageLabel = barstate.islast ? label.new(bar_index + 5, crs, text=labelText, color=labelboxColor, textcolor=color_text, style=label.style_label_left, textalign=text.align_left, yloc=yloc.price) : na
label.set_tooltip(changePercentageLabel, labelToolTipText)
label.delete(changePercentageLabel[1])
//Plot
plot(crs, linewidth=3, color=CRSColor, title='CRS') // CRS
plot(showRefLine ? refCRS : na, linewidth=2, color=color.new(color.yellow, 0), title='ARS Reference Line') // Zero Line
plot(showMA ? CRS_MA : na, color=color.new(color.purple, 30), linewidth=2, title='EMA') //Moving Average
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.