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
|
---|---|---|---|---|---|---|---|---|
TREND RB | https://www.tradingview.com/script/Z2Notbxh-TREND-RB/ | PULLBACKINDICATORS | https://www.tradingview.com/u/PULLBACKINDICATORS/ | 207 | 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/
//@version=4
study("TREND RB", precision = 0)
dlen = input(defval = 20, title = "Ribbon Period", minval = 10)
dchannel(len)=>
float hh = highest(len)
float ll = lowest(len)
int trend = 0
trend := close > hh[1] ? 1 : close < ll[1] ? -1 : nz(trend[1])
dchannelalt(len, maintrend)=>
float hh = highest(len)
float ll = lowest(len)
int trend = 0
trend := close > hh[1] ? 1 : close < ll[1] ? -1 : nz(trend[1])
maintrend == 1 ? trend == 1 ? #00FF00ff : #00FF009f :
maintrend == -1 ? trend == -1 ? #FF0000ff : #FF00009f :
na
maintrend = dchannel(dlen)
plot( 5, color = dchannelalt(dlen - 0, maintrend), style = plot.style_area, histbase= 0)
plot(10, color = dchannelalt(dlen - 1, maintrend), style = plot.style_columns, histbase= 5)
plot(15, color = dchannelalt(dlen - 2, maintrend), style = plot.style_columns, histbase=10)
plot(20, color = dchannelalt(dlen - 3, maintrend), style = plot.style_columns, histbase=15)
plot(25, color = dchannelalt(dlen - 4, maintrend), style = plot.style_columns, histbase=20)
plot(30, color = dchannelalt(dlen - 5, maintrend), style = plot.style_columns, histbase=25)
plot(35, color = dchannelalt(dlen - 6, maintrend), style = plot.style_columns, histbase=30)
plot(40, color = dchannelalt(dlen - 7, maintrend), style = plot.style_columns, histbase=35)
plot(45, color = dchannelalt(dlen - 8, maintrend), style = plot.style_columns, histbase=40)
plot(50, color = dchannelalt(dlen - 9, maintrend), style = plot.style_columns, histbase=45)
|
MAHMOUD ADEL | https://www.tradingview.com/script/4ACoDNep-MAHMOUD-ADEL/ | mhihomody | https://www.tradingview.com/u/mhihomody/ | 55 | 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/
// © CHART ENG
//@version=5
indicator("MAHMOUD ADEL",overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500)
length = input.float(500,'Window Size',maxval=500,minval=0)
h = input.float(8.,'Bandwidth')
mult = input.float(3.)
src = input.source(close,'Source')
up_col = input.color(#39ff14,'Colors',inline='col')
dn_col = input.color(#ff1100,'',inline='col')
disclaimer = input(false, 'Hide Disclaimer')
//----
n = bar_index
var k = 2
var upper = array.new_line(0)
var lower = array.new_line(0)
lset(l,x1,y1,x2,y2,col)=>
line.set_xy1(l,x1,y1)
line.set_xy2(l,x2,y2)
line.set_color(l,col)
line.set_width(l,2)
if barstate.isfirst
for i = 0 to length/k-1
array.push(upper,line.new(na,na,na,na))
array.push(lower,line.new(na,na,na,na))
//----
line up = na
line dn = na
//----
cross_up = 0.
cross_dn = 0.
if barstate.islast
y = array.new_float(0)
sum_e = 0.
for i = 0 to length-1
sum = 0.
sumw = 0.
for j = 0 to length-1
w = math.exp(-(math.pow(i-j,2)/(h*h*2)))
sum += src[j]*w
sumw += w
y2 = sum/sumw
sum_e += math.abs(src[i] - y2)
array.push(y,y2)
mae = sum_e/length*mult
for i = 1 to length-1
y2 = array.get(y,i)
y1 = array.get(y,i-1)
up := array.get(upper,i/k)
dn := array.get(lower,i/k)
lset(up,n-i+1,y1 + mae,n-i,y2 + mae,up_col)
lset(dn,n-i+1,y1 - mae,n-i,y2 - mae,dn_col)
if src[i] > y1 + mae and src[i+1] < y1 + mae
label.new(n-i,src[i],'▼',color=#00000000,style=label.style_label_down,textcolor=dn_col,textalign=text.align_center)
if src[i] < y1 - mae and src[i+1] > y1 - mae
label.new(n-i,src[i],'▲',color=#00000000,style=label.style_label_up,textcolor=up_col,textalign=text.align_center)
cross_up := array.get(y,0) + mae
cross_dn := array.get(y,0) - mae
alertcondition(ta.crossover(src,cross_up),'Down','Down')
alertcondition(ta.crossunder(src,cross_dn),'Up','Up')
//----
var tb = table.new(position.top_right, 1, 1
, bgcolor = #35202b)
if barstate.isfirst and not disclaimer
table.cell(tb, 0, 0, 'ADEL REPAINTS'
, text_size = size.small
, text_color = #cc2f3c)
|
Nadaraya-Watson: Rational Quadratic Kernel (Non-Repainting) | https://www.tradingview.com/script/AWNvbPRM-Nadaraya-Watson-Rational-Quadratic-Kernel-Non-Repainting/ | jdehorty | https://www.tradingview.com/u/jdehorty/ | 1,951 | 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/
// © jdehorty
// @version=5
// A non-repainting implementation of Nadaraya–Watson Regression using a Rational Quadratic Kernel.
indicator('Nadaraya-Watson: Rational Quadratic Kernel (Non-Repainting)', overlay=true, timeframe="")
// Settings
src = input.source(close, 'Source')
h = input.float(8., 'Lookback Window', minval=3., tooltip='The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50')
r = input.float(8., 'Relative Weighting', step=0.25, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25')
x_0 = input.int(25, "Start Regression at Bar", tooltip='Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit. Recommended range: 5-25')
smoothColors = input.bool(false, "Smooth Colors", tooltip="Uses a crossover based mechanism to determine colors. This often results in less color transitions overall.", inline='1', group='Colors')
lag = input.int(2, "Lag", tooltip="Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2", inline='1', group='Colors')
size = array.size(array.from(src)) // size of the data series
// Further Reading:
// The Kernel Cookbook: Advice on Covariance functions. David Duvenaud. Published June 2014.
// Estimation of the bandwidth parameter in Nadaraya-Watson kernel non-parametric regression based on universal threshold level. Ali T, Heyam Abd Al-Majeed Hayawi, Botani I. Published February 26, 2021.
kernel_regression(_src, _size, _h) =>
float _currentWeight = 0.
float _cumulativeWeight = 0.
for i = 0 to _size + x_0
y = _src[i]
w = math.pow(1 + (math.pow(i, 2) / ((math.pow(_h, 2) * 2 * r))), -r)
_currentWeight += y*w
_cumulativeWeight += w
_currentWeight / _cumulativeWeight
// Estimations
yhat1 = kernel_regression(src, size, h)
yhat2 = kernel_regression(src, size, h-lag)
// Rates of Change
bool wasBearish = yhat1[2] > yhat1[1]
bool wasBullish = yhat1[2] < yhat1[1]
bool isBearish = yhat1[1] > yhat1
bool isBullish = yhat1[1] < yhat1
bool isBearishChange = isBearish and wasBullish
bool isBullishChange = isBullish and wasBearish
// Crossovers
bool isBullishCross = ta.crossover(yhat2, yhat1)
bool isBearishCross = ta.crossunder(yhat2, yhat1)
bool isBullishSmooth = yhat2 > yhat1
bool isBearishSmooth = yhat2 < yhat1
// Colors
color c_bullish = input.color(#3AFF17, 'Bullish Color', group='Colors')
color c_bearish = input.color(#FD1707, 'Bearish Color', group='Colors')
color colorByCross = isBullishSmooth ? c_bullish : c_bearish
color colorByRate = isBullish ? c_bullish : c_bearish
color plotColor = smoothColors ? colorByCross : colorByRate
// Plot
plot(yhat1, "Rational Quadratic Kernel Estimate", color=plotColor, linewidth=2)
// Alert Variables
bool alertBullish = smoothColors ? isBearishCross : isBearishChange
bool alertBearish = smoothColors ? isBullishCross : isBullishChange
// Alerts for Color Changes
alertcondition(condition=alertBullish, title='Bearish Color Change', message='Nadaraya-Watson: {{ticker}} ({{interval}}) turned Bearish ▼')
alertcondition(condition=alertBearish, title='Bullish Color Change', message='Nadaraya-Watson: {{ticker}} ({{interval}}) turned Bullish ▲')
// Non-Displayed Plot Outputs (i.e., for use in other indicators)
plot(alertBearish ? -1 : alertBullish ? 1 : 0, "Alert Stream", display=display.none) |
Mehrdad Banakar - Multiple RMA channels | https://www.tradingview.com/script/70L88GgF-Mehrdad-Banakar-Multiple-RMA-channels/ | Mehrdadcoin | https://www.tradingview.com/u/Mehrdadcoin/ | 16 | 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/
// © Mehrdadcoin
//@version=5
indicator("RMA channels",overlay=true)
length1=input(50)
length2=input(100)
length3=input(200)
length4=input(300)
length5=input(400)
length6=input(500)
ma51=ta.rma(high,length1)
y1=plot(ma51,title='highlengh1',color=color.new(color.aqua, 70))
ma511=ta.rma(low,length1)
y2=plot(ma511,title='lowlengh1',color=color.new(color.aqua,70))
fill(y1,y2,color=color.new(color.aqua,70))
ma61=ta.rma(high,length2)
c2=plot(ma61,title='highlengh2',color=color.new(color.white,70))
ma611=ta.rma(low,length2)
c1=plot(ma611,title='lowlengh2',color=color.new(color.white, 70))
fill(c1,c2,color=color.new(color.white,70))
ma71=ta.rma(high,length3)
o1=plot(ma71,title='highlengh3',color=color.new(color.gray,70))
ma711=ta.rma(low,length3)
o2=plot(ma711,title='lowlengh3',color=color.new(color.gray,70))
fill(o1,o2,color=color.new(color.gray,70))
ma81=ta.rma(high,length4)
n2=plot(ma81,title='highlengh4',color=color.new(color.red,70))
ma811=ta.rma(low,length4)
n1=plot(ma811,title='lowlengh4',color=color.new(color.red,70))
fill(n1,n2,color=color.new(color.red,70))
ma91=ta.rma(high,length5)
p1=plot(ma91,title='highlengh5',color=color.new(color.purple,70))
ma911=ta.rma(low,length5)
p2=plot(ma911,title='lowlengh5',color=color.new(color.purple,70))
fill(p1,p2,color=color.new(color.purple,70))
ma101=ta.rma(low,length6)
t1=plot(ma101,title='highlengh6',color=color.new(color.yellow,70))
ma1011=ta.rma(high,length6)
t2=plot(ma1011,title='lowlengh6',color=color.new(color.yellow,70))
fill(t1,t2,color=color.new(color.yellow,70))
|
Adaptive Two-Pole Super Smoother Entropy MACD [Loxx] | https://www.tradingview.com/script/Mwkju5tX-Adaptive-Two-Pole-Super-Smoother-Entropy-MACD-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 153 | 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/
// © loxx
//@version=5
indicator("Adaptive Two-Pole Super Smoother Entropy (Math) MACD",
shorttitle='ATPSSEMACD [Loxx]',
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
trig
twopoless(float src, len)=>
float a1 = 0.
float b1 = 0.
float coef1 = 0.
float coef2 = 0.
float coef3 = 0.
float filt = 0
float trig = 0.
a1 := math.exp(-1.414 * math.pi / len)
b1 := 2 * a1 * math.cos(1.414 * math.pi / len)
coef2 := b1
coef3 := -a1 * a1
coef1 := 1 - coef2 - coef3
filt := coef1 * src + coef2 * nz(filt[1]) + coef3 * nz(filt[2])
filt := bar_index < 3 ? src : filt
filt
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
numbars = input.int(21, "Period", group = "Basic Settings")
AdaptPeriod = input.int(15, "Adapting Period", group = "Basic Settings")
signal_length = input.int(9, "Signal Period", group = "Signal/DSL Settings")
sigmatype = input.string("Exponential Moving Average - EMA", "Signal/DSL Smoothing", options = ["Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA"], group = "Signal/DSL Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
P = 0.
G = 0.
dev = ta.stdev(src, AdaptPeriod)
avg = ta.sma(dev, AdaptPeriod)
coeff = 1.
if dev != 0
coeff := avg / dev
sumx = 0.0
sumx2 = 0.0
avgx = 0.0
rmsx = 1.0
for j = 0 to numbars + 1
r = math.log(nz(src[j]) / nz(src[j + 1]))
sumx += r
sumx2 += r * r
if numbars == 0
avgx := src
rmsx := 0.0
else
avgx := sumx / numbars
rmsx := math.sqrt(sumx2 / numbars)
if rmsx != 0
P := ((avgx / rmsx) + 1) / 2.0
else
P := 0
G := P * math.log(1 + rmsx) + (1 - P) * math.log(1 - rmsx)
out = twopoless(G, coeff * numbars)
sig = out[1]
levelu = 0., leveld = 0., mid = 0.
levelu := (out > sig) ? variant(sigmatype, out, signal_length) : nz(levelu[1])
leveld := (out < sig) ? variant(sigmatype, out, signal_length) : nz(leveld[1])
colorout = out > levelu ? greencolor : out < leveld ? redcolor : color.gray
plot(levelu, "Upper DSL", color = color.gray)
plot(leveld, "Lower DSL", color = color.gray)
plot(out, "ATPSSEMACD", color = colorout, linewidth = 2)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(out, levelu)
goShort = ta.crossover(out, leveld)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Adaptive Two-Pole Super Smoother Entropy (Math) MACD: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Adaptive Two-Pole Super Smoother Entropy (Math) MACD: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Variety, Low-Pass, FIR Filter Impulse Response Explorer [Loxx] | https://www.tradingview.com/script/Y0lJ9zYJ-Variety-Low-Pass-FIR-Filter-Impulse-Response-Explorer-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 53 | 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/
// © loxx
//@version=5
indicator("Variety, Low-Pass, FIR Filter Impulse Response Explorer [Loxx]",
shorttitle = "VLFDFIFE [Loxx]",
overlay = false,
max_lines_count = 500,
precision = 8)
greencolor = #2DD204
redcolor = #D2042D
powercos = "N-Order Power of Cosine"
sincfir_hamm = "Hamming"
sincfir_hanning = "Hanning"
sincfir_black = "Blackman"
sincfir_blackh = "Blackman Harris"
sincfir_blacknutt = "Blackman Nutall"
sincfir_nutt = "Nutall"
sincfir_bartzep = "Bartlet Zero End Points"
sincfir_barthann = "Bartlet-Hann"
sincfir_hann = "Hann"
sincfir_sine = "Sine"
sincfir_lan = "Lanczos"
sincfir_flat = "Flat Top"
fir_rect = "Rectangular"
fir_lwma = "Linear"
fir_tma = "Triangular"
fact(int n)=>
float out = 1
for i = 1 to n
out *= i
out
nOrderPowerOfCosineDesign(int per, int order, float frequencyCutoff, int multiplier, bool sinc)=>
float ppastri = 0
var float[] pastri = array.new<float>(order + 1, 0.)
int pdepth = order - 1
for k = 0 to order / 2 - 1
ppastri := nz(fact(pdepth) / (fact(pdepth - k) * fact(k)), 1)
for k = 0 to order
array.set(pastri, k, nz(fact(order) / (fact(order - k) * fact(k)), 1))
array<float> outpastri = array.slice(pastri, 0, order / 2)
array.reverse(outpastri)
float[] coeffs = array.new<float>(per, 0)
int N = per - 1
float sum = 0
for n = 0 to per - 1
float div = n - N / 2.0
if div == 0
array.set(coeffs, n, 2.0 * math.pi * frequencyCutoff)
else
array.set(coeffs, n, math.sin(2.0 * math.pi * frequencyCutoff * div) / div)
int sign = -1
float coeff = ppastri
for k = 0 to array.size(outpastri) - 1
coeff += sign * array.get(outpastri, k) * math.cos((k + 1) * 2 * math.pi * n / N)
sign *= -1
coeff := coeff / (array.sum(outpastri) + ppastri)
if sinc
array.set(coeffs, n, array.get(coeffs, n) * coeff)
sum += array.get(coeffs, n)
else
array.set(coeffs, n, coeff)
if sinc
for k = 0 to per - 1
array.set(coeffs, k, array.get(coeffs, k) / sum)
array.set(coeffs, k, array.get(coeffs, k) * multiplier)
coeffs
fircoeff(string type, int per, float frequencyCutoff, int multiplier, bool sinc)=>
array<float> coeffs = array.new<float>(per, 0)
float sum = 0
int N = per - 1
for n = 0 to per - 1
float div = n - N / 2.0
if div == 0
array.set(coeffs, n, 2.0 * math.pi * frequencyCutoff)
else
array.set(coeffs, n, math.sin(2.0 * math.pi * frequencyCutoff * div) / div)
float temp = 0.
switch type
sincfir_hamm =>
temp := 0.54 - 0.46 * math.cos(2 * math.pi * n / N)
sincfir_hanning =>
temp := 0.50 - 0.50 * math.cos(2 * math.pi * n / N)
sincfir_black =>
temp := 0.42
- 0.50 * math.cos(2 * math.pi * n / N)
+ 0.08 * math.cos(4 * math.pi * n / N)
sincfir_blackh =>
temp := 0.35875
- 0.48829 * math.cos(2 * math.pi * n / N)
+ 0.14128 * math.cos(4 * math.pi * n / N)
+ 0.01168 * math.cos(6 * math.pi * n / N)
sincfir_blacknutt =>
temp := 0.3635819
- 0.4891775 * math.cos(2 * math.pi * n / N)
+ 0.1365995 * math.cos(4 * math.pi * n / N)
+ 0.0106411 * math.cos(6 * math.pi * n / N)
sincfir_nutt =>
temp := 0.355768
- 0.487396 * math.cos(2 * math.pi * n / N)
+ 0.144232 * math.cos(4 * math.pi * n / N)
+ 0.012604 * math.cos(6 * math.pi * n / N)
sincfir_bartzep =>
temp := 2.0 / N * (N / 2.0 - math.abs(n - N / 2))
sincfir_barthann =>
temp := 0.62 - 0.48 * math.abs(n / N - 0.5) * 0.38 * math.cos(2.0 * math.pi * n / N)
sincfir_hann =>
temp := 0.50 * (1.0 - math.cos(2.0 * math.pi * n / N))
sincfir_sine =>
temp := math.sin(math.pi * n / N)
sincfir_lan =>
float ttx = (n / N) - 1.0
if ttx == 0
temp := 0
else
temp := math.sin(ttx) / (ttx)
sincfir_flat =>
temp := 1
- 1.93 * math.cos(2 * math.pi * n / N)
+ 1.29 * math.cos(4 * math.pi * n / N)
+ 0.388 * math.cos(6 * math.pi * n / N)
+ 0.388 * math.cos(8 * math.pi * n / N)
if sinc
array.set(coeffs, n, array.get(coeffs, n) * temp)
sum += array.get(coeffs, n)
else
array.set(coeffs, n, temp)
if sinc
for k = 0 to per - 1
array.set(coeffs, k, array.get(coeffs, k) / sum)
array.set(coeffs, k, array.get(coeffs, k) * multiplier)
coeffs
simplefircoeff(int per, string type)=>
float[] coeffs = array.new<float>(per, 0)
float coeff = 1
for i = 0 to per - 1
switch type
fir_rect =>
coeff := 1.0
fir_lwma =>
coeff := per - i
fir_tma =>
coeff := i + 1.0
if (coeff > ((per + 1.0) / 2.0))
coeff := per - i
array.set(coeffs,i, coeff)
coeffs
//Normalize data
_InSigNormalize(float[] aa)=>
float sum_sqrt = 0.
int element_count = array.size(aa)
for i = 0 to element_count - 1
sum_sqrt += math.pow(array.get(aa, i), 2)
sum_sqrt := math.sqrt(sum_sqrt)
if (sum_sqrt != 0)
for i = 0 to element_count - 1
array.set(aa, i, array.get(aa, i) / sum_sqrt)
aa
wper = input.int(300, "Number of Coefficients to Calculatt", maxval = 500, group = "Basic Settings")
type = input.string(sincfir_black, "FIR Digital Filter Type",
options = [powercos, fir_rect, fir_lwma, fir_tma, sincfir_hamm,
sincfir_hanning, sincfir_black, sincfir_blackh, sincfir_blacknutt,
sincfir_nutt, sincfir_bartzep, sincfir_barthann,
sincfir_hann, sincfir_sine ,sincfir_lan, sincfir_flat],
group = "Basic Settings")
mult = input.int(1, "Multiplier", group = "Sinc Settings")
fcut = input.float(0.01, "Frequency Cutoff", maxval = 0.5, minval = 0, step = 0.01, group = "Sinc Settings")
addsinc = input.bool(false, "Turn on Sinc?", group = "Sinc Settings", tooltip = "Applies to all except for Rectangular, Linear Weighted, and Triangular")
order = input.int(10, "Order", group = "Power-of-Cosine Settings")
var pvlines = array.new_line(0)
if barstate.isfirst
for i = 0 to wper - 1
array.push(pvlines, line.new(na, na, na, na))
if barstate.islast
sincarry = array.new_string(15, "")
array.push(sincarry, sincfir_hamm)
array.push(sincarry, sincfir_hanning)
array.push(sincarry, sincfir_black)
array.push(sincarry, sincfir_blacknutt)
array.push(sincarry, sincfir_bartzep)
array.push(sincarry, sincfir_blackh)
array.push(sincarry, sincfir_nutt)
array.push(sincarry, sincfir_barthann)
array.push(sincarry, sincfir_flat)
array.push(sincarry, sincfir_lan)
array.push(sincarry, sincfir_sine)
array.push(sincarry, sincfir_hann)
LastBar = int(wper / 2)
regarray = array.new_string(10, "")
array.push(regarray, fir_rect)
array.push(regarray, fir_tma)
array.push(regarray, fir_lwma)
var testTable = table.new(position = position.top_center, columns = 1, rows = 1, bgcolor = color.yellow, border_width = 1)
table.cell(table_id = testTable, column = 0, row = 0, text = type)
var coeffs =
array.includes(sincarry, type) ? array.copy(fircoeff(type, wper, fcut, mult, addsinc)) :
array.includes(regarray, type) ? array.copy(simplefircoeff(wper, type)) : nOrderPowerOfCosineDesign(wper, order, fcut, mult, addsinc)
var ttd = array.size(coeffs)
_InSigNormalize(coeffs)
for i = 0 to array.size(pvlines) - 1
if i > wper - 2
break
pvline = array.get(pvlines, i)
line.set_xy1(pvline, bar_index + i - LastBar, array.get(coeffs, i + 1))
line.set_xy2(pvline, bar_index + i - 1 - LastBar, array.get(coeffs, i))
line.set_color(pvline, greencolor)
line.set_style(pvline, line.style_solid)
line.set_width(pvline, 1)
hline(0)
|
Lyapunov Hodrick-Prescott Oscillator w/ DSL [Loxx] | https://www.tradingview.com/script/YPRDlHYT-Lyapunov-Hodrick-Prescott-Oscillator-w-DSL-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
indicator("Lyapunov Hodrick-Prescott Oscillator w/ DSL [Loxx]",
shorttitle='LHPODSL [Loxx]',
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
trig
_HPFilter(src, lamb, per)=>
H1 = 0., H2 = 0., H3 = 0., H4 = 0., H5 = 0.,
HH1 = 0., HH2 = 0., HH3 = 0., HH5 = 0.
HB= 0., HC= 0., Z= 0.
a = array.new<float>(per, 0.)
b = array.new<float>(per, 0.)
c = array.new<float>(per, 0.)
out = array.new<float>(per, 0.)
for i = 0 to per - 1
array.set(out, i, nz(src[i]))
array.set(a, 0, 1.0 + lamb)
array.set(b, 0, -2.0 * lamb)
array.set(c, 0, lamb)
for i = 1 to per - 3
array.set(a, i, 6.0 * lamb + 1.0)
array.set(b, i, -4.0 * lamb)
array.set(c, i, lamb)
array.set(a, 1, 5.0 * lamb + 1)
array.set(a, per - 1, 1.0 + lamb)
array.set(a, per - 2, 5.0 * lamb + 1.0)
array.set(b, per - 2, -2.0 * lamb)
array.set(b, per - 1, 0.)
array.set(c, per - 2, 0.)
array.set(c, per - 1, 0.)
for i = 0 to per - 1
Z := array.get(a, i) - H4 * H1 - HH5 * HH2
if (Z == 0)
break
HB := array.get(b, i)
HH1 := H1
H1 := (HB - H4 * H2) / Z
array.set(b, i, H1)
HC := array.get(c, i)
HH2 := H2
H2 := HC / Z
array.set(c, i, H2)
array.set(a, i, (array.get(out, i) - HH3 * HH5 - H3 * H4) / Z)
HH3 := H3
H3 := array.get(a, i)
H4 := HB - H5 * HH1
HH5 := H5
H5 := HC
H2 := 0
H1 := array.get(a, per - 1)
array.set(out, per - 1, H1)
for i = per - 2 to 0
array.set(out, i, array.get(a, i) - array.get(b, i) * H1 - array.get(c, i) * H2)
H2 := H1
H1 := array.get(out, i)
lhp = array.new<float>(per, 0.)
for i = 0 to per - 2
array.set(lhp, i, math.log(math.abs(array.get(out, i) / array.get(out, i + 1))))
lhp
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
fastper = input.int(50, 'Period', minval=4, group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
dzper = input.int(35, "Dynamic Zone Period", group = "Levels Settings")
dzbuyprob = input.float(0.9 , "Dynamic Zone Buy Probability", group = "Levels Settings", maxval = 1)
dzsellprob = input.float(0.9 , "Dynamic Zone Sell Probability", group = "Levels Settings", maxval = 1)
signal_length = input.int(9, "Signal Period", group = "Signal/DSL Settings")
sigmatype = input.string("Exponential Moving Average - EMA", "Signal/DSL Smoothing", options = ["Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA"], group = "Signal/DSL Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
lambfast = 0.0625 / math.pow(math.sin(math.pi / fastper), 4)
lhpfast = _HPFilter(src, lambfast, fastper)
out = array.get(lhpfast, 0)
sig = out[1]
levelu = 0., leveld = 0., mid = 0.
levelu := (out > sig) ? variant(sigmatype, out, signal_length) : nz(levelu[1])
leveld := (out < sig) ? variant(sigmatype, out, signal_length) : nz(leveld[1])
colorout = out > levelu ? greencolor : out < leveld ? redcolor : color.gray
plot(levelu, "Upper DSL", color = color.gray)
plot(leveld, "Lower DSL", color = color.gray)
plot(out, "LHPODSL", color = colorout, linewidth = 2)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(out, levelu)
goShort = ta.crossunder(out, leveld)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Lyapunov Hodrick-Prescott Oscillator w/ DSL [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Lyapunov Hodrick-Prescott Oscillator w/ DSL [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Lowry Up/Down % Volume | https://www.tradingview.com/script/RbTtXMVP-Lowry-Up-Down-Volume/ | ReactReflect | https://www.tradingview.com/u/ReactReflect/ | 56 | 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/
// referenced script: Up Volume vs Down Volume by ChartingCycles
// For usage of Up/Down Vol to identify market bottom, see
// https://recessionalert.com/wp-content/uploads/2021/08/identifying-bear-market-bottoms-and-new-bull-markets.pdf
// by Lowry’s Reports Inc
//@version=5
indicator(title = "Lowry Up/Down % Volume", shorttitle="Up/Down % Vol", precision=2)
sym(s) => request.security(s, "D", close)
// Calculation
// Get total volume or the sum of Upside Volume and Downside Volume
// Divide Upside Volume by total volume to get Upside % Volume
up_percentage = (sym("USI:UPVOL.NY")) / (sym("USI:TVOL.NY"))
down_percentage = (sym("USI:DNVOL.NY")) / (sym("USI:TVOL.NY"))
is_u80 = up_percentage >= .80 and up_percentage < .90
is_d80 = down_percentage >= .80 and down_percentage < .90
is_u90 = up_percentage >= .90
is_d90 = down_percentage >= .90
up_bar_color = is_u90 ? #7CFC00 : is_u80 ? #7FFFD4 : up_percentage <= .10 ? color.olive : color.olive
down_bar_color = is_d90 ? #FF0000 : is_d80 ? color.fuchsia : down_percentage <= .10 ? color.maroon : color.maroon
plot(up_percentage, "Up Volume Percentage", up_bar_color, style=plot.style_columns)
plot(-down_percentage, "Down Volume Percentage", down_bar_color, style=plot.style_columns)
plotshape((is_u80), title="is 80 Up-day?", style=shape.diamond, size=size.tiny,text="8",textcolor=up_bar_color,color=up_bar_color, location=location.bottom)
plotshape((is_d80), title="is 80 Down-day?", style=shape.diamond, size=size.tiny,text="8",textcolor=down_bar_color,color=down_bar_color, location=location.top)
plotshape((is_u90), title="is 90 Up-day?", style=shape.triangleup, size=size.tiny,text="9",textcolor=up_bar_color,color=up_bar_color, location=location.bottom)
plotshape((is_d90), title="is 90 Down-day?", style=shape.triangledown, size=size.tiny,text="9",textcolor=down_bar_color,color=down_bar_color, location=location.top)
var string GP2 = 'Display'
show_header = timeframe.isdaily ? input.bool(true, title='Show Table Header', inline='10', group=GP2) : false
// show_header = true
string i_tableYpos = input.string('bottom', '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)
first_time = 0
first_time := bar_index == 0 ? time : first_time[1]
if barstate.islast
// We only populate the table on the last bar.
if show_header == true
table.cell(dtrDisplay, 1, 0, 'Up Volume', bgcolor=color.black, text_size=textsize, text_color=color.white)
table.cell(dtrDisplay, 1, 1, str.tostring(math.round(up_percentage,3)*100) + '%', bgcolor=color.black, text_size=textsize, text_color=color.white)
table.cell(dtrDisplay, 2, 0, 'Down Volume', bgcolor=color.black, text_size=textsize, text_color=color.white)
table.cell(dtrDisplay, 2, 1, str.tostring(math.round(down_percentage,3)*100) + '%', bgcolor=color.black, text_size=textsize, text_color=color.white) |
STD-Adaptive T3 [Loxx] | https://www.tradingview.com/script/f8TtFz5c-STD-Adaptive-T3-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 124 | 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/
// © loxx
//@version=5
indicator("STD-Adaptive T3 [Loxx]",
shorttitle = "STDT3 [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
t3filter(float src, float per, float hot, string clean)=>
float a = hot
float _c1 = -a * a * a
float _c2 = 3 * a * a + 3 * a * a * a
float _c3 = -6 * a * a - 3 * a - 3 * a * a * a
float _c4 = 1 + 3 * a + a * a * a + 3 * a * a
float alpha = 0.
if (clean == "T3 New")
alpha := 2.0 / (2.0 + (per - 1.0) / 2.0)
else
alpha := 2.0 / (1.0 + per)
float _t30 = src, _t31 = src
float _t32 = src, _t33 = src
float _t34 = src, _t35 = src
_t30 := nz(_t30[1]) + alpha * (src - nz(_t30[1]))
_t31 := nz(_t31[1]) + alpha * (_t30 - nz(_t31[1]))
_t32 := nz(_t32[1]) + alpha * (_t31 - nz(_t32[1]))
_t33 := nz(_t33[1]) + alpha * (_t32 - nz(_t33[1]))
_t34 := nz(_t34[1]) + alpha * (_t33 - nz(_t34[1]))
_t35 := nz(_t35[1]) + alpha * (_t34 - nz(_t35[1]))
float out =
_c1 * _t35 + _c2 * _t34 +
_c3 * _t33 + _c4 * _t32
out
_stdPer(float src, int per, int adaptper)=>
float dev = ta.stdev(src, adaptper)
float avg = ta.sma(dev, adaptper)
float period = (dev!=0) ? math.max(per * avg/dev, 2) : math.max(per, 1)
period := int(period)
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
t3hot = input.float(.7, "T3 Hot", group= "T3 Settings")
t3swt = input.string("T3 New", "T3 Type", options = ["T3 New", "T3 Original"], group = "T3 Settings")
SmtPeriod = input.int(15, "Smoother Period", group = "Adaptive Settings")
AdaptivePeriod = input.int(25, "Adaptive Period", group = "Adaptive Settings")
ColorSteps = input.int(50, "Color Period", group = "Adaptive Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
len = _stdPer(src, SmtPeriod, AdaptivePeriod)
t3 = t3filter(src, len, t3hot, t3swt)
min = ta.lowest(t3, ColorSteps)
max = ta.highest(t3, ColorSteps)
mid = (max + min) / 2
colorBuffer = color.from_gradient(t3, min, mid, redcolor, greencolor)
plot(t3, color = colorBuffer, linewidth = 5)
barcolor(colorbars ? colorBuffer : na) |
Stochastic of Two-Pole SuperSmoother [Loxx] | https://www.tradingview.com/script/SisGUrF0-Stochastic-of-Two-Pole-SuperSmoother-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 241 | 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/
// © loxx
//@version=5
indicator("Stochastic of Two-Pole SuperSmoother [Loxx]",
shorttitle = "STPSS [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
trig
twopoless(float src, len)=>
float a1 = 0.
float b1 = 0.
float coef1 = 0.
float coef2 = 0.
float coef3 = 0.
float filt = 0
float trig = 0.
a1 := math.exp(-1.414 * math.pi / len)
b1 := 2 * a1 * math.cos(1.414 * math.pi / len)
coef2 := b1
coef3 := -a1 * a1
coef1 := 1 - coef2 - coef3
filt := coef1 * src + coef2 * nz(filt[1]) + coef3 * nz(filt[2])
filt := bar_index < 3 ? src : filt
filt
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(32, "Period")
sper = input.int(25, "2-Pole SuperSmoother Period")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
signal_length = input.int(9, "Signal Period", group = "Signal/DSL Settings")
sigmatype = input.string("Exponential Moving Average - EMA", "Signal/DSL Smoothing", options = ["Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA"], group = "Signal/DSL Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
ssm = twopoless(src, sper)
fmin = ta.lowest(ssm, per)
fmax = ta.highest(ssm, per)
out = 0.
if (fmax - fmin) == 0
out := 50
else
out := 100 * (ssm - fmin) / (fmax - fmin)
sig = out[1]
levelu = 0., leveld = 0., mid = 0.
levelu := (out > sig) ? variant(sigmatype, out, signal_length) : nz(levelu[1])
leveld := (out < sig) ? variant(sigmatype, out, signal_length) : nz(leveld[1])
colorBuffer = color.from_gradient(out, 0, 100, redcolor, greencolor)
plot(out, "STPSS", color = colorBuffer, linewidth = 2)
plot(levelu, "Upper DSL", color = color.gray)
plot(leveld, "Lower DSL", color = color.gray)
barcolor(colorbars ? colorBuffer : na)
goLong = ta.crossover(out, levelu)
goShort = ta.crossunder(out, leveld)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Stochastic of Two-Pole SuperSmoother [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Stochastic of Two-Pole SuperSmoother [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}") |
ATR Trend Following | https://www.tradingview.com/script/rXkPTIwC-ATR-Trend-Following/ | Sharmasagar1 | https://www.tradingview.com/u/Sharmasagar1/ | 22 | 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/
// © Sharmasagar1
//@version=4
study("ATR Trend Following", overlay = true)
fun = sma(close, 350)[1]
fun2 = atr(14)[1]
p1 = fun + 7*fun2
p3 = fun + 5*fun2
//plot(fun, color = color.white)
plot(p1, color = color.green )
plot(p3, color = color.orange)
con1 = close[1] < p1[1] and close > p1
con2 = close[1] > p3[1] and close < p3
plotshape(con1, location = location.belowbar, text = "B")
plotshape(con2, location = location.abovebar, text = "S") |
Variance (Welford) [Loxx] | https://www.tradingview.com/script/nGelcFY5-Variance-Welford-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 36 | 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/
// © loxx
//@version=5
indicator("Variance (Welford) [Loxx]",
shorttitle = "VW [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
inpVarPeriod = input.int(14, "Period", group = "Basic Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
_m = 0., _s = 0., _oldm = 0.
for k = 0 to inpVarPeriod - 1
_oldm := _m
_m := _m + (nz(src[k]) - _m) / (1.0 + k)
_s := _s + (nz(src[k]) - _m) * (nz(src[k]) - _oldm)
out = (_s / (inpVarPeriod - 1))
plot(out, "VW", color = greencolor, linewidth =2)
|
FDI-Adaptive Non-Lag Moving Average [Loxx] | https://www.tradingview.com/script/JuU7De7l-FDI-Adaptive-Non-Lag-Moving-Average-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 191 | 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/
// © loxx
//@version=5
indicator("FDI-Adaptive Non-Lag Moving Average [Loxx]",
shorttitle = "FDIANLMA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
fdip(float src, int per, int speedin)=>
float fmax = ta.highest(src, per)
float fmin = ta.lowest(src, per)
float length = 0
float diff = 0
for i = 1 to per - 1
diff := (nz(src[i]) - fmin) / (fmax - fmin)
if i > 0
length += math.sqrt( math.pow(nz(diff[i]) - nz(diff[i + 1]), 2) + (1 / math.pow(per, 2)))
float fdi = 1 + (math.log(length) + math.log(2)) / math.log(2 * per)
float traildim = 1 / (2 - fdi)
float alpha = traildim / 2
int speed = math.round(speedin * alpha)
speed
nonlagma(float src, float len)=>
float cycle = 4.0
float coeff = 3.0 * math.pi
float phase = len - 1.0
int _len = int(len * cycle + phase)
float weight = 0., float alfa = 0., float out = 0.
float[] alphas = array.new_float(_len, 0.)
for k = 0 to _len - 1
float t = 0.
t := k <= phase - 1 ? 1.0 * k / (phase - 1) : 1.0 + (k - phase + 1) * (2.0 * cycle - 1.0) / (cycle * len -1.0)
float beta = math.cos(math.pi * t)
float g = 1.0/(coeff * t + 1)
g := t <= 0.5 ? 1 : g
array.set(alphas, k, g * beta)
weight += array.get(alphas, k)
if (weight > 0)
float sum = 0.
for k = 0 to _len - 1
sum += array.get(alphas, k) * nz(src[k])
out := (sum / weight)
out
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(30, "Fractal Period Ingest", group = "Adaptive Settings")
speed = input.int(20, "Speed", group = "Adaptive Settings")
ColorSteps = input.int(50, "Color Period", group = "Adaptive Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
len = fdip(src, per, speed)
nonlag = nonlagma(src, len)
min = ta.lowest(nonlag, ColorSteps)
max = ta.highest(nonlag, ColorSteps)
mid = (max + min) / 2
colorBuffer = color.from_gradient(nonlag, min, mid, redcolor, greencolor)
plot(nonlag, "Adaptive Non-Lag MA", color = colorBuffer, linewidth = 3)
barcolor(colorbars ? colorBuffer : na)
|
Price Levels | https://www.tradingview.com/script/00DYmBDJ-Price-Levels/ | tomorme88 | https://www.tradingview.com/u/tomorme88/ | 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/
// © tomorme88
//@version=5
indicator('Price Levels', overlay=true)
g = bar_index == 1
ath() =>
a = 0.0
a := g ? high : high > a[1] ? high : a[1]
a
a = request.security(syminfo.tickerid, 'M', ath(), lookahead=barmerge.lookahead_on)
plot(a, title='ATH', linewidth=2, trackprice=true, color=color.new(color.maroon, 0), offset=-9999)
atl() =>
r = 0.0
r := g ? low : low < r[1] ? low : r[1]
r
r = request.security(syminfo.tickerid, 'M', atl(), lookahead=barmerge.lookahead_on)
plot(r, title='ATL', linewidth=2, trackprice=true, color=color.new(color.maroon, 0), offset=-9999)
plot((a-r)*0.5,title='50%',linewidth=2, trackprice=true, color=color.maroon, offset=-9999)
plot((a-r)*0.166,title='16.6%%',linewidth=2, trackprice=true, color=color.maroon, offset=-9999)
plot((a-r)*0.382,title='38.2%%',linewidth=2, trackprice=true, color=color.maroon, offset=-9999)
plot((a-r)*0.618,title='61.8%',linewidth=2, trackprice=true, color=color.maroon, offset=-9999)
plot((a-r)*0.786,title='78.6%',linewidth=2, trackprice=true, color=color.maroon, offset=-9999)
|
Yearly Candles | https://www.tradingview.com/script/ymNgireq-Yearly-Candles/ | iravan | https://www.tradingview.com/u/iravan/ | 43 | 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/
// © iravan
//@version=5
indicator("Yearly Candles", overlay=false, max_boxes_count=500, max_lines_count=500)
var matched = timeframe.ismonthly and timeframe.multiplier == 1
if not matched and barstate.islast
label.new(bar_index, close, "Please change timeframe to 1M", color=color.yellow, style=label.style_label_center)
var float o = na
var float h = na
var float l = na
var float c = na
var float po = na
var float ph = na
var float pl = na
var float pc = na
var pos = color.teal
var neg = color.red
var start_index = 0
var prev_year = 0
if prev_year != year(time_close) and matched
prev_year := year(time_close)
c := close[1]
if not barstate.isfirst
mid_index = math.floor((start_index + bar_index) / 2)
box.new(start_index + 1, o, bar_index - 1, c, bgcolor=c>=o?pos:neg, border_width=0)
line.new(start_index + 1, o, bar_index - 1, o, color=c>=o?pos:neg)
line.new(mid_index, l, mid_index, h, color=c>=o?pos:neg)
po := o
ph := h
pl := l
pc := c
o := open
h := high
l := low
start_index := bar_index > 0 ? bar_index: 0
l := low < l ? low : l
h := high > h ? high : h
if barstate.islast and matched
status = "O:" + str.tostring(o) +", H:" + str.tostring(h) + ", L:" + str.tostring(l) +", C:" + str.tostring(close) + ", " + str.tostring(close - c) +", (" + str.tostring(math.round((close - c)/c*100, 2)) + "%)"
c := close
box.new(start_index + 1, o, bar_index + (12 - month(time)), c, bgcolor=c>=o?pos:neg, border_color=color.rgb(0,0,0,100))
line.new(bar_index - month(time) + 6 + 1, l, bar_index - month(time) + 6 + 1, h, color=c>=o?pos:neg)
label.new(bar_index - month(time) + 6 + 8, close, status, color=color.rgb(255,255,0,90), textcolor=c>=o?pos:neg, style=label.style_label_left)
plot(year(time_close) == year(timenow)?year(time_close[12]):year(time_close), title="Year", display=display.status_line+display.data_window, editable=false)
plot(po, offset=-12, title="Open", color=pc>=po?pos:neg, display=display.status_line+display.data_window, editable=false)
plot(ph, offset=-12, title="High", color=pc>=po?pos:neg, display=display.status_line+display.data_window, editable=false)
plot(pl, offset=-12, title="Low", color=pc>=po?pos:neg, display=display.status_line+display.data_window, editable=false)
plot(pc, offset=-12, title="Close", color=pc>=po?pos:neg, display=display.status_line+display.data_window, editable=false)
plot(pc - pc[12], offset=-12, title="Change", color=pc>=po?pos:neg, display=display.status_line+display.data_window, editable=false)
plot(math.round((pc - pc[12]) / pc[12] * 100, 2), offset=-12, title="Change %", color=pc>=po?pos:neg, display=display.status_line+display.data_window, editable=false)
|
Aarika RSI | https://www.tradingview.com/script/Y7Ea5krc-Aarika-RSI/ | hlsolanki | https://www.tradingview.com/u/hlsolanki/ | 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/
// © ParkF
//@version=5
indicator('Aarika RSI', overlay=false, max_bars_back=1500)
// rsi divergence
// input
rsig = 'RSI'
rb = input(5, 'How many Right Bars for Pivots', group=rsig)
lb = input(15, 'How many Left Bars for Pivots', group=rsig)
sph = input(close, 'Pivot source for Bear Divs', group=rsig)
spl = input(close, 'Pivots Source for Bull Divs', group=rsig)
len = input.int(9, ' RSI Length', minval=1, group=rsig)
lvl = input.int(5, 'Lookback Level for Divs', options=[1, 2, 3, 4, 5], group=rsig)
// pivot
ph = ta.pivothigh(sph, lb, rb)
pl = ta.pivotlow(spl, lb, rb)
hi0 = ta.valuewhen(ph, sph[rb], 0)
hi1 = ta.valuewhen(ph, sph[rb], 1)
hi2 = ta.valuewhen(ph, sph[rb], 2)
hi3 = ta.valuewhen(ph, sph[rb], 3)
hi4 = ta.valuewhen(ph, sph[rb], 4)
hi5 = ta.valuewhen(ph, sph[rb], 5)
lo0 = ta.valuewhen(pl, spl[rb], 0)
lo1 = ta.valuewhen(pl, spl[rb], 1)
lo2 = ta.valuewhen(pl, spl[rb], 2)
lo3 = ta.valuewhen(pl, spl[rb], 3)
lo4 = ta.valuewhen(pl, spl[rb], 4)
lo5 = ta.valuewhen(pl, spl[rb], 5)
lox0 = ta.valuewhen(pl, bar_index[rb], 0)
lox1 = ta.valuewhen(pl, bar_index[rb], 1)
lox2 = ta.valuewhen(pl, bar_index[rb], 2)
lox3 = ta.valuewhen(pl, bar_index[rb], 3)
lox4 = ta.valuewhen(pl, bar_index[rb], 4)
lox5 = ta.valuewhen(pl, bar_index[rb], 5)
hix0 = ta.valuewhen(ph, bar_index[rb], 0)
hix1 = ta.valuewhen(ph, bar_index[rb], 1)
hix2 = ta.valuewhen(ph, bar_index[rb], 2)
hix3 = ta.valuewhen(ph, bar_index[rb], 3)
hix4 = ta.valuewhen(ph, bar_index[rb], 4)
hix5 = ta.valuewhen(ph, bar_index[rb], 5)
rsi = ta.rsi(close, len)
rh0 = ta.valuewhen(ph, rsi[rb], 0)
rh1 = ta.valuewhen(ph, rsi[rb], 1)
rh2 = ta.valuewhen(ph, rsi[rb], 2)
rh3 = ta.valuewhen(ph, rsi[rb], 3)
rh4 = ta.valuewhen(ph, rsi[rb], 4)
rh5 = ta.valuewhen(ph, rsi[rb], 5)
rl0 = ta.valuewhen(pl, rsi[rb], 0)
rl1 = ta.valuewhen(pl, rsi[rb], 1)
rl2 = ta.valuewhen(pl, rsi[rb], 2)
rl3 = ta.valuewhen(pl, rsi[rb], 3)
rl4 = ta.valuewhen(pl, rsi[rb], 4)
rl5 = ta.valuewhen(pl, rsi[rb], 5)
// rsi candle (with wick)
// rsi configuration
rsrc = close
ad = true
// rsi function
pine_rsi(rsrc, len) =>
u = math.max(rsrc - rsrc[1], 0)
d = math.max(rsrc[1] - rsrc, 0)
rs = ta.rma(u, len) / ta.rma(d, len)
res = 100 - 100 / (1 + rs)
res
pine_rma(rsrc, length) =>
b = 1 / length
sum = 0.0
sum := na(sum[1]) ? ta.sma(rsrc, length) : b * rsrc + (1 - b) * nz(sum[1])
u = math.max(rsrc - rsrc[1], 0)
d = math.max(rsrc[1] - rsrc, 0)
b = 1 / len
ruh = b * math.max(high - close[1], 0) + (1 - b) * ta.rma(u, len)[1]
rdh = (1 - b) * ta.rma(d, len)[1]
rul = (1 - b) * ta.rma(u, len)[1]
rdl = b * math.max(close[1] - low, 0) + (1 - b) * ta.rma(d, len)[1]
function(rsi, len) =>
f = -math.pow(math.abs(math.abs(rsi - 50) - 50), 1 + math.pow(len / 14, 0.618) - 1) / math.pow(50, math.pow(len / 14, 0.618) - 1) + 50
rsiadvanced = if rsi > 50
f + 50
else
-f + 50
rsiadvanced
rsiha = 100 - 100 / (1 + ruh / rdh)
rsila = 100 - 100 / (1 + rul / rdl)
rsia = ta.rsi(rsrc, len)
rsih = if ad
function(rsiha, len)
else
rsiha
rsil = if ad
function(rsila, len)
else
rsila
// rsi bought & sold zone
plot_bands = true
reb2 = hline(plot_bands ? 80 : na, 'Extreme-Bought', color.new(color.red, 0), linewidth=2, linestyle=hline.style_solid)
reb1 = hline(plot_bands ? 70 : na, 'Over-Bought', color.new(color.red, 50), linewidth=2, linestyle=hline.style_dashed)
rmb = hline(plot_bands ? 50 : na, 'Neutral', color.new(color.black, 0), linewidth=1, linestyle=hline.style_dotted)
res1 = hline(plot_bands ? 30 : na, 'Over-Sold', color.new(color.green, 50), linewidth=2, linestyle=hline.style_dashed)
res2 = hline(plot_bands ? 20 : na, 'Extreme-Sold', color.new(color.green, 0), linewidth=2, linestyle=hline.style_solid)
// candle
plotcandle(rsi[1], rsih, rsil, rsi, 'RSI_Candle', color=ta.change(rsi) > 0 ? color.new(color.green, 0) : color.new(color.red, 0), wickcolor=#000000, bordercolor=#2a2e39)
plot(rsi, 'RSI_Line', color= ta.change(rsi) > 0 ? color.black : color.black, display=display.none, linewidth=2)
|
Softmax Normalized Jurik Filter Histogram [Loxx] | https://www.tradingview.com/script/ZlMY7UOL-Softmax-Normalized-Jurik-Filter-Histogram-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 138 | 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/
// © loxx
//@version=5
indicator("Softmax Normalized Jurik Filter Histogram [Loxx]",
shorttitle="SNJFH [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxjuriktools/1 as jf
greencolor = #2DD204
redcolor = #D2042D
softmax(float src, int per)=>
float mean = ta.sma(src, per)
float dev = ta.stdev(src, per)
float zmean = (src - mean) / dev
float val = (1.0 - math.exp(-zmean)) / (1.0 + math.exp(-zmean))
val
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(20, "Period", group= "Basic Settings")
jphs = input.float(0., "Jurik Phase", group = "Basic Settings")
normper = input.int(30, "Normalization Period")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
out = jf.jurik_filt(src, per, jphs)
out := softmax(out, normper)
sig = 0
colorout = out > sig ? greencolor : out < sig ? redcolor : color.gray
plot(out, "SNJF", color = colorout, linewidth = 2, style = plot.style_histogram)
plot(sig, "Mid", color = bar_index % 2 ? color.gray : na)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(out, sig)
goShort = ta.crossunder(out, sig)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title = "Long", message = "Softmax Normalized Jurik Filter Histogram [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Softmax Normalized Jurik Filter Histogram [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Possible RSI [Loxx] | https://www.tradingview.com/script/xvhQoboJ-Possible-RSI-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
indicator("Possible RSI [Loxx]",
shorttitle='PRSI [Loxx]',
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxdynamiczone/3
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxvarietyrsi/1
greencolor = #2DD204
redcolor = #D2042D
darkGreenColor = #1B7E02
darkRedColor = #93021F
gauss = "Gaussian (Fisher)"
soft = "Softmax"
regnorm = "Regular Norm"
SM02 = 'Slope'
SM03 = 'Dynamic Middle Crossover'
SM04 = 'Levels Crossover'
SM05 = 'Zeroline Crossover'
highpass(float src, int period) =>
float a1 = math.exp(-1.414 * math.pi / period)
float b1 = 2 * a1 * math.cos(1.414 * math.pi / period)
float c2 = b1
float c3 = -a1 * a1
float c1 = (1 + c2 - c3) / 4
float hp = 0.0
hp := bar_index < 4 ? 0 : c1 * (src - 2 * nz(src[1]) + nz(src[2])) + (c2 * nz(hp[1])) + (c3 * nz(hp[2]))
hp
softmax(float src, int per)=>
float mean = ta.sma(src, per)
float dev = ta.stdev(src, per)
float zmean = (src - mean) / dev
float val = (1.0 - math.exp(-zmean)) / (1.0 + math.exp(-zmean))
val
regnorm(float src, int per)=>
float mean = ta.sma(src, per)
float dev = ta.stdev(src, per)
float zmean = (src - mean) / (dev * 3)
zmean
round_(float val) =>
val > .99 ? .999 : val < -.99 ? -.999 : val
fisherTransform(float src, len)=>
float high_ = ta.highest(src, len)
float low_ = ta.lowest(src, len)
float value = 0.0
value := round_(.66 * ((src - low_) / (high_ - low_) - .5) + .67 * nz(value[1]))
float fish1 = 0.0
fish1 := .5 * math.log((1 + value) / (1 - value)) + .5 * nz(fish1[1])
fish1
nonlagma(float src, int len)=>
float cycle = 4.0
float coeff = 3.0 * math.pi
float phase = len - 1.0
int _len = int(len * cycle + phase)
float weight = 0., float alfa = 0., float out = 0.
float[] alphas = array.new_float(_len, 0.)
for k = 0 to _len - 1
float t = 0.
t := k <= phase - 1 ? 1.0 * k / (phase - 1) : 1.0 + (k - phase + 1) * (2.0 * cycle - 1.0) / (cycle * len -1.0)
float beta = math.cos(math.pi * t)
float g = 1.0/(coeff * t + 1)
g := t <= 0.5 ? 1 : g
array.set(alphas, k, g * beta)
weight += array.get(alphas, k)
if (weight > 0)
float sum = 0.
for k = 0 to _len - 1
sum += array.get(alphas, k) * nz(src[k])
out := (sum / weight)
out
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
runhp = input.bool(false, "Filter Price w/ High-Pass Filter?", group = "Source Settings")
hper = input.int(15, "High-Pass Period", group = "Source Settings")
per = input.int(32, "RSI Period", group = "Basic Settings")
rsitype = input.string("Regular", "RSI Type", options = ["RSX", "Regular", "Slow", "Rapid", "Harris", "Cuttler", "Ehlers Smoothed"], group = "Basic Settings")
norm = input.int(100, "Min/Max Norm Period", group = "Basic Settings")
ntype = input.string(gauss, "Normalizatino Function", options = [gauss, soft, regnorm], group = "Basic Settings")
norm1 = input.int(15, "Fisher/Softmax Normalization Period", group = "Basic Settings")
nonlag = input.int(15, "Non-Lag Smoother Period", group = "Basic Settings")
dzper = input.int(20, "Dynamic Zone Period", group = "Levels Settings")
buy1 = input.float(0.2 , "Dynamic Zone Buy Probability Level 1", group = "Levels Settings", maxval = 0.5)
sell1 = input.float(0.2 , "Dynamic Zone Sell Probability Level 1", group = "Levels Settings", maxval = 0.5)
sigtype = input.string(SM05, "Signal type", options = [SM02, SM03, SM04, SM05], group = "Signal Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showSigs = input.bool(true, "Show Signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
rsimode = switch rsitype
"RSX" => "rsi_rsx"
"Regular" => "rsi_rsi"
"Slow" => "rsi_slo"
"Rapid" => "rsi_rap"
"Harris" => "rsi_har"
"Cuttler" => "rsi_cut"
"Ehlers Smoothed" => "rsi_ehl"
=> "rsi_rsi"
src := runhp ? highpass(src, hper) : src
rsi = loxxvarietyrsi.rsiVariety(rsimode, src, per)
float fmax = ta.highest(rsi, norm)
float fmin = ta.lowest(rsi, norm)
float rng = (fmax - fmin) / 100.0
val = (rsi - fmin) / rng
val := ntype == gauss ? fisherTransform(val, norm1) : ntype == soft ? softmax(val, norm1) : regnorm(val, norm1)
val := nonlagma(val, nonlag)
sig = val[1]
mid = 0
bl1 = loxxdynamiczone.dZone("buy", val, buy1, dzper)
sl1 = loxxdynamiczone.dZone("sell", val, sell1, dzper)
zli = loxxdynamiczone.dZone("sell", val, 0.5 , dzper)
state = 0.
if sigtype == SM02
if (val<sig)
state :=-1
if (val>sig)
state := 1
else if sigtype == SM03
if (val<zli)
state :=-1
if (val>zli)
state := 1
else if sigtype == SM04
if (val<bl1)
state :=-1
if (val>sl1)
state := 1
else if sigtype == SM05
if (val < mid)
state :=-1
if (val > mid)
state := 1
colorout = state == -1 ? redcolor : state == 1 ? greencolor : color.gray
plot(val, color = colorout, linewidth = 2)
plot(bl1, color = darkGreenColor)
plot(sl1, color = darkRedColor)
plot(zli, color = color.white)
plot(mid, color = bar_index % 2 ? color.white : na)
barcolor(colorbars ? colorout : na)
hline(0)
goLong =
sigtype == SM02 ? ta.crossover(val, sig) :
sigtype == SM03 ? ta.crossover(val, zli) :
sigtype == SM04 ? ta.crossover(val, sl1) :
ta.crossover(val, mid)
goShort =
sigtype == SM02 ? ta.crossunder(val, sig) :
sigtype == SM03 ? ta.crossunder(val, zli) :
sigtype == SM04 ? ta.crossunder(val, bl1) :
ta.crossunder(val, mid)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Possible RSI [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Possible RSI [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Wavetrend Moving Average (WTMA) [Loxx] | https://www.tradingview.com/script/hJ9OE8tZ-Wavetrend-Moving-Average-WTMA-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 263 | 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/
// © loxx
//@version=5
indicator("Wavetrend Moving Average (WTMA) [Loxx]",
shorttitle='WTMA [Loxx]',
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
regnorm(float src, int per)=>
float mean = ta.sma(src, per)
float dev = ta.stdev(src, per)
float zmean = (src - mean) / dev
zmean
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("HAB Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
n1 = input(10, "Channel Length", group = "Wavetrend Settings")
n2 = input(21, "Average Length", group = "Wavetrend Settings")
nper = input.int(40, "Normalization Period", group = "Wavetrend MA Settings")
hiloper = input.int(20, "HiLo Period", group = "Wavetrend MA Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showSigs = input.bool(true, "Show Signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
ap = src
esa = ta.ema(ap, n1)
d = ta.ema(math.abs(ap - esa), n1)
ci = (ap - esa) / (0.015 * d)
tci = ta.ema(ci, n2)
wt1 = regnorm(tci, nper)
fmax = ta.highest(high, hiloper)
fmin = ta.lowest(low, hiloper)
rng = fmax - fmin
dnlvl = fmin + rng * wt1 / 100
uplvl = fmax + rng * wt1 / 100
mid = (uplvl + dnlvl) /2
colorout = tci > 0 ? greencolor : redcolor
plot(mid, "WTMA", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(tci, 0)
goShort = ta.crossunder(tci, 0)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="Wavetrend Moving Average (WTMA) [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Wavetrend Moving Average (WTMA) [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
International [interest, exchange] rates | https://www.tradingview.com/script/xOLBArA6-International-interest-exchange-rates/ | Bill_Howell | https://www.tradingview.com/u/Bill_Howell/ | 6 | 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/
// © Bill_Howell
//@version=4
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// 19Sep2022 initial, 20Sep2022 fixed colored labels, added min,max from my previous scripts
// see https://www.tradingview.com/script/xOLBArA6-International-interest-exchange-rates/
// All manually-provided constants for del[Min, Max]_<sym>10Y will become inaccurate with time!!
// ONLY time.periods [3M, 6M, 1Y, 5Y] work.
// time.periods [1D, 5D, 1M, ALL] do NOT work - I haven't manually provided values from charts.
// there are some errors in my manually [read, record] of the 5Y time-periods
// additionally, this Pine Script was thrown together in a day, no rigorous testing
// exchange rates are shown by darker colors, interest rates lighter similar colors
// China - green, Euro - purple, Great Britain - blue, Japan - orange (you can see this in the4 code below!)
// stable rates : [JP10Y, CN10Y]
// https://www.tradingview.com/x/OXFvIi7I/
// policy-manipulated rates : [TNX, EU10Y, GB10Y]
// https://www.tradingview.com/x/V4LOppCz/
//**********************************
study(title="International 10Y rates minus US", shorttitle=" ", overlay=true, resolution="")
//+-----------------------------------------------------------------+
//+-----------------------------------------------------------------+
// Code in this section was taken from my earlier PineScripts
// (eg "SP500 [Puetz time, Fibonacci price]Fractals [trend, relStdDev] 1926-2020")
//+-----+
// https://www.tradingview.com/pine-script-docs/en/v4/appendix/HOWTOs.html#count-bars-in-a-dataset
// Find the highest and lowest values for the entire dataset
// 20Mar2021 Howell - adapt this for viewable data
// 20Sep2022 WARNING!!
// PineScript fails at providing functions that work over the full length of the visible stock period.
// One cannot accurately determine the start time bar
// functions like [big, small]est below give WRONG results!! - best to hand-craft answers
biggest(series,size) =>
max = 0.0
for j = 0 to size
if series[j] > max
max := series[j]
max
smalest(series,size) =>
min = 100000.
for j = size to 0
if series[j] < min
min := series[j]
min
//+-----+
// Setup - timeframe.period, n_bars, [min, max] of tracked main price series in chart
// User must turn OFF : SP500 axis menu -> Labels -> Indicators and financials name labels (no checkmark)
// timeIdx = index to ary_t_length, the active chart timeSpan
// t_lengthYear = duration of graph timescale for each timeperiod
// visual = "1D" "5D" "1M" "3M" "6M" "1Y" "5Y" "All"
// actual = 1 1 30 120 D W 30? or 20?
//qnial> (1/365.25) (5/365.25) (1/12) (3/12) (1/2) (1.0) (5.0) (20)
// .00273785 0.0136893 0.0833333 0.25 0.5 1. 5. 20.
var int timeIdx = 0 // index to UWS constants
// 20Sep2022 NOTE : hand-derived values below!!! (Pine Script no good for these kinds of things)
// Formulae don't work in PineScript for full time-period
// if (timeframe.period == "1")
// timeIdx := 0
// else if (timeframe.period == "5")
// timeIdx := 1
// else if (timeframe.period == "30")
// timeIdx := 2
// else if (timeframe.period == "60")
// timeIdx := 3
// else if (timeframe.period == "120")
// timeIdx := 4
// else if (timeframe.period == "D")
// timeIdx := 5
// else if (timeframe.period == "W")
// timeIdx := 6
// else if (timeframe.period == "M")
// timeIdx := 7
delMin_CN10Y = 0.
delMin_EU10Y = 0.
delMin_GB10Y = 0.
delMin_JP10Y = 0.
delMax_CN10Y = 1.
delMax_EU10Y = 1.
delMax_GB10Y = 1.
delMax_JP10Y = 1.
// hand-crafted off chart, typed in!! To read the values :
// set params like this for a given time.period
// [save, run] script
// enter [min, max] values shown on graph for the given time.period of :
// d_CN10Y = (v_TNX - v_CN10Y - delMin_CN10Y)/(delMax_CN10Y - delMin_CN10Y)
// = (v_TNX - v_CN10Y)
// = del_CN10Y
// YES - this is STUPID work that PineScript should do well...
// delMin_CN10Y := 0.
// delMin_EU10Y := 0.
// delMin_GB10Y := 0.
// delMin_JP10Y := 0.
// delMax_CN10Y := 1.
// delMax_EU10Y := 1.
// delMax_GB10Y := 1.
if (timeframe.period == "1") // 1 day
delMin_CN10Y := 0.
delMin_EU10Y := 0.
delMin_GB10Y := 0.
delMin_JP10Y := 0.
delMax_CN10Y := 1.
delMax_EU10Y := 1.
delMax_GB10Y := 1.
delMax_JP10Y := 1.
else if (timeframe.period == "5") // 5 days
delMin_CN10Y := 0.
delMin_EU10Y := 0.
delMin_GB10Y := 0.
delMin_JP10Y := 0.
delMax_CN10Y := 1.
delMax_EU10Y := 1.
delMax_GB10Y := 1.
delMax_JP10Y := 1.
else if (timeframe.period == "30") // 1 month
delMin_CN10Y := 0.
delMin_EU10Y := 0.
delMin_GB10Y := 0.
delMin_JP10Y := 0.
delMax_CN10Y := 1.
delMax_EU10Y := 1.
delMax_GB10Y := 1.
delMax_JP10Y := 1.
else if (timeframe.period == "60") // 3 months
delMin_CN10Y := -0.158
delMin_EU10Y := 1.452
delMin_GB10Y := 0.110
delMin_JP10Y := 2.412
delMax_CN10Y := 0.920
delMax_EU10Y := 1.951
delMax_GB10Y := 0.986
delMax_JP10Y := 3.336
else if (timeframe.period == "120") // 6 months
delMin_CN10Y := -0.664
delMin_EU10Y := 1.455
delMin_GB10Y := 0.109
delMin_JP10Y := 1.946
delMax_CN10Y := 0.910
delMax_EU10Y := 2.084
delMax_GB10Y := 1.247
delMax_JP10Y := 3.338
else if (timeframe.period == "D") // 1 year
delMin_CN10Y := -1.559
delMin_EU10Y := 1.483
delMin_GB10Y := 0.127
delMin_JP10Y := 1.261
delMax_CN10Y := 0.815
delMax_EU10Y := 2.029
delMax_GB10Y := 1.189
delMax_JP10Y := 3.252
else if (timeframe.period == "W") // 5 years
delMin_CN10Y := -0.397
delMin_EU10Y := -0.854
delMin_GB10Y := 0.084
delMin_JP10Y := -0.371
delMax_CN10Y := 1.041
delMax_EU10Y := 2.374
delMax_GB10Y := 1.624
delMax_JP10Y := 1.034
else if (timeframe.period == "M") // ALL years
delMin_CN10Y := 0.
delMin_EU10Y := 0.
delMin_GB10Y := 0.
delMin_JP10Y := 0.
delMax_CN10Y := 1.
delMax_EU10Y := 1.
delMax_GB10Y := 1.
delMax_JP10Y := 1.
//+-----------------------------------------------------------------+
//+-----------------------------------------------------------------+
// Code adapted from my previous PineScript
v_TNX = security("TVC:TNX", timeframe.period, close)
v_CN10Y = security("TVC:CN10Y", timeframe.period, close)
v_EU10Y = security("TVC:EU10Y", timeframe.period, close)
v_GB10Y = security("TVC:GB10Y", timeframe.period, close)
v_JP10Y = security("TVC:JP10Y", timeframe.period, close)
del_CN10Y = v_TNX - v_CN10Y
del_EU10Y = v_TNX - v_EU10Y
del_GB10Y = v_TNX - v_GB10Y
del_JP10Y = v_TNX - v_JP10Y
// 20Sep2022 Cannot use - give wrong results :
// delMin_CN10Y = smalest(del_CN10Y,n_bars)
// delMin_EU10Y = smalest(del_EU10Y,n_bars)
// delMin_GB10Y = smalest(del_GB10Y,n_bars)
// delMin_JP10Y = smalest(del_JP10Y,n_bars)
//
// delMax_CN10Y = biggest(del_CN10Y,n_bars)
// delMax_EU10Y = biggest(del_EU10Y,n_bars)
// delMax_GB10Y = biggest(del_GB10Y,n_bars)
// delMax_JP10Y = biggest(del_JP10Y,n_bars)
d_CN10Y = (v_TNX - v_CN10Y - delMin_CN10Y)/(delMax_CN10Y - delMin_CN10Y)
d_EU10Y = (v_TNX - v_EU10Y - delMin_EU10Y)/(delMax_EU10Y - delMin_EU10Y)
d_GB10Y = (v_TNX - v_GB10Y - delMin_GB10Y)/(delMax_GB10Y - delMin_GB10Y)
d_JP10Y = (v_TNX - v_JP10Y - delMin_JP10Y)/(delMax_JP10Y - delMin_JP10Y)
// standard named colors :
// https://www.tradingview.com/pine-script-reference/v5/#var_color{dot}black
// "see also" list of named colors
// color.[black, silver, gray, white, red, purple, fuchsia, green, lime, olive, yellow, navy, blue, teal, aqua, orange]
plot(d_CN10Y, color=color.lime, linewidth=1, title="d_CN10Y") // go with green
plot(d_EU10Y, color=color.fuchsia, linewidth=1, title="d_EU10Y") // purple
plot(d_GB10Y, color=color.aqua, linewidth=1, title="d_GB10Y") // blue
plot(d_JP10Y, color=color.yellow, linewidth=2, title="d_JP10Y") // orange
// endcode
|
Shaikh Saab Ki Magarmach | https://www.tradingview.com/script/I1SvcVkU-Shaikh-Saab-Ki-Magarmach/ | Shaikhoo | https://www.tradingview.com/u/Shaikhoo/ | 16 | 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/
// © Shaikhoo
//@version=5
indicator(title="Shaikh Saab ki Magarmach", shorttitle="Shaikhoological", overlay=true, timeframe="", timeframe_gaps=true)
smma(src, length) =>
smma = 0.0
smma := na(smma[1]) ? ta.sma(src, length) : (smma[1] * (length - 1) + src) / length
smma
jawLength =(13)
teethLength =(8)
lipsLength = (5)
jawOffset = (8)
teethOffset = (5)
lipsOffset = (3)
jaw = smma(hl2, jawLength)
teeth = smma(hl2, teethLength)
lips = smma(hl2, lipsLength)
Shaikhoology = smma(close,200)
plot(Shaikhoology,title="AttackLine", color=color.black)
plot(jaw, "Jaw", offset = jawOffset, color=#2962FF)
plot(teeth, "Teeth", offset = teethOffset, color=color.red)
plot(lips, "Lips", offset = lipsOffset, color=color.green)
|
Prev 2M, 2W, 2D Lvls | https://www.tradingview.com/script/ehVPc3s4-Prev-2M-2W-2D-Lvls/ | SchroedingerzCat | https://www.tradingview.com/u/SchroedingerzCat/ | 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/
// © SchroedingerzCat
//@version=5
indicator(title='Prev 2M, 2W, 2D Lvls', shorttitle = " ",overlay=true)
tfd = timeframe.isintraday?1:0
tfw = 1
if tfd!=1
tfd:=timeframe.isdaily?1:0
if tfd!=1
tfw := timeframe.isweekly?1:0
show_last_2_mon = input(true,title="Show previous 2 month lines")
show_last_2_wk = input(true,title="Show previous 2 Week lines")
show_last_2_dy = input(true,title="Show previous 2 Day lines")
C1 = input.color(#00bcd4,"Select -1W color")
C2 = input.color(#006064,"Select -2W color")
C3 = input.color(#9c27b0,"Select -1D color")
C4 = input.color(#880e4f,"Select -2D color")
C5 = input.color(#ffffff, "Select -1M color")
C6 = input.color(#b2b5be, "Select -2M color")
pw1h = request.security(syminfo.tickerid, 'W', high[1])
pw1l = request.security(syminfo.tickerid, 'W', low[1])
pw2h = request.security(syminfo.tickerid, 'W', high[2])
pw2l = request.security(syminfo.tickerid, 'W', low[2])
pw2t = request.security(syminfo.tickerid, 'W', time[2])
pw1t = request.security(syminfo.tickerid, 'W', time[1])
pd1h = request.security(syminfo.tickerid, 'D', high[1])
pd1l = request.security(syminfo.tickerid, 'D', low[1])
pd2h = request.security(syminfo.tickerid, 'D', high[2])
pd2l = request.security(syminfo.tickerid, 'D', low[2])
pd2t = request.security(syminfo.tickerid, 'D', time[2])
pd1t = request.security(syminfo.tickerid, 'D', time[1])
pm1h = request.security(syminfo.tickerid, 'M', high[1])
pm1l = request.security(syminfo.tickerid, 'M', low[1])
pm2h = request.security(syminfo.tickerid, 'M', high[2])
pm2l = request.security(syminfo.tickerid, 'M', low[2])
pm2t = request.security(syminfo.tickerid, 'M', time[2])
pm1t = request.security(syminfo.tickerid, 'M', time[1])
W1H="-1W"+" H"
W1L="-1W"+" L"
W2H="-2W"+" H"
W2L="-2W"+" L"
D1H="-1D"+" H"
D1L="-1D"+" L"
D2H="-2D"+" H"
D2L="-2D"+" L"
M1H="-1M"+" H"
M2H="-2M"+" H"
M1L="-1M"+" L"
M2L="-2M"+" L"
if show_last_2_dy
if tfd==1
ld1h=line.new(x1=pd1t,y1=pd1h,x2=time, y2=pd1h,xloc=xloc.bar_time,extend=extend.right,color=C3,style=line.style_solid,width=1)
ld1l=line.new(x1=pd1t,y1=pd1l,x2=time, y2=pd1l,xloc=xloc.bar_time,extend=extend.right,color=C3,style=line.style_solid,width=1)
ld2h=line.new(x1=pd2t,y1=pd2h,x2=time, y2=pd2h,xloc=xloc.bar_time,extend=extend.right,color=C4,style=line.style_solid,width=1)
ld2l=line.new(x1=pd2t,y1=pd2l,x2=time, y2=pd2l,xloc=xloc.bar_time,extend=extend.right,color=C4,style=line.style_solid,width=1)
line.delete(ld1h[1])
line.delete(ld1l[1])
line.delete(ld2h[1])
line.delete(ld2l[1])
plot(pd1h, title=D1H, editable=true, color=C3, linewidth=1, offset=-9999, display=display.none)
plot(pd1l, title=D1L, editable=true, color=C3, linewidth=1, offset=-9999, display=display.none)
plot(pd2h, title=D2H, editable=true, color=C4, linewidth=1, offset=-9999, display=display.none)
plot(pd2l, title=D2L, editable=true, color=C4, linewidth=1, offset=-9999, display=display.none)
if show_last_2_wk
if tfw==1
lw1h=line.new(x1=pw1t,y1=pw1h,x2=time, y2=pw1h,xloc=xloc.bar_time,extend=extend.right,color=C1,style=line.style_solid,width=0)
lw1l=line.new(x1=pw1t,y1=pw1l,x2=time, y2=pw1l,xloc=xloc.bar_time,extend=extend.right,color=C1,style=line.style_solid,width=1)
lw2h=line.new(x1=pw2t,y1=pw2h,x2=time, y2=pw2h,xloc=xloc.bar_time,extend=extend.right,color=C2,style=line.style_solid,width=1)
lw2l=line.new(x1=pw2t,y1=pw2l,x2=time, y2=pw2l,xloc=xloc.bar_time,extend=extend.right,color=C2,style=line.style_solid,width=1)
line.delete(lw1h[1])
line.delete(lw1l[1])
line.delete(lw2h[1])
line.delete(lw2l[1])
plot(pw1h, title=W1H, editable=true, color=C1, linewidth=1, offset=-9999, display=display.none)
plot(pw1l, title=W1L, editable=true, color=C1, linewidth=1, offset=-9999, display=display.none)
plot(pw2h, title=W2H, editable=true, color=C2, linewidth=1, offset=-9999, display=display.none)
plot(pw2l, title=W2L, editable=true, color=C2, linewidth=1, offset=-9999, display=display.none)
if show_last_2_mon
lm1h=line.new(x1=pm1t,y1=pm1h,x2=time, y2=pm1h,xloc=xloc.bar_time,extend=extend.right,color=C5,style=line.style_solid,width=1)
lm1l=line.new(x1=pm1t,y1=pm1l,x2=time, y2=pm1l,xloc=xloc.bar_time,extend=extend.right,color=C5,style=line.style_solid,width=1)
lm2h=line.new(x1=pm2t,y1=pm2h,x2=time, y2=pm2h,xloc=xloc.bar_time,extend=extend.right,color=C6,style=line.style_solid,width=1)
lm2l=line.new(x1=pm2t,y1=pm2l,x2=time, y2=pm2l,xloc=xloc.bar_time,extend=extend.right,color=C6,style=line.style_solid,width=1)
line.delete(lm1h[1])
line.delete(lm2h[1])
line.delete(lm1l[1])
line.delete(lm2l[1])
plot(pm1h, title=M1H, editable=true, color=C5, linewidth=1, offset=-9999, display=display.none)
plot(pm1l, title=M1L, editable=true, color=C5, linewidth=1, offset=-9999, display=display.none)
plot(pm2h, title=M2H, editable=true, color=C6, linewidth=1, offset=-9999, display=display.none)
plot(pm2l, title=M2L, editable=true, color=C6, linewidth=1, offset=-9999, display=display.none)
|
Automatic Order Block + Imbalance by D. Brigaglia | https://www.tradingview.com/script/40a7WxD6/ | dadoesploso | https://www.tradingview.com/u/dadoesploso/ | 893 | 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="Automatic Order Block + Imbalance", overlay=true)
lenght = input(title="Rect Lenght", type=input.integer, defval=350)
//bullish OB
if close > (high[3] + 3.5 * atr(14)) and open[3] > close[3]
box.new(left=bar_index[3], top=high[3], right=bar_index + lenght, bottom=low[3],
border_color=color.blue, border_width=3, bgcolor=na)
//bearish OB
if close < (low[3] - 3.5 * atr(14)) and open[3] < close[3]
box.new(left=bar_index[3], top=high[3], right=bar_index + lenght, bottom=low[3],
border_color=color.red, border_width=3, bgcolor=na)
//buy side imbalance
if (high[2] < low[0]) and (close[1] - open[1] > 3 * atr(14))
box.new(left=bar_index[2], top=low[0], right=bar_index + lenght, bottom=high[2],
border_color=color.green, border_width=2, bgcolor=na)
//sell side imbalance
if (low[2] > high[0]) and (open[1] - close[1] > 3 * atr(14))
box.new(left=bar_index[2], top=low[2], right=bar_index + lenght, bottom=high[0],
border_color=color.orange, border_width=2, bgcolor=na) |
RSI Past Can Turn RSI Into a Directional Tool | https://www.tradingview.com/script/2tennpoc-RSI-Past-Can-Turn-RSI-Into-a-Directional-Tool/ | TradeStation | https://www.tradingview.com/broker/TradeStation/ | 1,708 | 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/
// © TradeStation
// RSI Past
//@version=5
indicator(title="RSI Past", shorttitle="RSI Past", overlay=false, precision=0)
// RSI input settings
rsiLength = input.int(14, title="Length", minval=2, group="RSI Settings")
rsiSource = input(close, title="Price", group="RSI Settings")
rsiOverbought = input.float(70, title="Overbought Threshold", group="RSI Settings")
rsiOversold = input.float(30, title="Oversold Threshold", group="RSI Settings")
// RSI input colors
color aboveColor = input.color(color.green, "Above 0 Color", group="Color Settings")
color belowColor = input.color(color.red, "Below 0 Color", group="Color Settings")
color zeroColor = input.color(color.black, "Zero Line Color", group="Color Settings")
var color plotColor = zeroColor
var int lastBullish = na
var int lastBearish = na
var float reading = na
rsiValue = ta.rsi(rsiSource, rsiLength)
if rsiValue < rsiOversold
lastBearish := bar_index
else if rsiValue > rsiOverbought
lastBullish := bar_index
if lastBullish and lastBearish
reading := lastBullish - lastBearish
if reading
if reading > 0
plotColor := aboveColor
else if reading < 0
plotColor := belowColor
else
plotColor := zeroColor
readingPlot = plot(reading, title="RSI Pass", color=plotColor, style=plot.style_area, linewidth=3) |
6 Multi-Timeframe Supertrend with Heikin Ashi as Source | https://www.tradingview.com/script/WkSPLtHY-6-Multi-Timeframe-Supertrend-with-Heikin-Ashi-as-Source/ | Thinkologist | https://www.tradingview.com/u/Thinkologist/ | 181 | 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/
// @Shamshiri_investments
// Author : Mohammad Hossein Shamshiri
//
//@version=5
indicator(title="6 Multi-Timeframe supertrend with Heikin Ashi source",shorttitle="6 Heikin Ashi supertrend", overlay = true,timeframe="")
Mult = input.float(defval = 1.0, title = "ATR Factor", minval = 0.5, maxval = 100, step = 0.1)
Mult2 = input.float(defval = 2.0, title = "ATR Factor", minval = 0.5, maxval = 100, step = 0.1)
Mult3 = input.float(defval = 3.0, title = "ATR Factor", minval = 0.5, maxval = 100, step = 0.1)
Mult4 = input.float(defval = 4.0, title = "ATR Factor", minval = 0.5, maxval = 100, step = 0.1)
Mult5 = input.float(defval = 5.0, title = "ATR Factor", minval = 0.5, maxval = 100, step = 0.1)
Mult51 = input.float(defval = 6.0, title = "ATR Factor", minval = 0.5, maxval = 100, step = 0.1)
Period = input.int(defval = 7, title = "ATR Period", minval = 1,maxval = 100)
//Heikin Ashi high, low, close
h = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
l = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
c = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
//HeikinAshi atr
Atr = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ta.atr(Period))
Up = (h + l) / 2 - (Mult * Atr)
Dn = (h + l) / 2 + (Mult * Atr)
float TUp = na
float TDown = na
Trend = 0
TUp := c[1] > TUp[1] ? math.max(Up,TUp[1]) : Up
TDown := c[1] < TDown[1] ? math.min(Dn,TDown[1]) : Dn
Trend := c > TDown[1] ? 1: c < TUp[1]? -1: nz(Trend[1],1)
Trailingsl = Trend == 1 ? TUp : TDown
plot(Trailingsl, color = color.blue , linewidth = 2, title = "SuperTrend 1")
Up2 = (h + l) / 2 - (Mult2 * Atr)
Dn2 = (h + l) / 2 + (Mult2 * Atr)
float TUp2 = na
float TDown2 = na
Trend2 = 0
TUp2 := c[1] > TUp2[1] ? math.max(Up2,TUp2[1]) : Up2
TDown2 := c[1] < TDown2[1] ? math.min(Dn2,TDown2[1]) : Dn2
Trend2 := c > TDown2[1] ? 1: c < TUp2[1]? -1: nz(Trend2[1],1)
Trailingsl2 = Trend2 == 1 ? TUp2 : TDown2
plot(Trailingsl2, color = color.orange , linewidth = 2, title = "SuperTrend 2")
Up3 = (h + l) / 2 - (Mult3 * Atr)
Dn3 = (h + l) / 2 + (Mult3 * Atr)
float TUp3 = na
float TDown3 = na
Trend3 = 0
TUp3 := c[1] > TUp3[1] ? math.max(Up3,TUp3[1]) : Up3
TDown3 := c[1] < TDown3[1] ? math.min(Dn3,TDown3[1]) : Dn3
Trend3 := c > TDown3[1] ? 1: c < TUp3[1]? -1: nz(Trend3[1],1)
Trailingsl3 = Trend3 == 1 ? TUp3 : TDown3
plot(Trailingsl3, color = color.black , linewidth = 2, title = "SuperTrend 3")
Up4 = (h + l) / 2 - (Mult4 * Atr)
Dn4 = (h + l) / 2 + (Mult4 * Atr)
float TUp4 = na
float TDown4 = na
Trend4 = 0
TUp4 := c[1] > TUp4[1] ? math.max(Up4,TUp4[1]) : Up4
TDown4 := c[1] < TDown4[1] ? math.min(Dn4,TDown4[1]) : Dn4
Trend4 := c > TDown4[1] ? 1: c < TUp4[1]? -1: nz(Trend4[1],1)
Trailingsl4 = Trend4 == 1 ? TUp4 : TDown4
plot(Trailingsl4, color = color.lime , linewidth = 2, title = "SuperTrend 4")
Up5 = (h + l) / 2 - (Mult5 * Atr)
Dn5 = (h + l) / 2 + (Mult5 * Atr)
float TUp5 = na
float TDown5 = na
Trend5 = 0
TUp5 := c[1] > TUp5[1] ? math.max(Up5,TUp5[1]) : Up5
TDown5 := c[1] < TDown5[1] ? math.min(Dn5,TDown5[1]) : Dn5
Trend5 := c > TDown5[1] ? 1: c < TUp5[1]? -1: nz(Trend5[1],1)
Trailingsl5 = Trend5 == 1 ? TUp5 : TDown5
plot(Trailingsl5, color = color.teal , linewidth = 2, title = "SuperTrend 5")
Up51 = (h + l) / 2 - (Mult51 * Atr)
Dn51 = (h + l) / 2 + (Mult51 * Atr)
float TUp51 = na
float TDown51 = na
Trend51 = 0
TUp51 := c[1] > TUp51[1] ? math.max(Up51,TUp51[1]) : Up5
TDown51 := c[1] < TDown51[1] ? math.min(Dn51,TDown51[1]) : Dn5
Trend51 := c > TDown51[1] ? 1: c < TUp51[1]? -1: nz(Trend51[1],1)
Trailingsl51 = Trend51 == 1 ? TUp51 : TDown51
plot(Trailingsl51, color = color.maroon , linewidth = 2, title = "SuperTrend 6")
//Alerts
alertcondition(Trend3 == 1 and Trend3[1] == -1, title='Supertrend 3 Trend Up', message='Supertrend 3 Trend Up')
alertcondition(Trend3 == -1 and Trend3[1] == 1, title='Supertrend 3 Trend Down', message='Supertrend 3 Trend Down')
|
[MAD] Multi-MA MTF | https://www.tradingview.com/script/hLvQyo40-MAD-Multi-MA-MTF/ | djmad | https://www.tradingview.com/u/djmad/ | 30 | 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/
// © djmad
// @ for Fibstep -> Sofien-Kaabar
//@version=5
indicator(title='[MAD] Multi-MA MTF', overlay=true)
import djmad/MAD_MATH/3 as mathematics
//************************************************************************************************************
// Variables and Inputs {
//************************************************************************************************************
labels_switch = input.bool(false, title="Show labels", group = "Lables")
string B1_TF1 = input.timeframe('', title='TF1',group="MA-1", inline="1a")
int B1_len = input.int(20, minval=1, title='Length',group="MA-1", inline="1a")
string B1_type = input.string("SMA", "MA Type", options=['OFF','WMA','HMA','VWMA','LMA','RMA','SMA','EMA','Ehlers EMA','Ehlers Gaussian','Ehlers Smoother','Ehlers Supersmoother','Ehlers Butterworth','ChebyshevI','ChebyshevII'],group="MA-1")
string B2_TF2 = input.timeframe('', title='TF 2',group="MA-2", inline="2a")
int B2_len = input.int(50, minval=1, title='Length',group="MA-2", inline="2a")
string B2_type = input.string("SMA", "MA Type", options=['OFF','WMA','HMA','VWMA','LMA','RMA','SMA','EMA','Ehlers EMA','Ehlers Gaussian','Ehlers Smoother','Ehlers Supersmoother','Ehlers Butterworth','ChebyshevI','ChebyshevII'],group="MA-2")
string B3_TF3 = input.timeframe('', title='TF 3',group="MA-3", inline="3a")
int B3_len = input.int(100, minval=1, title='Length',group="MA-3", inline="3a")
string B3_type = input.string("SMA", "MA Type", options=['OFF','WMA','HMA','VWMA','LMA','RMA','SMA','EMA','Ehlers EMA','Ehlers Gaussian','Ehlers Smoother','Ehlers Supersmoother','Ehlers Butterworth','ChebyshevI','ChebyshevII'],group="MA-3")
string B4_TF4 = input.timeframe('', title='TF 3',group="MA-4", inline="4a")
int B4_len = input.int(200, minval=1, title='Length',group="MA-4", inline="4a")
string B4_type = input.string("SMA", "MA Type", options=['OFF','WMA','HMA','VWMA','LMA','RMA','SMA','EMA','Ehlers EMA','Ehlers Gaussian','Ehlers Smoother','Ehlers Supersmoother','Ehlers Butterworth','ChebyshevI','ChebyshevII'],group="MA-4")
string B5_TF5 = input.timeframe('', title='TF 3',group="MA-5", inline="5a")
int B5_len = input.int(300, minval=1, title='Length',group="MA-5", inline="5a")
string B5_type = input.string("SMA", "MA Type", options=['OFF','WMA','HMA','VWMA','LMA','RMA','SMA','EMA','Ehlers EMA','Ehlers Gaussian','Ehlers Smoother','Ehlers Supersmoother','Ehlers Butterworth','ChebyshevI','ChebyshevII'],group="MA-5")
string B6_TF6 = input.timeframe('', title='TF 3',group="MA-6", inline="6a")
int B6_len = input.int(600, minval=1, title='Length',group="MA-6", inline="6a")
string B6_type = input.string("SMA", "MA Type", options=['OFF','WMA','HMA','VWMA','LMA','RMA','SMA','EMA','Ehlers EMA','Ehlers Gaussian','Ehlers Smoother','Ehlers Supersmoother','Ehlers Butterworth','ChebyshevI','ChebyshevII'],group="MA-6")
MA_res_01 = request.security(syminfo.tickerid, B1_TF1, mathematics.f_getall(_type = B1_type, _src = close, _length = B1_len), barmerge.gaps_off, barmerge.lookahead_off)
MA_res_02 = request.security(syminfo.tickerid, B2_TF2, mathematics.f_getall(_type = B2_type, _src = close, _length = B2_len), barmerge.gaps_off, barmerge.lookahead_off)
MA_res_03 = request.security(syminfo.tickerid, B3_TF3, mathematics.f_getall(_type = B3_type, _src = close, _length = B3_len), barmerge.gaps_off, barmerge.lookahead_off)
MA_res_04 = request.security(syminfo.tickerid, B4_TF4, mathematics.f_getall(_type = B4_type, _src = close, _length = B4_len), barmerge.gaps_off, barmerge.lookahead_off)
MA_res_05 = request.security(syminfo.tickerid, B5_TF5, mathematics.f_getall(_type = B5_type, _src = close, _length = B5_len), barmerge.gaps_off, barmerge.lookahead_off)
MA_res_06 = request.security(syminfo.tickerid, B6_TF6, mathematics.f_getall(_type = B6_type, _src = close, _length = B6_len), barmerge.gaps_off, barmerge.lookahead_off)
plot(MA_res_01, color=color.new(color.red, 0))
plot(MA_res_02, color=color.new(color.orange, 0))
plot(MA_res_03, color=color.new(#d4aa00, 0))
plot(MA_res_04, color=color.new(#00d420, 0))
plot(MA_res_05, color=color.new(#006ad4, 0))
plot(MA_res_06, color=color.new(#0019d4, 0))
f_round(_val, _decimals) =>
// Rounds _val to _decimals places.
_p = math.pow(10, _decimals)
math.round(math.abs(_val) * _p) / _p * math.sign(_val)
textcoloring = input(color.rgb(255, 255, 255, 0), title='textcolor')
//LABELS
var label T1 = na
var label T2 = na
var label T3 = na
var label T4 = na
var label T5 = na
var label T6 = na
label.delete(T1)
label.delete(T2)
label.delete(T3)
label.delete(T4)
label.delete(T5)
label.delete(T6)
T1 := labels_switch? label.new(bar_index, MA_res_01, style=label.style_label_left, text=B1_type + '-' + str.tostring(B1_len) + '-' + B1_TF1 + ' - ' + str.tostring(f_round(MA_res_01, 2)), textcolor=textcoloring, color=#00000000):na
T2 := labels_switch? label.new(bar_index, MA_res_02, style=label.style_label_left, text=B2_type + '-' + str.tostring(B2_len) + '-' + B2_TF2 + ' - ' + str.tostring(f_round(MA_res_02, 2)), textcolor=textcoloring, color=#00000000):na
T3 := labels_switch? label.new(bar_index, MA_res_03, style=label.style_label_left, text=B3_type + '-' + str.tostring(B3_len) + '-' + B3_TF3 + ' - ' + str.tostring(f_round(MA_res_03, 2)), textcolor=textcoloring, color=#00000000):na
T4 := labels_switch? label.new(bar_index, MA_res_04, style=label.style_label_left, text=B4_type + '-' + str.tostring(B4_len) + '-' + B4_TF4 + ' - ' + str.tostring(f_round(MA_res_04, 2)), textcolor=textcoloring, color=#00000000):na
T5 := labels_switch? label.new(bar_index, MA_res_05, style=label.style_label_left, text=B5_type + '-' + str.tostring(B5_len) + '-' + B5_TF5 + ' - ' + str.tostring(f_round(MA_res_05, 2)), textcolor=textcoloring, color=#00000000):na
T6 := labels_switch? label.new(bar_index, MA_res_06, style=label.style_label_left, text=B6_type + '-' + str.tostring(B6_len) + '-' + B6_TF6 + ' - ' + str.tostring(f_round(MA_res_06, 2)), textcolor=textcoloring, color=#00000000):na
//////////////////// SIGNAL Daisychain
string inputtype = input.string("NoInput" , title="Signal Type", group='Multibit signal config', options=["MultiBit", "MultiBit_pass", "NoInput"], tooltip='Multibit Daisychain with and without infusing\nMutlibit is the Signal-Type used in my Backtestsystem',inline='3a')
float inputModule = input(title='Select L1 Indicator Signal', group='Multibit signal config', defval=close, inline='3a')
Signal_Channel_Line1= input.int(-1, "MA 1 switch", minval=-1, maxval=15,group='Multibit',inline='1a')
Signal_Channel_Line2= input.int(-1, "MA 2 switch", minval=-1, maxval=15,group='Multibit',inline='1a')
Signal_Channel_Line3= input.int(-1, "MA 3 switch", minval=-1, maxval=15,group='Multibit',inline='1b')
Signal_Channel_Line4= input.int(-1, "MA 4 switch", minval=-1, maxval=15,group='Multibit',inline='1b')
Signal_Channel_Line5= input.int(-1, "MA 5 switch", minval=-1, maxval=15,group='Multibit',inline='1c')
Signal_Channel_Line6= input.int(-1, "MA 6 switch", minval=-1, maxval=15,group='Multibit',inline='1c')
bool a_MAs_1 = close > MA_res_01
bool a_MAs_2 = close > MA_res_02
bool a_MAs_3 = close > MA_res_03
bool a_MAs_4 = close > MA_res_04
bool a_MAs_5 = close > MA_res_05
bool a_MAs_6 = close > MA_res_06
//*********** MULTIBIT Implementation
import djmad/Signal_transcoder_library/7 as transcode
bool [] Multibit = array.new<bool>(16,false)
if inputtype == "MultiBit" or inputtype == "MultiBit_pass"
Multibit := transcode._16bit_decode(inputModule)
if inputtype != "MultiBit_pass"
transcode.f_infuse_signal(Signal_Channel_Line1, a_MAs_1, Signal_Channel_Line2, a_MAs_2, Signal_Channel_Line3, a_MAs_3, Signal_Channel_Line4, a_MAs_4, Signal_Channel_Line5, a_MAs_5, Signal_Channel_Line6, a_MAs_6, Multibit)
float plot_output = transcode._16bit_encode(Multibit)
plot(plot_output,title='MultiBit Signal',display=display.none) |
SuperTrend Momentum Table | https://www.tradingview.com/script/Crpak2eX-SuperTrend-Momentum-Table/ | VonnyFX | https://www.tradingview.com/u/VonnyFX/ | 67 | 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/
// © VonnyFX
//@version=5
indicator("SuperTrend Momentum Table", shorttitle="SuperTrend Momentum Table", max_bars_back=5000)
// User inputs
factor = input.float(0.99, "Factor", step = 0.05, tooltip="Momentum Sensitivity", group="Smart Momentum")
atrLength = input.int(2, "ATR Length", step = 1, tooltip="Momentum Sensitivity", group="Smart Momentum")
bullColor1 = input.color(#00ff99, title="Time Frame #1 Bull color", inline="1", group="Time Frame Colors")
bearColor1 = input.color(#f0ba00, title="------------------ Bear color", inline="1", group="Time Frame Colors")
bullColor2 = input.color(#22ad22, title="Time Frame #2 Bull color", inline="1", group="Time Frame Colors")
bearColor2 = input.color(#e10000, title="------------------ Bear color", inline="1", group="Time Frame Colors")
bullColor3 = input.color(#ff1c69, title="Time Frame #3 Bull color", inline="1", group="Time Frame Colors")
bearColor3 = input.color(#9c27b0, title="------------------ Bear color", inline="1", group="Time Frame Colors")
bullColor4 = input.color(#00bcd4, title="Time Frame #4 Bull color", inline="1", group="Time Frame Colors")
bearColor4 = input.color(#fb6417, title="------------------ Bear color", inline="1", group="Time Frame Colors")
bullColor5 = input.color(#f0ba00, title="Time Frame #5 Bull color", inline="1", group="Time Frame Colors")
bearColor5 = input.color(#0c3299, title="------------------ Bear color", inline="1", group="Time Frame Colors")
bullColor6 = input.color(#00ff00, title="Time Frame #6 Bull color", inline="1", group="Time Frame Colors")
bearColor6 = input.color(#4a148c, title="------------------ Bear color", inline="1", group="Time Frame Colors")
bullColor7 = input.color(#faa1a4, title="Time Frame #7 Bull color", inline="1", group="Time Frame Colors")
bearColor7 = input.color(#801922, title="------------------ Bear color", inline="1", group="Time Frame Colors")
momentumSwitch = input.bool(false, title="[Momentum Switch]", inline="1", group="Momentum Switch")
momentumSwitchBull = input.color(#ffe900, title="[Momentum Bull]", inline="1", group="Momentum Switch")
momentumSwitchBear = input.color(#0006ff, title="[Momentum Bear]", inline="1", group="Momentum Switch")
timeFrameAmount = input.int(7,title="Amount of Time Frames", tooltip="How much time frames to fill the table with", group="Higher Time Frame Inputs", maxval=7, minval=1)
res = input.timeframe(title= "TimeFrame#1", defval="1", tooltip="Choose your desired time frame to fill your table", group="Higher Time Frame Inputs")
res2 = input.timeframe(title= "TimeFrame#2", defval="3", group="Higher Time Frame Inputs")
res3 = input.timeframe(title= "TimeFrame#3", defval="5", group="Higher Time Frame Inputs")
res4 = input.timeframe(title= "TimeFrame#4", defval="15", group="Higher Time Frame Inputs")
res5 = input.timeframe(title= "TimeFrame#5", defval="60", group="Higher Time Frame Inputs")
res6 = input.timeframe(title= "TimeFrame#6", defval="240", group="Higher Time Frame Inputs")
res7 = input.timeframe(title= "TimeFrame#7", defval="D", group="Higher Time Frame Inputs")
//Wait for candle to close before you show signal or change in realtime
closeRrealtime = true
barState = (closeRrealtime == true) ? barstate.isconfirmed : barstate.isrealtime
// Get SuperTrend Values
[supertrend, direction] = ta.supertrend(factor, atrLength)
// Get Higher time Frame and insert SuperTrend
htfSuperTrend = request.security(syminfo.tickerid, res, supertrend[barState ? 0 : 1])
htfSuperTrend2 = request.security(syminfo.tickerid, res2, supertrend[barState ? 0 : 1])
htfSuperTrend3 = request.security(syminfo.tickerid, res3, supertrend[barState ? 0 : 1])
htfSuperTrend4 = request.security(syminfo.tickerid, res4, supertrend[barState ? 0 : 1])
htfSuperTrend5 = request.security(syminfo.tickerid, res5, supertrend[barState ? 0 : 1])
htfSuperTrend6 = request.security(syminfo.tickerid, res6, supertrend[barState ? 0 : 1])
htfSuperTrend7 = request.security(syminfo.tickerid, res7, supertrend[barState ? 0 : 1])
htfClose = request.security(syminfo.tickerid, res, close[barState ? 0 : 1])
htfClose2 = request.security(syminfo.tickerid, res2, close[barState ? 0 : 1])
htfClose3 = request.security(syminfo.tickerid, res3, close[barState ? 0 : 1])
htfClose4 = request.security(syminfo.tickerid, res4, close[barState ? 0 : 1])
htfClose5 = request.security(syminfo.tickerid, res5, close[barState ? 0 : 1])
htfClose6 = request.security(syminfo.tickerid, res6, close[barState ? 0 : 1])
htfClose7 = request.security(syminfo.tickerid, res7, close[barState ? 0 : 1])
//HTF signal is true for the first bar that closes above supertrend and for the
//first bar that closes below supertrend
bull_HTFe = htfClose > htfSuperTrend and htfClose[1] < htfSuperTrend[1]
bear_HTFe = htfClose < htfSuperTrend and htfClose[1] > htfSuperTrend[1]
bull_HTF2 = htfClose2 > htfSuperTrend2 and htfClose2[1] < htfSuperTrend2[1]
bear_HTF2 = htfClose2 < htfSuperTrend2 and htfClose2[1] > htfSuperTrend2[1]
bull_HTF3 = htfClose3 > htfSuperTrend3 and htfClose3[1] < htfSuperTrend3[1]
bear_HTF3 = htfClose3 < htfSuperTrend3 and htfClose3[1] > htfSuperTrend3[1]
bull_HTF4 = htfClose4 > htfSuperTrend4 and htfClose4[1] < htfSuperTrend4[1]
bear_HTF4 = htfClose4 < htfSuperTrend4 and htfClose4[1] > htfSuperTrend4[1]
bull_HTF5 = htfClose5 > htfSuperTrend5 and htfClose5[1] < htfSuperTrend5[1]
bear_HTF5 = htfClose5 < htfSuperTrend5 and htfClose5[1] > htfSuperTrend5[1]
bull_HTF6 = htfClose6 > htfSuperTrend6 and htfClose6[1] < htfSuperTrend6[1]
bear_HTF6 = htfClose6 < htfSuperTrend6 and htfClose6[1] > htfSuperTrend6[1]
bull_HTF7 = htfClose7 > htfSuperTrend7 and htfClose7[1] < htfSuperTrend7[1]
bear_HTF7 = htfClose7 < htfSuperTrend7 and htfClose7[1] > htfSuperTrend7[1]
// If price closes above supertrend return true if not return false.
momentum = htfClose > htfSuperTrend ? true : false
momentum2 = htfClose2 > htfSuperTrend2 ? true : false
momentum3 = htfClose3 > htfSuperTrend3 ? true : false
momentum4 = htfClose4 > htfSuperTrend4 ? true : false
momentum5 = htfClose5 > htfSuperTrend5 ? true : false
momentum6 = htfClose6 > htfSuperTrend6 ? true : false
momentum7 = htfClose7 > htfSuperTrend7 ? true : false
// Create hLines's to be filled
hline_ = hline(timeFrameAmount < 7 ? 120: 0, color=color.new(color.black,100), editable=false, linewidth=1, linestyle=hline.style_solid)
hline0 = hline(timeFrameAmount < 6 ? 120: 20, color=color.new(color.black,100), editable=false, linewidth=1, linestyle=hline.style_solid)
hline20 = hline(timeFrameAmount < 5 ? 120: 40, color=color.new(color.black,100), editable=false, linewidth=1, linestyle=hline.style_solid)
hline40 = hline(timeFrameAmount < 4 ? 120: 60, color=color.new(color.black,100), editable=false, linewidth=1, linestyle=hline.style_solid)
hline60 = hline(timeFrameAmount < 3 ? 120: 80, color=color.new(color.black,100), editable=false, linewidth=1, linestyle=hline.style_solid)
hline80 = hline(timeFrameAmount < 2 ? 120: 100, color=color.new(color.black,100), editable=false, linewidth=1, linestyle=hline.style_solid)
hline100 = hline(120, color=color.new(color.black,100), editable=false, linewidth=1, linestyle=hline.style_solid)
hline120 = hline(140, color=color.new(color.black,100), editable=false, linewidth=1, linestyle=hline.style_solid, title="More Space?")
// Htf Momentum colors
trendColor = bull_HTFe and momentumSwitch ? momentumSwitchBull : bear_HTFe and momentumSwitch ? momentumSwitchBear : momentum ? bullColor1 : bearColor1
trendColor2 = bull_HTF2 and momentumSwitch ? momentumSwitchBull : bear_HTF2 and momentumSwitch ? momentumSwitchBear : momentum2 ? bullColor2 : bearColor2
trendColor3 = bull_HTF3 and momentumSwitch ? momentumSwitchBull : bear_HTF3 and momentumSwitch ? momentumSwitchBear : momentum3 ? bullColor3 : bearColor3
trendColor4 = bull_HTF4 and momentumSwitch ? momentumSwitchBull : bear_HTF4 and momentumSwitch ? momentumSwitchBear : momentum4 ? bullColor4 : bearColor4
trendColor5 = bull_HTF5 and momentumSwitch ? momentumSwitchBull : bear_HTF5 and momentumSwitch ? momentumSwitchBear : momentum5 ? bullColor5 : bearColor5
trendColor6 = bull_HTF6 and momentumSwitch ? momentumSwitchBull : bear_HTF6 and momentumSwitch ? momentumSwitchBear : momentum6 ? bullColor6 : bearColor6
trendColor7 = bull_HTF7 and momentumSwitch ? momentumSwitchBull : bear_HTF7 and momentumSwitch ? momentumSwitchBear : momentum7 ? bullColor7 : bearColor7
//Fill hLines's with HTF Momentum Colors
fill(hline_, hline0, trendColor7, editable=false)
fill(hline0, hline20, trendColor6, editable=false)
fill(hline20, hline40, trendColor5, editable=false)
fill(hline40, hline60, trendColor4, editable=false)
fill(hline60, hline80, trendColor3, editable=false)
fill(hline80, hline100, trendColor2, editable=false)
fill(hline100, hline120, trendColor, editable=false)
|
Filtered, N-Order Power-of-Cosine, Sinc FIR Filter [Loxx] | https://www.tradingview.com/script/qnx1Nohx-Filtered-N-Order-Power-of-Cosine-Sinc-FIR-Filter-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 130 | 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/
// © loxx
//@version=5
indicator("Filtered, N-Order Power-of-Cosine, Sinc FIR Filter [Loxx]",
shorttitle = "FNOPOCSFIRF [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
//Factorial calcuation
fact(int n)=>
float out = 1
for i = 1 to n
out *= i
out
duelElementLagReducer(float[] coeff, int LagReductionFactor)=>
if LagReductionFactor > 0
per = array.size(coeff)
for i = per - 1 to 0
if i >= LagReductionFactor
array.set(coeff, i, 2 * array.get(coeff, i) - array.get(coeff, i - LagReductionFactor))
else
array.set(coeff, i, 2 * array.get(coeff, i))
coeff
nOrderPowerOfCosineSinc(int per, int order, float frequencyCutoff, int multiplier)=>
float ppastri = 0
var float[] pastri = array.new<float>(order + 1, 0.)
int pdepth = order - 1
for k = 0 to order / 2 - 1
ppastri := nz(fact(pdepth) / (fact(pdepth - k) * fact(k)), 1)
for k = 0 to order
array.set(pastri, k, nz(fact(order) / (fact(order - k) * fact(k)), 1))
array<float> outpastri = array.slice(pastri, 0, order / 2)
array.reverse(outpastri)
float[] coeffs = array.new<float>(per, 0)
int N = per - 1
float sum = 0
for n = 0 to per - 1
float div = n - N / 2.0
if div == 0
array.set(coeffs, n, 2.0 * math.pi * frequencyCutoff)
else
array.set(coeffs, n, math.sin(2.0 * math.pi * frequencyCutoff * div) / div)
int sign = -1
float coeff = ppastri
for k = 0 to array.size(outpastri) - 1
coeff += sign * array.get(outpastri, k) * math.cos((k + 1) * 2 * math.pi * n / N)
sign *= -1
coeff := coeff / (array.sum(outpastri) + ppastri)
array.set(coeffs, n, array.get(coeffs, n) * coeff)
sum += array.get(coeffs, n)
for k = 0 to per - 1
array.set(coeffs, k, array.get(coeffs, k) / sum)
array.set(coeffs, k, array.get(coeffs, k) * multiplier)
coeffs
clutterFilt(float src, float threshold)=>
bool out = math.abs(ta.roc(src, 1)) > threshold
out
stdFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("HAB Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(14, "Period", group = "Basic Settings")
type = input.int(4, "Alpha", minval = 2, step = 2, maxval = 50, group = "Basic Settings")
sth = input.float(0.1, "Clutter Filter Threshold", group = "Basic Settings", step = 0.001)
lagr = input.int(0, "Lag Reduction Factor", group = "Basic Settings")
mult = input.int(1, "Multiplier", group = "Sinc Settings")
fcut = input.float(0.01, "Frequency Cutoff", maxval = 0.5, minval = 0, step = 0.01, group = "Sinc Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
showdeadzones = input.bool(false, "Show dead zones?", group= "UI Options")
filterop = input.string("Both", "Filter Options", options = ["Price", "STDCFNOPOCFIRF", "Both", "None"], group= "Filter Settings")
filter = input.float(0, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? stdFilter(src, filterperiod, filter) : src
coeffs = nOrderPowerOfCosineSinc(per, type, fcut, mult)
duelElementLagReducer(coeffs, lagr)
coeffsSum = array.sum(coeffs)
float dSum = 0
for k = 0 to array.size(coeffs) - 1
dSum += nz(src[k]) * array.get(coeffs, k)
out = coeffsSum != 0 ? dSum / coeffsSum : 0
out := filterop == "Both" or filterop == "FNOPOCSFIRF" and filter > 0 ? stdFilter(out, filterperiod, filter) : out
sig = nz(out[1])
filtTrend = clutterFilt(out, sth)
state = filtTrend ? (out > sig ? 1 : out < sig ? -1 : 0) : 0
pregoLong = state == 1
pregoShort =state == -1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
color colorout = na
colorout := filtTrend ? (state == 1 ? greencolor : state == -1 ? redcolor : showdeadzones ? color.gray : colorout[1]) : showdeadzones ? color.gray : colorout[1]
plot(out, "STDCFNOPOCFIRF", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "Filtered, N-Order Power-of-Cosine, Sinc FIR Filter [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Filtered, N-Order Power-of-Cosine, Sinc FIR Filter [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
All-in-One-BTFinancials | https://www.tradingview.com/script/vJsolal9-All-in-One-BTFinancials/ | balusen | https://www.tradingview.com/u/balusen/ | 35 | 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='All-in-One-BTFinancials', shorttitle='All-in-One-BTFinancials', overlay=true, max_boxes_count=20, format=format.price, precision=0)
_v = input.string("1.0.1", title="Version", options=["1.0.1"], group="Balusen", tooltip="MOhanOBChop")
sens = input.int(28, minval=1, title='MohanOBChop', group='Balusen', tooltip='MohanOBChop')
sens /= 100
//OB Colors
col_bullish = input.color(#5db49e, title="Bullish OB Border", inline="a", group="Order Block")
col_bullish_ob = input.color(color.new(#64C4AC, 90), title="Background", inline="a", group="Order Block")
col_bearish = input.color(#4760bb, title="Bearish OB Border", inline="b", group="Order Block")
col_bearish_ob = input.color(color.new(#506CD3, 90), title="Background", inline="b", group="Order Block")
// Alerts
buy_alert = input.bool(title='Buy Signal', defval=true, group='Alerts', tooltip='An alert will be sent when price goes below the top of a bullish order block.')
sell_alert = input.bool(title='Sell Signal', defval=true, group='Alerts', tooltip='An alert will be sent when price goes above the bottom of a bearish order block.')
// Delacring Variables
bool ob_created = false
bool ob_created_bull = false
var int cross_index = na
// Declaring Box Arrays
var box drawlongBox = na
var longBoxes = array.new_box()
var box drawShortBox = na
var shortBoxes = array.new_box()
// Custom Rate of Change (ROC) calculation. This is to calculate high momentum moves in the market.
pc = (open - open[4]) / open[4] * 100
// If the ROC crossover our Sensitivty input - Then create an Order Block
// Sensitivty is negative as this is a Bearish OB
if ta.crossunder(pc, -sens)
ob_created := true
cross_index := bar_index
cross_index
// If the ROC crossover our Sensitivty input - Then create an Order Block
if ta.crossover(pc, sens)
ob_created_bull := true
cross_index := bar_index
cross_index
// -------------------------------
// Bearish OB Creation
// -------------------------------
// Check if we should create a OB, Also check if we haven't created an OB in the last 5 candles.
if ob_created and cross_index - cross_index[1] > 5
float last_green = 0
float highest = 0
// Loop through the most recent candles and find the first GREEN (Bullish) candle. We will place our OB here.
for i = 4 to 15 by 1
if close[i] > open[i]
last_green := i
break
// Draw our OB on that candle - then push the box into our box arrays.
drawShortBox := box.new(left=bar_index[last_green], top=high[last_green], bottom=low[last_green], right=bar_index[last_green], bgcolor=col_bearish_ob, border_color=col_bearish, border_width=0, extend=extend.right)
array.push(shortBoxes, drawShortBox)
alert("Resistance OB Created - SELL NOW")
// -------------------------------
// Bullish OB Creation
// -------------------------------
// Check if we should create a OB, Also check if we haven't created an OB in the last 5 candles.
if ob_created_bull and cross_index - cross_index[1] > 5
float last_red = 0
float highest = 0
// Loop through the most recent candles and find the first RED (Bearish) candle. We will place our OB here.
for i = 4 to 15 by 1
if close[i] < open[i]
last_red := i
break
// Draw our OB on that candle - then push the box into our box arrays.
drawlongBox := box.new(left=bar_index[last_red], top=high[last_red], bottom=low[last_red], right=bar_index[last_red], bgcolor=col_bullish_ob, border_color=col_bullish, border_width=0, extend=extend.right)
array.push(longBoxes, drawlongBox)
alert("Support OB Created - BUY NOW")
// ----------------- Bearish Order Block -------------------
// Clean up OB boxes and place alerts
if array.size(shortBoxes) > 0
for i = array.size(shortBoxes) - 1 to 0 by 1
sbox = array.get(shortBoxes, i)
top = box.get_top(sbox)
bot = box.get_bottom(sbox)
// If the two last closes are above the high of the bearish OB - Remove the OB
if close[1] > top and close[2] > top
array.remove(shortBoxes, i)
box.delete(sbox)
// Alerts
if high > bot and sell_alert
alert('Price inside Resistance OB BOX', alert.freq_once_per_bar)
// ----------------- Bullish Clean Up -------------------
// Clean up OB boxes and place alerts
if array.size(longBoxes) > 0
for i = array.size(longBoxes) - 1 to 0 by 1
sbox = array.get(longBoxes, i)
bot = box.get_bottom(sbox)
top = box.get_top(sbox)
// If the two last closes are below the low of the bullish OB - Remove the OB
if close[1] < bot and close[2] < bot
array.remove(longBoxes, i)
box.delete(sbox)
// Alerts
if low < top and buy_alert
alert('Price inside SUPPORT OB BOX', alert.freq_once_per_bar)
// CPR START
pivottimeframe = input.timeframe(title="Pivot Resolution", defval="D", options=["D", "W", "M"])
dp = input(true, title="Display Floor Pivots")
cp = input(true, title="Display Camarilla Pivots")
hl = input(true, title="Display M, W, D Highs/Lows")
tp = input(false, title="Display Tomorrow Pivots")
//dp in the prefix implies daily pivot calculation
dpopen = request.security(syminfo.tickerid, pivottimeframe, open[1], barmerge.gaps_off, barmerge.lookahead_on)
dphigh = request.security(syminfo.tickerid, pivottimeframe, high[1], barmerge.gaps_off, barmerge.lookahead_on)
dplow = request.security(syminfo.tickerid, pivottimeframe, low[1], barmerge.gaps_off, barmerge.lookahead_on)
dpclose = request.security(syminfo.tickerid, pivottimeframe, close[1], barmerge.gaps_off, barmerge.lookahead_on)
dprange = dphigh - dplow
//Expanded Floor Pivots Formula
pivot = (dphigh + dplow + dpclose) / 3.0
bc = (dphigh + dplow) / 2.0
tc = pivot - bc + pivot
r1 = pivot * 2 - dplow
r2 = pivot + dphigh - dplow
r3 = r1 + dphigh - dplow
r4 = r3 + r2 - r1
s1 = pivot * 2 - dphigh
s2 = pivot - (dphigh - dplow)
s3 = s1 - (dphigh - dplow)
s4 = s3 - (s1 - s2)
//Expanded Camarilla Pivots Formula
h1 = dpclose + dprange * (1.1 / 12)
h2 = dpclose + dprange * (1.1 / 6)
h3 = dpclose + dprange * (1.1 / 4)
h4 = dpclose + dprange * (1.1 / 2)
h5 = dphigh / dplow * dpclose
l1 = dpclose - dprange * (1.1 / 12)
l2 = dpclose - dprange * (1.1 / 6)
l3 = dpclose - dprange * (1.1 / 4)
l4 = dpclose - dprange * (1.1 / 2)
l5 = dpclose - (h5 - dpclose)
// AUTO FIBONACCI start
devTooltip = "Deviation is a multiplier that affects how much the price should deviate from the previous pivot in order for the bar to become a new pivot."
depthTooltip = "The minimum number of bars that will be taken into account when calculating the indicator."
// pivots threshold
threshold_multiplier = input.float(title="Deviation", defval=2.5, minval=0, tooltip=devTooltip)
dev_threshold = ta.atr(10) / close * 100 * threshold_multiplier
depth = input.int(title="Depth", defval=100, minval=1, tooltip=depthTooltip)
deleteLastLine = input.bool(title="Delete Last Line", defval=false)
bgcolorChange = input.bool(title="Change BgColor", defval=false)
reverse = input(false, "Reverse")
var extendLeft = input(false, "Extend Left | Extend Right", inline = "Extend Lines")
var extendRight = input(true, "", inline = "Extend Lines")
var extending = extend.none
if extendLeft and extendRight
extending := extend.both
if extendLeft and not extendRight
extending := extend.left
if not extendLeft and extendRight
extending := extend.right
prices = input(true, "Show Prices")
levels = input(true, "Show Levels", inline = "Levels")
levelsFormat = input.string("Values", "", options = ["Values", "Percent"], inline = "Levels")
labelsPosition = input.string("Right", "Labels Position", options = ["Left", "Right"])
var int bg = input.int(100, "bg", minval = 0, maxval = 100)
var line lineLast = na
var int iLast = 0
var int iPrev = 0
var float pLast = 0
var isHighLast = false // otherwise the last pivot is a low pivot
pivots(src, length, isHigh) =>
l2 = length * 2
c = nz(src[length])
ok = true
for i = 0 to l2
if isHigh and src[i] > c
ok := false
if not isHigh and src[i] < c
ok := false
if ok
[bar_index[length], c]
else
[int(na), float(na)]
[iH, pH] = pivots(high, depth / 2, true)
[iL, pL] = pivots(low, depth / 2, false)
calc_dev(base_price, price) =>
100 * (price - base_price) / price
pivotFound(dev, isHigh, index, price) =>
if isHighLast == isHigh and not na(lineLast)
// same direction
if isHighLast ? price > pLast : price < pLast
line.set_xy2(lineLast, index, price)
[lineLast, isHighLast]
else
[line(na), bool(na)]
else // reverse the direction (or create the very first line)
if math.abs(dev) > dev_threshold
// price move is significant
id = line.new(iLast, pLast, index, price, color=color.gray, width=1, style=line.style_dashed)
[id, isHigh]
else
[line(na), bool(na)]
if not na(iH)
dev = calc_dev(pLast, pH)
[id, isHigh] = pivotFound(dev, true, iH, pH)
if not na(id)
if id != lineLast
line.delete(lineLast)
lineLast := id
isHighLast := isHigh
iPrev := iLast
iLast := iH
pLast := pH
else
if not na(iL)
dev = calc_dev(pLast, pL)
[id, isHigh] = pivotFound(dev, false, iL, pL)
if not na(id)
if id != lineLast and deleteLastLine
line.delete(lineLast)
lineLast := id
isHighLast := isHigh
iPrev := iLast
iLast := iL
pLast := pL
_draw_line(price, col) =>
var id = line.new(iLast, price, bar_index, price, color=col, width=1, extend=extend.right)
if not na(lineLast)
line.set_xy1(id, line.get_x1(lineLast), price)
line.set_xy2(id, line.get_x2(lineLast), price)
id
_draw_label(price, txt, txtColor) =>
x = labelsPosition == "Left" ? line.get_x1(lineLast) : not extendRight ? line.get_x2(lineLast) : bar_index
labelStyle = labelsPosition == "Left" ? label.style_label_right : label.style_label_left
align = labelsPosition == "Left" ? text.align_right : text.align_left
labelsAlignStrLeft = txt + '\n \n'
labelsAlignStrRight = ' ' + txt + '\n \n'
labelsAlignStr = labelsPosition == "Left" ? labelsAlignStrLeft : labelsAlignStrRight
var id = label.new(x=x, y=price, text=labelsAlignStr, textcolor=txtColor, style=labelStyle, textalign=align, color=#00000000)
label.set_xy(id, x, price)
label.set_text(id, labelsAlignStr)
label.set_textcolor(id, txtColor)
_wrap(txt) =>
"(" + str.tostring(txt, format.mintick) + ")"
_label_txt(level, price) =>
l = levelsFormat == "Values" ? str.tostring(level) : str.tostring(level * 100) + "%"
(levels ? l : "") + (prices ? _wrap(price) : "")
_crossing_level(sr, r) =>
(r > sr and r < sr[1]) or (r < sr and r > sr[1])
startPrice = reverse ? line.get_y1(lineLast) : pLast
endPrice = reverse ? pLast : line.get_y1(lineLast)
iHL = startPrice > endPrice
diff = (iHL ? -1 : 1) * math.abs(startPrice - endPrice)
processLevel(show, value, colorL, lineIdOther) =>
float m = value
r = startPrice + diff * m
if show
lineId = _draw_line(r, colorL)
_draw_label(r, _label_txt(m, r), colorL)
if _crossing_level(close, r)
alert("Autofib: " + syminfo.ticker + " crossing level " + str.tostring(value),alert.freq_once_per_bar_close)
if not na(lineIdOther)
//linefill.new(lineId, lineIdOther, color = color.new(colorL, bg))
linefill.new(lineId, lineIdOther, color = color.new(colorL, 100))
lineId
else
lineIdOther
show_0 = input(true, "", inline = "Level0")
value_0 = input(0, "", inline = "Level0")
color_0 = input(#787b86, "", inline = "Level0")
show_0_236 = input(true, "", inline = "Level0")
value_0_236 = input(0.236, "", inline = "Level0")
color_0_236 = input(#f44336, "", inline = "Level0")
show_0_382 = input(true, "", inline = "Level1")
value_0_382 = input(0.382, "", inline = "Level1")
color_0_382 = input(#81c784, "", inline = "Level1")
show_0_5 = input(true, "", inline = "Level1")
value_0_5 = input(0.5, "", inline = "Level1")
color_0_5 = input(#4caf50, "", inline = "Level1")
show_0_618 = input(true, "", inline = "Level2")
value_0_618 = input(0.618, "", inline = "Level2")
color_0_618 = input(#009688, "", inline = "Level2")
show_0_65 = input(false, "", inline = "Level2")
value_0_65 = input(0.65, "", inline = "Level2")
color_0_65 = input(#009688, "", inline = "Level2")
show_0_786 = input(true, "", inline = "Level3")
value_0_786 = input(0.786, "", inline = "Level3")
color_0_786 = input(#64b5f6, "", inline = "Level3")
show_1 = input(true, "", inline = "Level3")
value_1 = input(1, "", inline = "Level3")
color_1 = input(#787b86, "", inline = "Level3")
show_1_272 = input(false, "", inline = "Level4")
value_1_272 = input(1.272, "", inline = "Level4")
color_1_272 = input(#81c784, "", inline = "Level4")
show_1_414 = input(false, "", inline = "Level4")
value_1_414 = input(1.414, "", inline = "Level4")
color_1_414 = input(#f44336, "", inline = "Level4")
show_1_618 = input(true, "", inline = "Level5")
value_1_618 = input(1.618, "", inline = "Level5")
color_1_618 = input(#2962ff, "", inline = "Level5")
show_1_65 = input(false, "", inline = "Level5")
value_1_65 = input(1.65, "", inline = "Level5")
color_1_65 = input(#2962ff, "", inline = "Level5")
show_2_618 = input(true, "", inline = "Level6")
value_2_618 = input(2.618, "", inline = "Level6")
color_2_618 = input(#f44336, "", inline = "Level6")
show_2_65 = input(false, "", inline = "Level6")
value_2_65 = input(2.65, "", inline = "Level6")
color_2_65 = input(#f44336, "", inline = "Level6")
show_3_618 = input(true, "", inline = "Level7")
value_3_618 = input(3.618, "", inline = "Level7")
color_3_618 = input(#9c27b0, "", inline = "Level7")
show_3_65 = input(false, "", inline = "Level7")
value_3_65 = input(3.65, "", inline = "Level7")
color_3_65 = input(#9c27b0, "", inline = "Level7")
show_4_236 = input(true, "", inline = "Level8")
value_4_236 = input(4.236, "", inline = "Level8")
color_4_236 = input(#e91e63, "", inline = "Level8")
show_4_618 = input(false, "", inline = "Level8")
value_4_618 = input(4.618, "", inline = "Level8")
color_4_618 = input(#81c784, "", inline = "Level8")
show_neg_0_236 = input(false, "", inline = "Level9")
value_neg_0_236 = input(-0.236, "", inline = "Level9")
color_neg_0_236 = input(#f44336, "", inline = "Level9")
show_neg_0_382 = input(false, "", inline = "Level9")
value_neg_0_382 = input(-0.382, "", inline = "Level9")
color_neg_0_382 = input(#81c784, "", inline = "Level9")
show_neg_0_618 = input(false, "", inline = "Level10")
value_neg_0_618 = input(-0.618, "", inline = "Level10")
color_neg_0_618 = input(#009688, "", inline = "Level10")
show_neg_0_65 = input(false, "", inline = "Level10")
value_neg_0_65 = input(-0.65, "", inline = "Level10")
color_neg_0_65 = input(#009688, "", inline = "Level10")
lineId0 = processLevel(show_neg_0_65, value_neg_0_65, color_neg_0_65, line(na))
lineId1 = processLevel(show_neg_0_618, value_neg_0_618, color_neg_0_618, lineId0)
lineId2 = processLevel(show_neg_0_382, value_neg_0_382, color_neg_0_382, lineId1)
lineId3 = processLevel(show_neg_0_236, value_neg_0_236, color_neg_0_236, lineId2)
lineId4 = processLevel(show_0, value_0, color_0, lineId3)
lineId5 = processLevel(show_0_236, value_0_236, color_0_236, lineId4)
lineId6 = processLevel(show_0_382, value_0_382, color_0_382, lineId5)
lineId7 = processLevel(show_0_5, value_0_5, color_0_5, lineId6)
lineId8 = processLevel(show_0_618, value_0_618, color_0_618, lineId7)
lineId9 = processLevel(show_0_65, value_0_65, color_0_65, lineId8)
lineId10 = processLevel(show_0_786, value_0_786, color_0_786, lineId9)
lineId11 = processLevel(show_1, value_1, color_1, lineId10)
lineId12 = processLevel(show_1_272, value_1_272, color_1_272, lineId11)
lineId13 = processLevel(show_1_414, value_1_414, color_1_414, lineId12)
lineId14 = processLevel(show_1_618, value_1_618, color_1_618, lineId13)
lineId15 = processLevel(show_1_65, value_1_65, color_1_65, lineId14)
lineId16 = processLevel(show_2_618, value_2_618, color_2_618, lineId15)
lineId17 = processLevel(show_2_65, value_2_65, color_2_65, lineId16)
lineId18 = processLevel(show_3_618, value_3_618, color_3_618, lineId17)
lineId19 = processLevel(show_3_65, value_3_65, color_3_65, lineId18)
lineId20 = processLevel(show_4_236, value_4_236, color_4_236, lineId19)
lineId21 = processLevel(show_4_618, value_4_618, color_4_618, lineId20)
//AUTO IMPULSIVE MOVE - SUPPORT and RESISTANCE
// Get starting and ending high/low price of the current pivot line
//bgcolorChange = input.bool(title="Change BgColor", defval=false)
startIndex = line.get_x1(lineLast)
startPrice := line.get_y1(lineLast)
endIndex = line.get_x2(lineLast)
endPrice := line.get_y2(lineLast)
// Draw top & bottom of impulsive move
plot(startPrice, color=color.green)
plot(endPrice, color=color.red)
shortest = ta.ema(close, 8)
short = ta.ema(close, 16)
longer = ta.ema(close, 100)
longest = ta.ema(close, 200)
longCond = ta.crossover(shortest, short)
shortCond = ta.crossunder(shortest, short)
//longCond = ta.crossover(shortest, short) and (short > longer) and (longer > longest)
//shortCond = ta.crossunder(shortest, short) and (short < longer) and (longer < longest)
plotshape(series=longCond, title="Long", style=shape.triangleup, location=location.belowbar, color=#43A047, text="", size=size.small)
plotshape(series=shortCond, title="Short", style=shape.triangledown, location=location.abovebar, color=#e91e1e, text="", size=size.small)
// Do what you like with these pivot values :)
// Keep in mind there will be an X bar delay between pivot price values updating based on Depth setting
//dist = math.abs(startPrice - endPrice)
//plot(dist, color=color.new(color.purple,100))
//bullish = endPrice > startPrice
//offsetBG = -(impulsiveDepth / 2)
//bgcolor(bgcolorChange ? bullish ? color.new(color.green,90) : color.new(color.red,90) : na, offset=offsetBG)
//AUTO PIVOT - SUPPORT and RESISTANCE END
//AUTO FIBONACCI end |
PipMotionFX | https://www.tradingview.com/script/1UTb09vS-PipMotionFX/ | UnknownUnicorn16954350 | https://www.tradingview.com/u/UnknownUnicorn16954350/ | 2 | 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/
// © PipMotionFX
//@version=4
study(title = "PipMotionFX", overlay = true)
//text inputs
title = input("PipMotionFX", "Tittle", group = "text")
subtitle= input("PATIENCE | DISCIPLINE | FEARLESS", "Subtitle", group = "text")
//symbol info
symInfoCheck = input(title="Show Symbol Info", type=input.bool, defval=true, group = "watermark position")
symInfo= syminfo.ticker + " | " + timeframe.period + (timeframe.isminutes ? "M" : na)
date = tostring(dayofmonth(time_close)) + "/" + tostring(month(time_close)) + "/" + tostring(year(time_close))
//text positioning
textVPosition = input("top", "Vertical Position", options = ["top", "middle", "bottom"], group = "watermark position")
textHPosition = input("center", "Horizontal Position", options = ["left", "center", "right"], group = "watermark position")
//symbol info positioning
symVPosition = input("bottom", "Vertical Position", options = ["top", "middle", "bottom"], group = "symbol position")
symHPosition = input("center", "Horizontal Position", options = ["left", "center", "right"], group = "symbol position")
//cell size
width = input(0, "Width", minval = 0, maxval = 100, tooltip="The width of the cell as a % of the indicator's visual space. Optional. By default, auto-adjusts the width based on the text inside the cell. Value 0 has the same effect.", group = "cell size")
height = input(0, "Height", minval = 0, maxval = 100, tooltip="The height of the cell as a % of the indicator's visual space. Optional. By default, auto-adjusts the height based on the text inside of the cell. Value 0 has the same effect.", group = "cell size")
//title settings
c_title = input(color.new(color.yellow, 0), "Title Color", group = "title settings")
s_title = input("large", "Title Size", options = ["tiny", "small", "normal", "large", "huge", "auto"], group = "title settings")
a_title = input("center","Title Alignment", options = ["center","left", "right"], group = "title settings")
//subtitle settings
c_subtitle = input(color.new(color.white, 30), "Subitle Color", group = "subtitle settings")
s_subtitle = input("normal", "Subtitle Size", options = ["tiny", "small", "normal", "large", "huge", "auto"], group = "subtitle settings")
a_subtitle = input("center","Subtitle Alignment", options = ["center","left", "right"], group = "subtitle settings")
//symbol settings
c_symInfo = input(color.new(color.black, 30), "Subitle Color", group = "symbol settings")
s_symInfo = input("normal", "Subtitle Size", options = ["tiny", "small", "normal", "large", "huge", "auto"], group = "symbol settings")
a_symInfo = input("center","Subtitle Alignment", options = ["center","left", "right"], group = "symbol settings")
c_bg = input(color.new(color.blue, 100), "Background", group = "background")
//text watermark creation
textWatermark = table.new(textVPosition + "_" + textHPosition, 1, 3)
table.cell(textWatermark, 0, 0, title, width, height, c_title, a_title, text_size = s_title, bgcolor = c_bg)
table.cell(textWatermark, 0, 1, subtitle, width, height, c_subtitle, a_subtitle, text_size = s_subtitle, bgcolor = c_bg)
//symbol info watermark creation
symWatermark = table.new(symVPosition + "_" + symHPosition, 5, 5)
if symInfoCheck == true
table.cell(symWatermark, 0, 1, symInfo, width, height, c_symInfo, a_symInfo, text_size = s_symInfo, bgcolor = c_bg)
table.cell(symWatermark,0, 0, date, width, height, c_symInfo, a_symInfo, text_size = s_symInfo, bgcolor = c_bg)
|
[EDU] Close Open Estimation Signals (COE Signals) | https://www.tradingview.com/script/WjKPyA19-edu-close-open-estimation-signals-coe-signals/ | tarasenko_ | https://www.tradingview.com/u/tarasenko_/ | 190 | 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/
// © tarasenko_
//@version=5
indicator("[EDU] Close Open Estimation Signals (COE Signals)", shorttitle = "[EDU] COE Signals", overlay = 1)
// Lookback
src_inp = input.string("EMA-smoothed", "Source", group = "COE Settings", options= ["EMA-smoothed", "Classic"], tooltip = "EMA-smoothed: using EMA to smooth source data in order to 'cleaner' data.\n\nClassic: using classic sum of close-open formula.")
p = input(12, "Lookback", group = "COE Settings")
mp = input(26, "Smoother period", group = "COE Settings")
p1 = input(9, "EMA period", group = "COE Settings")
// Declarations & Calculations
zco(p, mp) =>
z = 0.0
ma = ta.ema(open, p1)
for i = 1 to p
z += src_inp == "EMA-smoothed" ? ma - ma[1] : close[i] - open[i]
ta.ema(z, mp)
coe = zco(p, mp)
v_coe = ta.ema(coe - coe[1], mp) // COE's volatility
// Signal logic
v_coe_entry = ta.ema(v_coe - v_coe[1], mp)
v_coe_rev = ta.ema(v_coe_entry - v_coe_entry[1], mp) // Behaviour os this one when crossing 0 is very similar to getting derivatives of higher ranks from a function in math.
b_entry = ta.crossover(v_coe_entry, 0)
s_entry = ta.crossunder(v_coe_entry, 0)
rev = ta.cross(v_coe_rev, 0)
// Plottings
plotshape(b_entry, style = shape.labelup, location = location.belowbar, size = size.tiny, text = "Buy", textcolor = color.white, color = #009B00)
plotshape(s_entry, style = shape.labeldown, size = size.tiny, text = "Sell", textcolor = color.white, color = #CC0000) |
SuperTrend Support & Resistance | https://www.tradingview.com/script/FUlhSmg3-SuperTrend-Support-Resistance/ | VonnyFX | https://www.tradingview.com/u/VonnyFX/ | 337 | 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/
// © VonnyFX
//@version=5
indicator("SuperTrend Support & Resistance", "SuperTrend [S & R]", overlay=true, max_bars_back=5000, max_lines_count=500, max_labels_count=500)
import VonnyFX/VonnyPublicLibrary/1 as von
// User inputs
factor = input.float(0.99, "Factor", step = 0.05, group="Smart Momentum", inline="h")
atrPeriod = input.int(2, "ATR Period", step = 1, group="Smart Momentum", inline="h")
bar_DEXX = input.int(300,title="[BAR_INDEX]", group="Smart Momentum", inline="z")
highNLowPiv = input.bool(defval=false, title="[High & Low]", group="Smart Momentum", inline="z")
closePiv = input.bool(defval=false, title="[Close]", group="Smart Momentum", inline="z")
// Time Frame #1 Display Settings
TrendLabel = input.bool(true,"Trend or Basic", group="Time Frame #1 Display Inputs", inline="j")
noLabel = input.bool(false,"No Label", group="Time Frame #1 Display Inputs", inline="j")
highColor = input.color(#00ff99, "High Color", group="Time Frame #1 Display Inputs", inline="y")
lowColor = input.color(#a97809, "Low Color", group="Time Frame #1 Display Inputs", inline="y")
labelColor = input.color(color.white,"Label Color", group="Time Frame #1 Display Inputs", inline="y")
lineLengthLeft = input.int(5, "Line Length Left", group="Time Frame #1 Display Inputs", inline="x")
lineLengthRight = input.int(5, "Length Right", group="Time Frame #1 Display Inputs", inline="x")
lineWidth = input.int(2, "lineWidth", group="Time Frame #1 Display Inputs", inline="x")
lineStylex = input.string("Solid", title="| -----Line Style--|", options=["Solid","Dotted","Dashed"],group="Time Frame #1 Display Inputs", inline="x")
labelDistance = input.float(0.45, "Label Distance", step=0.05, group="Time Frame #1 Display Inputs", inline="x")
labelSizex = input.string("Small", title="|--Label Size|", options=["Tiny","Small","Normal","Large","Huge"],group="Time Frame #1 Display Inputs", inline="x")
labelBgSizex = input.string("Tiny", title="Label BackGround Size", options=["Tiny","Small","Normal","Large","Huge"],group="Time Frame #1 Display Inputs", inline="x")
labelBgColor = input.color(color.new(#000000,0),"BackGround Color", group="Time Frame #1 Display Inputs", inline="x")
// Time Frame #2 Display Settings
TrendLabel2 = input.bool(true,"Trend or Basic", group="Time Frame #2 Display Inputs", inline="j")
noLabel2 = input.bool(false,"No Label", group="Time Frame #2 Display Inputs", inline="j")
highColor2 = input.color(#22ad22, "High Color", group="Time Frame #2 Display Inputs", inline="y")
lowColor2 = input.color(#e10000, "Low Color", group="Time Frame #2 Display Inputs", inline="y")
labelColor2 = input.color(color.white,"Label Color", group="Time Frame #2 Display Inputs", inline="y")
lineLengthLeft2 = input.int(11, "Line Length Left", group="Time Frame #2 Display Inputs", inline="x")
lineLengthRight2 = input.int(11, "Length Right", group="Time Frame #2 Display Inputs", inline="x")
lineWidth2 = input.int(4, "lineWidth", group="Time Frame #2 Display Inputs", inline="x")
lineStylex2 = input.string("Solid", title="| -----Line Style--|", options=["Solid","Dotted","Dashed"],group="Time Frame #2 Display Inputs", inline="x")
labelDistance2 = input.float(0.51, "Label Distance", step=0.05, group="Time Frame #2 Display Inputs", inline="x")
labelSizex2 = input.string("Normal", title="|--Label Size|", options=["Tiny","Small","Normal","Large","Huge"],group="Time Frame #2 Display Inputs", inline="x")
labelBgSizex2 = input.string("Small", title="Label BackGround Size", options=["Tiny","Small","Normal","Large","Huge"],group="Time Frame #2 Display Inputs", inline="x")
labelBgColor2 = input.color(#000000,"BackGround Color", group="Time Frame #2 Display Inputs", inline="x")
// Time Frame #2 Display Settings
TrendLabel3 = input.bool(true,"Trend or Basic", group="Time Frame #3 Display Inputs", inline="j")
noLabel3 = input.bool(false,"No Label", group="Time Frame #3 Display Inputs", inline="j")
highColor3 = input.color(#ff1c69, "High Color", group="Time Frame #3 Display Inputs", inline="y")
lowColor3 = input.color(#9c27b0, "Low Color", group="Time Frame #3 Display Inputs", inline="y")
labelColor3 = input.color(color.white,"Label Color", group="Time Frame #3 Display Inputs", inline="y")
lineLengthLeft3 = input.int(20, "Line Length Left", group="Time Frame #3 Display Inputs", inline="x")
lineLengthRight3 = input.int(20, "Length Right", group="Time Frame #3 Display Inputs", inline="x")
lineWidth3 = input.int(6, "lineWidth", group="Time Frame #3 Display Inputs", inline="x")
lineStylex3 = input.string("Solid", title="| -----Line Style--|", options=["Solid","Dotted","Dashed"],group="Time Frame #3 Display Inputs", inline="x")
labelDistance3 = input.float(0.6, "Label Distance", step=0.05, group="Time Frame #3 Display Inputs", inline="x")
labelSizex3 = input.string("Large", title="|--Label Size|", options=["Tiny","Small","Normal","Large","Huge"],group="Time Frame #3 Display Inputs", inline="x")
labelBgSizex3 = input.string("Normal", title="Label BackGround Size", options=["Tiny","Small","Normal","Large","Huge"],group="Time Frame #3 Display Inputs", inline="x")
labelBgColor3 = input.color(#000000,"BackGround Color", group="Time Frame #3 Display Inputs", inline="x")
//Time Frame inputs
timeFrameAmount = input.int(1,title="Amount of Time Frames", tooltip="How much time frames to show", group="Higher Time Frame [S & R]", maxval=3, minval=0)
res = input.timeframe(title= "TimeFrame#1", defval="1", group="Higher Time Frame [S & R]")
res2 = input.timeframe(title= "TimeFrame#2", defval="3", group="Higher Time Frame [S & R]")
res3 = input.timeframe(title= "TimeFrame#3", defval="5", group="Higher Time Frame [S & R]")
chartPositionx = input.string(title="[Chart Position]",group="Trend Chart", defval="Middle Right",
options=["Top Right", "Top Center", "Top Left", "Middle Right", "Middle Center", "Middle Left", "Bottom Right", "Bottom Center", "Bottom Left"], inline="j")
chartSizex = input.string("Small", title="Chart Size", options=["Tiny","Small","Normal","Large","Huge"],group="Trend Chart", inline="j")
chartOn = input.bool(true,"Chart [On/Off]", group="Trend Chart", inline="j")
//get ATR
atr = ta.atr(20)
//chart size Dynamic Size input Setup
var chartSize = size.normal
if chartSizex == "Tiny"
chartSize := size.tiny
if chartSizex == "Small"
chartSize := size.small
if chartSizex == "Normal"
chartSize := size.normal
if chartSizex == "Large"
chartSize := size.large
if chartSizex == "Huge"
chartSize := size.huge
//Label size Dynamic Size input Setup
var labelSize = size.normal
if labelSizex == "Tiny"
labelSize := size.tiny
if labelSizex == "Small"
labelSize := size.small
if labelSizex == "Normal"
labelSize := size.normal
if labelSizex == "Large"
labelSize := size.large
if labelSizex == "Huge"
labelSize := size.huge
//222222222222222222222222222
var labelSize2 = size.normal
if labelSizex2 == "Tiny"
labelSize2 := size.tiny
if labelSizex2 == "Small"
labelSize2 := size.small
if labelSizex2 == "Normal"
labelSize2 := size.normal
if labelSizex2 == "Large"
labelSize2 := size.large
if labelSizex2 == "Huge"
labelSize2 := size.huge
//3333333333333333333333333333
var labelSize3 = size.normal
if labelSizex3 == "Tiny"
labelSize3 := size.tiny
if labelSizex3 == "Small"
labelSize3 := size.small
if labelSizex3 == "Normal"
labelSize3 := size.normal
if labelSizex3 == "Large"
labelSize3 := size.large
if labelSizex3 == "Huge"
labelSize3 := size.huge
//Label Dynamic Size input Setup
var labelBgSize = size.normal
if labelBgSizex == "Tiny"
labelBgSize := size.tiny
if labelBgSizex == "Small"
labelBgSize := size.small
if labelBgSizex == "Normal"
labelBgSize := size.normal
if labelBgSizex == "Large"
labelBgSize := size.large
if labelBgSizex == "Huge"
labelBgSize := size.huge
//22222222222222222222222222222
var labelBgSize2 = size.normal
if labelBgSizex2 == "Tiny"
labelBgSize2 := size.tiny
if labelBgSizex2 == "Small"
labelBgSize2 := size.small
if labelBgSizex2 == "Normal"
labelBgSize2 := size.normal
if labelBgSizex2 == "Large"
labelBgSize2 := size.large
if labelBgSizex2 == "Huge"
labelBgSize2 := size.huge
//333333333333333333333333333333
var labelBgSize3 = size.normal
if labelBgSizex3 == "Tiny"
labelBgSize3 := size.tiny
if labelBgSizex3 == "Small"
labelBgSize3 := size.small
if labelBgSizex3 == "Normal"
labelBgSize3 := size.normal
if labelBgSizex3 == "Large"
labelBgSize3 := size.large
if labelBgSizex3 == "Huge"
labelBgSize3 := size.huge
// Dynamic Style input setup
var lineStyle = line.style_solid
if lineStylex == "Solid"
lineStyle := line.style_solid
if lineStylex == "Dotted"
lineStyle := line.style_dotted
if lineStylex == "Dashed"
lineStyle := line.style_dashed
//2222222222222222222222222222222
var lineStyle2 = line.style_solid
if lineStylex2 == "Solid"
lineStyle2 := line.style_solid
if lineStylex2 == "Dotted"
lineStyle2 := line.style_dotted
if lineStylex2 == "Dashed"
lineStyle2 := line.style_dashed
//33333333333333333333333333333333
var lineStyle3 = line.style_solid
if lineStylex3 == "Solid"
lineStyle3 := line.style_solid
if lineStylex3 == "Dotted"
lineStyle3 := line.style_dotted
if lineStylex3 == "Dashed"
lineStyle3 := line.style_dashed
//Wait for candle to close before you show signal or change in realtime
closeRrealtime = true
barState = (closeRrealtime == true) ? barstate.isconfirmed : barstate.isrealtime
[htf_High, htf_Low, htf_Close, htf_Open] = request.security(syminfo.tickerid, res, [high[barState ? 0 : 1],low[barState ? 0 : 1], close[barState ? 0 : 1], open[barState ? 0 : 1]])
[htf_High2, htf_Low2, htf_Close2, htf_Open2] = request.security(syminfo.tickerid, res2, [high[barState ? 0 : 1],low[barState ? 0 : 1], close[barState ? 0 : 1], open[barState ? 0 : 1]])
[htf_High3, htf_Low3, htf_Close3, htf_Open3] = request.security(syminfo.tickerid, res3, [high[barState ? 0 : 1],low[barState ? 0 : 1], close[barState ? 0 : 1], open[barState ? 0 : 1]])
HTF_hRC = closePiv and not highNLowPiv ? htf_Close : htf_High
HTF_lRC = closePiv and not highNLowPiv ? htf_Close : htf_Low
HTF_hRO = closePiv and not highNLowPiv ? htf_Open : htf_High
HTF_lRO = closePiv and not highNLowPiv ? htf_Open : htf_Low
HTF_hRC2 = closePiv and not highNLowPiv ? htf_Close2 : htf_High2
HTF_lRC2 = closePiv and not highNLowPiv ? htf_Close2 : htf_Low2
HTF_hRO2 = closePiv and not highNLowPiv ? htf_Open2 : htf_High2
HTF_lRO2 = closePiv and not highNLowPiv ? htf_Open2 : htf_Low2
HTF_hRC3 = closePiv and not highNLowPiv ? htf_Close3 : htf_High3
HTF_lRC3 = closePiv and not highNLowPiv ? htf_Close3 : htf_Low3
HTF_hRO3 = closePiv and not highNLowPiv ? htf_Open3 : htf_High3
HTF_lRO3 = closePiv and not highNLowPiv ? htf_Open3 : htf_Low3
// To get around runtime issue
bar_DEX =(bar_index > bar_DEXX)
// Get SuperTrend Values
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
// Get Higher time Frame and insert SuperTrend
htfSuperTrend = barstate.isconfirmed ? request.security(syminfo.tickerid, res, supertrend[barState ? 0 : 1]) : na
htfSuperTrend2 = barstate.isconfirmed ? request.security(syminfo.tickerid, res2, supertrend[barState ? 0 : 1]) : na
htfSuperTrend3 = barstate.isconfirmed ? request.security(syminfo.tickerid, res3, supertrend[barState ? 0 : 1]) : na
// Entry signal
bullEC = von.EntryBull(htf_Close,htfSuperTrend)
bearEC = von.EntryBear(htf_Close,htfSuperTrend)
bullEC2 = von.EntryBull(htf_Close2,htfSuperTrend2)
bearEC2 = von.EntryBear(htf_Close2,htfSuperTrend2)
bullEC3 = von.EntryBull(htf_Close3,htfSuperTrend3)
bearEC3 = von.EntryBear(htf_Close3,htfSuperTrend3)
min3Bull = timeFrameAmount < 3 ? true : ta.barssince(bullEC3) > 4
min3Bear = timeFrameAmount < 3 ? true : ta.barssince(bearEC3) > 4
// get lookback
lookBack = von.lookBack(bullEC, bearEC)
lookBack2 = von.lookBack(bullEC2, bearEC2)
lookBack3 = von.lookBack(bullEC3, bearEC3)
//Detect pivots
highPiv = von.HighestPivot(bullEC, bearEC, bar_DEX, htf_High, htf_High)
highPivClose = von.HighestPivot(bullEC, bearEC, bar_DEX, htf_Close, htf_Open)
lowPiv = von.LowestPivot(bullEC, bearEC, bar_DEX, htf_Low, htf_Low)
lowPivClose = von.LowestPivot(bullEC, bearEC, bar_DEX, htf_Close, htf_Open)
highPiv2 = von.HighestPivot(bullEC2, bearEC2, bar_DEX, htf_High2, htf_High2)
highPivClose2 = von.HighestPivot(bullEC2, bearEC2, bar_DEX, htf_Close2, htf_Open2)
lowPiv2 = von.LowestPivot(bullEC2, bearEC2, bar_DEX, htf_Low2, htf_Low2)
lowPivClose2 = von.LowestPivot(bullEC2, bearEC2, bar_DEX, htf_Close2, htf_Open2)
highPiv3 = von.HighestPivot(bullEC3, bearEC3, bar_DEX, htf_High3, htf_High3)
highPivClose3 = von.HighestPivot(bullEC3, bearEC3, bar_DEX, htf_Close3, htf_Open3)
lowPiv3 = von.LowestPivot(bullEC3, bearEC3, bar_DEX, htf_Low3, htf_Low3)
lowPivClose3 = von.LowestPivot(bullEC3, bearEC3, bar_DEX, htf_Close3, htf_Open3)
myPivotHigh = closePiv == true and highNLowPiv != true ? highPivClose : highPiv
myPivotLow = closePiv == true and highNLowPiv != true ? lowPivClose : lowPiv
myPivotHigh2 = closePiv == true and highNLowPiv != true ? highPivClose2 : highPiv2
myPivotLow2= closePiv == true and highNLowPiv != true ? lowPivClose2 : lowPiv2
myPivotHigh3 = closePiv == true and highNLowPiv != true ? highPivClose3 : highPiv3
myPivotLow3 = closePiv == true and highNLowPiv != true ? lowPivClose3 : lowPiv3
// Create an array for the last 2 low levels
var l_ = array.new_float(2)
if bullEC
array.push(l_,lowPiv)
array.remove(l_,0)
low0 = math.round(array.get(l_,0),5)
low1 = math.round(array.get(l_,1),5)
//222222222222222222222222222
var l_2 = array.new_float(2)
if bullEC2
array.push(l_2,lowPiv2)
array.remove(l_2,0)
low02 = math.round(array.get(l_2,0),5)
low12 = math.round(array.get(l_2,1),5)
//33333333333333333333333333
var l_3 = array.new_float(2)
if bullEC3
array.push(l_3,lowPiv3)
array.remove(l_3,0)
low03 = math.round(array.get(l_3,0),5)
low13 = math.round(array.get(l_3,1),5)
////////////////////////////
// Create an array for the last 2 low levels
var l_Close = array.new_float(2)
if bullEC
array.push(l_Close,lowPivClose)
array.remove(l_Close,0)
lowClose0 = math.round(array.get(l_Close,0),5)
lowClose1 = math.round(array.get(l_Close,1),5)
//222222222222222222222222222
var l_Close2 = array.new_float(2)
if bullEC2
array.push(l_Close2,lowPivClose2)
array.remove(l_Close2,0)
lowClose02 = math.round(array.get(l_Close2,0),5)
lowClose12 = math.round(array.get(l_Close2,1),5)
//33333333333333333333333333
var l_Close3 = array.new_float(2)
if bullEC3
array.push(l_Close3,lowPivClose3)
array.remove(l_Close3,0)
lowClose03 = math.round(array.get(l_Close3,0),5)
lowClose13 = math.round(array.get(l_Close3,1),5)
////////////////////////////
// Create Labels based on Array and basic LL and HL Trend detection
lowType = low1 < low0 ? "LL" : "HL"
lowCloseType = lowClose1 < lowClose0 ? "LL" : "HL"
lowNCloseType = lowClose1 < low0 ? "LL" : "HL"
lowMultiPiv = closePiv == true and highNLowPiv != true ? lowCloseType : closePiv == false and highNLowPiv == true ? lowType : lowNCloseType
lowLabelColor= lowMultiPiv == "LL" ? lowColor : highColor
labelColorL = TrendLabel ? lowLabelColor : labelColor
//2222222222222222222222222222
lowType2 = low12 < low02 ? "LL" : "HL"
lowCloseType2 = lowClose12 < lowClose02 ? "LL" : "HL"
lowNCloseType2 = lowClose12 < low02 ? "LL" : "HL"
lowMultiPiv2 = closePiv == true and highNLowPiv != true ? lowCloseType2 : closePiv == false and highNLowPiv == true ? lowType2 : lowNCloseType2
lowLabelColor2= lowMultiPiv2 == "LL" ? lowColor2 : highColor2
labelColorL2 = TrendLabel2 ? lowLabelColor2 : labelColor2
//333333333333333333333333333
lowType3 = low13 < low03 ? "LL" : "HL"
lowCloseType3 = lowClose13 < lowClose03 ? "LL" : "HL"
lowNCloseType3 = lowClose13 < low03 ? "LL" : "HL"
lowMultiPiv3 = closePiv == true and highNLowPiv != true ? lowCloseType3 : closePiv == false and highNLowPiv == true ? lowType3 : lowNCloseType3
lowLabelColor3= lowMultiPiv3 == "LL" ? lowColor3 : highColor3
labelColorL3 = TrendLabel3 ? lowLabelColor3 : labelColor3
// Create an array for the last 2 high levels
var h_ = array.new_float(2)
if bearEC
array.push(h_,highPiv)
array.remove(h_,0)
high0 = math.round(array.get(h_,0),5)
high1 = math.round(array.get(h_,1),5)
//222222222222222222222222
var h_2 = array.new_float(2)
if bearEC2
array.push(h_2,highPiv2)
array.remove(h_2,0)
high02 = math.round(array.get(h_2,0),5)
high12 = math.round(array.get(h_2,1),5)
//33333333333333333333333
var h_3 = array.new_float(2)
if bearEC3
array.push(h_3,highPiv3)
array.remove(h_3,0)
high03 = math.round(array.get(h_3,0),5)
high13 = math.round(array.get(h_3,1),5)
////////////////////////////
// Create an array for the last 2 highest close levels
var h_Close = array.new_float(2)
if bearEC
array.push(h_Close,highPivClose)
array.remove(h_Close,0)
highClose0 = math.round(array.get(h_Close,0),5)
highClose1 = math.round(array.get(h_Close,1),5)
//222222222222222222222222
var h_Close2 = array.new_float(2)
if bearEC2
array.push(h_Close2,highPivClose2)
array.remove(h_Close2,0)
highClose02 = math.round(array.get(h_Close2,0),5)
highClose12 = math.round(array.get(h_Close2,1),5)
//33333333333333333333333
var h_Close3 = array.new_float(2)
if bearEC3
array.push(h_Close3,highPivClose3)
array.remove(h_Close3,0)
highClose03 = math.round(array.get(h_Close3,0),5)
highClose13 = math.round(array.get(h_Close3,1),5)
////////////////////////////
// Create Labels based on Array and basic HH and LH Trend detection
highType = high1 > high0 ? "HH" : "LH"
highCloseType = highClose1 > highClose0 ? "HH" : "LH"
highNCloseType = highClose1 > high0 ? "HH" : "LH"
highMultiPiv = highNLowPiv and not closePiv ? highType : closePiv and not highNLowPiv ? highCloseType : highNCloseType
highLabelColor = highMultiPiv == "HH" ? highColor: lowColor
labelColorH = TrendLabel ? highLabelColor : labelColor
//22222222222222222222222
highType2 = high12 > high02 ? "HH" : "LH"
highCloseType2 = highClose12 > highClose02 ? "HH" : "LH"
highNCloseType2 = highClose12 > high02 ? "HH" : "LH"
highMultiPiv2 = highNLowPiv and not closePiv ? highType2 : closePiv and not highNLowPiv ? highCloseType2 : highNCloseType2
highLabelColor2 = highMultiPiv2 == "HH" ? highColor2: lowColor2
labelColorH2 = TrendLabel2 ? highLabelColor2 : labelColor2
//33333333333333333333333
highType3 = high13 > high03 ? "HH" : "LH"
highCloseType3 = highClose13 > highClose03 ? "HH" : "LH"
highNCloseType3 = highClose13 > high03 ? "HH" : "LH"
highMultiPiv3 = highNLowPiv and not closePiv ? highType3 : closePiv and not highNLowPiv ? highCloseType3 : highNCloseType3
highLabelColor3 = highMultiPiv3 == "HH" ? highColor3: lowColor3
labelColorH3 = TrendLabel3 ? highLabelColor3 : labelColor3
// Create a point to refrence your High and Low lines
highCandle = bar_DEX ? (ta.highestbars(high,lookBack) * -1) : na
lowCandle = bar_DEX ? (ta.lowestbars(low,lookBack) * -1) : na
highCandle2 = bar_DEX ? (ta.highestbars(high,lookBack2) * -1) : na
lowCandle2 = bar_DEX ? (ta.lowestbars(low,lookBack2) * -1) : na
highCandle3 = bar_DEX ? (ta.highestbars(high,lookBack3) * -1) : na
lowCandle3 = bar_DEX ? (ta.lowestbars(low,lookBack3) * -1) : na
// Color for Time Frame Chart
var myTrendColor = color.white
if high1 > high0 or low1 > low0
myTrendColor := highColor
if high1 < high0 or low1 < low0
myTrendColor := lowColor
if htf_Close < low1
myTrendColor := lowColor
if htf_Close > high1
myTrendColor := highColor
///////////////////////////////
var myTrendColor2 = color.white
if high12 > high02 or low12 > low02
myTrendColor2 := highColor2
if low12 < low02 or high12 < high02
myTrendColor2 := lowColor2
if htf_Close2 < low12
myTrendColor2 := lowColor2
if htf_Close2 > high12
myTrendColor2 := highColor2
/////////////////////////////////
var myTrendColor3 = color.white
if high13 > high03 or low13 > low03
myTrendColor3 := highColor3
if low13 < low03 or high13 < high03
myTrendColor3 := lowColor3
if htf_Close3 < low13
myTrendColor3 := lowColor3
if htf_Close3 > high13
myTrendColor3 := highColor3
//plot lines using lowPiv and highPiv values
labelHighsB = bearEC and barstate.isconfirmed and not noLabel and timeFrameAmount >= 1 ? label.new(bar_index[highCandle], (myPivotHigh + (atr*labelDistance)), text = highMultiPiv, style=label.style_label_center, color=labelBgColor, textcolor= color.new(color.gray,100), size=labelBgSize) : na
labelLowsB = bullEC and barstate.isconfirmed and not noLabel and timeFrameAmount >= 1 ? label.new(bar_index[lowCandle], (myPivotLow - (atr*labelDistance)), text = lowMultiPiv, style=label.style_label_center, color=labelBgColor, textcolor= color.new(color.gray,100), size=labelBgSize) : na
labelHighs = bearEC and barstate.isconfirmed and not noLabel and timeFrameAmount >= 1 ? label.new(bar_index[highCandle], (myPivotHigh + (atr*labelDistance)), text = highMultiPiv, style=label.style_label_center, color=color.new(color.green,100), textcolor= labelColorH, size=labelSize) : na
labelLows = bullEC and barstate.isconfirmed and not noLabel and timeFrameAmount >= 1 ? label.new(bar_index[lowCandle], (myPivotLow - (atr*labelDistance)), text = lowMultiPiv, style=label.style_label_center, color=color.new(color.red,100) , textcolor= labelColorL, size=labelSize) : na
mylineLow = bullEC and barstate.isconfirmed and timeFrameAmount >= 1 ? line.new(x1=bar_index[lowCandle] + lineLengthRight, y1=myPivotLow, x2=bar_index[lowCandle] - lineLengthLeft, y2=myPivotLow, color=TrendLabel ? labelColorL: lowColor , width=lineWidth, style=lineStyle) : na
mylineHigh = bearEC and barstate.isconfirmed and timeFrameAmount >= 1 ? line.new(x1=bar_index[highCandle] + lineLengthRight, y1=myPivotHigh, x2=bar_index[highCandle] - lineLengthLeft, y2=myPivotHigh, color=TrendLabel ? labelColorH : highColor , width=lineWidth, style=lineStyle) : na
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
labelHighsB2 = bearEC2 and barstate.isconfirmed and not noLabel2 and timeFrameAmount >= 2 ? label.new(bar_index[highCandle2], (myPivotHigh2 + (atr*labelDistance2)), text = highMultiPiv2, style=label.style_label_center, color=labelBgColor2, textcolor= color.new(color.gray,100), size=labelBgSize2) : na
labelLowsB2 = bullEC2 and barstate.isconfirmed and not noLabel2 and timeFrameAmount >= 2 ? label.new(bar_index[lowCandle2], (myPivotLow2 - (atr*labelDistance2)), text = lowMultiPiv2, style=label.style_label_center, color=labelBgColor2, textcolor= color.new(color.gray,100), size=labelBgSize2) : na
labelHighs2 = bearEC2 and barstate.isconfirmed and not noLabel2 and timeFrameAmount >= 2 ? label.new(bar_index[highCandle2], (myPivotHigh2 + (atr*labelDistance2)), text = highMultiPiv2, style=label.style_label_center, color=color.new(color.green,100), textcolor= labelColorH2, size=labelSize2) : na
labelLows2 = bullEC2 and barstate.isconfirmed and not noLabel2 and timeFrameAmount >= 2 ? label.new(bar_index[lowCandle2], (myPivotLow2 - (atr*labelDistance2)), text = lowMultiPiv2, style=label.style_label_center, color=color.new(color.red,100) , textcolor= labelColorL2, size=labelSize2) : na
mylineLow2 = bullEC2 and barstate.isconfirmed and timeFrameAmount >= 2 ? line.new(x1=bar_index[lowCandle2] + lineLengthRight2, y1=myPivotLow2, x2=bar_index[lowCandle2] - lineLengthLeft2, y2=myPivotLow2, color= TrendLabel2 ? labelColorL2 : lowColor2, width=lineWidth2, style=lineStyle2) : na
mylineHigh2 = bearEC2 and barstate.isconfirmed and timeFrameAmount >= 2 ? line.new(x1=bar_index[highCandle2] + lineLengthRight2, y1=myPivotHigh2, x2=bar_index[highCandle2] - lineLengthLeft2, y2=myPivotHigh2, color=TrendLabel2 ? labelColorH2 : highColor2, width=lineWidth2, style=lineStyle2) : na
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
labelHighsB3 = bearEC3 and barstate.isconfirmed and not noLabel3 and timeFrameAmount >= 3 ? label.new(bar_index[highCandle3], (myPivotHigh3 + (atr*labelDistance3)), text = highMultiPiv3, style=label.style_label_center, color=labelBgColor3, textcolor= color.new(color.gray,100), size=labelBgSize3) : na
labelLowsB3 = bullEC3 and barstate.isconfirmed and not noLabel3 and timeFrameAmount >= 3 ? label.new(bar_index[lowCandle3], (myPivotLow3 - (atr*labelDistance3)), text = lowMultiPiv3, style=label.style_label_center, color=labelBgColor3, textcolor= color.new(color.gray,100), size=labelBgSize3) : na
labelHighs3 = bearEC3 and barstate.isconfirmed and not noLabel3 and timeFrameAmount >= 3 ? label.new(bar_index[highCandle3], (myPivotHigh3 + (atr*labelDistance3)), text = highMultiPiv3, style=label.style_label_center, color=color.new(color.green,100), textcolor= labelColorH3, size=labelSize3) : na
labelLows3 = bullEC3 and barstate.isconfirmed and not noLabel3 and timeFrameAmount >= 3 ? label.new(bar_index[lowCandle3], (myPivotLow3 - (atr*labelDistance3)), text = lowMultiPiv3, style=label.style_label_center, color=color.new(color.red,100) , textcolor= labelColorL3, size=labelSize3) : na
mylineLow3 = bullEC3 and barstate.isconfirmed and timeFrameAmount >= 3 ? line.new(x1=bar_index[lowCandle3] + lineLengthRight3, y1=myPivotLow3, x2=bar_index[lowCandle3] - lineLengthLeft3, y2=myPivotLow3, color= TrendLabel3 ? labelColorL3: lowColor3 , width=lineWidth3, style=lineStyle3) : na
mylineHigh3 = bearEC3 and barstate.isconfirmed and timeFrameAmount >= 3 ? line.new(x1=bar_index[highCandle3] + lineLengthRight3, y1=myPivotHigh3, x2=bar_index[highCandle3] - lineLengthLeft3, y2=myPivotHigh3, color= TrendLabel3 ? labelColorH3: highColor3 , width=lineWidth3, style=lineStyle3) : na
// Dynamic Table Position using user input string
var chartPosition = position.top_right
if chartPositionx == "Top Right"
chartPosition := position.top_right
if chartPositionx == "Top Center"
chartPosition := position.top_center
if chartPositionx == "Top Left"
chartPosition := position.top_left
if chartPositionx == "Middle Right"
chartPosition := position.middle_right
if chartPositionx == "Middle Center"
chartPosition := position.middle_center
if chartPositionx == "Middle Left"
chartPosition := position.middle_left
if chartPositionx == "Bottom Right"
chartPosition := position.bottom_right
if chartPositionx == "Bottom Center"
chartPosition := position.bottom_center
if chartPositionx == "Bottom Left"
chartPosition := position.bottom_left
//Prepare a table
var table myHTFTable = table.new(chartPosition, 3, 1, border_width=1)
//Draw table
if barstate.isconfirmed and chartOn and timeFrameAmount >= 1
table.cell(myHTFTable, column = 0, row = 0 ,text=res , text_size=chartSize, text_color=color.black,
bgcolor=myTrendColor )
if barstate.isconfirmed and chartOn and timeFrameAmount >= 2
table.cell(myHTFTable, column = 1, row = 0 ,text=res2 , text_size=chartSize, text_color=color.black,
bgcolor=myTrendColor2 )
if barstate.isconfirmed and chartOn and timeFrameAmount >= 3
table.cell(myHTFTable, column = 2, row = 0 ,text=res3 , text_size=chartSize, text_color=color.black,
bgcolor=myTrendColor3)
|
Moving Average Channel | https://www.tradingview.com/script/YEMY73tm-Moving-Average-Channel/ | viewer405 | https://www.tradingview.com/u/viewer405/ | 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/
// © viewer405
//@version=5
indicator("Moving Average Channel", shorttitle="MAC", overlay=true)
uLength = input.int(10, "Upper MAC Length", minval=1, step=1)
lLength = input.int(8, "Lower MAC Length", minval=1, step=1)
upper = ta.sma(high, uLength)
lower = ta.sma(low, lLength)
upperPlot = plot(upper, title="Upper MA Channel", color=color.green)
lowerPlot = plot(lower, title="Lower MA Channel", color=color.red)
fill(upperPlot, lowerPlot, color=color.new(color.blue, 95), title="MAC Ribbon") |
Fibonacci Ratios with Volatility(Weekly Time Frame.) | https://www.tradingview.com/script/Brp9bTXD-Fibonacci-Ratios-with-Volatility-Weekly-Time-Frame/ | DoctorDee75 | https://www.tradingview.com/u/DoctorDee75/ | 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/
// © pbghosh
//@version=5
indicator(title='Fibonacci Ratios with Volatility', shorttitle='WFibo', overlay=true, format=format.price, precision=2)
var totLn = 0.0
var totLnSqr = 0.0
var lnAvg = 0.0
var lnSqrAvg = 0.0
var variance = 0.0
var dailyVolatility = 0.0
var price = 0.0
var priceRange = 0.0
var r1Level = 0.0
var r2Level = 0.0
var r3Level = 0.0
var r4Level = 0.0
var r5Level = 0.0
var r6Level = 0.0
var r7Level = 0.0
var r8Level = 0.0
var r9Level = 0.0
var s1Level = 0.0
var s2Level = 0.0
var s3Level = 0.0
var s4Level = 0.0
var s5Level = 0.0
var s6Level = 0.0
var s7Level = 0.0
var s8Level = 0.0
var s9Level = 0.0
is_new_day() =>
d = dayofweek
na(d[1]) or d != d[1]
bars = ta.barssince(is_new_day())
o = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', open, lookahead=barmerge.lookahead_on), 0)
ph = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', high[1], lookahead=barmerge.lookahead_on), 0)
pl = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', low[1], lookahead=barmerge.lookahead_on), 0)
pc = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', close[1], lookahead=barmerge.lookahead_on), 0)
lowerTimeframe = timeframe.period == '1' or timeframe.period == '2' or timeframe.period == '3' or timeframe.period == '5' or timeframe.period == '10' or timeframe.period == '15' or timeframe.period == '30' or timeframe.period == '45' or timeframe.period == '60' or timeframe.period == '120' or timeframe.period == '240'
c1 = ta.valuewhen(bars == 0, o > ph or o < pl ? o : request.security(syminfo.tickerid, 'W', close[1], lookahead=barmerge.lookahead_on), 0)
c2 = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', close[2], lookahead=barmerge.lookahead_on), 0)
c3 = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', close[3], lookahead=barmerge.lookahead_on), 0)
c4 = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', close[4], lookahead=barmerge.lookahead_on), 0)
c5 = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', close[5], lookahead=barmerge.lookahead_on), 0)
c6 = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', close[6], lookahead=barmerge.lookahead_on), 0)
c7 = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', close[7], lookahead=barmerge.lookahead_on), 0)
c8 = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', close[8], lookahead=barmerge.lookahead_on), 0)
c9 = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', close[9], lookahead=barmerge.lookahead_on), 0)
c10 = ta.valuewhen(bars == 0, request.security(syminfo.tickerid, 'W', close[10], lookahead=barmerge.lookahead_on), 0)
calculateLN() =>
tot = 0.0
tot := math.log(c1 / c2) + math.log(c2 / c3) + math.log(c3 / c4) + math.log(c4 / c5) + math.log(c5 / c6) + math.log(c6 / c7) + math.log(c7 / c8) + math.log(c8 / c9) + math.log(c9 / c10)
tot
calculateLNSquare() =>
tot = 0.0
tot := math.pow(math.log(c1 / c2), 2) + math.pow(math.log(c2 / c3), 2) + math.pow(math.log(c3 / c4), 2) + math.pow(math.log(c4 / c5), 2) + math.pow(math.log(c5 / c6), 2) + math.pow(math.log(c6 / c7), 2) + math.pow(math.log(c7 / c8), 2) + math.pow(math.log(c8 / c9), 2) + math.pow(math.log(c9 / c10), 2)
tot
calculatePivot() =>
(ph + pl + pc) / 3
pivot = ta.valuewhen(bars == 0, calculatePivot(), 0)
totLn := ta.valuewhen(bars == 0, calculateLN(), 0)
totLnSqr := ta.valuewhen(bars == 0, calculateLNSquare(), 0)
lnAvg := ta.valuewhen(bars == 0, totLn / 9, 0)
lnSqrAvg := ta.valuewhen(bars == 0, totLnSqr / 9, 0)
variance := ta.valuewhen(bars == 0, lnSqrAvg - math.pow(lnAvg, 2), 0)
dailyVolatility := ta.valuewhen(bars == 0, math.sqrt(variance), 0)
price := ta.valuewhen(bars == 0, o > ph or o < pl ? o : c1, 0)
priceRange := ta.valuewhen(bars == 0, dailyVolatility * price, 0)
r1Level := priceRange * 0.236 + price
r2Level := priceRange * 0.382 + price
r3Level := priceRange * 0.500 + price
r4Level := priceRange * 0.618 + price
r5Level := priceRange * 0.786 + price
r6Level := priceRange * 1.000 + price
r7Level := priceRange * 1.236 + price
r8Level := priceRange * 1.618 + price
r9Level := priceRange * 2.000 + price
s1Level := price - priceRange * 0.236
s2Level := price - priceRange * 0.382
s3Level := price - priceRange * 0.500
s4Level := price - priceRange * 0.618
s5Level := price - priceRange * 0.786
s6Level := price - priceRange * 1.000
s7Level := price - priceRange * 1.236
s8Level := price - priceRange * 1.618
s9Level := price - priceRange * 2.000
plot(series=lowerTimeframe ? price : na, title='0%', color=pivot[1] != pivot and lowerTimeframe ? na : color.white, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? r1Level : na, title='23.6%', color=pivot[1] != pivot and lowerTimeframe ? na : color.green, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? r2Level : na, title='38.2%', color=pivot[1] != pivot and lowerTimeframe ? na : color.gray, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? r3Level : na, title='50%', color=pivot[1] != pivot and lowerTimeframe ? na : color.gray, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? r4Level : na, title='61.8%', color=pivot[1] != pivot and lowerTimeframe ? na : color.gray, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? r5Level : na, title='78.6%', color=pivot[1] != pivot and lowerTimeframe ? na : color.gray, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? r6Level : na, title='100%', color=pivot[1] != pivot and lowerTimeframe ? na : color.green, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? r7Level : na, title='123.6%', color=pivot[1] != pivot and lowerTimeframe ? na : color.green, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? r8Level : na, title='161.8%', color=pivot[1] != pivot and lowerTimeframe ? na : color.green, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? r9Level : na, title='200%', color=pivot[1] != pivot and lowerTimeframe ? na : color.green, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? s1Level : na, title='-23.6%', color=pivot[1] != pivot and lowerTimeframe ? na : color.red, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? s2Level : na, title='-38.2%', color=pivot[1] != pivot and lowerTimeframe ? na : color.gray, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? s3Level : na, title='-50%', color=pivot[1] != pivot and lowerTimeframe ? na : color.gray, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? s4Level : na, title='-61.8%', color=pivot[1] != pivot and lowerTimeframe ? na : color.gray, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? s5Level : na, title='-78.6%', color=pivot[1] != pivot and lowerTimeframe ? na : color.gray, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? s6Level : na, title='-100%', color=pivot[1] != pivot and lowerTimeframe ? na : color.red, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? s7Level : na, title='-123.6%', color=pivot[1] != pivot and lowerTimeframe ? na : color.red, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? s8Level : na, title='-161.8%', color=pivot[1] != pivot and lowerTimeframe ? na : color.red, style=plot.style_linebr, linewidth=1)
plot(series=lowerTimeframe ? s9Level : na, title='-200%', color=pivot[1] != pivot and lowerTimeframe ? na : color.red, style=plot.style_linebr, linewidth=1)
|
Squeeze Index [LuxAlgo] | https://www.tradingview.com/script/Et6YD2t4-Squeeze-Index-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,025 | 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("Squeeze Index [LuxAlgo]", "Squeeze Index [LuxAlgo]")
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
conv = input(50, 'Convergence Factor')
length = input(20)
src = input(close)
//Style
col_0 = input(#ffeb3b, 'Gradient'
, inline = 'inline0'
, group = 'Style')
col_1 = input(#ff5d00, ''
, inline = 'inline0'
, group = 'Style')
col_2 = input(#ff1100, ''
, inline = 'inline0'
, group = 'Style')
//-----------------------------------------------------------------------------}
//Squeeze index
//-----------------------------------------------------------------------------{
var max = 0.
var min = 0.
max := nz(math.max(src, max - (max - src) / conv), src)
min := nz(math.min(src, min + (src - min) / conv), src)
diff = math.log(max - min)
psi = -50 * ta.correlation(diff, bar_index, length) + 50
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
css1 = color.from_gradient(psi, 0, 80, col_0, col_1)
css2 = color.from_gradient(psi, 80, 100, css1, col_2)
plot_0 = plot(psi, 'PSI', psi > 80 ? na : css2)
plot(psi, 'Dots', psi > 80 ? css2 : na, style = plot.style_cross)
plot_1 = plot(80, display = display.none, editable = false)
fill(plot_0, plot_1, psi < 80 ? na : color.new(#ff1100, 80))
hline(80)
//-----------------------------------------------------------------------------} |
Softmax Normalized T3 Histogram [Loxx] | https://www.tradingview.com/script/iacIVBrJ-Softmax-Normalized-T3-Histogram-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 116 | 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/
// © loxx
//@version=5
indicator("Softmax Normalized T3 [Loxx]",
shorttitle="SNT3 [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
softmax(float src, int per)=>
float mean = ta.sma(src, per)
float dev = ta.stdev(src, per)
float zmean = (src - mean) / dev
float val = (1.0 - math.exp(-zmean)) / (1.0 + math.exp(-zmean))
val
_iT3(src, per, hot, clean)=>
a = hot
_c1 = -a * a * a
_c2 = 3 * a * a + 3 * a * a * a
_c3 = -6 * a * a - 3 * a - 3 * a * a * a
_c4 = 1 + 3 * a + a * a * a + 3 * a * a
alpha = 0.
if (clean == "T3 New")
alpha := 2.0 / (2.0 + (per - 1.0) / 2.0)
else
alpha := 2.0 / (1.0 + per)
_t30 = src, _t31 = src
_t32 = src, _t33 = src
_t34 = src, _t35 = src
_t30 := nz(_t30[1]) + alpha * (src - nz(_t30[1]))
_t31 := nz(_t31[1]) + alpha * (_t30 - nz(_t31[1]))
_t32 := nz(_t32[1]) + alpha * (_t31 - nz(_t32[1]))
_t33 := nz(_t33[1]) + alpha * (_t32 - nz(_t33[1]))
_t34 := nz(_t34[1]) + alpha * (_t33 - nz(_t34[1]))
_t35 := nz(_t35[1]) + alpha * (_t34 - nz(_t35[1]))
out =
_c1 * _t35 + _c2 * _t34 +
_c3 * _t33 + _c4 * _t32
out
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
T3Period = input.int(20, "Period", group= "Basic Settings")
t3hot = input.float(.7, "T3 Hot", group= "Basic Settings")
t3swt = input.string("T3 New", "T3 Type", options = ["T3 New", "T3 Original"], group = "Basic Settings")
normper = input.int(30, "Normalization Period")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
out = _iT3(src, T3Period, t3hot, t3swt)
out := softmax(out, normper)
sig = 0
colorout = out > sig ? greencolor : out < sig ? redcolor : color.gray
plot(out, "SNT3", color = colorout, linewidth = 2, style = plot.style_histogram)
plot(sig, "Mid", color = bar_index % 2 ? color.gray : na)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(out, sig)
goShort = ta.crossunder(out, sig)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title = "Long", message = "Softmax Normalized T3 [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Softmax Normalized T3 [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Range-Analysis | https://www.tradingview.com/script/fnAsUroK/ | mgruner | https://www.tradingview.com/u/mgruner/ | 61 | 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/
// © mgruner
// this script calculates the average range over the last x (default 10) days for different session types (currently 1st hour and regular trading session, but can be configured otherwise) for the current instrument
//@version=5
indicator("Range-Analysis", overlay=true)
InpFirstSessionShow = input.bool(defval=false, title="Show Session", inline="First")
InpFirstSession = input.session("0830-0930",title="First-Session times", inline="First")
InpFirstColor = input(title="First-session line", defval=color.green, inline="FirstLine")
InpFirstWidth = input.int(5,"Line width", inline="FirstLine")
InpFirstName = input("First Hour", title="First-Session Name", inline="FirstText")
InpFirstShowMax = input.bool(defval=true, title="Show Max-Values",inline="FirstText")
InpSecondSessionShow = input.bool(defval=false, title="Show Session", inline="Second")
InpSecondSession = input.session("0830-1500",title="Second-Session times", inline="Second")
InpSecondColor = input(title="Second-session line", defval=color.green, inline="SecondLine")
InpSecondWidth = input.int(5,"Line width", inline="SecondLine")
InpSecondName = input("Regular session",title="Second-Session Name", inline="SecondText")
InpSecondShowMax = input.bool(defval=false, title="Show Max-Values",inline="SecondText")
InpThirdSessionShow = input.bool(defval=false, title="Show Session", inline="Third")
InpThirdSession = input.session("1700-0830",title="Third-Session times", inline="Third")
InpThirdColor = input(title="Third-session line", defval=color.green, inline="ThirdLine")
InpThirdWidth = input.int(5,"Line width", inline="ThirdLine")
InpThirdName = input("Overnight session",title="Third-Session Name", inline="ThirdText")
InpThirdShowMax = input.bool(defval=false, title="Show Max-Values",inline="ThirdText")
InpFourthSessionShow = input.bool(defval=false, title="Show Session", inline="Fourth")
InpFourthSession = input.session("1701-1645",title="Fourth-Session times", inline="Fourth")
InpFourthColor = input(title="Fourth-session line", defval=color.green, inline="FourthLine")
InpFourthWidth = input.int(5,"Line width", inline="FourthLine")
InpFourthName = input("24 hours session",title="Fourth-Session Name", inline="FourthText")
InpFourthShowMax = input.bool(defval=false, title="Show Max-Values",inline="FourthText")
InpAvgDays = input.int(10, "Average-Days")
InpLabelOffset = input.int(title="Label-Offset", defval=20, inline="Label")
InpLabelText = input.color(defval=color.white,title="Label-Text", inline="Label")
InpLabelBackground = input.color(defval=color.gray,title="Label-Background", inline="Label")
InpDeleteAfterSession = input.bool(defval=false,title="Delete drawings and labels after session end")
// SessionHigh() returns the highest price during the specified
// session, optionally corrected for the given time zone.
// Returns 'na' when the session hasn't started or isn't on the chart.
SessionHigh(sessionTime, sessionTimeZone=syminfo.timezone) =>
insideSession = not na(time(timeframe.period, sessionTime, sessionTimeZone))
var float sessionHighPrice = na
if insideSession and not insideSession[1]
sessionHighPrice := high
else if insideSession
sessionHighPrice := math.max(sessionHighPrice, high)
sessionHighPrice
SessionLow(sessionTime, sessionTimeZone=syminfo.timezone) =>
insideSession = not na(time(timeframe.period, sessionTime, sessionTimeZone))
var float sessionLowPrice = na
if insideSession and not insideSession[1]
sessionLowPrice := low
else if insideSession
sessionLowPrice := math.min(sessionLowPrice, low)
sessionLowPrice
// IsSessionOver() returns 'true' when the current bar is the first one
// after the given session, adjusted to the specified time zone (optional).
// Returns 'false' for other bars after the session ends, bars inside the
// session, and when the time frame is daily or higher.
IsSessionOver(sessionTime, sessionTimeZone=syminfo.timezone) =>
inSess = not na(time(timeframe.period, sessionTime, sessionTimeZone))
not inSess and inSess[1]
// IsSessionStart() returns 'true' when the current bar is the first one
// inside the specified session, adjusted to the given time zone (optional).
// Returns 'false' for other bars inside the session, bars outside the
// session, and when the time frame is 1 day or higher.
IsSessionStart(sessionTime, sessionTimeZone=syminfo.timezone) =>
inSess = not na(time(timeframe.period, sessionTime, sessionTimeZone))
inSess and not inSess[1]
// InSession() returns 'true' when the current bar happens inside
// the specified session, corrected for the given time zone (optional).
// Returns 'false' when the bar doesn't happen in that time period,
// or when the chart's time frame is 1 day or higher.
InSession(sessionTime, sessionTimeZone=syminfo.timezone) =>
not na(time(timeframe.period, sessionTime, sessionTimeZone))
// function to draw the line and the labels
fDrawLineLabel(sSessionName, sValueName, fInstrumentValue, cColor, iWidth) =>
lLine = line.new(bar_index-1,fInstrumentValue,bar_index+5,fInstrumentValue, color=cColor, width=iWidth)
lLabel = label.new(bar_index+InpLabelOffset,fInstrumentValue,(sValueName + " " + sSessionName + " "+str.tostring(fInstrumentValue)),style=label.style_label_center, color=InpLabelBackground, textcolor=InpLabelText)
[lLine, lLabel]
// function to move the lines and labels to the new instrument value
fMoveLineLabel(sSessionName, sValueName, lLine, lLabel, fInstrumentValue) =>
line.set_y1(lLine,fInstrumentValue)
line.set_y2(lLine,fInstrumentValue)
line.set_x2(lLine,bar_index+5)
label.set_xy(lLabel,bar_index+InpLabelOffset, fInstrumentValue)
label.set_text(lLabel,(sValueName + " " + sSessionName + " "+str.tostring(fInstrumentValue)))
fProcessSession(sSession, sSessionName, aValues, cColor, iWidth, bShowMax) =>
/////First Session
var SessionRange = 0.0
var line lineAvgHigh = na
var line lineAvgLow = na
var label labelAvgHigh = na
var label labelAvgLow = na
var line lineMaxHigh = na
var line lineMaxLow = na
var label labelMaxHigh = na
var label labelMaxLow = na
SessionRange := SessionHigh(sSession)-SessionLow(sSession)
if IsSessionOver(sSession)
if array.size(aValues) > InpAvgDays-1
array.shift(aValues)
array.push(aValues, SessionRange)
if InpDeleteAfterSession
line.delete(lineAvgHigh)
line.delete(lineAvgLow)
label.delete(labelAvgHigh)
label.delete(labelAvgLow)
if bShowMax
line.delete(lineMaxHigh)
line.delete(lineMaxLow)
label.delete(labelMaxHigh)
label.delete(labelMaxLow)
avgRangeHigh = SessionLow(sSession)+array.avg(aValues)
avgRangeLow = SessionHigh(sSession)-array.avg(aValues)
maxRangeHigh = SessionLow(sSession)+array.max(aValues)
maxRangeLow = SessionHigh(sSession)-array.max(aValues)
if IsSessionStart(sSession)
[_lineHigh, _labelHigh] = fDrawLineLabel(sSessionName,"Avg",avgRangeHigh,cColor, iWidth)
[_lineLow, _labelLow] = fDrawLineLabel(sSessionName,"Avg", avgRangeLow,cColor, iWidth)
lineAvgHigh := _lineHigh
labelAvgHigh := _labelHigh
lineAvgLow := _lineLow
labelAvgLow := _labelLow
if bShowMax
[__lineHigh, __labelHigh] = fDrawLineLabel(sSessionName,"Max",maxRangeHigh,cColor, iWidth)
[__lineLow, __labelLow] = fDrawLineLabel(sSessionName,"Max", maxRangeLow,cColor, iWidth)
lineMaxHigh := __lineHigh
labelMaxHigh := __labelHigh
lineMaxLow := __lineLow
labelMaxLow := __labelLow
if InSession(sSession)
fMoveLineLabel(sSessionName, "Avg", lineAvgHigh, labelAvgHigh, avgRangeHigh)
fMoveLineLabel(sSessionName, "Avg", lineAvgLow, labelAvgLow, avgRangeLow)
if bShowMax
fMoveLineLabel(sSessionName, "Max", lineMaxHigh, labelMaxHigh, maxRangeHigh)
fMoveLineLabel(sSessionName, "Max", lineMaxLow, labelMaxLow, maxRangeLow)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// end of functions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if InpFirstSessionShow
var aFirstSessionRange = array.new_float(InpAvgDays)
fProcessSession(InpFirstSession, InpFirstName, aFirstSessionRange, InpFirstColor, InpFirstWidth, InpFirstShowMax)
if InpSecondSessionShow
var aSecondSessionRange = array.new_float(InpAvgDays)
fProcessSession(InpSecondSession, InpSecondName, aSecondSessionRange, InpSecondColor, InpSecondWidth, InpSecondShowMax)
if InpThirdSessionShow
var aThirdSessionRange = array.new_float(InpAvgDays)
fProcessSession(InpThirdSession, InpThirdName, aThirdSessionRange, InpThirdColor, InpThirdWidth, InpThirdShowMax)
if InpFourthSessionShow
var aFourthSessionRange = array.new_float(InpAvgDays)
fProcessSession(InpFourthSession, InpFourthName, aFourthSessionRange, InpFourthColor, InpFourthWidth, InpFourthShowMax)
|
Historical Volatility Bands [Loxx] | https://www.tradingview.com/script/7exumlfH-Historical-Volatility-Bands-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 136 | 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/
// © loxx
//@version=5
indicator("Historical Volatility Bands [Loxx]",
shorttitle = "HVB [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
ema(float src, float per)=>
float alpha = 2.0 / (1.0 + per)
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
sma(float src, float per)=>
float sum = 0
float out = src
for k = 0 to per - 1
sum += nz(src[k])
out := sum / per
out
smma(float src, float per)=>
float alpha = 1.0 / per
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
lwma(float src, float per)=>
float sumw = 0
float sum = 0
float out = 0
for i = 0 to per - 1
float weight = (per - i) * per
sumw += weight
sum += nz(src[i]) * weight
out := sum / sumw
out
pwma(float src, float per, float pow)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = math.pow((per - k), pow)
sumw += weight
sum += nz(src[k]) * weight
out := sum / sumw
out
lsma(float src, float per)=>
float out = 0
out := 3.0 * lwma(src, per) - 2.0 * sma(src, per)
out
hma(float src, float per)=>
int HalfPeriod = math.floor(per / 2)
int HullPeriod = math.floor(math.sqrt(per))
float out = 0
float price1 = 2.0 * lwma(src, HalfPeriod) - lwma(src, per)
out := lwma(price1, HullPeriod)
out
tma(float src, float per)=>
float half = (per + 1.0) / 2.0
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = k + 1
if weight > half
weight := per - k
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
swma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
weight = math.sin((k + 1) * math.pi / (per + 1))
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
vwma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = nz(volume[k])
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
nonlagma(float src, float len)=>
float cycle = 4.0
float coeff = 3.0 * math.pi
float phase = len - 1.0
int _len = int(len * cycle + phase)
float weight = 0.
float alfa = 0.
float out = 0.
float[] alphas = array.new_float(_len, 0)
for k = 0 to _len - 1
float t = 0.
t := k <= phase - 1 ? 1.0 * k / (phase - 1) : 1.0 + (k - phase + 1) * (2.0 * cycle - 1.0) / (cycle * len -1.0)
beta = math.cos(math.pi * t)
float g = 1.0/(coeff * t + 1)
g := t <= 0.5 ? 1 : g
array.set(alphas, k, g * beta)
weight += array.get(alphas, k)
if (weight > 0)
float sum = 0.
for k = 0 to _len - 1
sum += array.get(alphas, k) * nz(src[k])
out := (sum / weight)
out
variant(type, src, len) =>
out = 0.0
switch type
"Exponential Moving Average - EMA" => out := ema(src, len)
"Hull Moving Average - HMA" => out := hma(src, len)
"Linear Regression Value - LSMA (Least Squares Moving Average)" => out := lsma(src, len)
"Linear Weighted Moving Average - LWMA" => out := lwma(src, len)
"Non-Lag Moving Average" => out := nonlagma(src, len)
"Parabolic Weighted Moving Average" => out := pwma(src, len, 2)
"Simple Moving Average - SMA" => out := sma(src, len)
"Sine Weighted Moving Average" => out := swma(src, len)
"Smoothed Moving Average - SMMA" => out := smma(src, len)
"Triangular Moving Average - TMA" => out := tma(src, len)
"Volume Weighted Moving Average - VWMA" => out := vwma(src, len)
=> out := sma(src, len)
out
hvbands(string type, float src, int per, float dev)=>
float avg = 0
float sum = 0
float work = 0
for k = 0 to per - 1
if k > 0
work := math.log(nz(src[k]) / nz(src[k-1]))
avg += work
avg /= per
for k = 0 to per - 1
sum += (nz(work[k]) - avg) * (nz(work[k]) - avg)
float deviation = math.sqrt(sum / per) * src
bufferMe = variant(type, src, per)
bufferUp = bufferMe + deviation * dev
bufferDn = bufferMe - deviation * dev
bufferUpc = 0
bufferDnc = 0
bufferUpc := nz(bufferUpc[1])
bufferDnc := nz(bufferDnc[1])
if bufferUp > nz(bufferUp[1])
bufferUpc := 0
if bufferUp < nz(bufferUp[1])
bufferUpc := 1
if bufferDn> nz(bufferDn[1])
bufferDnc := 0
if bufferDn< nz(bufferDn[1])
bufferDnc := 1
bufferMec = (bufferUpc == 0 and bufferDnc == 0) ? 0 : (bufferUpc == 1 and bufferDnc == 1) ? 1 : 2
[bufferUp, bufferDn, bufferMe, bufferMec, bufferUpc, bufferDnc]
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(40, "Period", group = "Basic Settings")
type = input.string("Hull Moving Average - HMA", "Double Smoothing MA Type", options = ["Exponential Moving Average - EMA"
, "Hull Moving Average - HMA"
, "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA"
, "Non-Lag Moving Average"
, "Parabolic Weighted Moving Average"
, "Simple Moving Average - SMA"
, "Sine Weighted Moving Average"
, "Smoothed Moving Average - SMMA"
, "Triangular Moving Average - TMA"
, "Volume Weighted Moving Average - VWMA"],
group = "Bands Settings")
dev = input.float(1.0, "Deviations", group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
[bufferUp, bufferDn, bufferMe, bufferMec, bufferUpc, bufferDnc] = hvbands(type, src, per, dev)
pregoLong = bufferMec == 0
pregoShort = bufferMec == 1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
colorout = bufferMec == 0 ? greencolor : bufferMec == 1 ? redcolor : color.white
coloroutu = bufferUpc == 0 ? greencolor : bufferUpc == 1 ? redcolor : color.white
coloroutd = bufferDnc == 0 ? greencolor : bufferDnc == 1 ? redcolor : color.white
plot(bufferMe, "Middle", color = colorout, linewidth = 3)
plot(bufferUp, "Up band", color = coloroutu)
plot(bufferDn, "Down band", color = coloroutd)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "Historical Volatility Bands [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Historical Volatility Bands [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Parkinson's Historical Volatility Bands [Loxx] | https://www.tradingview.com/script/Ptd5DLzk-Parkinson-s-Historical-Volatility-Bands-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 81 | 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/
// © loxx
//@version=5
indicator("Parkinson's Historical Volatility Bands [Loxx]",
shorttitle = "PHVB [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
ema(float src, float per)=>
float alpha = 2.0 / (1.0 + per)
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
sma(float src, float per)=>
float sum = 0
float out = src
for k = 0 to per - 1
sum += nz(src[k])
out := sum / per
out
smma(float src, float per)=>
float alpha = 1.0 / per
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
lwma(float src, float per)=>
float sumw = 0
float sum = 0
float out = 0
for i = 0 to per - 1
float weight = (per - i) * per
sumw += weight
sum += nz(src[i]) * weight
out := sum / sumw
out
pwma(float src, float per, float pow)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = math.pow((per - k), pow)
sumw += weight
sum += nz(src[k]) * weight
out := sum / sumw
out
lsma(float src, float per)=>
float out = 0
out := 3.0 * lwma(src, per) - 2.0 * sma(src, per)
out
hma(float src, float per)=>
int HalfPeriod = math.floor(per / 2)
int HullPeriod = math.floor(math.sqrt(per))
float out = 0
float price1 = 2.0 * lwma(src, HalfPeriod) - lwma(src, per)
out := lwma(price1, HullPeriod)
out
tma(float src, float per)=>
float half = (per + 1.0) / 2.0
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = k + 1
if weight > half
weight := per - k
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
swma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
weight = math.sin((k + 1) * math.pi / (per + 1))
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
vwma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = nz(volume[k])
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
nonlagma(float src, float len)=>
float cycle = 4.0
float coeff = 3.0 * math.pi
float phase = len - 1.0
int _len = int(len * cycle + phase)
float weight = 0.
float alfa = 0.
float out = 0.
float[] alphas = array.new_float(_len, 0)
for k = 0 to _len - 1
float t = 0.
t := k <= phase - 1 ? 1.0 * k / (phase - 1) : 1.0 + (k - phase + 1) * (2.0 * cycle - 1.0) / (cycle * len -1.0)
beta = math.cos(math.pi * t)
float g = 1.0/(coeff * t + 1)
g := t <= 0.5 ? 1 : g
array.set(alphas, k, g * beta)
weight += array.get(alphas, k)
if (weight > 0)
float sum = 0.
for k = 0 to _len - 1
sum += array.get(alphas, k) * nz(src[k])
out := (sum / weight)
out
variant(type, src, len) =>
out = 0.0
switch type
"Exponential Moving Average - EMA" => out := ema(src, len)
"Hull Moving Average - HMA" => out := hma(src, len)
"Linear Regression Value - LSMA (Least Squares Moving Average)" => out := lsma(src, len)
"Linear Weighted Moving Average - LWMA" => out := lwma(src, len)
"Non-Lag Moving Average" => out := nonlagma(src, len)
"Parabolic Weighted Moving Average" => out := pwma(src, len, 2)
"Simple Moving Average - SMA" => out := sma(src, len)
"Sine Weighted Moving Average" => out := swma(src, len)
"Smoothed Moving Average - SMMA" => out := smma(src, len)
"Triangular Moving Average - TMA" => out := tma(src, len)
"Volume Weighted Moving Average - VWMA" => out := vwma(src, len)
=> out := sma(src, len)
out
hvbands(string type, float src, int per, float dev)=>
volConst = 1.0 / (4.0 * per * math.log(2))
sum = volConst * math.sum(math.pow(math.log(high / low), 2), per)
float deviation = math.sqrt(sum) * src
bufferMe = variant(type, src, per)
bufferUp = bufferMe + deviation * dev
bufferDn = bufferMe - deviation * dev
bufferUpc = 0
bufferDnc = 0
bufferUpc := nz(bufferUpc[1])
bufferDnc := nz(bufferDnc[1])
if bufferUp > nz(bufferUp[1])
bufferUpc := 0
if bufferUp < nz(bufferUp[1])
bufferUpc := 1
if bufferDn> nz(bufferDn[1])
bufferDnc := 0
if bufferDn< nz(bufferDn[1])
bufferDnc := 1
bufferMec = (bufferUpc == 0 and bufferDnc == 0) ? 0 : (bufferUpc == 1 and bufferDnc == 1) ? 1 : 2
[bufferUp, bufferDn, bufferMe, bufferMec, bufferUpc, bufferDnc]
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(40, "Period", group = "Basic Settings")
type = input.string("Hull Moving Average - HMA", "Double Smoothing MA Type", options = ["Exponential Moving Average - EMA"
, "Hull Moving Average - HMA"
, "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA"
, "Non-Lag Moving Average"
, "Parabolic Weighted Moving Average"
, "Simple Moving Average - SMA"
, "Sine Weighted Moving Average"
, "Smoothed Moving Average - SMMA"
, "Triangular Moving Average - TMA"
, "Volume Weighted Moving Average - VWMA"],
group = "Bands Settings")
dev = input.float(1.0, "Deviations", group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
[bufferUp, bufferDn, bufferMe, bufferMec, bufferUpc, bufferDnc] = hvbands(type, src, per, dev)
pregoLong = bufferMec == 0
pregoShort = bufferMec == 1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
colorout = bufferMec == 0 ? greencolor : bufferMec == 1 ? redcolor : color.white
coloroutu = bufferUpc == 0 ? greencolor : bufferUpc == 1 ? redcolor : color.white
coloroutd = bufferDnc == 0 ? greencolor : bufferDnc == 1 ? redcolor : color.white
plot(bufferMe, "Middle", color = colorout, linewidth = 3)
plot(bufferUp, "Up band", color = coloroutu)
plot(bufferDn, "Down band", color = coloroutd)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "Parkinson's Historical Volatility Bands [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Parkinson's Historical Volatility Bands [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Garman-Klass-Yang-Zhang Historical Volatility Bands [Loxx] | https://www.tradingview.com/script/769aHr2F-Garman-Klass-Yang-Zhang-Historical-Volatility-Bands-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 195 | 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/
// © loxx
//@version=5
indicator("Garman-Klass-Yang-Zhang Historical Volatility Bands [Loxx]",
shorttitle = "GKYZHVB [Loxx]",
overlay = true,
precision = 15,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
ema(float src, float per)=>
float alpha = 2.0 / (1.0 + per)
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
sma(float src, float per)=>
float sum = 0
float out = src
for k = 0 to per - 1
sum += nz(src[k])
out := sum / per
out
smma(float src, float per)=>
float alpha = 1.0 / per
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
lwma(float src, float per)=>
float sumw = 0
float sum = 0
float out = 0
for i = 0 to per - 1
float weight = (per - i) * per
sumw += weight
sum += nz(src[i]) * weight
out := sum / sumw
out
pwma(float src, float per, float pow)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = math.pow((per - k), pow)
sumw += weight
sum += nz(src[k]) * weight
out := sum / sumw
out
lsma(float src, float per)=>
float out = 0
out := 3.0 * lwma(src, per) - 2.0 * sma(src, per)
out
hma(float src, float per)=>
int HalfPeriod = math.floor(per / 2)
int HullPeriod = math.floor(math.sqrt(per))
float out = 0
float price1 = 2.0 * lwma(src, HalfPeriod) - lwma(src, per)
out := lwma(price1, HullPeriod)
out
tma(float src, float per)=>
float half = (per + 1.0) / 2.0
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = k + 1
if weight > half
weight := per - k
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
swma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
weight = math.sin((k + 1) * math.pi / (per + 1))
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
vwma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = nz(volume[k])
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
nonlagma(float src, float len)=>
float cycle = 4.0
float coeff = 3.0 * math.pi
float phase = len - 1.0
int _len = int(len * cycle + phase)
float weight = 0.
float alfa = 0.
float out = 0.
float[] alphas = array.new_float(_len, 0)
for k = 0 to _len - 1
float t = 0.
t := k <= phase - 1 ? 1.0 * k / (phase - 1) : 1.0 + (k - phase + 1) * (2.0 * cycle - 1.0) / (cycle * len -1.0)
beta = math.cos(math.pi * t)
float g = 1.0/(coeff * t + 1)
g := t <= 0.5 ? 1 : g
array.set(alphas, k, g * beta)
weight += array.get(alphas, k)
if (weight > 0)
float sum = 0.
for k = 0 to _len - 1
sum += array.get(alphas, k) * nz(src[k])
out := (sum / weight)
out
variant(type, src, len) =>
out = 0.0
switch type
"Exponential Moving Average - EMA" => out := ema(src, len)
"Hull Moving Average - HMA" => out := hma(src, len)
"Linear Regression Value - LSMA (Least Squares Moving Average)" => out := lsma(src, len)
"Linear Weighted Moving Average - LWMA" => out := lwma(src, len)
"Non-Lag Moving Average" => out := nonlagma(src, len)
"Parabolic Weighted Moving Average" => out := pwma(src, len, 2)
"Simple Moving Average - SMA" => out := sma(src, len)
"Sine Weighted Moving Average" => out := swma(src, len)
"Smoothed Moving Average - SMMA" => out := smma(src, len)
"Triangular Moving Average - TMA" => out := tma(src, len)
"Volume Weighted Moving Average - VWMA" => out := vwma(src, len)
=> out := sma(src, len)
out
//Returns % volatlity on chart timeframe
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
hvbands(string type, float src, simple int per, float dev)=>
float deviation = gkyzvol(per) * src
bufferMe = variant(type, src, per)
bufferUp = bufferMe + deviation * dev
bufferDn = bufferMe - deviation * dev
bufferUpc = 0
bufferDnc = 0
bufferUpc := nz(bufferUpc[1])
bufferDnc := nz(bufferDnc[1])
if bufferUp > nz(bufferUp[1])
bufferUpc := 0
if bufferUp < nz(bufferUp[1])
bufferUpc := 1
if bufferDn> nz(bufferDn[1])
bufferDnc := 0
if bufferDn< nz(bufferDn[1])
bufferDnc := 1
bufferMec = (bufferUpc == 0 and bufferDnc == 0) ? 0 : (bufferUpc == 1 and bufferDnc == 1) ? 1 : 2
[bufferUp, bufferDn, bufferMe, bufferMec, bufferUpc, bufferDnc]
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(40, "Period", group = "Basic Settings")
type = input.string("Hull Moving Average - HMA", "Double Smoothing MA Type", options = ["Exponential Moving Average - EMA"
, "Hull Moving Average - HMA"
, "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA"
, "Non-Lag Moving Average"
, "Parabolic Weighted Moving Average"
, "Simple Moving Average - SMA"
, "Sine Weighted Moving Average"
, "Smoothed Moving Average - SMMA"
, "Triangular Moving Average - TMA"
, "Volume Weighted Moving Average - VWMA"],
group = "Basic Settings")
dev = input.float(1.0, "Deviations", group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
[bufferUp, bufferDn, bufferMe, bufferMec, bufferUpc, bufferDnc] = hvbands(type, src, per, dev)
pregoLong = bufferMec == 0
pregoShort = bufferMec == 1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
colorout = bufferMec == 0 ? greencolor : bufferMec == 1 ? redcolor : color.white
coloroutu = bufferUpc == 0 ? greencolor : bufferUpc == 1 ? redcolor : color.white
coloroutd = bufferDnc == 0 ? greencolor : bufferDnc == 1 ? redcolor : color.white
plot(bufferMe, "Middle", color = colorout, linewidth = 3)
plot(bufferUp, "Up band", color = coloroutu)
plot(bufferDn, "Down band", color = coloroutd)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "Garman-Klass-Yang-Zhang Historical Volatility Bands [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Garman-Klass-Yang-Zhang Historical Volatility Bands [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Fractal-Dimension-Index-Adaptive Trend Cipher Candles [Loxx] | https://www.tradingview.com/script/aNyo818b-Fractal-Dimension-Index-Adaptive-Trend-Cipher-Candles-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
indicator('Fractal-Dimension-Index-Adaptive Trend Cipher Candles [Loxx]',
shorttitle = "FDIATCC [Loxx]",
timeframe="",
timeframe_gaps=true,
overlay = true)
import loxx/loxxexpandedsourcetypes/4
fdip(float src, int per, int speedin)=>
float fmax = ta.highest(src, per)
float fmin = ta.lowest(src, per)
float length = 0
float diff = 0
for i = 1 to per - 1
diff := (nz(src[i]) - fmin) / (fmax - fmin)
if i > 0
length += math.sqrt( math.pow(nz(diff[i]) - nz(diff[i + 1]), 2) + (1 / math.pow(per, 2)))
float fdi = 1 + (math.log(length) + math.log(2)) / math.log(2 * per)
float traildim = 1 / (2 - fdi)
float alpha = traildim / 2
int speed = math.round(speedin * alpha)
speed
_corrrelation(x, y, len)=>
float meanx = math.sum(x, len) / len
float meany = math.sum(y, len) / len
float sumxy = 0
float sumx = 0
float sumy = 0
for i = 0 to len - 1
sumxy := sumxy + (nz(x[i]) - meanx) * (nz(y[i]) - meany)
sumx := sumx + math.pow(nz(x[i]) - meanx, 2)
sumy := sumy + math.pow(nz(y[i]) - meany, 2)
sumxy / math.sqrt(sumy * sumx)
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(30, "FDI Period", group = "FDI Ingest Settings")
speed = input.int(20, "FDI Speec", group = "FDI Ingest Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
out = fdip(src, per, speed)
correlate = _corrrelation(src, bar_index, out)
colorCorrelate =
correlate > 0.95 ? #FFF300 :
correlate > 0.9 ? #80ff5f :
correlate > 0.8 ? #58ff2e :
correlate > 0.6 ? #33fc00 :
correlate > 0.4 ? #29cc00 :
correlate > 0.2 ? #1f9b00 :
correlate > 0.0 ? #156a00 :
correlate < -0.95 ? #FF0EF3 :
correlate < -0.9 ? #ff2e57 :
correlate < -0.8 ? #fc0031 :
correlate < -0.6 ? #cc0028 :
correlate < -0.4 ? #9b001e :
correlate < -0.2 ? #6a0014 :
#6a0014
color_out = color.new(colorCorrelate, 0)
barcolor(color_out)
|
Roger & Satchell Estimator Historical Volatility Bands [Loxx] | https://www.tradingview.com/script/Bmar3Byk-Roger-Satchell-Estimator-Historical-Volatility-Bands-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 298 | 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/
// © loxx
//@version=5
indicator("Roger & Satchell Estimator Historical Volatility Bands [Loxx]",
shorttitle = "RSHVB [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
ema(float src, float per)=>
float alpha = 2.0 / (1.0 + per)
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
sma(float src, float per)=>
float sum = 0
float out = src
for k = 0 to per - 1
sum += nz(src[k])
out := sum / per
out
smma(float src, float per)=>
float alpha = 1.0 / per
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
lwma(float src, float per)=>
float sumw = 0
float sum = 0
float out = 0
for i = 0 to per - 1
float weight = (per - i) * per
sumw += weight
sum += nz(src[i]) * weight
out := sum / sumw
out
pwma(float src, float per, float pow)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = math.pow((per - k), pow)
sumw += weight
sum += nz(src[k]) * weight
out := sum / sumw
out
lsma(float src, float per)=>
float out = 0
out := 3.0 * lwma(src, per) - 2.0 * sma(src, per)
out
hma(float src, float per)=>
int HalfPeriod = math.floor(per / 2)
int HullPeriod = math.floor(math.sqrt(per))
float out = 0
float price1 = 2.0 * lwma(src, HalfPeriod) - lwma(src, per)
out := lwma(price1, HullPeriod)
out
tma(float src, float per)=>
float half = (per + 1.0) / 2.0
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = k + 1
if weight > half
weight := per - k
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
swma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
weight = math.sin((k + 1) * math.pi / (per + 1))
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
vwma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = nz(volume[k])
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
nonlagma(float src, float len)=>
float cycle = 4.0
float coeff = 3.0 * math.pi
float phase = len - 1.0
int _len = int(len * cycle + phase)
float weight = 0.
float alfa = 0.
float out = 0.
float[] alphas = array.new_float(_len, 0)
for k = 0 to _len - 1
float t = 0.
t := k <= phase - 1 ? 1.0 * k / (phase - 1) : 1.0 + (k - phase + 1) * (2.0 * cycle - 1.0) / (cycle * len -1.0)
beta = math.cos(math.pi * t)
float g = 1.0/(coeff * t + 1)
g := t <= 0.5 ? 1 : g
array.set(alphas, k, g * beta)
weight += array.get(alphas, k)
if (weight > 0)
float sum = 0.
for k = 0 to _len - 1
sum += array.get(alphas, k) * nz(src[k])
out := (sum / weight)
out
variant(type, src, len) =>
out = 0.0
switch type
"Exponential Moving Average - EMA" => out := ema(src, len)
"Hull Moving Average - HMA" => out := hma(src, len)
"Linear Regression Value - LSMA (Least Squares Moving Average)" => out := lsma(src, len)
"Linear Weighted Moving Average - LWMA" => out := lwma(src, len)
"Non-Lag Moving Average" => out := nonlagma(src, len)
"Parabolic Weighted Moving Average" => out := pwma(src, len, 2)
"Simple Moving Average - SMA" => out := sma(src, len)
"Sine Weighted Moving Average" => out := swma(src, len)
"Smoothed Moving Average - SMMA" => out := smma(src, len)
"Triangular Moving Average - TMA" => out := tma(src, len)
"Volume Weighted Moving Average - VWMA" => out := vwma(src, len)
=> out := sma(src, len)
out
hvbands(string type, float src, int per, float dev)=>
sum = math.sum(math.log(high/ close) * math.log(high / open)
+ math.log(low / close) * math.log(low / open), per) / per
float deviation = math.sqrt(sum) * src
bufferMe = variant(type, src, per)
bufferUp = bufferMe + deviation * dev
bufferDn = bufferMe - deviation * dev
bufferUpc = 0
bufferDnc = 0
bufferUpc := nz(bufferUpc[1])
bufferDnc := nz(bufferDnc[1])
if bufferUp > nz(bufferUp[1])
bufferUpc := 0
if bufferUp < nz(bufferUp[1])
bufferUpc := 1
if bufferDn> nz(bufferDn[1])
bufferDnc := 0
if bufferDn< nz(bufferDn[1])
bufferDnc := 1
bufferMec = (bufferUpc == 0 and bufferDnc == 0) ? 0 : (bufferUpc == 1 and bufferDnc == 1) ? 1 : 2
[bufferUp, bufferDn, bufferMe, bufferMec, bufferUpc, bufferDnc]
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(40, "Period", group = "Basic Settings")
type = input.string("Hull Moving Average - HMA", "Double Smoothing MA Type", options = ["Exponential Moving Average - EMA"
, "Hull Moving Average - HMA"
, "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA"
, "Non-Lag Moving Average"
, "Parabolic Weighted Moving Average"
, "Simple Moving Average - SMA"
, "Sine Weighted Moving Average"
, "Smoothed Moving Average - SMMA"
, "Triangular Moving Average - TMA"
, "Volume Weighted Moving Average - VWMA"],
group = "Bands Settings")
dev = input.float(1.0, "Deviations", group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
[bufferUp, bufferDn, bufferMe, bufferMec, bufferUpc, bufferDnc] = hvbands(type, src, per, dev)
pregoLong = bufferMec == 0
pregoShort = bufferMec == 1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
colorout = bufferMec == 0 ? greencolor : bufferMec == 1 ? redcolor : color.white
coloroutu = bufferUpc == 0 ? greencolor : bufferUpc == 1 ? redcolor : color.white
coloroutd = bufferDnc == 0 ? greencolor : bufferDnc == 1 ? redcolor : color.white
plot(bufferMe, "Middle", color = colorout, linewidth = 3)
plot(bufferUp, "Up band", color = coloroutu)
plot(bufferDn, "Down band", color = coloroutd)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "Roger & Satchell Estimator Historical Volatility Bands [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Roger & Satchell Estimator Historical Volatility Bands [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Garman & Klass Estimator Historical Volatility Bands [Loxx] | https://www.tradingview.com/script/6vG4XTPr-Garman-Klass-Estimator-Historical-Volatility-Bands-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 109 | 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/
// © loxx
//@version=5
indicator("Garman & Klass Estimator Historical Volatility Bands [Loxx]",
shorttitle = "GKEHVB [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
ema(float src, float per)=>
float alpha = 2.0 / (1.0 + per)
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
sma(float src, float per)=>
float sum = 0
float out = src
for k = 0 to per - 1
sum += nz(src[k])
out := sum / per
out
smma(float src, float per)=>
float alpha = 1.0 / per
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
lwma(float src, float per)=>
float sumw = 0
float sum = 0
float out = 0
for i = 0 to per - 1
float weight = (per - i) * per
sumw += weight
sum += nz(src[i]) * weight
out := sum / sumw
out
pwma(float src, float per, float pow)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = math.pow((per - k), pow)
sumw += weight
sum += nz(src[k]) * weight
out := sum / sumw
out
lsma(float src, float per)=>
float out = 0
out := 3.0 * lwma(src, per) - 2.0 * sma(src, per)
out
hma(float src, float per)=>
int HalfPeriod = math.floor(per / 2)
int HullPeriod = math.floor(math.sqrt(per))
float out = 0
float price1 = 2.0 * lwma(src, HalfPeriod) - lwma(src, per)
out := lwma(price1, HullPeriod)
out
tma(float src, float per)=>
float half = (per + 1.0) / 2.0
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = k + 1
if weight > half
weight := per - k
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
swma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
weight = math.sin((k + 1) * math.pi / (per + 1))
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
vwma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = nz(volume[k])
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
nonlagma(float src, float len)=>
float cycle = 4.0
float coeff = 3.0 * math.pi
float phase = len - 1.0
int _len = int(len * cycle + phase)
float weight = 0.
float alfa = 0.
float out = 0.
float[] alphas = array.new_float(_len, 0)
for k = 0 to _len - 1
float t = 0.
t := k <= phase - 1 ? 1.0 * k / (phase - 1) : 1.0 + (k - phase + 1) * (2.0 * cycle - 1.0) / (cycle * len -1.0)
beta = math.cos(math.pi * t)
float g = 1.0/(coeff * t + 1)
g := t <= 0.5 ? 1 : g
array.set(alphas, k, g * beta)
weight += array.get(alphas, k)
if (weight > 0)
float sum = 0.
for k = 0 to _len - 1
sum += array.get(alphas, k) * nz(src[k])
out := (sum / weight)
out
variant(type, src, len) =>
out = 0.0
switch type
"Exponential Moving Average - EMA" => out := ema(src, len)
"Hull Moving Average - HMA" => out := hma(src, len)
"Linear Regression Value - LSMA (Least Squares Moving Average)" => out := lsma(src, len)
"Linear Weighted Moving Average - LWMA" => out := lwma(src, len)
"Non-Lag Moving Average" => out := nonlagma(src, len)
"Parabolic Weighted Moving Average" => out := pwma(src, len, 2)
"Simple Moving Average - SMA" => out := sma(src, len)
"Sine Weighted Moving Average" => out := swma(src, len)
"Smoothed Moving Average - SMMA" => out := smma(src, len)
"Triangular Moving Average - TMA" => out := tma(src, len)
"Volume Weighted Moving Average - VWMA" => out := vwma(src, len)
=> out := sma(src, len)
out
//Returns % volatlity on chart timeframe
garmanKlass(int per)=>
float hllog = math.log(high / low)
float oplog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(hllog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(oplog, 2), per)
float sum = parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
hvbands(string type, float src, simple int per, float dev)=>
float deviation = garmanKlass(per) * src
bufferMe = variant(type, src, per)
bufferUp = bufferMe + deviation * dev
bufferDn = bufferMe - deviation * dev
bufferUpc = 0
bufferDnc = 0
bufferUpc := nz(bufferUpc[1])
bufferDnc := nz(bufferDnc[1])
if bufferUp > nz(bufferUp[1])
bufferUpc := 0
if bufferUp < nz(bufferUp[1])
bufferUpc := 1
if bufferDn> nz(bufferDn[1])
bufferDnc := 0
if bufferDn< nz(bufferDn[1])
bufferDnc := 1
bufferMec = (bufferUpc == 0 and bufferDnc == 0) ? 0 : (bufferUpc == 1 and bufferDnc == 1) ? 1 : 2
[bufferUp, bufferDn, bufferMe, bufferMec, bufferUpc, bufferDnc]
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(40, "Period", group = "Basic Settings")
type = input.string("Hull Moving Average - HMA", "Double Smoothing MA Type", options = ["Exponential Moving Average - EMA"
, "Hull Moving Average - HMA"
, "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA"
, "Non-Lag Moving Average"
, "Parabolic Weighted Moving Average"
, "Simple Moving Average - SMA"
, "Sine Weighted Moving Average"
, "Smoothed Moving Average - SMMA"
, "Triangular Moving Average - TMA"
, "Volume Weighted Moving Average - VWMA"],
group = "Basic Settings")
dev = input.float(1.0, "Deviations", group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
[bufferUp, bufferDn, bufferMe, bufferMec, bufferUpc, bufferDnc] = hvbands(type, src, per, dev)
pregoLong = bufferMec == 0
pregoShort = bufferMec == 1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
colorout = bufferMec == 0 ? greencolor : bufferMec == 1 ? redcolor : color.white
coloroutu = bufferUpc == 0 ? greencolor : bufferUpc == 1 ? redcolor : color.white
coloroutd = bufferDnc == 0 ? greencolor : bufferDnc == 1 ? redcolor : color.white
plot(bufferMe, "Middle", color = colorout, linewidth = 3)
plot(bufferUp, "Up band", color = coloroutu)
plot(bufferDn, "Down band", color = coloroutd)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "Garman & Klass Estimator Historical Volatility Bands [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Garman & Klass Estimator Historical Volatility Bands [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
PA Swings [TTA] | https://www.tradingview.com/script/d7pAbqsp-PA-Swings-TTA/ | TradingTacticsPro | https://www.tradingview.com/u/TradingTacticsPro/ | 209 | 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/
// © TTA
//@version=5
indicator("PA Swings [TTA]",
overlay = true, max_lines_count = 500, max_labels_count = 500)
_data = input.string(defval = "SH/SL", title = "Swings to Show", options = ["SH", "SL", "SH/SL"])
_hideDev = input.bool(defval = true, title = "Hide Far Away Lines?")
_devDelete = input.float(defval = 15, title = "Hide Far Away Lines After Price Deviates (%)", minval = 0) / 100
_hide_r = input.bool(defval = false, title = "Delete Inactive Lines?")
_hide_days = input.int(defval = 3, title = "Delete Inactive Lines After => Bars")
_avgGainInput = input.int(defval = 10, title = "Number of Bars Included For Avg. Gain/Loss Following Retest")
_lineOnly = input.bool(defval = false, title = "Show Lines Only")
_logR = input.bool(defval = true, title = "Use Log Returns")
_showLab = input.bool(defval = false, title = "Show Labels on Chart")
_sVolBool = input.bool(defval = false, title = "Show High Volume Swings Only")
_textSize = input.string(defval = "Normal", title = "Text Size",
options = ["Tiny", "Small", "Normal", "Large", "Huge", "Auto"])
_hidePanel = input.bool(defval = false, title = "Hide Color Identity Panel")
_finalSize = switch _textSize
"Normal" => size.normal
"Tiny" => size.tiny
"Small" => size.small
"Large" => size.large
"Huge" => size.huge
"Auto" => size.auto
// ------{{Swing High}}------
var string [] _rankTrack = array.new_string()
_sHighN = close[3] > open[3] and close[2] > open[2] and close[2] > close[3] and high[2] > high[3] and close[1] < open[1] and high < high[2] and high[1] < high[2] and close < open
var float [] _sHighVol = array.new_float()
var bool _sHighNx = na
if _sVolBool == true
array.push(_sHighVol, volume)
_sHighNx := array.size(_sHighVol) > 5 ? _sHighN and array.percentrank(_sHighVol, array.size(_sHighVol) - 3) > 80 : na
if array.size(_sHighVol) > 300
array.shift(_sHighVol)
_sHighLasts = switch _sVolBool
true => _sHighNx
false => _sHighN
_sLowN = close[3] < open[3] and close[2] < open[2] and close[2] < close[3] and high[2] < high[3] and close[1] > open[1] and high > high[2] and high[1] > high[2] and close > open
var bool _sLowNx = na
if _sVolBool == true
_sLowNx := array.size(_sHighVol) > 5 ? _sLowN and array.percentrank(_sHighVol, array.size(_sHighVol) - 3) > 80 : na
_sLowLasts = switch _sVolBool
true => _sLowNx
false => _sLowN
var int _session = 0
var bool _sesC = false
if barstate.isfirst
_session := math.round(time)
else
if session.isfirstbar_regular and _sesC == false
_session := math.round(time) - _session
_sesC := true
var label [] _arrayLabel = array.new_label() , var label [] _r = array.new_label()
var float [] _avgRetest = array.new_float() , var float [] _avgMax = array.new_float()
var line [] _sLow = array.new_line() , var label [] _arrayLabelLow = array.new_label()
var int [] _barCountLow = array.new_int() , var float [] _avgMin = array.new_float()
var float [] _arrayHoldLow = array.new_float() , var float [] _arrayHoldLow2 = array.new_float()
var line [] _arrayLineLow = array.new_line() , var line [] _arrayLineLow2 = array.new_line()
var float [] _min = array.new_float() , var int [] _line2CountLow = array.new_int()
var int [] _avgRetestBarLow = array.new_int() , var float [] _avgRetestLow = array.new_float()
var label [] _rLow = array.new_label() , var float [] _sLowVolTrack = array.new_float()
var string [] _rankTrackH = array.new_string() , var float [] _sHighVolTrack = array.new_float()
var line [] _sHigh = array.new_line() , var int [] _barCount = array.new_int()
if last_bar_index - bar_index <= 7000
if _data != "SL"
var string _pRank = ""
if _sHighLasts
if _sVolBool == true
array.push(_sHighVolTrack, volume)
_pRank := array.size(_sHighVol) > 5 ? "\nVol. Rank: " + str.tostring(array.percentrank(_sHighVol, array.size(_sHighVol) - 3), format.percent) : ""
array.push(_rankTrackH, _pRank)
array.push(_sHighVolTrack, volume)
var float [] _arrayHold = array.new_float()
var float [] _arrayHold2 = array.new_float()
var line [] _arrayLine = array.new_line()
var line [] _arrayLine2 = array.new_line()
if _sHighLasts
array.push(_sHigh, line.new(time[2], high[2], time, high[2], color = #c8e6c9, xloc = xloc.bar_time))
array.push(_arrayLabel, label.new(time, line.get_y1(array.get(_sHigh, array.size(_sHigh) - 1)),
"(" + str.tostring(0, "#") + ")" + "\n" +
str.tostring((close / line.get_y1(array.get(_sHigh, array.size(_sHigh) - 1)) - 1) * 100, format.percent) + _pRank, color = na,
textcolor = _showLab == true ?
#c8e6c9 : color.new(color.black, 100), xloc = xloc.bar_time, size = size.small))
array.push(_barCount, bar_index)
var float [] _max = array.new_float()
var int [] _line2Count = array.new_int()
var int [] _avgRetestBar = array.new_int()
if array.size(_sHigh) > 0
for i = 0 to array.size(_sHigh) - 1
if high[1] > line.get_y1(array.get(_sHigh, i)) and array.includes(_arrayHold, line.get_y1(array.get(_sHigh, i))) == false
array.push(_arrayHold, line.get_y1(array.get(_sHigh, i)))
if _sVolBool == true
if array.size(_rankTrackH) == array.size(_sHigh)
label.set_text(array.get(_arrayLabel, i), "Impulse Up\n" + "Vol. Rank: " + array.get(_rankTrackH, i))
else
label.set_text(array.get(_arrayLabel, i), "Impulse Up")
if _hide_r == true
line.set_color(array.get(_sHigh, i), na)
if array.size(_sHigh) > 0
for i = 0 to array.size(_sHigh) - 1
if array.includes(_arrayHold, line.get_y1(array.get(_sHigh, i))) == false
line.set_x2(array.get(_sHigh, i), time)
line.set_color(array.get(_sHigh, i), color.from_gradient(time, line.get_x1(array.get(_sHigh, i)), line.get_x1(array.get(_sHigh, i)) +
_session * 100, color.lime, #c8e6c9))
if _sVolBool == false
label.set_text(array.get(_arrayLabel, i), "(" + str.tostring(bar_index - array.get(_barCount, i), "#") + ")" + "\n"
+ str.tostring((close / line.get_y1(array.get(_sHigh, i)) - 1) * 100, format.percent))
else
if array.size(_rankTrackH) > 0
label.set_text(array.get(_arrayLabel, i), "(" + str.tostring(bar_index - array.get(_barCount, i), "#") + ")" + "\n"
+ str.tostring((close / line.get_y1(array.get(_sHigh, i)) - 1) * 100, format.percent) + array.get(_rankTrackH, i))
if _showLab == true
label.set_textcolor(array.get(_arrayLabel, i), color.from_gradient(time, line.get_x1(array.get(_sHigh, i)), line.get_x1(array.get(_sHigh, i)) +
_session * 100, color.lime, #c8e6c9))
label.set_x(array.get(_arrayLabel, i), time - line.get_x1(array.get(_sHigh, i)) >= _session * 15 ?
math.round(
math.avg(
line.get_x1(
array.get(_sHigh, i)), line.get_x2(array.get(_sHigh, i)))) : time)
else
if array.includes(_arrayHold2, line.get_y1(array.get(_sHigh, i))) == false
array.push(_arrayLine2, line.new(time[1], line.get_y1(array.get(_sHigh, i)), time, line.get_y1(array.get(_sHigh, i)), color = na,
style = line.style_dashed, xloc = xloc.bar_time))
array.push(_arrayHold2, line.get_y1(array.get(_sHigh, i)))
array.push(_line2Count, 0)
array.push(_max, high)
if _hideDev == true
if math.abs(close / line.get_y1(array.get(_sHigh, i)) - 1) >= _devDelete
line.set_x2(array.get(_sHigh, i), line.get_x1(array.get(_sHigh, i)))
label.set_x(array.get(_arrayLabel, i), line.get_x1(array.get(_sHigh, i)))
label.set_textcolor(array.get(_arrayLabel, i), na)
if array.size(_max) > 0
for i = 0 to array.size(_max) - 1
array.set(_max, i, math.max(array.get(_max, i), high))
if array.size(_arrayLine2) > 0
for i = 0 to array.size(_arrayLine2) - 1
if array.get(_line2Count, i) == 0
if low > line.get_y1(array.get(_arrayLine2, i))
line.set_x2(array.get(_arrayLine2, i), time)
line.set_color(array.get(_arrayLine2, i), color.from_gradient(time, line.get_x1(array.get(_arrayLine2, i)),
line.get_x1(array.get(_arrayLine2, i)) + (_session * 100), color.yellow, #fff9c4))
array.set(_line2Count, i, 1)
if array.get(_line2Count, i) == 1
line.set_x2(array.get(_arrayLine2, i), time)
line.set_color(array.get(_arrayLine2, i), color.from_gradient(time, line.get_x1(array.get(_arrayLine2, i)),
line.get_x1(array.get(_arrayLine2, i)) + (_session * 100), color.yellow, #fff9c4))
if low <= line.get_y1(array.get(_arrayLine2, i)) and high >= line.get_y1(array.get(_arrayLine2, i))
array.set(_line2Count, i, 2)
array.push(_r, label.new(bar_index, line.get_y1(array.get(_arrayLine2, i)), "(Retest)" , xloc = xloc.bar_index,
size = size.small, color = color.new(color.black, 100), style = label.style_label_up,
textcolor = _showLab == true ? color.from_gradient(time, line.get_x1(array.get(_arrayLine2, i)),
line.get_x1(array.get(_arrayLine2, i)) + _session * 100, color.yellow, #fff9c4) : color.new(color.black, 100)))
array.push(_avgMax, _logR == true ? math.log(array.get(_max, i) / line.get_y1(array.get(_arrayLine2, i))) :
array.get(_max, i) / line.get_y1(array.get(_arrayLine2, i)) - 1)
array.push(_avgRetestBar, bar_index)
if array.get(_line2Count, i) == 2
if time - line.get_x2(array.get(_arrayLine2, i)) >= _session * _hide_days
line.delete(array.remove(_arrayLine2, i))
array.remove(_line2Count, i)
break
// if i < array.size(_arrayLine2)
// continue
if _hideDev == true
if math.abs(close / line.get_y1(array.get(_arrayLine2, i)) - 1) >= _devDelete
line.set_x2(array.get(_arrayLine2, i), line.get_x1(array.get(_arrayLine2, i)))
label.set_x(array.get(_arrayLabel, i), line.get_x1(array.get(_sHigh, i)))
label.set_textcolor(array.get(_arrayLabel, i), na)
if _hide_r ==true
if array.size(_r) > 0
for n = 0 to array.size(_r) - 1
if bar_index - label.get_x(array.get(_r, n)) >= _hide_days
label.set_textcolor(array.get(_r, n), na)
if _hideDev ==true
if array.size(_r) > 0
for n = 0 to array.size(_r) - 1
if math.abs(close / label.get_y(array.get(_r, n)) - 1) >= _devDelete
label.set_textcolor(array.get(_r, n), na)
else
if _showLab == true
label.set_textcolor(array.get(_r, n), color.yellow)
if array.size(_r) > 0
for i = 0 to array.size(_r) - 1
if bar_index - array.get(_avgRetestBar, i) == _avgGainInput
array.push(_avgRetest, _logR == true ? math.log(close / label.get_y(array.get(_r, i)))
: close / label.get_y(array.get(_r, i)) - 1)
// ------{{Swing Low}}------
if _data != "SH"
var string _pRank = ""
if _sLowLasts
if _sVolBool == true
array.push(_sLowVolTrack, volume)
_pRank := array.size(_sHighVol) > 5 ? "\nVol. Rank: " + str.tostring(array.percentrank(_sHighVol, array.size(_sHighVol) - 3), format.percent) : ""
array.push(_rankTrack, _pRank)
array.push(_sLow, line.new(time[2], low[2], time, low[2], color = #b2ebf2, xloc = xloc.bar_time))
array.push(_arrayLabelLow, label.new(time, line.get_y1(array.get(_sLow, array.size(_sLow) - 1)),
"(" + str.tostring(0, "#") + ")" + "\n" +
str.tostring((close / line.get_y1(array.get(_sLow, array.size(_sLow) - 1)) - 1) * 100, format.percent) + _pRank, color = na,
textcolor = _showLab == true ?
#c8e6c9 : color.new(color.black,100), xloc = xloc.bar_time, size = size.small))
array.push(_barCountLow, bar_index)
if array.size(_sLow) > 0
for i = 0 to array.size(_sLow) - 1
if low[1] < line.get_y1(array.get(_sLow, i)) and array.includes(_arrayHoldLow, line.get_y1(array.get(_sLow, i))) == false
array.push(_arrayHoldLow, line.get_y1(array.get(_sLow, i)))
if _sVolBool == true
label.set_text(array.get(_arrayLabelLow, i), "Impulse Dn\n" + "Vol. Rank: " + array.get(_rankTrack, i))
else
label.set_text(array.get(_arrayLabelLow, i), "Impulse Dn")
if _hide_r == true
line.set_color(array.get(_sLow, i), na)
if array.size(_sLow) > 0
for i = 0 to array.size(_sLow) - 1
if array.includes(_arrayHoldLow, line.get_y1(array.get(_sLow, i))) == false
line.set_x2(array.get(_sLow, i), time)
line.set_color(array.get(_sLow, i), color.from_gradient(time, line.get_x1(array.get(_sLow, i)), line.get_x1(array.get(_sLow, i)) +
_session * 100, color.aqua, #80deea))
if _sVolBool == false
label.set_text(array.get(_arrayLabelLow, i), "(" + str.tostring(bar_index - array.get(_barCountLow, i), "#") + ")" + "\n" +
str.tostring((close / line.get_y1(array.get(_sLow, i)) - 1) * 100, format.percent))
else
if array.size(_rankTrack) > 0
label.set_text(array.get(_arrayLabelLow, i), "(" + str.tostring(bar_index - array.get(_barCountLow, i), "#") + ")" + "\n" +
str.tostring((close / line.get_y1(array.get(_sLow, i)) - 1) * 100, format.percent) + array.get(_rankTrack, i))
if _showLab == true
label.set_textcolor(array.get(_arrayLabelLow, i), color.from_gradient(time, line.get_x1(array.get(_sLow, i)), line.get_x1(array.get(_sLow, i)) +
_session * 100, color.aqua, #80deea))
label.set_x(array.get(_arrayLabelLow, i), time - line.get_x1(array.get(_sLow, i)) >= _session * 15 ?
math.round(
math.avg(
line.get_x1(
array.get(_sLow, i)), line.get_x2(array.get(_sLow, i)))) : time)
else
if array.includes(_arrayHoldLow2, line.get_y1(array.get(_sLow, i))) == false
array.push(_arrayLineLow2, line.new(time[1], line.get_y1(array.get(_sLow, i)), time, line.get_y1(array.get(_sLow, i)),
color = na, style = line.style_dashed, xloc = xloc.bar_time))
array.push(_arrayHoldLow2, line.get_y1(array.get(_sLow, i)))
array.push(_line2CountLow, 0)
array.push(_min, low)
if _hideDev == true
if math.abs(close / line.get_y1(array.get(_sLow, i)) - 1) >= _devDelete
line.set_x2(array.get(_sLow, i), line.get_x1(array.get(_sLow, i)))
label.set_x(array.get(_arrayLabelLow, i), line.get_x1(array.get(_sLow, i)))
if _showLab == true
label.set_textcolor(array.get(_arrayLabelLow, i), na)
if array.size(_min) > 0
for i = 0 to array.size(_min) - 1
array.set(_min, i, math.min(array.get(_min, i), low))
if array.size(_arrayLineLow2) > 0
for i = 0 to array.size(_arrayLineLow2) - 1
if array.get(_line2CountLow, i) == 0
if high < line.get_y1(array.get(_arrayLineLow2, i))
line.set_x2(array.get(_arrayLineLow2, i), time)
line.set_color(array.get(_arrayLineLow2, i), color.from_gradient(time, line.get_x1(array.get(_arrayLineLow2, i)),
line.get_x1(array.get(_arrayLineLow2, i)) + (_session * 100), color.purple, #ce93d8))
array.set(_line2CountLow, i, 1)
if array.get(_line2CountLow, i) == 1
line.set_x2(array.get(_arrayLineLow2, i), time)
line.set_color(array.get(_arrayLineLow2, i), color.from_gradient(time, line.get_x1(array.get(_arrayLineLow2, i)),
line.get_x1(array.get(_arrayLineLow2, i)) + (_session * 100), color.purple, #ce93d8))
if high >= line.get_y1(array.get(_arrayLineLow2, i)) and low <= line.get_y1(array.get(_arrayLineLow2, i))
array.set(_line2CountLow, i, 2)
array.push(_rLow, label.new(bar_index, line.get_y1(array.get(_arrayLineLow2, i)), "(Retest)" , xloc = xloc.bar_index,
size = size.small, color = color.new(color.black, 100), style = label.style_label_down,
textcolor = _showLab == true ? color.from_gradient(time, line.get_x1(array.get(_arrayLineLow2, i)),
line.get_x1(array.get(_arrayLineLow2, i)) + _session * 100, color.purple, #ce93d8) : color.new(color.black, 100)))
array.push(_avgMin, _logR == true ? math.log(array.get(_min, i) / line.get_y1(array.get(_arrayLineLow2, i))) :
array.get(_min, i) / line.get_y1(array.get(_arrayLineLow2, i)) - 1)
array.push(_avgRetestBarLow, bar_index)
if array.get(_line2CountLow, i) == 2
if time - line.get_x2(array.get(_arrayLineLow2, i)) >= _session * _hide_days
line.delete(array.remove(_arrayLineLow2, i))
array.remove(_line2CountLow, i)
break
// if i < array.size(_arrayLineLow2)
// continue
if _hideDev == true
if math.abs(close / line.get_y1(array.get(_arrayLineLow2, i)) - 1) >= _devDelete
line.set_x2(array.get(_arrayLineLow2, i), line.get_x1(array.get(_arrayLineLow2, i)))
label.set_x(array.get(_arrayLabelLow, i), line.get_x1(array.get(_sLow, i)))
if _showLab == true
label.set_textcolor(array.get(_arrayLabelLow, i), na)
if _hide_r ==true
if array.size(_rLow) > 0
for n = 0 to array.size(_rLow) - 1
if bar_index - label.get_x(array.get(_rLow, n)) >= _hide_days
label.set_textcolor(array.get(_rLow, n), na)
if _hideDev ==true
if array.size(_rLow) > 0
for n = 0 to array.size(_rLow) - 1
if math.abs(close / label.get_y(array.get(_rLow, n)) - 1) >= _devDelete
label.set_textcolor(array.get(_rLow, n), na)
else
if _showLab == true
label.set_textcolor(array.get(_rLow, n), color.purple)
if array.size(_rLow) > 0
for i = 0 to array.size(_rLow) - 1
if bar_index - array.get(_avgRetestBarLow, i) == _avgGainInput
array.push(_avgRetestLow, _logR == true ? math.log(close / label.get_y(array.get(_rLow, i))) :
close / label.get_y(array.get(_rLow, i)) - 1)
if barstate.islast
var table statisticsTable = table.new(position.bottom_right, 5, 5, frame_color = color.white, border_color = color.white, frame_width = 1, border_width = 1)
if array.size(_avgMax) > 0
table.cell(statisticsTable, 0, 0, "Avg. Percent Gain Following Impulse Up,\nUntil Level is Retested\n" + str.tostring(array.avg(_avgMax) * 100, format.percent),
text_color = color.white, bgcolor = color.new(#26c6da, 90), text_size = _finalSize)
table.cell(statisticsTable, 0, 1, "Avg. " + str.tostring(_avgGainInput, "#") + "-Bar Percent Gain/Loss Following Retest (Swing High)\n" +
str.tostring(array.avg(_avgRetest) * 100, format.percent),
text_color = color.white, bgcolor = color.new(#4dd0e1, 90), text_size = _finalSize)
if array.size(_avgMin) > 0
table.cell(statisticsTable, 0, 2, "Avg. Percent Loss Following Impulse Down,\nUntil Level is Retested\n" + str.tostring(array.avg(_avgMin) * 100, format.percent),
text_color = color.white, bgcolor = color.new(#80deea, 90), text_size = _finalSize)
table.cell(statisticsTable, 0, 3, "Avg. " + str.tostring(_avgGainInput, "#") + "-Bar Percent Gain/Loss Following Retest (Swing Low)\n" +
str.tostring(array.avg(_avgRetestLow) * 100, format.percent),
text_color = color.white, bgcolor = color.new(#0097a7, 90), text_size = _finalSize)
if _lineOnly == true
for i = 0 to array.size(_arrayLabel) - 1
label.set_textcolor(array.get(_arrayLabel, i), na)
for i = 0 to array.size(_arrayLabelLow) - 1
label.set_textcolor(array.get(_arrayLabelLow, i), na)
for i = 0 to array.size(_r) - 1
label.set_textcolor(array.get(_r, i), na)
for i = 0 to array.size(_rLow) - 1
label.set_textcolor(array.get(_rLow, i), na)
var table _colorCoord = table.new(position.top_right, 20, 20)
if _showLab == false and _lineOnly == false
if _hidePanel == false
table.cell(_colorCoord, 0, 0, text = "Color Identity (SH)", text_color = color.white)
table.cell(_colorCoord, 0, 1, text = '"⎯⎯⎯⎯" = Swing High (Recent)',bgcolor = na, text_color = color.lime, text_halign = text.align_left)
table.cell(_colorCoord, 0, 2, text = '"⎯⎯⎯⎯" = Swing High (Older)',bgcolor = na, text_color = #c8e6c9, text_halign = text.align_left)
table.cell(_colorCoord, 0, 3, text = '"------" = Violated Swing High / Retest Level (Recent)',bgcolor = na, text_color = color.yellow, text_halign = text.align_left)
table.cell(_colorCoord, 0, 4, text = '"------" = Violated Swing High / Retest Level (Older)',bgcolor = na, text_color = #fff9c4, text_halign = text.align_left)
table.cell(_colorCoord, 0, 5, text = "\nColor Identity (SL)", text_color = color.white)
table.cell(_colorCoord, 0, 6, text = '"⎯⎯⎯⎯" = Swing Low (Recent)',bgcolor = na, text_color = color.aqua, text_halign = text.align_left)
table.cell(_colorCoord, 0, 7, text = '"⎯⎯⎯⎯" = Swing Low (Older)',bgcolor = na, text_color = #80deea, text_halign = text.align_left)
table.cell(_colorCoord, 0, 8, text = '"------" = Violated Swing Low / Retest Level (Recent)',bgcolor = na, text_color = color.purple, text_halign = text.align_left)
table.cell(_colorCoord, 0, 9, text = '"------" = Violated Swing Low / Retest Level (Older)',bgcolor = na, text_color = #ce93d8, text_halign = text.align_left)
|
Moving Average Compendium Refurbished | https://www.tradingview.com/script/CEyNpwaS-Moving-Average-Compendium-Refurbished/ | andre_007 | https://www.tradingview.com/u/andre_007/ | 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/
// © andre_007
//@version=5
indicator("Moving Average Compendium Refurbished", shorttitle='MA Compendium Refurbished', format=format.price, precision=2, overlay=true)
import andre_007/MovingAveragesProxy/2 as MaProxy
// ———————————————————————————————————————— Constants {
var string AARMA = 'Adaptive Autonomous Recursive Moving Average'
var string ADEMA = '* Alpha-Decreasing Exponential Moving Average'
var string AHMA = 'Ahrens Moving Average'
var string ALMA = 'Arnaud Legoux Moving Average'
var string ALSMA = 'Adaptive Least Squares'
var string AUTOL = 'Auto-Line'
var string CMA = 'Corrective Moving average'
var string CORMA = 'Correlation Moving Average Price'
var string COVWEMA = 'Coefficient of Variation Weighted Exponential Moving Average'
var string COVWMA = 'Coefficient of Variation Weighted Moving Average'
var string DEMA = 'Double Exponential Moving Average'
var string DONCHIAN = 'Donchian Middle Channel'
var string DONCHIAN_HL = 'Donchian Middle Channel High-Low Version'
var string EDMA = 'Exponentially Deviating Moving Average'
var string EDSMA = 'Ehlers Dynamic Smoothed Moving Average'
var string EFRAMA = '* Ehlrs Modified Fractal Adaptive Moving Average'
var string EHMA = 'Exponential Hull Moving Average'
var string EMA = 'Exponential Moving Average'
var string EPMA = 'End Point Moving Average'
var string ETMA = 'Exponential Triangular Moving Average'
var string EVWMA = 'Elastic Volume Weighted Moving Average'
var string FAMA = 'Following Adaptive Moving Average'
var string FIBOWMA = 'Fibonacci Weighted Moving Average'
var string FISHLSMA = 'Fisher Least Squares Moving Average'
var string FRAMA = 'Fractal Adaptive Moving Average'
var string GMA = 'Geometric Moving Average'
var string HKAMA = 'Hilbert based Kaufman\'s Adaptive Moving Average'
var string HMA = 'Hull Moving Average'
var string JURIK = 'Jurik Moving Average'
var string KAMA = 'Kaufman\'s Adaptive Moving Average'
var string LC_LSMA = '1LC-LSMA (1 line code lsma with 3 functions)'
var string LEOMA = 'Leo Moving Average'
var string LINWMA = 'Linear Weighted Moving Average'
var string LSMA = 'Least Squares Moving Average'
var string MAMA = 'MESA Adaptive Moving Average'
var string MCMA = 'McNicholl Moving Average'
var string MEDIAN = 'Median'
var string REGMA = 'Regularized Exponential Moving Average'
var string REMA = 'Range EMA'
var string REPMA = 'Repulsion Moving Average'
var string RMA = 'Relative Moving Average'
var string RSIMA = 'RSI Moving average'
var string RVWAP = '* Rolling VWAP'
var string SMA = 'Simple Moving Average'
var string SMMA = 'Smoothed Moving Average'
var string SRWMA = 'Square Root Weighted Moving Average'
var string SW_MA = 'Sine-Weighted Moving Average'
var string SWMA = '* Symmetrically Weighted Moving Average'
var string TEMA = 'Triple Exponential Moving Average'
var string THMA = 'Triple Hull Moving Average'
var string TREMA = 'Triangular Exponential Moving Average'
var string TRSMA = 'Triangular Simple Moving Average'
var string TT3 = 'Tillson T3'
var string VAMA = 'Volatility Adjusted Moving Average'
var string VIDYA = 'Variable Index Dynamic Average'
var string VWAP = '* VWAP'
var string VWMA = 'Volume-weighted Moving Average'
var string WMA = 'Weighted Moving Average'
var string WWMA = 'Welles Wilder Moving Average'
var string XEMA = 'Optimized Exponential Moving Average'
var string ZEMA = 'Zero-Lag Exponential Moving Average'
var string ZSMA = 'Zero-Lag Simple Moving Average'
// ———————————————————————————————————————— }
// ———————————————————————————————————————— Inputs {
var string inputTypeMa = input.string(SMA, 'Type',
options=[AARMA,ALSMA,AHMA,ADEMA,ALMA,AUTOL,COVWEMA,COVWMA,CMA,CORMA,DEMA,DONCHIAN,DONCHIAN_HL,EFRAMA,EDSMA,EVWMA,EPMA,EDMA,EHMA,EMA,ETMA,FIBOWMA,FISHLSMA,FAMA,FRAMA,GMA,HKAMA,HMA,JURIK,KAMA,LC_LSMA,LEOMA,LSMA,LINWMA,MEDIAN,MAMA,MCMA,XEMA,REMA,REGMA,RMA,REPMA,RVWAP,RSIMA,SMA,SW_MA,SRWMA,SMMA,SWMA,TT3,TREMA,TRSMA,TEMA,THMA,VIDYA,VAMA,VWAP,WMA,WWMA,ZEMA,ZSMA])
var int inputLengthMa = input.int(55, minval=1, title='Length')
float inputSourceMa = input.source(close, title='Source')
var int inputOffsetMa = input.int(title='Offset', defval=0, minval=-500, maxval=500)
var string GRP_VWMA = 'Volume Weighted Moving Average'
var string GRP_VWMA_TOOLTIP = 'The most common "Volume Weighted Moving Average" is a Simple Moving Average of Price x Volume, divided by Simple Moving Average of Volume. \n' +
'Enabling this checkbox, it\'s possible to have other types and less common moving averages weighted by volume, for example, Exponencial Volume Weighted Moving Average, Alma Volume Weighted Moving Average, etc...'
var bool applyVolumeWeighted = input.bool(title="Volume Weighted Moving Average?", defval=false, group=GRP_VWMA, tooltip=GRP_VWMA_TOOLTIP)
var string GROUP_COLORS = 'Colors'
var bool inputLineColors = input.bool(title="Change line colors when moving average is below or above source?", defval=true, group=GROUP_COLORS)
var color inputLineBull = input.color(#3af13c, 'Bullish', inline='A', group=GROUP_COLORS)
var color inputLineBear = input.color(#bd0000, 'Bearish', inline='A', group=GROUP_COLORS)
var color inputLineDefault = input.color(color.white, 'Neutral', inline='A', group=GROUP_COLORS)
var bool inputBarColors = input.bool(title="Change bar colors when source are bellow or above MA?", defval=true, group=GROUP_COLORS)
var color inputBarBull = input.color(#3af13c, 'Bullish', inline='B', group=GROUP_COLORS)
var color inputBarBear = input.color(#bd0000, 'Bearish', inline='B', group=GROUP_COLORS)
// ———————————————————————————————————————— }
// ———————————————————————————————————————— Functions {
// @function applyBarColor
// @description Returns a bull color if price source is greater than a moving average.
// Otherwise returns a bear color.
// @returns Color
applyBarColor(series float src, series float avg) =>
_barColor = if inputBarColors
if src >= nz(avg)
inputBarBull
else
inputBarBear
else
na
// @function applyLineColor
// @description Returns a bull color if moving average is greater than price source.
// Otherwise returns a bear color.
// @returns Color
applyLineColor(series float src, series float avg) =>
_lineColor = if inputLineColors
if src >= nz(avg)
inputLineBull
else
inputLineBear
else
inputLineDefault
// ———————————————————————————————————————— }
// ———————————————————————————————————————— Calcs {
movingAverage = MaProxy.getMovingAverage(type=inputTypeMa, src=inputSourceMa, len=inputLengthMa, volumeWeighted=applyVolumeWeighted)
// ———————————————————————————————————————— }
// ———————————————————————————————————————— Graphics {
plot = plot(movingAverage, title="Moving Average",
color=applyLineColor(inputSourceMa, movingAverage),
offset=inputOffsetMa,
linewidth=1)
barcolor( applyBarColor(inputSourceMa, movingAverage) )
// ———————————————————————————————————————— } |
Kalman Gain Parameter Mechanics | https://www.tradingview.com/script/PwKxN1hf-Kalman-Gain-Parameter-Mechanics/ | capissimo | https://www.tradingview.com/u/capissimo/ | 35 | 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/
// © capissimo
//@version=5
indicator('Kalman Gain Parameter Mechanics', '', true)
// Explanation of Gain parameter of Kalman function in HMA-Kalman & Trendlines script.
// To see better results set your Chart's timeframe to Daily.
//-- Inputs
ds = input.source(close, 'Dataset')
g1 = input.bool(true, 'Kalman', inline='g1')
g2 = input.bool(false, 'Kalman', inline='g2')
g3 = input.bool(false, 'Kalman', inline='g3')
g4 = input.bool(false, 'Kalman', inline='g4')
g5 = input.bool(false, 'Kalman', inline='g5')
gain1 = input.int(1, 'Gain1', 1, step=1, inline='g1')
gain2 = input.int(10, 'Gain2', 1, step=1, inline='g2')
gain3 = input.int(100, 'Gain3', 1, step=1, inline='g3')
gain4 = input.int(1000, 'Gain4', 1, step=1, inline='g4')
gain5 = input.int(10000, 'Gain5', 1, step=1, inline='g5')
strat = input.bool(false, 'Show Strategy Code')
//-- Functions
kalman(x, g) =>
gn = g/1000000 //-- smoothing magnitude adjustment
kf = 0.0
dk = x - nz(kf[1], x)
smooth = nz(kf[1],x)+dk*math.sqrt(gn*2) //-- serves as a smoothing factor
velo = 0.0
velo := nz(velo[1],0) + (gn*dk)
kf := smooth+velo
//-- Logic
k1 = kalman(ds, gain1)
k2 = kalman(ds, gain2)
k3 = kalman(ds, gain3)
k4 = kalman(ds, gain4)
k5 = kalman(ds, gain5)
//-- Visuals
plot(g1 ? k1 : na, 'K1', color.orange)
plot(g2 ? k2 : na, 'K2', color.red)
plot(g3 ? k3 : na, 'K3', color.green)
plot(g4 ? k4 : na, 'K4', color.olive)
plot(g5 ? k5 : na, 'K5', color.gray)
//-- Strategy Logic
var int signal = 0
signal := ta.crossover(k4,k5) ? -1 : ta.crossunder(k4,k5) ? 1 : nz(signal[1])
changed = ta.change(signal)
long = changed and signal== 1
short = changed and signal==-1
//-- Visuals
plot(strat? k4 : na, 'K4', color.olive, 2)
plot(strat? k5 : na, 'K5', color.gray, 2)
plotshape(strat and long ?low :na, '', shape.labelup, location.belowbar, color.green, size=size.small)
plotshape(strat and short?high:na, '', shape.labeldown, location.abovebar, color.red, size=size.small)
|
BTMM V2 | https://www.tradingview.com/script/XUsNqEDu-BTMM-V2/ | RektNoodle | https://www.tradingview.com/u/RektNoodle/ | 170 | 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/
//CREDIT: © Texmoonbeam
// Original pattern formation by plasmapug, rise retrace continuation to the upside by infernix, peshocore and xtech5192
//Initial Balance session by © boitoki
//////INITIAL BALANCE by © noop42
//@version=5
indicator("BTMM R.NOODLE", overlay=true, max_bars_back=300,max_boxes_count=500, max_lines_count=500, max_labels_count=500)
//timeframe = input.timeframe(defval = '240')
abr = input.bool(defval = true, title="Abbreviate Labels", group="Mondays, Weekly, Monthly", inline="0")
zone = input.string('GMT-4', title='Timezone', options=['GMT-11', 'GMT-10', 'GMT-9', 'GMT-8', 'GMT-7', 'GMT-6', 'GMT-5', 'GMT-4', 'GMT-3', 'GMT-2', 'GMT-1', 'GMT', 'GMT+1', 'GMT+2', 'GMT+3', 'GMT+330', 'GMT+4', 'GMT+430', 'GMT+5', 'GMT+530', 'GMT+6', 'GMT+7', 'GMT+8', 'GMT+9', 'GMT+10', 'GMT+11', 'GMT+12'], tooltip='e.g. \'America/New_York\', \'Asia/Tokyo\', \'GMT-4\', \'GMT+9\'...', group="Sessions")
ShowAsia = input.bool(defval = true, title="Show Asia Session ", group="Sessions", inline="1")
ExtendAsia = input.bool(defval = false, title="Extend?", group="Sessions", inline="1")
AsiaOpen = input.bool(defval = false, title="Show Open?", group="Sessions", inline="1")
AsiaOpenCol = input.color(color.new(color.green,25), title="Open Colour", group="Sessions", inline="1")
AsiaSession = input.session("2000-2300:1234567", "Asia Session ", group="Sessions", inline="2")
AsiaCol = input.color(color.new(color.black,90), "Colour", group="Sessions", inline="2")
ShowLon = input.bool(defval = true, title="Show London Session", group="Sessions", inline="4")
ExtendLon = input.bool(defval = false, title="Extend?", group="Sessions", inline="4")
LonOpen = input.bool(defval = false, title="Show Open?", group="Sessions", inline="4")
LonOpenCol = input.color(color.new(color.red,25), title="Open Colour", group="Sessions", inline="4")
LonSession = input.session("0300-0600:1234567", "London Session", group="Sessions", inline="5")
LonCol = input.color(color.new(color.red,90), "Colour", group="Sessions", inline="5")
ShowNY = input.bool(defval = true, title="Show NY Session ", group="Sessions", inline="7")
ExtendNY = input.bool(defval = false, title="Extend?", group="Sessions", inline="7")
NYOpen = input.bool(defval = false, title="Show Open?", group="Sessions", inline="7")
NYOpenCol = input.color(color.new(color.aqua,25), title="Open Colour", group="Sessions", inline="7")
NYSession = input.session("0930-1230:1234567", "NY Session ", group="Sessions", inline="8")
NYCol = input.color(color.new(color.aqua,90), "Colour", group="Sessions", inline="8")
i_show_history = input.bool(defval=false, title='History?', group="Sessions", inline="A")
i_sess_border_style = input.string(line.style_solid, 'Line Style', options=[line.style_solid, line.style_dotted, line.style_dashed], group="Sessions", inline="B")
i_sess_border_width = input.int(1, 'Line Width', minval=0, group="Sessions", inline="B")
i_sess_bgopacity = input.int(80, 'Background Transparency', minval=0, maxval=100, step=1, group="Sessions", tooltip='100 = No Background', inline="C")
Custom1 = input.bool(defval = false, title="Show Custom Level 1 ", group="Custom Levels", inline="1")
Custom1Label = input.string(defval="", title="Label", group="Custom Levels", inline="1")
Custom1Type = input.string('high', title=' Level', options=["high", "low", "open"], group="Custom Levels", inline="1")
Custom1Time = input.session("0000-2345", "Custom Time Range", group="Custom Levels", inline="2")
Custom1Days = input.string("23456", title="Days Included ", tooltip="Enter a digit for each day of the week\n1 = Sunday, 2 = Monday, 3 = Tuesday, etc\nFor example Monday to Friday would be 23456.\nFor a continous line through all included days, use time 00:00 - 00:00\nFor a separate line per day, use any time from 00:00 - 23:45.", group="Custom Levels", inline="2")
Custom1Col = input.color(defval = color.black, title="Custom Level 1 Colour", group="Custom Levels", inline="3")
ExtendCustom1 = input.bool(defval = false, title="Extend?", group="Custom Levels", inline="3")
Custom1History = input.bool(defval=false, title='History?', group="Custom Levels", inline="3")
Custom2 = input.bool(defval = false, title="Show Custom Level 2 ", group="Custom Levels", inline="4")
Custom2Label = input.string(defval="", title="Label", group="Custom Levels", inline="4")
Custom2Type = input.string('high', title=' Level', options=["high", "low", "open"], group="Custom Levels", inline="4")
Custom2Time = input.session("0015-2345", "Custom Time Range", tooltip="", group="Custom Levels", inline="5")
Custom2Days = input.string("23456", title="Days Included ", tooltip="Enter a digit for each day of the week\n1 = Sunday, 2 = Monday, 3 = Tuesday, etc\nFor example Monday to Friday would be 23456.\nFor a continous line through all included days, use time 00:00 - 00:00\nFor a separate line per day, use any time from 00:00 - 23:45.", group="Custom Levels", inline="5")
Custom2Col = input.color(defval = color.black, title="Custom Level 2 Colour", group="Custom Levels", inline="6")
ExtendCustom2 = input.bool(defval = false, title="Extend?", group="Custom Levels", inline="6")
Custom2History = input.bool(defval=false, title='History?', group="Custom Levels", inline="6")
Custom3 = input.bool(defval = false, title="Show Custom Level 3 ", group="Custom Levels", inline="7")
Custom3Label = input.string(defval="", title="Label", group="Custom Levels", inline="7")
Custom3Type = input.string('high', title=' Level', options=["high", "low", "open"], group="Custom Levels", inline="7")
Custom3Time = input.session("1200-1400", "Custom Time Range", group="Custom Levels", inline="8")
Custom3Days = input.string("23456", title="Days Included ", tooltip="Enter a digit for each day of the week\n1 = Sunday, 2 = Monday, 3 = Tuesday, etc\nFor example Monday to Friday would be 23456.\nFor a continous line through all included days, use time 00:00 - 00:00\nFor a separate line per day, use any time from 00:00 - 23:45.", group="Custom Levels", inline="8")
Custom3Col = input.color(defval = color.black, title="Custom Level 3 Colour", group="Custom Levels", inline="9")
ExtendCustom3 = input.bool(defval = false, title="Extend?", group="Custom Levels", inline="9")
Custom3History = input.bool(defval=false, title='History?', group="Custom Levels", inline="9")
Custom1Session = Custom1Time+":"+Custom1Days
Custom2Session = Custom2Time+":"+Custom2Days
Custom3Session = Custom3Time+":"+Custom3Days
ResolutionToSec(res)=>
mins = res == "1" ? 1 :
res == "3" ? 3 :
res == "5" ? 5 :
res == "10" ? 10 :
res == "15" ? 15 :
res == "30" ? 30 :
res == "45" ? 45 :
res == "60" ? 60 :
res == "120" ? 120 :
res == "180" ? 180 :
res == "240" ? 240 :
res == "D" or res == "1D" ? 1440 :
res == "W" or res == "1W" ? 10080 :
res == "M" or res == "1M" ? 43200 : 0
ms = mins * 60 * 1000
bar = ResolutionToSec(timeframe.period)
get_Sessions()=>
highs= array.new_float(0)
lows= array.new_float(0)
starttimes= array.new_int(0)
for n = 0 to 96
array.push(highs, high[n])
array.push(lows, low[n])
array.push(starttimes, time[n])
[highs, lows, starttimes]
///////////////
// Defined
///////////////
show = true
pips = syminfo.mintick * 10
max_bars = 500
fmt_price = '{0,number,#.#####}'
fmt_pips = '{0,number,#.#}'
icon_separator = ' • '
c_none = color.new(color.black, 100)
is_weekends = dayofweek == 7 or dayofweek == 1
f_get_time_by_bar(bar_count) => timeframe.multiplier * bar_count * 60 * 1000
f_get_period (_session, _start, _lookback) =>
result = math.max(_start, 1)
for i = result to _lookback
if na(_session[i+1]) and _session[i]
result := i+1
break
result
f_get_label_position (_y, _side) =>
switch _y
'top' => _side == 'outside' ? label.style_label_lower_left : label.style_label_upper_left
'bottom' => _side == 'outside' ? label.style_label_upper_left : label.style_label_lower_left
f_get_day (n) =>
switch n
1 => 'Sun'
2 => 'Mon'
3 => 'Tue'
4 => 'Wed'
5 => 'Thu'
6 => 'Fri'
7 => 'Sat'
f_get_started (_session) => na(_session[1]) and _session
f_get_ended (_session) => na(_session) and _session[1]
i_lookback = 12 * 60
f_render_session (_show, _session, _showOpen, _is_started, _is_ended, _color, _openColor, _top, _bottom, _is_extend, _delete_history) =>
var box my_box = na
var line my_line = na
var label my_label = na
x0_1 = ta.valuewhen(na(_session[1]) and _session, bar_index, 1)
x0_2 = ta.valuewhen(na(_session) and _session[1], bar_index, 0)
var x1 = 0
var x2 = 0
var session_open = 0.0
var session_high = 0.0
var session_low = 0.0
if _show
if _is_started
diff = math.abs(x0_2 - x0_1)
x1 := bar_index
x2 := bar_index + (math.min(diff, max_bars))
my_box := box.new(x1, _top, x2, _bottom, color.new(_color, i_sess_bgopacity/1.1), i_sess_border_width, i_sess_border_style, bgcolor=color.new(_color, i_sess_bgopacity))
if (_showOpen == true)
my_line := line.new(x1, open, x2, open, color = _openColor, extend= extend.none, style= i_sess_border_style, width=i_sess_border_width)
my_label := label.new(x=x2-2, y=open, text=(abr == true?"O":"Open"), color=color.white, style=label.style_none, textcolor=_openColor, size=size.small, textalign=text.align_left)
session_open := open
session_high := _top
session_low := _bottom
if _is_extend
box.set_extend(my_box, extend.right)
line.set_extend(my_line, extend.right)
if _delete_history
box.delete(my_box[1])
line.delete(my_line[1])
label.delete(my_label[1])
else if _session
box.set_top(my_box, _top)
box.set_bottom(my_box, _bottom)
session_high := _top
session_low := _bottom
else if _is_ended
session_open := na
box.set_right(my_box, bar_index)
[x1, x2, session_open, session_high, session_low]
f_render_custom (_show, _session, _is_started, _is_ended, _color, _label, _type, _top, _bottom, _is_extend, _delete_history) =>
var line my_line = na
var label my_label = na
x0_1 = ta.valuewhen(na(_session[1]) and _session, bar_index, 1)
x0_2 = ta.valuewhen(na(_session) and _session[1], bar_index, 0)
var x1 = 0
var x2 = 0
var session_open = 0.0
var session_high = 0.0
var session_low = 0.0
var level = 0.0
if _show
level := _type == "high" ? _top : _type == "low" ? _bottom : session_open
if _is_started
diff = math.abs(x0_2 - x0_1)
x1 := bar_index
x2 := bar_index + (math.min(diff, max_bars))
my_line := line.new(x1, level, x2, level, color = _color, extend= extend.none, style= i_sess_border_style, width=i_sess_border_width)
my_label := label.new(x=x2-2, y=level, text=_label, color=color.white, style=label.style_none, textcolor=_color, size=size.normal, textalign=text.align_left)
session_open := open
session_high := _top
session_low := _bottom
if _is_extend
line.set_extend(my_line, extend.right)
if _delete_history
line.delete(my_line[1])
label.delete(my_label[1])
else if _session
line.set_y1(my_line, level)
line.set_y2(my_line, level)
label.set_y(my_label, level)
session_high := _top
session_low := _bottom
else if _is_ended
session_open := na
line.set_x2(my_line, bar_index)
label.set_x(my_label, bar_index)
[x1, x2, session_open, session_high, session_low]
draw (_show,_showOpen, _session, _color, _openColor, is_extend, _lookback) =>
max = f_get_period(_session, 1, _lookback)
top = ta.highest(high, max)
bottom = ta.lowest(low, max)
is_started = f_get_started(_session)
is_ended = f_get_ended(_session)
delete_history = (not i_show_history) or is_extend
[x1, x2, _open, _high, _low] = f_render_session(_show, _session, _showOpen, is_started, is_ended, _color, _openColor, top, bottom, is_extend, delete_history)
[_session, _open, _high, _low]
drawcustom (_show, _session, _color, _label, _type, is_extend, _lookback, custom_history) =>
max = f_get_period(_session, 1, _lookback)
top = ta.highest(high, max)
bottom = ta.lowest(low, max)
is_started = f_get_started(_session)
is_ended = f_get_ended(_session)
delete_history = (not custom_history) or is_extend
[x1, x2, _open, _high, _low] = f_render_custom(_show, _session, is_started, is_ended, _color, _label, _type, top, bottom, is_extend, delete_history)
[_session, _open, _high, _low]
int sess1 = time(timeframe.period, AsiaSession, zone)
int sess2 = time(timeframe.period, LonSession, zone)
int sess3 = time(timeframe.period, NYSession, zone)
int customsess1 = time(timeframe.period, Custom1Session, zone)
int customsess2 = time(timeframe.period, Custom2Session, zone)
int customsess3 = time(timeframe.period, Custom3Session, zone)
draw(ShowAsia, AsiaOpen, sess1, AsiaCol, AsiaOpenCol, ExtendAsia, i_lookback)
draw(ShowLon, LonOpen, sess2, LonCol, LonOpenCol,ExtendLon, i_lookback)
draw(ShowNY, NYOpen, sess3, NYCol, NYOpenCol,ExtendNY, i_lookback)
drawcustom(Custom1, customsess1, Custom1Col, Custom1Label, Custom1Type, ExtendCustom1, i_lookback, Custom1History)
drawcustom(Custom2, customsess2, Custom2Col, Custom2Label, Custom2Type, ExtendCustom2, i_lookback, Custom2History)
drawcustom(Custom3, customsess3, Custom3Col, Custom3Label, Custom3Type, ExtendCustom3, i_lookback, Custom3History)
//1stfriday + monday
c = #fc1687
final_color = if dayofmonth < 8 and dayofweek == 6
color.new(#fc1687, 70)
else
color_1 = color.new(c, 90)
color_2 = color.new(c, 100)
color_3 = color.new(c, 100)
color_4 = color.new(c, 100)
color_5 = color.new(c, 100)
color_6 = color.new(color.black, 0)
dayofweek == dayofweek.monday ? color_1 : dayofweek == dayofweek.tuesday ? color_2 : dayofweek == dayofweek.wednesday ? color_3 : dayofweek == dayofweek.thursday ? color_4 : dayofweek == dayofweek.friday ? color_5 : color_6
bgcolor(color=final_color, transp=90)
//35 works
displayStyle = input.string(defval='Standard', title='Display Style', options=['Standard', 'Right Anchored'], inline='Display')
mergebool = input.bool(defval=true, title='Merge Levels?', inline='Display')
distanceright = input.int(defval=30, title='Distance', minval=5, maxval=500, inline='Dist')
radistance = input.int(defval=250, title='Anchor Distance', minval=5, maxval=500, inline='Dist')
labelsize = input.string(defval='Medium', title='Text Size', options=['Small', 'Medium', 'Large'])
linesize = input.string(defval='Small', title='Line Width', options=['Small', 'Medium', 'Large'], inline='Line')
linestyle = input.string(defval='Solid', title='Line Style', options=['Solid', 'Dashed', 'Dotted'], inline='Line')
GlobalTextType = input.bool(defval=false, title='Global Text ShortHand', tooltip='Enable for shorthand text on all text')
var globalcoloring = input.bool(defval=false, title='Global Coloring', tooltip='Enable for all color controls via one color', inline='GC')
GlobalColor = input.color(title='', defval=color.white, inline='GC')
//var show_tails = input(defval = false, title = "Always Show", type = input.bool)
[daily_time, daily_open] = request.security(syminfo.tickerid, 'D', [time, open], lookahead=barmerge.lookahead_on)
[dailyh_time, dailyh_open] = request.security(syminfo.tickerid, 'D', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[dailyl_time, dailyl_open] = request.security(syminfo.tickerid, 'D', [time[1], low[1]], lookahead=barmerge.lookahead_on)
cdailyh_open = request.security(syminfo.tickerid, 'D', high, lookahead=barmerge.lookahead_on)
cdailyl_open = request.security(syminfo.tickerid, 'D', low, lookahead=barmerge.lookahead_on)
var monday_time = time
var monday_high = high
var monday_low = low
[weekly_time, weekly_open] = request.security(syminfo.tickerid, 'W', [time, open], lookahead=barmerge.lookahead_on)
[weeklyh_time, weeklyh_open] = request.security(syminfo.tickerid, 'W', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[weeklyl_time, weeklyl_open] = request.security(syminfo.tickerid, 'W', [time[1], low[1]], lookahead=barmerge.lookahead_on)
[monthly_time, monthly_open] = request.security(syminfo.tickerid, 'M', [time, open], lookahead=barmerge.lookahead_on)
[monthlyh_time, monthlyh_open] = request.security(syminfo.tickerid, 'M', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[monthlyl_time, monthlyl_open] = request.security(syminfo.tickerid, 'M', [time[1], low[1]], lookahead=barmerge.lookahead_on)
[quarterly_time, quarterly_open] = request.security(syminfo.tickerid, '3M', [time, open], lookahead=barmerge.lookahead_on)
[quarterlyh_time, quarterlyh_open] = request.security(syminfo.tickerid, '3M', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[quarterlyl_time, quarterlyl_open] = request.security(syminfo.tickerid, '3M', [time[1], low[1]], lookahead=barmerge.lookahead_on)
[yearly_time, yearly_open] = request.security(syminfo.tickerid, '12M', [time, open], lookahead=barmerge.lookahead_on)
[yearlyh_time, yearlyh_open] = request.security(syminfo.tickerid, '12M', [time, high], lookahead=barmerge.lookahead_on)
[yearlyl_time, yearlyl_open] = request.security(syminfo.tickerid, '12M', [time, low], lookahead=barmerge.lookahead_on)
[intra_time, intra_open] = request.security(syminfo.tickerid, '240', [time, open], lookahead=barmerge.lookahead_on)
[intrah_time, intrah_open] = request.security(syminfo.tickerid, '240', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[intral_time, intral_open] = request.security(syminfo.tickerid, '240', [time[1], low[1]], lookahead=barmerge.lookahead_on)
//------------------------------ Inputs -------------------------------
var is_intra_enabled = input.bool(defval=false, title='Open', group='4H', inline='4H')
var is_intrarange_enabled = input.bool(defval=false, title='Prev H/L', group='4H', inline='4H')
var is_intram_enabled = input.bool(defval=false, title='Prev Mid', group='4H', inline='4H')
IntraTextType = input.bool(defval=false, title='ShortHand', group='4H', inline='4Hsh')
var is_daily_enabled = input.bool(defval=true, title='Open', group='Daily', inline='Daily')
var is_dailyrange_enabled = input.bool(defval=false, title='Prev H/L', group='Daily', inline='Daily')
var is_dailym_enabled = input.bool(defval=false, title='Prev Mid', group='Daily', inline='Daily')
DailyTextType = input.bool(defval=false, title='ShortHand', group='Daily', inline='Dailysh')
var is_monday_enabled = input.bool(defval=true, title='Range', group='Monday Range', inline='Monday')
var is_monday_mid = input.bool(defval=true, title='Mid', group='Monday Range', inline='Monday')
var untested_monday = false
MondayTextType = input.bool(defval=false, title='ShortHand', group='Monday Range', inline='Mondaysh')
var is_weekly_enabled = input.bool(defval=true, title='Open', group='Weekly', inline='Weekly')
var is_weeklyrange_enabled = input.bool(defval=true, title='Prev H/L', group='Weekly', inline='Weekly')
var is_weekly_mid = input.bool(defval=true, title='Prev Mid', group='Weekly', inline='Weekly')
WeeklyTextType = input.bool(defval=false, title='ShortHand', group='Weekly', inline='Weeklysh')
var is_monthly_enabled = input.bool(defval=true, title='Open', group='Monthly', inline='Monthly')
var is_monthlyrange_enabled = input.bool(defval=true, title='Prev H/L', group='Monthly', inline='Monthly')
var is_monthly_mid = input.bool(defval=true, title='Prev Mid', group='Monthly', inline='Monthly')
MonthlyTextType = input.bool(defval=false, title='ShortHand', group='Monthly', inline='Monthlysh')
var is_quarterly_enabled = input.bool(defval=true, title='Open', group='Quarterly', inline='Quarterly')
var is_quarterlyrange_enabled = input.bool(defval=false, title='Prev H/L', group='Quarterly', inline='Quarterly')
var is_quarterly_mid = input.bool(defval=true, title='Prev Mid', group='Quarterly', inline='Quarterly')
QuarterlyTextType = input.bool(defval=false, title='ShortHand', group='Quarterly', inline='Quarterlysh')
var is_yearly_enabled = input.bool(defval=true, title='Open', group='Yearly', inline='Yearly')
var is_yearlyrange_enabled = input.bool(defval=false, title='Current H/L', group='Yearly', inline='Yearly')
var is_yearly_mid = input.bool(defval=true, title='Mid', group='Yearly', inline='Yearly')
YearlyTextType = input.bool(defval=false, title='ShortHand', group='Yearly', inline='Yearlysh')
DailyColor = input.color(title='', defval=#08bcd4, group='Daily', inline='Dailysh')
MondayColor = input.color(title='', defval=color.white, group='Monday Range', inline='Mondaysh')
WeeklyColor = input.color(title='', defval=#fffcbc, group='Weekly', inline='Weeklysh')
MonthlyColor = input.color(title='', defval=#08d48c, group='Monthly', inline='Monthlysh')
YearlyColor = input.color(title='', defval=color.red, group='Yearly', inline='Yearlysh')
quarterlyColor = input.color(title='', defval=color.red, group='Quarterly', inline='Quarterlysh')
IntraColor = input.color(title='', defval=color.orange, group='4H', inline='4Hsh')
var pdhtext = GlobalTextType or DailyTextType ? 'PDH' : 'Prev Day High'
var pdltext = GlobalTextType or DailyTextType ? 'PDL' : 'Prev Day Low'
var dotext = GlobalTextType or DailyTextType ? 'DO' : 'Daily Open'
var pdmtext = GlobalTextType or DailyTextType ? 'PDM' : 'Prev Day Mid'
var pwhtext = GlobalTextType or WeeklyTextType ? 'PWH' : 'Prev Week High'
var pwltext = GlobalTextType or WeeklyTextType ? 'PWL' : 'Prev Week Low'
var wotext = GlobalTextType or WeeklyTextType ? 'WO' : 'Weekly Open'
var pwmtext = GlobalTextType or WeeklyTextType ? 'PWM' : 'Prev Week Mid'
var pmhtext = GlobalTextType or MonthlyTextType ? 'PMH' : 'Prev Month High'
var pmltext = GlobalTextType or MonthlyTextType ? 'PML' : 'Prev Month Low'
var motext = GlobalTextType or MonthlyTextType ? 'MO' : 'Monthly Open'
var pmmtext = GlobalTextType or MonthlyTextType ? 'PMM' : 'Prev Month Mid'
var pqhtext = GlobalTextType or QuarterlyTextType ? 'PQH' : 'Prev Quarter High'
var pqltext = GlobalTextType or QuarterlyTextType ? 'PQL' : 'Prev Quarter Low'
var qotext = GlobalTextType or QuarterlyTextType ? 'QO' : 'Quarterly Open'
var pqmtext = GlobalTextType or QuarterlyTextType ? 'PQM' : 'Prev Quarter Mid'
var cyhtext = GlobalTextType or YearlyTextType ? 'CYH' : 'Current Year High'
var cyltext = GlobalTextType or YearlyTextType ? 'CYL' : 'Current Year Low'
var yotext = GlobalTextType or YearlyTextType ? 'YO' : 'Yearly Open'
var cymtext = GlobalTextType or YearlyTextType ? 'CYM' : 'Current Year Mid'
var pihtext = GlobalTextType or IntraTextType ? 'P-4H-H' : 'Prev 4H High'
var piltext = GlobalTextType or IntraTextType ? 'P-4H-L' : 'Prev 4H Low'
var iotext = GlobalTextType or IntraTextType ? '4H-O' : '4H Open'
var pimtext = GlobalTextType or IntraTextType ? 'P-4H-M' : 'Prev 4H Mid'
var pmonhtext = GlobalTextType or MondayTextType ? 'MDAY-H' : 'Monday High'
var pmonltext = GlobalTextType or MondayTextType ? 'MDAY-L' : 'Monday Low'
var pmonmtext = GlobalTextType or MondayTextType ? 'MDAY-M' : 'Monday Mid'
if globalcoloring == true
DailyColor := GlobalColor
MondayColor := GlobalColor
WeeklyColor := GlobalColor
MonthlyColor := GlobalColor
YearlyColor := GlobalColor
quarterlyColor := GlobalColor
IntraColor := GlobalColor
IntraColor
if weekly_time != weekly_time[1]
untested_monday := false
untested_monday
if is_monday_enabled == true and untested_monday == false
untested_monday := true
monday_time := daily_time
monday_high := cdailyh_open
monday_low := cdailyl_open
monday_low
linewidthint = 1
if linesize == 'Small'
linewidthint := 1
linewidthint
if linesize == 'Medium'
linewidthint := 2
linewidthint
if linesize == 'Large'
linewidthint := 3
linewidthint
var DEFAULT_LINE_WIDTH = linewidthint
var DEFAULT_TAIL_WIDTH = linewidthint
fontsize = size.small
if labelsize == 'Small'
fontsize := size.small
fontsize
if labelsize == 'Medium'
fontsize := size.normal
fontsize
if labelsize == 'Large'
fontsize := size.large
fontsize
linestyles = line.style_solid
if linestyle == 'Dashed'
linestyles := line.style_dashed
linestyles
if linestyle == 'Dotted'
linestyles := line.style_dotted
linestyles
var DEFAULT_LABEL_SIZE = fontsize
var DEFAULT_LABEL_STYLE = label.style_none
var DEFAULT_EXTEND_RIGHT = distanceright
//------------------------------ Plotting ------------------------------
var pricearray = array.new_float(0)
var labelarray = array.new_label(0)
f_LevelMerge(pricearray, labelarray, currentprice, currentlabel, currentcolor) =>
if array.includes(pricearray, currentprice)
whichindex = array.indexof(pricearray, currentprice)
labelhold = array.get(labelarray, whichindex)
whichtext = label.get_text(labelhold)
label.set_text(labelhold, label.get_text(currentlabel) + ' / ' + whichtext)
label.set_text(currentlabel, '')
label.set_textcolor(labelhold, currentcolor)
else
array.push(pricearray, currentprice)
array.push(labelarray, currentlabel)
var can_show_daily = is_daily_enabled and timeframe.isintraday
var can_show_weekly = is_weekly_enabled and not timeframe.isweekly and not timeframe.ismonthly
var can_show_monthly = is_monthly_enabled and not timeframe.ismonthly
get_limit_right(bars) =>
timenow + (time - time[1]) * bars
// the following code doesn't need to be processed on every candle
if barstate.islast
is_weekly_open = dayofweek == dayofweek.monday
is_monthly_open = dayofmonth == 1
can_draw_daily = (is_weekly_enabled ? not is_weekly_open : true) and (is_monthly_enabled ? not is_monthly_open : true)
can_draw_weekly = is_monthly_enabled ? not(is_monthly_open and is_weekly_open) : true
can_draw_intra = is_intra_enabled
can_draw_intrah = is_intrarange_enabled
can_draw_intral = is_intrarange_enabled
can_draw_intram = is_intram_enabled
pricearray := array.new_float(0)
labelarray := array.new_label(0)
/////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
if can_draw_intra
intra_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
intra_time := get_limit_right(radistance)
intra_time
var intra_line = line.new(x1=intra_time, x2=intra_limit_right, y1=intra_open, y2=intra_open, color=IntraColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var intra_label = label.new(x=intra_limit_right, y=intra_open, text=iotext, style=DEFAULT_LABEL_STYLE, textcolor=IntraColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(intra_line, intra_time)
line.set_x2(intra_line, intra_limit_right)
line.set_y1(intra_line, intra_open)
line.set_y2(intra_line, intra_open)
label.set_x(intra_label, intra_limit_right)
label.set_y(intra_label, intra_open)
label.set_text(intra_label, iotext)
if mergebool
f_LevelMerge(pricearray, labelarray, intra_open, intra_label, IntraColor)
//////////////////////////////////////////////////////////////////////////////////
//HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH
if can_draw_intrah
intrah_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
intrah_time := get_limit_right(radistance)
intrah_time
var intrah_line = line.new(x1=intrah_time, x2=intrah_limit_right, y1=intrah_open, y2=intrah_open, color=IntraColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var intrah_label = label.new(x=intrah_limit_right, y=intrah_open, text=pihtext, style=DEFAULT_LABEL_STYLE, textcolor=IntraColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(intrah_line, intrah_time)
line.set_x2(intrah_line, intrah_limit_right)
line.set_y1(intrah_line, intrah_open)
line.set_y2(intrah_line, intrah_open)
label.set_x(intrah_label, intrah_limit_right)
label.set_y(intrah_label, intrah_open)
label.set_text(intrah_label, pihtext)
if mergebool
f_LevelMerge(pricearray, labelarray, intrah_open, intrah_label, IntraColor)
//////////////////////////////////////////////////////////////////////////////////
//LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW
if can_draw_intral
intral_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
intral_time := get_limit_right(radistance)
intral_time
var intral_line = line.new(x1=intral_time, x2=intral_limit_right, y1=intral_open, y2=intral_open, color=IntraColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var intral_label = label.new(x=intral_limit_right, y=intral_open, text=piltext, style=DEFAULT_LABEL_STYLE, textcolor=IntraColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(intral_line, intral_time)
line.set_x2(intral_line, intral_limit_right)
line.set_y1(intral_line, intral_open)
line.set_y2(intral_line, intral_open)
label.set_x(intral_label, intral_limit_right)
label.set_y(intral_label, intral_open)
label.set_text(intral_label, piltext)
if mergebool
f_LevelMerge(pricearray, labelarray, intral_open, intral_label, IntraColor)
///////////////////////////////////////////////////////////////////////////////
if can_draw_intram
intram_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
intram_time = intrah_time
intram_open = (intral_open + intrah_open) / 2
if displayStyle == 'Right Anchored'
intram_time := get_limit_right(radistance)
intram_time
var intram_line = line.new(x1=intram_time, x2=intram_limit_right, y1=intram_open, y2=intram_open, color=IntraColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var intram_label = label.new(x=intram_limit_right, y=intram_open, text=pimtext, style=DEFAULT_LABEL_STYLE, textcolor=IntraColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(intram_line, intram_time)
line.set_x2(intram_line, intram_limit_right)
line.set_y1(intram_line, intram_open)
line.set_y2(intram_line, intram_open)
label.set_x(intram_label, intram_limit_right)
label.set_y(intram_label, intram_open)
label.set_text(intram_label, pimtext)
if mergebool
f_LevelMerge(pricearray, labelarray, intram_open, intram_label, IntraColor)
////////////////////////////////////////// MONDAY
if is_monday_enabled
monday_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
monday_time := get_limit_right(radistance)
monday_time
var monday_line = line.new(x1=monday_time, x2=monday_limit_right, y1=monday_high, y2=monday_high, color=MondayColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var monday_label = label.new(x=monday_limit_right, y=monday_high, text=pmonhtext, style=DEFAULT_LABEL_STYLE, textcolor=MondayColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(monday_line, monday_time)
line.set_x2(monday_line, monday_limit_right)
line.set_y1(monday_line, monday_high)
line.set_y2(monday_line, monday_high)
label.set_x(monday_label, monday_limit_right)
label.set_y(monday_label, monday_high)
label.set_text(monday_label, pmonhtext)
if mergebool
f_LevelMerge(pricearray, labelarray, monday_high, monday_label, MondayColor)
if is_monday_enabled
monday_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
monday_time := get_limit_right(radistance)
monday_time
var monday_low_line = line.new(x1=monday_time, x2=monday_limit_right, y1=monday_low, y2=monday_low, color=MondayColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var monday_low_label = label.new(x=monday_limit_right, y=monday_low, text=pmonltext, style=DEFAULT_LABEL_STYLE, textcolor=MondayColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(monday_low_line, monday_time)
line.set_x2(monday_low_line, monday_limit_right)
line.set_y1(monday_low_line, monday_low)
line.set_y2(monday_low_line, monday_low)
label.set_x(monday_low_label, monday_limit_right)
label.set_y(monday_low_label, monday_low)
label.set_text(monday_low_label, pmonltext)
if mergebool
f_LevelMerge(pricearray, labelarray, monday_low, monday_low_label, MondayColor)
if is_monday_mid
mondaym_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
mondaym_open = (monday_high + monday_low) / 2
if displayStyle == 'Right Anchored'
monday_time := get_limit_right(radistance)
monday_time
var mondaym_line = line.new(x1=monday_time, x2=mondaym_limit_right, y1=mondaym_open, y2=mondaym_open, color=MondayColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var mondaym_label = label.new(x=mondaym_limit_right, y=mondaym_open, text=pmonmtext, style=DEFAULT_LABEL_STYLE, textcolor=MondayColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(mondaym_line, monday_time)
line.set_x2(mondaym_line, mondaym_limit_right)
line.set_y1(mondaym_line, mondaym_open)
line.set_y2(mondaym_line, mondaym_open)
label.set_x(mondaym_label, mondaym_limit_right)
label.set_y(mondaym_label, mondaym_open)
label.set_text(mondaym_label, pmonmtext)
if mergebool
f_LevelMerge(pricearray, labelarray, mondaym_open, mondaym_label, MondayColor)
//////////////////////////////////////////////////////////////////////////////////
////////////////////////DAILY OPEN DAILY OPEN DAILY OPEN DAILY OPEN DAILY OPEN DAILY OPEN DAILY OPEN
if is_daily_enabled
daily_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
daily_time := get_limit_right(radistance)
daily_time
var daily_line = line.new(x1=daily_time, x2=daily_limit_right, y1=daily_open, y2=daily_open, color=DailyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var daily_label = label.new(x=daily_limit_right, y=daily_open, text=dotext, style=DEFAULT_LABEL_STYLE, textcolor=DailyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(daily_line, daily_time)
line.set_x2(daily_line, daily_limit_right)
line.set_y1(daily_line, daily_open)
line.set_y2(daily_line, daily_open)
label.set_x(daily_label, daily_limit_right)
label.set_y(daily_label, daily_open)
label.set_text(daily_label, dotext)
if mergebool
f_LevelMerge(pricearray, labelarray, daily_open, daily_label, DailyColor)
//////////////////////////////////////////////////////////////////////////////////
//////////////////DAILY HIGH DAILY HIGH DAILY HIGH DAILY HIGH DAILY HIGH DAILY HIGH DAILY HIGH
if is_dailyrange_enabled
dailyh_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
dailyh_time := get_limit_right(radistance)
dailyh_time
// draw tails before lines for better visual
var dailyh_line = line.new(x1=dailyh_time, x2=dailyh_limit_right, y1=dailyh_open, y2=dailyh_open, color=DailyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var dailyh_label = label.new(x=dailyh_limit_right, y=dailyh_open, text=pdhtext, style=DEFAULT_LABEL_STYLE, textcolor=DailyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(dailyh_line, dailyh_time)
line.set_x2(dailyh_line, dailyh_limit_right)
line.set_y1(dailyh_line, dailyh_open)
line.set_y2(dailyh_line, dailyh_open)
label.set_x(dailyh_label, dailyh_limit_right)
label.set_y(dailyh_label, dailyh_open)
label.set_text(dailyh_label, pdhtext)
if mergebool
f_LevelMerge(pricearray, labelarray, dailyh_open, dailyh_label, DailyColor)
//////////////////////////////////////////////////////////////////////////////////
//////////////////DAILY LOW DAILY LOW DAILY LOW DAILY LOW DAILY LOW DAILY LOW DAILY LOW DAILY LOW
if is_dailyrange_enabled
dailyl_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
dailyl_time := get_limit_right(radistance)
dailyl_time
var dailyl_line = line.new(x1=dailyl_time, x2=dailyl_limit_right, y1=dailyl_open, y2=dailyl_open, color=DailyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var dailyl_label = label.new(x=dailyl_limit_right, y=dailyl_open, text=pdltext, style=DEFAULT_LABEL_STYLE, textcolor=DailyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(dailyl_line, dailyl_time)
line.set_x2(dailyl_line, dailyl_limit_right)
line.set_y1(dailyl_line, dailyl_open)
line.set_y2(dailyl_line, dailyl_open)
label.set_x(dailyl_label, dailyl_limit_right)
label.set_y(dailyl_label, dailyl_open)
label.set_text(dailyl_label, pdltext)
if mergebool
f_LevelMerge(pricearray, labelarray, dailyl_open, dailyl_label, DailyColor)
//////////////////////////////////////////////////////////////////////////////// Daily MID
if is_dailym_enabled
dailym_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
dailym_time = dailyh_time
dailym_open = (dailyl_open + dailyh_open) / 2
if displayStyle == 'Right Anchored'
dailym_time := get_limit_right(radistance)
dailym_time
var dailym_line = line.new(x1=dailym_time, x2=dailym_limit_right, y1=dailym_open, y2=dailym_open, color=DailyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var dailym_label = label.new(x=dailym_limit_right, y=dailym_open, text=pdmtext, style=DEFAULT_LABEL_STYLE, textcolor=DailyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(dailym_line, dailym_time)
line.set_x2(dailym_line, dailym_limit_right)
line.set_y1(dailym_line, dailym_open)
line.set_y2(dailym_line, dailym_open)
label.set_x(dailym_label, dailym_limit_right)
label.set_y(dailym_label, dailym_open)
label.set_text(dailym_label, pdmtext)
if mergebool
f_LevelMerge(pricearray, labelarray, dailym_open, dailym_label, DailyColor)
//////////////////////////////////////////////////////////////////////////////////
if is_weekly_enabled
weekly_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
cweekly_time = weekly_time
if displayStyle == 'Right Anchored'
cweekly_time := get_limit_right(radistance)
cweekly_time
var weekly_line = line.new(x1=cweekly_time, x2=weekly_limit_right, y1=weekly_open, y2=weekly_open, color=WeeklyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var weekly_label = label.new(x=weekly_limit_right, y=weekly_open, text=wotext, style=DEFAULT_LABEL_STYLE, textcolor=WeeklyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(weekly_line, cweekly_time)
line.set_x2(weekly_line, weekly_limit_right)
line.set_y1(weekly_line, weekly_open)
line.set_y2(weekly_line, weekly_open)
label.set_x(weekly_label, weekly_limit_right)
label.set_y(weekly_label, weekly_open)
label.set_text(weekly_label, wotext)
if mergebool
f_LevelMerge(pricearray, labelarray, weekly_open, weekly_label, WeeklyColor)
// the weekly open can be the daily open too (monday)
// only the weekly will be draw, in these case we update its label
// if is_weekly_open and can_show_daily
// label.set_text(weekly_label, "DO / WO ")
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// WEEKLY HIGH WEEKLY HIGH WEEKLY HIGH
if is_weeklyrange_enabled
weeklyh_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
weeklyh_time := get_limit_right(radistance)
weeklyh_time
var weeklyh_line = line.new(x1=weeklyh_time, x2=weeklyh_limit_right, y1=weeklyh_open, y2=weeklyh_open, color=WeeklyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var weeklyh_label = label.new(x=weeklyh_limit_right, y=weeklyh_open, text=pwhtext, style=DEFAULT_LABEL_STYLE, textcolor=WeeklyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(weeklyh_line, weeklyh_time)
line.set_x2(weeklyh_line, weeklyh_limit_right)
line.set_y1(weeklyh_line, weeklyh_open)
line.set_y2(weeklyh_line, weeklyh_open)
label.set_x(weeklyh_label, weeklyh_limit_right)
label.set_y(weeklyh_label, weeklyh_open)
label.set_text(weeklyh_label, pwhtext)
if mergebool
f_LevelMerge(pricearray, labelarray, weeklyh_open, weeklyh_label, WeeklyColor)
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// WEEKLY LOW WEEKLY LOW WEEKLY LOW
if is_weeklyrange_enabled
weeklyl_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
weeklyl_time := get_limit_right(radistance)
weeklyl_time
var weeklyl_line = line.new(x1=weeklyl_time, x2=weeklyl_limit_right, y1=weekly_open, y2=weekly_open, color=WeeklyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var weeklyl_label = label.new(x=weeklyl_limit_right, y=weeklyl_open, text=pwltext, style=DEFAULT_LABEL_STYLE, textcolor=WeeklyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(weeklyl_line, weeklyl_time)
line.set_x2(weeklyl_line, weeklyl_limit_right)
line.set_y1(weeklyl_line, weeklyl_open)
line.set_y2(weeklyl_line, weeklyl_open)
label.set_x(weeklyl_label, weeklyl_limit_right)
label.set_y(weeklyl_label, weeklyl_open)
label.set_text(weeklyl_label, pwltext)
if mergebool
f_LevelMerge(pricearray, labelarray, weeklyl_open, weeklyl_label, WeeklyColor)
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// Weekly MID
if is_weekly_mid
weeklym_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
weeklym_time = weeklyh_time
weeklym_open = (weeklyl_open + weeklyh_open) / 2
if displayStyle == 'Right Anchored'
weeklym_time := get_limit_right(radistance)
weeklym_time
var weeklym_line = line.new(x1=weeklym_time, x2=weeklym_limit_right, y1=weeklym_open, y2=weeklym_open, color=WeeklyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var weeklym_label = label.new(x=weeklym_limit_right, y=weeklym_open, text=pwmtext, style=DEFAULT_LABEL_STYLE, textcolor=WeeklyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(weeklym_line, weeklym_time)
line.set_x2(weeklym_line, weeklym_limit_right)
line.set_y1(weeklym_line, weeklym_open)
line.set_y2(weeklym_line, weeklym_open)
label.set_x(weeklym_label, weeklym_limit_right)
label.set_y(weeklym_label, weeklym_open)
label.set_text(weeklym_label, pwmtext)
if mergebool
f_LevelMerge(pricearray, labelarray, weeklym_open, weeklym_label, WeeklyColor)
////////////////////////////////////////////////////////////////////////////////// YEEEAARRLLYY LOW LOW LOW
if is_yearlyrange_enabled
yearlyl_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
yearlyl_time := get_limit_right(radistance)
yearlyl_time
var yearlyl_line = line.new(x1=yearlyl_time, x2=yearlyl_limit_right, y1=yearlyl_open, y2=yearlyl_open, color=YearlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var yearlyl_label = label.new(x=yearlyl_limit_right, y=yearlyl_open, text=cyltext, style=DEFAULT_LABEL_STYLE, textcolor=YearlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(yearlyl_line, yearlyl_time)
line.set_x2(yearlyl_line, yearlyl_limit_right)
line.set_y1(yearlyl_line, yearlyl_open)
line.set_y2(yearlyl_line, yearlyl_open)
label.set_x(yearlyl_label, yearlyl_limit_right)
label.set_y(yearlyl_label, yearlyl_open)
label.set_text(yearlyl_label, cyltext)
if mergebool
f_LevelMerge(pricearray, labelarray, yearlyl_open, yearlyl_label, YearlyColor)
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// YEEEAARRLLYY HIGH HIGH HIGH
if is_yearlyrange_enabled
yearlyh_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
yearlyh_time := get_limit_right(radistance)
yearlyh_time
var yearlyh_line = line.new(x1=yearlyh_time, x2=yearlyh_limit_right, y1=yearlyh_open, y2=yearlyh_open, color=YearlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var yearlyh_label = label.new(x=yearlyh_limit_right, y=yearlyh_open, text=cyhtext, style=DEFAULT_LABEL_STYLE, textcolor=YearlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(yearlyh_line, yearlyh_time)
line.set_x2(yearlyh_line, yearlyh_limit_right)
line.set_y1(yearlyh_line, yearlyh_open)
line.set_y2(yearlyh_line, yearlyh_open)
label.set_x(yearlyh_label, yearlyh_limit_right)
label.set_y(yearlyh_label, yearlyh_open)
label.set_text(yearlyh_label, cyhtext)
if mergebool
f_LevelMerge(pricearray, labelarray, yearlyh_open, yearlyh_label, YearlyColor)
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// YEEEAARRLLYY OPEN
if is_yearly_enabled
yearly_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
yearly_time := get_limit_right(radistance)
yearly_time
var yearly_line = line.new(x1=yearly_time, x2=yearly_limit_right, y1=yearly_open, y2=yearly_open, color=YearlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var yearly_label = label.new(x=yearly_limit_right, y=yearly_open, text=yotext, style=DEFAULT_LABEL_STYLE, textcolor=YearlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(yearly_line, yearly_time)
line.set_x2(yearly_line, yearly_limit_right)
line.set_y1(yearly_line, yearly_open)
line.set_y2(yearly_line, yearly_open)
label.set_x(yearly_label, yearly_limit_right)
label.set_y(yearly_label, yearly_open)
label.set_text(yearly_label, yotext)
if mergebool
f_LevelMerge(pricearray, labelarray, yearly_open, yearly_label, YearlyColor)
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// yearly MID
if is_yearly_mid
yearlym_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
yearlym_time = yearlyh_time
yearlym_open = (yearlyl_open + yearlyh_open) / 2
if displayStyle == 'Right Anchored'
yearlym_time := get_limit_right(radistance)
yearlym_time
var yearlym_line = line.new(x1=yearlym_time, x2=yearlym_limit_right, y1=yearlym_open, y2=yearlym_open, color=YearlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var yearlym_label = label.new(x=yearlym_limit_right, y=yearlym_open, text=cymtext, style=DEFAULT_LABEL_STYLE, textcolor=YearlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(yearlym_line, yearlym_time)
line.set_x2(yearlym_line, yearlym_limit_right)
line.set_y1(yearlym_line, yearlym_open)
line.set_y2(yearlym_line, yearlym_open)
label.set_x(yearlym_label, yearlym_limit_right)
label.set_y(yearlym_label, yearlym_open)
label.set_text(yearlym_label, cymtext)
if mergebool
f_LevelMerge(pricearray, labelarray, yearlym_open, yearlym_label, YearlyColor)
////////////////////////////////////////////////////////////////////////////////// QUATERLLYYYYY OPEN
if is_quarterly_enabled
quarterly_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
quarterly_time := get_limit_right(radistance)
quarterly_time
var quarterly_line = line.new(x1=quarterly_time, x2=quarterly_limit_right, y1=quarterly_open, y2=quarterly_open, color=quarterlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var quarterly_label = label.new(x=quarterly_limit_right, y=quarterly_open, text=qotext, style=DEFAULT_LABEL_STYLE, textcolor=quarterlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(quarterly_line, quarterly_time)
line.set_x2(quarterly_line, quarterly_limit_right)
line.set_y1(quarterly_line, quarterly_open)
line.set_y2(quarterly_line, quarterly_open)
label.set_x(quarterly_label, quarterly_limit_right)
label.set_y(quarterly_label, quarterly_open)
label.set_text(quarterly_label, qotext)
if mergebool
f_LevelMerge(pricearray, labelarray, quarterly_open, quarterly_label, quarterlyColor)
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// QUATERLLYYYYY High
if is_quarterlyrange_enabled
quarterlyh_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
quarterlyh_time := get_limit_right(radistance)
quarterlyh_time
var quarterlyh_line = line.new(x1=quarterlyh_time, x2=quarterlyh_limit_right, y1=quarterlyh_open, y2=quarterlyh_open, color=quarterlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var quarterlyh_label = label.new(x=quarterlyh_limit_right, y=quarterlyh_open, text=pqhtext, style=DEFAULT_LABEL_STYLE, textcolor=quarterlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(quarterlyh_line, quarterlyh_time)
line.set_x2(quarterlyh_line, quarterlyh_limit_right)
line.set_y1(quarterlyh_line, quarterlyh_open)
line.set_y2(quarterlyh_line, quarterlyh_open)
label.set_x(quarterlyh_label, quarterlyh_limit_right)
label.set_y(quarterlyh_label, quarterlyh_open)
label.set_text(quarterlyh_label, pqhtext)
if mergebool
f_LevelMerge(pricearray, labelarray, quarterlyh_open, quarterlyh_label, quarterlyColor)
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// QUATERLLYYYYY Low
if is_quarterlyrange_enabled
quarterlyl_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
quarterlyl_time := get_limit_right(radistance)
quarterlyl_time
var quarterlyl_line = line.new(x1=quarterlyl_time, x2=quarterlyl_limit_right, y1=quarterlyl_open, y2=quarterlyl_open, color=quarterlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var quarterlyl_label = label.new(x=quarterlyl_limit_right, y=quarterlyl_open, text=pqltext, style=DEFAULT_LABEL_STYLE, textcolor=quarterlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(quarterlyl_line, quarterlyl_time)
line.set_x2(quarterlyl_line, quarterlyl_limit_right)
line.set_y1(quarterlyl_line, quarterlyl_open)
line.set_y2(quarterlyl_line, quarterlyl_open)
label.set_x(quarterlyl_label, quarterlyl_limit_right)
label.set_y(quarterlyl_label, quarterlyl_open)
label.set_text(quarterlyl_label, pqltext)
if mergebool
f_LevelMerge(pricearray, labelarray, quarterlyl_open, quarterlyl_label, quarterlyColor)
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// QUATERLLYYYYY MID
if is_quarterly_mid
quarterlym_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
quarterlym_time = quarterlyh_time
quarterlym_open = (quarterlyl_open + quarterlyh_open) / 2
if displayStyle == 'Right Anchored'
quarterlym_time := get_limit_right(radistance)
quarterlym_time
var quarterlym_line = line.new(x1=quarterlym_time, x2=quarterlym_limit_right, y1=quarterlym_open, y2=quarterlym_open, color=quarterlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var quarterlym_label = label.new(x=quarterlym_limit_right, y=quarterlym_open, text=pqmtext, style=DEFAULT_LABEL_STYLE, textcolor=quarterlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(quarterlym_line, quarterlym_time)
line.set_x2(quarterlym_line, quarterlym_limit_right)
line.set_y1(quarterlym_line, quarterlym_open)
line.set_y2(quarterlym_line, quarterlym_open)
label.set_x(quarterlym_label, quarterlym_limit_right)
label.set_y(quarterlym_label, quarterlym_open)
label.set_text(quarterlym_label, pqmtext)
if mergebool
f_LevelMerge(pricearray, labelarray, quarterlym_open, quarterlym_label, quarterlyColor)
////////////////////////////////////////////////////////////////////////////////// Monthly LOW LOW LOW
if is_monthlyrange_enabled
monthlyl_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
monthlyl_time := get_limit_right(radistance)
monthlyl_time
var monthlyl_line = line.new(x1=monthlyl_time, x2=monthlyl_limit_right, y1=monthlyl_open, y2=monthlyl_open, color=MonthlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var monthlyl_label = label.new(x=monthlyl_limit_right, y=monthlyl_open, text=pmltext, style=DEFAULT_LABEL_STYLE, textcolor=MonthlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(monthlyl_line, monthlyl_time)
line.set_x2(monthlyl_line, monthlyl_limit_right)
line.set_y1(monthlyl_line, monthlyl_open)
line.set_y2(monthlyl_line, monthlyl_open)
label.set_x(monthlyl_label, monthlyl_limit_right)
label.set_y(monthlyl_label, monthlyl_open)
label.set_text(monthlyl_label, pmltext)
if mergebool
f_LevelMerge(pricearray, labelarray, monthlyl_open, monthlyl_label, MonthlyColor)
// the weekly open can be the daily open too (monday)
// only the weekly will be draw, in these case we update its label
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// MONTHLY HIGH HIGH HIGH
if is_monthlyrange_enabled
monthlyh_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
monthlyh_time := get_limit_right(radistance)
monthlyh_time
var monthlyh_line = line.new(x1=monthlyh_time, x2=monthlyh_limit_right, y1=monthlyh_open, y2=monthlyh_open, color=MonthlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var monthlyh_label = label.new(x=monthlyh_limit_right, y=monthlyh_open, text=pmhtext, style=DEFAULT_LABEL_STYLE, textcolor=MonthlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(monthlyh_line, monthlyl_time)
line.set_x2(monthlyh_line, monthlyh_limit_right)
line.set_y1(monthlyh_line, monthlyh_open)
line.set_y2(monthlyh_line, monthlyh_open)
label.set_x(monthlyh_label, monthlyh_limit_right)
label.set_y(monthlyh_label, monthlyh_open)
label.set_text(monthlyh_label, pmhtext)
if mergebool
f_LevelMerge(pricearray, labelarray, monthlyh_open, monthlyh_label, MonthlyColor)
// the weekly open can be the daily open too (monday)
// only the weekly will be draw, in these case we update its label
//////////////////////////////////////////////////////////////////////////////// MONTHLY MID
if is_monthly_mid
monthlym_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
monthlym_time = monthlyh_time
monthlym_open = (monthlyl_open + monthlyh_open) / 2
if displayStyle == 'Right Anchored'
monthlym_time := get_limit_right(radistance)
monthlym_time
var monthlym_line = line.new(x1=monthlym_time, x2=monthlym_limit_right, y1=monthlym_open, y2=monthlym_open, color=MonthlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var monthlym_label = label.new(x=monthlym_limit_right, y=monthlym_open, text=pmmtext, style=DEFAULT_LABEL_STYLE, textcolor=MonthlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(monthlym_line, monthlym_time)
line.set_x2(monthlym_line, monthlym_limit_right)
line.set_y1(monthlym_line, monthlym_open)
line.set_y2(monthlym_line, monthlym_open)
label.set_x(monthlym_label, monthlym_limit_right)
label.set_y(monthlym_label, monthlym_open)
label.set_text(monthlym_label, pmmtext)
if mergebool
f_LevelMerge(pricearray, labelarray, monthlym_open, monthlym_label, MonthlyColor)
//////////////////////////////////////////////////////////////////////////////////
if is_monthly_enabled
monthly_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
if displayStyle == 'Right Anchored'
monthly_time := get_limit_right(radistance)
monthly_time
var monthlyLine = line.new(x1=monthly_time, x2=monthly_limit_right, y1=monthly_open, y2=monthly_open, color=MonthlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
var monthlyLabel = label.new(x=monthly_limit_right, y=monthly_open, text=motext, style=DEFAULT_LABEL_STYLE, textcolor=MonthlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
line.set_x1(monthlyLine, monthly_time)
line.set_x2(monthlyLine, monthly_limit_right)
line.set_y1(monthlyLine, monthly_open)
line.set_y2(monthlyLine, monthly_open)
label.set_x(monthlyLabel, monthly_limit_right)
label.set_y(monthlyLabel, monthly_open)
label.set_text(monthlyLabel, motext)
if mergebool
f_LevelMerge(pricearray, labelarray, monthly_open, monthlyLabel, MonthlyColor)
/////////////////////////////////////////////////////////////////////////////
// the monthly open can be the weekly open (monday 1st) and/or daily open too
// only the monthly will be draw, in these case we update its label
// if is_monthly_open
// if can_show_daily
// label.set_text(monthlyLabel, "DO / MO ")
// if is_weekly_open
// if can_show_weekly
// label.set_text(monthlyLabel, "WO / MO ")
// if can_show_daily and can_show_weekly
// label.set_text(monthlyLabel, "DO / WO / MO ")
// the start of the line is drew from the first week of the month
// if the first day of the weekly candle (monday) is the 2nd of the month
// we fix the start of the line position on the Prev weekly candle
if timeframe.isweekly and dayofweek(monthly_time) != dayofweek.monday
line.set_x1(monthlyLine, monthly_time - (weekly_time - weekly_time[1]))
var picoLines = 10
var femtoLines = 6
var femtoLines1 = 6
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 picoStep = syminfo.mintick * (StepSize*1)
var FemtoStep1 = syminfo.mintick * (StepSize*0.50)
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')
lstyle3 = input.string(title='25R Style', defval='Dotted', options=['Solid', 'Dotted', 'Dashed'], group='Resistance')
lstyle4 = input.string(title='25S Style', defval='Dotted', options=['Solid', 'Dotted', 'Dashed'], group='Support')
lstyle5 = input.string(title='50R Style', defval='Dashed', options=['Solid', 'Dotted', 'Dashed'], group='Resistance')
lstyle6 = input.string(title='50S Style', defval='Dashed', 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
resistanceStyle1 = lstyle3 == 'Solid' ? line.style_solid : lstyle3 == 'Dotted' ? line.style_dotted : line.style_dashed
supportStyle1 = lstyle4 == 'Solid' ? line.style_solid : lstyle4 == 'Dotted' ? line.style_dotted : line.style_dashed
resistanceStyle2 = lstyle5 == 'Solid' ? line.style_solid : lstyle5 == 'Dotted' ? line.style_dotted : line.style_dashed
supportStyle2 = lstyle6 == 'Solid' ? line.style_solid : lstyle6 == 'Dotted' ? line.style_dotted : line.style_dashed
LineCol5 = input.color(color.new(#000000, 50), title='100 pip', inline='LineCol5', group='Resistance')
lineWidth5 = input.int(2, title='', minval=1, maxval=4, inline='LineCol5', group='Resistance')
LineCol6 = input.color(color.new(#000000, 50), title='100 pip', inline='LineCol6', group='Support')
lineWidth6 = input.int(2, title='', minval=1, maxval=4, inline='LineCol6', group='Support')
LineCol7 = input.color(color.new(#000000, 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(#000000, 50), title='25 pip', inline='LineCol8', group='Support')
lineWidth8 = input.int(1, title='', minval=1, maxval=4, inline='LineCol8', group='Support')
LineCol9 = input.color(color.new(#000000, 50), title='50 pip', inline='LineCol9', group='Resistance')
lineWidth9 = input.int(1, title='', minval=1, maxval=4, inline='LineCol9', group='Resistance')
LineCol10 = input.color(color.new(#000000, 50), title='50 pip', inline='LineCol10', group='Support')
lineWidth10 = input.int(1, title='', minval=1, maxval=4, inline='LineCol10', group='Support')
ll_offset3 = timenow + math.round(ta.change(time) * 30)
ll_offset4 = timenow + math.round(ta.change(time) * 10)
ll_offset5 = timenow + math.round(ta.change(time) * 20)
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 femtoLines1 - 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=resistanceStyle1)
label.new(ll_offset4, stepUp, na , 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=supportStyle1)
label.new(ll_offset4, stepDown, na , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol8, tooltip = 'Minor quarter')
if barstate.islast and timeframe.isminutes
for counter = 0 to femtoLines1 - 1 by 1
stepUp = math.ceil(close / FemtoStep1) * FemtoStep1 + counter * FemtoStep1
line.new(bar_index, stepUp, bar_index - 1, stepUp, xloc=xloc.bar_index, extend=extend.both, color=LineCol9, width=lineWidth9, style=resistanceStyle2)
label.new(ll_offset5, stepUp, na , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol9, tooltip = 'Minor half')
stepDown = math.floor(close / FemtoStep1) * FemtoStep1 - counter * FemtoStep1
line.new(bar_index, stepDown, bar_index - 1, stepDown, xloc=xloc.bar_index, extend=extend.both, color=LineCol10, width=lineWidth10, style=supportStyle2)
label.new(ll_offset5, stepDown, na , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol10, tooltip = 'Minor half')
// Options
/// Daily IB only on 1hr & below
bool show2 = timeframe.isminutes and timeframe.multiplier <= 60 and timeframe.multiplier >= 1
time_now_exchange = timestamp(year, month, dayofmonth, hour, minute, second)
ib_session = input.session("0300-0430", title="Calculation period for the initial balance", group="Calculation period")
show2_delta_analytics = input.bool(true, "Display IB delta analytics", group="Information")
high_col = input.color(color.green, "Initial balance high levels color", group="Drawings")
low_col = input.color(color.red, "Initial balance low levels color", group="Drawings")
middle_col = input.color(#ffa726, "50% initial balance color", group="Drawings")
var delta_history = array.new_float(20)
inSession(sess) => na(time(timeframe.period, sess)) == false
get_line_style(s) =>
s == "Solid" ? line.style_solid : s == "Dotted" ? line.style_dotted : line.style_dashed
get_levels(n) =>
h = high[1]
l = low[1]
for i=1 to n
if low[i] < l
l := low[i]
if high[i] > h
h := high[i]
[h, l, (h+l)/2]
var line ibh = na
var line ibl = na
var line ibm = na
var line ib_plus = na
var line ib_minus = na
var line ib_plus2 = na
var line ib_minus2 = na
var line ibm_plus = na
var line ibm_minus = na
var label labelh = na
var label labell = na
var label labelm = na
var label label_plus = na
var label label_minus = na
var label label_plus2 = na
var label label_minus2 = na
var label labelm_plus = na
var label labelm_minus = na
var box ib_area = na
var offset = 0
ins = inSession(ib_session)
var float ib_delta = na
if ins
offset += 1
if ins[1] and not ins
[h, l, m] = get_levels(offset)
ib_delta := h - l
if array.size(delta_history) >= 20
array.shift(delta_history)
array.push(delta_history, ib_delta)
if (not ins) and (not ins[1])
line.set_x2(ibh, bar_index)
line.set_x2(ibl, bar_index)
var table ib_analytics = table.new(position.bottom_left, 2, 6)
ib_sentiment() =>
h = array.max(delta_history)
l = array.min(delta_history)
a = array.avg(delta_history)
h_comp = ib_delta > h ? ib_delta - h : (ib_delta - h) * -1
l_comp = ib_delta > l ? ib_delta - l : (ib_delta - l) * -1
a_comp = ib_delta > a ? ib_delta - a : (ib_delta - a) * -1
(h_comp < l_comp and h_comp < a_comp) ? "Huge" : (l_comp < h_comp and l_comp < a_comp) ? "Small" : "Medium"
if show2_delta_analytics
table.cell(ib_analytics, 0, 0, "IB Delta", bgcolor=color.black, text_color=color.white)
table.cell(ib_analytics, 0, 1, "20D MAX", bgcolor=color.black, text_color=color.white)
table.cell(ib_analytics, 1, 1, str.tostring(array.max(delta_history), "#.####"), bgcolor=color.black, text_color=high_col)
table.cell(ib_analytics, 0, 2, "20D AVG", bgcolor=color.black, text_color=color.white)
table.cell(ib_analytics, 1, 2, str.tostring(array.avg(delta_history), "#.####"), bgcolor=color.black, text_color=middle_col)
table.cell(ib_analytics, 0, 3, "20D MIN", bgcolor=color.black, text_color=color.white)
table.cell(ib_analytics, 1, 3, str.tostring(array.min(delta_history), "#.####"), bgcolor=color.black, text_color=low_col)
table.cell(ib_analytics, 0, 4, "Today", bgcolor=color.black, text_color=color.white)
table.cell(ib_analytics, 1, 4, str.tostring(ib_delta), bgcolor=color.black, text_color=color.blue)
table.cell(ib_analytics, 0, 5, "Status", bgcolor=color.black, text_color=color.white)
table.cell(ib_analytics, 1, 5, ib_sentiment() , bgcolor=color.black, text_color=color.white)
|
Moving Average Directional Index | https://www.tradingview.com/script/ONXvMCU9-Moving-Average-Directional-Index/ | x10140 | https://www.tradingview.com/u/x10140/ | 354 | 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/
// © peacefulToucan67678
//@version=5
indicator("MADX")
length = input.int(100)
mahigh = ta.ema(high, length)
malow = ta.ema(low, length)
maclose = ta.ema(close, length)
bear = mahigh/maclose
bull = maclose/malow
plot(bear, color=#f44336, linewidth=2, title="MADX-")
plot(bull, color=#006064, linewidth=2, title="MADX+") |
FCF ROCE | https://www.tradingview.com/script/j1V786e7/ | formy76 | https://www.tradingview.com/u/formy76/ | 17 | 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/
//
//
// This is a rough version of the Return on Capital Employed
//@version=4
study("FCF ROCE", precision=2)
//
var fcf_ttm = float(na)
var fcf_q1 = 0.0
var fcf_q2 = 0.0
var fcf_q3 = 0.0
var fcf_q4 = 0.0
fcf_series_filled = financial(syminfo.tickerid, "FREE_CASH_FLOW", "FQ", false)
fcf_series_fq = financial(syminfo.tickerid, "FREE_CASH_FLOW", "FQ", true)
fcf_series_fy = financial(syminfo.tickerid, "FREE_CASH_FLOW", "FY", false)
if not na(fcf_series_fq[0])
fcf_q4 := fcf_q3
fcf_q3 := fcf_q2
fcf_q2 := fcf_q1
fcf_q1 := fcf_series_fq[0]
fcf_ttm := fcf_q1 + fcf_q2 + fcf_q3 + fcf_q4
else if na(fcf_series_filled[0]) and not na(fcf_series_fy[0])
fcf_ttm := fcf_series_fy[0]
tot_assets = na(financial(syminfo.tickerid, "TOTAL_ASSETS", "FQ")) ? financial(syminfo.tickerid, "TOTAL_ASSETS", "FY") : financial(syminfo.tickerid, "TOTAL_ASSETS", "FQ")
cur_liabilities = na(financial(syminfo.tickerid, "TOTAL_CURRENT_LIABILITIES", "FQ")) ? financial(syminfo.tickerid, "TOTAL_CURRENT_LIABILITIES", "FY") : financial(syminfo.tickerid, "TOTAL_CURRENT_LIABILITIES", "FQ")
tot_shares = na(financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")) ? financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FY") : financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")
stock = close
capital_employed = tot_assets[0] - cur_liabilities[0]
fcf_share = (fcf_ttm / tot_shares)
fcf_yield = (fcf_share/stock)*100
fcf_roce = (fcf_ttm / capital_employed)*100
c = if fcf_roce >= 20
color.new(color.green, 75)
else if fcf_roce > 0
color.new(color.yellow, 75)
else
color.new(color.red, 75)
plot(fcf_roce, color=c, style=plot.style_area, histbase=0)
plot(fcf_yield)
|
MACDBB HistoX | https://www.tradingview.com/script/QboPAX9p-MACDBB-HistoX/ | Auguraltrader | https://www.tradingview.com/u/Auguraltrader/ | 37 | 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/
// © Auguraltrader
//@version=4
study(title="MACDBB HistoX")
fast_length = 5
slow_length = 13
src = ohlc4
signal_length = 13
sma_source = input(title="Simple MA(Oscillator)", type=input.bool, defval=false)
sma_signal = input(title="Simple MA(Signal Line)", type=input.bool, defval=false)
// Calculation
fast_ma = ema(src, fast_length)
slow_ma = ema(src, slow_length)
macd = fast_ma - slow_ma
signal = ema(macd, signal_length)
hist = macd - signal
//BB
length = input(11, minval=1)
mult = input(0.5, minval=0.001, maxval=50, title="StdDev")
basis = sma(macd, length)
dev = mult * stdev(macd, length)
upper = basis + dev
lower = basis - dev
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
// Plot colors
col_grow_above = #26A69A
col_grow_below = #FFCDD2
col_fall_above = #B2DFDB
col_fall_below = #EF5350
col_macd = macd>upper? color.lime : macd<lower ? color.red : #0094ff
col_signal = color.orange //#ff6a00
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below) ), transp=78 )
plot(macd, title="MACD", color=col_macd, transp=0)
plot(signal, title="Signal", color=col_signal, transp=0)
// Calculation MACDCCD
fast_ma2 = ema(ohlc4, 13)
slow_ma2 = ema(ohlc4, 5)
macd2 = fast_ma2 - slow_ma2
signal2 = ema(macd2, 34)
fast_ma3 = ema(ohlc4, 5)
slow_ma3 = ema(ohlc4, 13)
macd3 = fast_ma3 - slow_ma3
signal3 = ema(macd3, 34)
histX = signal3 - signal2
plot(histX, title="HistogramX", style=plot.style_columns, color=(histX>=0 ? (histX[1] < histX ? col_grow_above : col_fall_above) : (histX[1] < histX ? col_grow_below : col_fall_below) ), transp=88 ) |
Pro Trading Art - Double Top & Bottom with alert | https://www.tradingview.com/script/92tmeSms-Pro-Trading-Art-Double-Top-Bottom-with-alert/ | protradingart | https://www.tradingview.com/u/protradingart/ | 1,277 | 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/
// © protradingart
//@version=5
indicator("Pro Trading Art - Double Top & Bottom with alert", "PTA - Double Top & Bottom", overlay=true, max_lines_count=500, max_labels_count=500)
//////////////////////////////////////////////////////
////////////////////////////////////////////////////////
method maintainPivot(array<float> srcArray, float value) =>
srcArray.push(value)
srcArray.shift()
method maintainIndex(array<int> srcArray, int value) =>
srcArray.push(value)
srcArray.shift()
method middleIndex(array<int> srcArray)=>
srcArray.get(srcArray.size()-2)
method middlePrice(array<float> srcArray)=>
srcArray.get(srcArray.size()-2)
drawLL(start, end, price, startText, endText, COLOR, style=label.style_label_down)=>
Line = line.new(x1=start, y1=price, x2=end, y2=price, color=COLOR, width=2)
A = label.new(x=start, y=price, text=startText, color=COLOR, style=style, textcolor=color.black, size=size.normal)
B = label.new(x=end, y=price, text=endText, color=COLOR, style=style, textcolor=color.black, size=size.normal)
[Line, A, B]
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
pivotLeg = input.int(10, "Pivot Length")
extendSignal = input.bool(false, "Extend Signal")
var top = array.new_float(3)
var bottom = array.new_float(3)
var topIndex = array.new_int(3)
var bottomIndex = array.new_int(3)
ph = ta.pivothigh(pivotLeg, pivotLeg)
pl = ta.pivotlow(pivotLeg, pivotLeg)
////////////// Top ///////////////////
if not na(ph)
top.maintainPivot(ph)
topIndex.maintainIndex(bar_index-pivotLeg)
////////////// Bottom ///////////////////
if not na(pl)
bottom.maintainPivot(pl)
bottomIndex.maintainIndex(bar_index-pivotLeg)
inRange = not na(top.first()) and (not na(bottom.first()))
////////////////////////// Top Calculation //////////////////////////////////////////////////////
topPrice = 0.0
isTop = false
var line topLine = na
var label topA = na
var label topB = na
if inRange
topStart = topIndex.last()
topPrice := top.last()
if topPrice < top.middlePrice() and topIndex.middleIndex() > bottomIndex.first()
topPrice := top.middlePrice()
topStart := topIndex.middleIndex()
max_index = top.indexof(top.max())
if topPrice < top.max() and topIndex.get(max_index) > bottomIndex.first()
topPrice := top.max()
topStart := topIndex.get(max_index)
isTop := high >= topPrice and high[1] < topPrice and low < topPrice and bottom.last() > bottom.middlePrice()
var lastStart = 0
var topEnd = 0
if isTop and topStart != lastStart
lastStart := topStart
[Line, A, B] = drawLL(topStart, bar_index, topPrice, "Top 1", "Top 2", color.lime)
topLine := Line
topA := A
topB := B
alert("Double Top In: "+str.tostring(syminfo.ticker), alert.freq_once_per_bar_close)
if ta.crossunder(close, topLine.get_y2()) and extendSignal
topLine.set_x2(bar_index)
label.new(bar_index, high, style = label.style_label_down, color=color.red)
alert("Double Top Breakdown In: "+str.tostring(syminfo.ticker), alert.freq_once_per_bar_close)
if ta.crossover(close, topLine.get_y2()) and extendSignal
topLine.set_x2(bar_index)
label.new(bar_index, low, style = label.style_label_up, color=color.green)
alert("Double Top Breakout In: "+str.tostring(syminfo.ticker), alert.freq_once_per_bar_close)
// ////////////////////////// Bottom Calculation //////////////////////////////////////////////////////
bottomPrice = 0.0
isBottom = false
var line bottomLine = na
var label bottomA = na
var label bottomB = na
if inRange
bottomStart = bottomIndex.last()
bottomPrice := bottom.last()
if bottomPrice > bottom.middlePrice() and bottomIndex.middleIndex() > topIndex.first()
bottomPrice := bottom.middlePrice()
bottomStart := bottomIndex.middleIndex()
min_index = bottom.indexof(bottom.min())
if bottomPrice > bottom.min() and bottomIndex.get(min_index) > topIndex.first()
bottomPrice := bottom.min()
bottomStart := bottomIndex.get(min_index)
isBottom := close <= bottomPrice and close[1] > bottomPrice and high > bottomPrice and top.last() < top.middlePrice()
var bottomEnd = 0
var lastStart = 0
if isBottom and bottomStart != lastStart
lastStart := bottomStart
[Line, A, B] = drawLL(bottomStart, bar_index, bottomPrice, "Bottom 1", "Bottom 2", color.red, label.style_label_up)
bottomLine := Line
bottomA := A
bottomB := B
alert("Double Bottom In: "+str.tostring(syminfo.ticker), alert.freq_once_per_bar_close)
if ta.crossunder(close, bottomLine.get_y2()) and extendSignal
bottomLine.set_x2(bar_index)
label.new(bar_index, high, style = label.style_label_down, color=color.red)
alert("Double Bottom Breakdown In: "+str.tostring(syminfo.ticker), alert.freq_once_per_bar_close)
if ta.crossover(close, bottomLine.get_y2()) and extendSignal
bottomLine.set_x2(bar_index)
label.new(bar_index, low, style = label.style_label_up, color=color.green)
alert("Double Bottom Breakout In: "+str.tostring(syminfo.ticker), alert.freq_once_per_bar_close)
|
STD-Filtered, Variety FIR Digital Filters w/ ATR Bands [Loxx] | https://www.tradingview.com/script/DOKj1S42-STD-Filtered-Variety-FIR-Digital-Filters-w-ATR-Bands-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 54 | 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/
// © loxx
//@version=5
indicator("STD-Filtered, Variety FIR Digital Filters w/ ATR Bands [Loxx]",
shorttitle = "STDFVFIRDFB [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
darkGreenColor = #1B7E02
darkRedColor = #93021F
fir_hamm = "Hamming"
fir_hanning = "Hanning"
fir_black = "Blackman"
fir_blackh = "Blackman Harris"
fir_blacknutt = "Blackman Nutall"
fir_nutt = "Nutall"
fir_bartzep = "Bartlet Zero End Points"
fir_barthann = "Bartlet-Hann"
fir_hann = "Hann"
fir_sine = "Sine"
fir_lan = "Lanczos"
fir_flat = "Flat Top"
ema(float src, float per)=>
float alpha = 2.0 / (1.0 + per)
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
sma(float src, float per)=>
float sum = 0
float out = src
for k = 0 to per - 1
sum += nz(src[k])
out := sum / per
out
smma(float src, float per)=>
float alpha = 1.0 / per
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
lwma(float src, float per)=>
float sumw = 0
float sum = 0
float out = 0
for i = 0 to per - 1
float weight = (per - i) * per
sumw += weight
sum += nz(src[i]) * weight
out := sum / sumw
out
pwma(float src, float per, float pow)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = math.pow((per - k), pow)
sumw += weight
sum += nz(src[k]) * weight
out := sum / sumw
out
lsma(float src, float per)=>
float out = 0
out := 3.0 * lwma(src, per) - 2.0 * sma(src, per)
out
hma(float src, float per)=>
int HalfPeriod = math.floor(per / 2)
int HullPeriod = math.floor(math.sqrt(per))
float out = 0
float price1 = 2.0 * lwma(src, HalfPeriod) - lwma(src, per)
out := lwma(price1, HullPeriod)
out
tma(float src, float per)=>
float half = (per + 1.0) / 2.0
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = k + 1
if weight > half
weight := per - k
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
swma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
weight = math.sin((k + 1) * math.pi / (per + 1))
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
vwma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = nz(volume[k])
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
nonlagma(float src, float len)=>
float cycle = 4.0
float coeff = 3.0 * math.pi
float phase = len - 1.0
int _len = int(len * cycle + phase)
float weight = 0.
float alfa = 0.
float out = 0.
float[] alphas = array.new_float(_len, 0)
for k = 0 to _len - 1
float t = 0.
t := k <= phase - 1 ? 1.0 * k / (phase - 1) : 1.0 + (k - phase + 1) * (2.0 * cycle - 1.0) / (cycle * len -1.0)
beta = math.cos(math.pi * t)
float g = 1.0/(coeff * t + 1)
g := t <= 0.5 ? 1 : g
array.set(alphas, k, g * beta)
weight += array.get(alphas, k)
if (weight > 0)
float sum = 0.
for k = 0 to _len - 1
sum += array.get(alphas, k) * nz(src[k])
out := (sum / weight)
out
powerOfCosineDesign(string type, int per, float frequencyCutoff, int multiplier)=>
array<float> coeffs = array.new<float>(per, 0)
float sum = 0
int N = per - 1
for n = 0 to per - 1
float div = n - N / 2.0
if div == 0
array.set(coeffs, n, 2.0 * math.pi * frequencyCutoff)
else
array.set(coeffs, n, math.sin(2.0 * math.pi * frequencyCutoff * div) / div)
float temp = 0.
switch type
fir_hamm =>
temp := 0.54 - 0.46 * math.cos(2 * math.pi * n / N)
fir_hanning =>
temp := 0.50 - 0.50 * math.cos(2 * math.pi * n / N)
fir_black =>
temp := 0.42
- 0.50 * math.cos(2 * math.pi * n / N)
+ 0.08 * math.cos(4 * math.pi * n / N)
fir_blackh =>
temp := 0.35875
- 0.48829 * math.cos(2 * math.pi * n / N)
+ 0.14128 * math.cos(4 * math.pi * n / N)
+ 0.01168 * math.cos(6 * math.pi * n / N)
fir_blacknutt =>
temp := 0.3635819
- 0.4891775 * math.cos(2 * math.pi * n / N)
+ 0.1365995 * math.cos(4 * math.pi * n / N)
+ 0.0106411 * math.cos(6 * math.pi * n / N)
fir_nutt =>
temp := 0.355768
- 0.487396 * math.cos(2 * math.pi * n / N)
+ 0.144232 * math.cos(4 * math.pi * n / N)
+ 0.012604 * math.cos(6 * math.pi * n / N)
fir_bartzep =>
temp := 2.0 / N * (N / 2.0 - math.abs(n - N / 2))
fir_barthann =>
temp := 0.62 - 0.48 * math.abs(n / N - 0.5) * 0.38 * math.cos(2.0 * math.pi * n / N)
fir_hann =>
temp := 0.50 * (1.0 - math.cos(2.0 * math.pi * n / N))
fir_sine =>
temp := math.sin(math.pi * n / N)
fir_lan =>
float ttx = (n / N) - 1.0
if ttx == 0
temp := 0
else
temp := math.sin(ttx) / (ttx)
fir_flat =>
temp := 1
- 1.93 * math.cos(2 * math.pi * n / N)
+ 1.29 * math.cos(4 * math.pi * n / N)
+ 0.388 * math.cos(6 * math.pi * n / N)
+ 0.388 * math.cos(8 * math.pi * n / N)
array.set(coeffs, n, array.get(coeffs, n) * temp)
sum += array.get(coeffs, n)
for k = 0 to per - 1
array.set(coeffs, k, array.get(coeffs, k) / sum)
array.set(coeffs, k, array.get(coeffs, k) * multiplier)
coeffs
stdFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("HAB Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(30, "Period", step = 2, group = "Basic Settings")
type = input.string(fir_hamm, "Filter Type", options = [fir_hamm, fir_hanning, fir_black, fir_blackh, fir_blacknutt, fir_nutt, fir_bartzep, fir_barthann, fir_hann, fir_sine, fir_lan, fir_flat], group = "Basic Settings")
mult = input.int(1, "Multiplier", group = "Basic Settings")
fcut = input.float(0.01, "Frequency Cutoff", maxval = 0.5, minval = 0, step = 0.01, group = "Basic Settings")
causal = input.bool(true, "Make it causal? ", group = "Basic Settings")
rngper = input.int(14, "Range Period", group = "Bands Settings")
rngtype = input.string("Simple Moving Average - SMA", "Double Smoothing MA Type", options = ["Exponential Moving Average - EMA"
, "Hull Moving Average - HMA"
, "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA"
, "Non-Lag Moving Average"
, "Parabolic Weighted Moving Average"
, "Simple Moving Average - SMA"
, "Sine Weighted Moving Average"
, "Smoothed Moving Average - SMMA"
, "Triangular Moving Average - TMA"
, "Volume Weighted Moving Average - VWMA"],
group = "Bands Settings")
UpDeviation = input.float(2, "Up Deviation", group = "Bands Settings")
DnDeviation = input.float(2, "Down Deviation", group = "Bands Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
filterop = input.string("Both", "Filter Options", options = ["Price", "STDFVFIRDFB", "Both", "None"], group= "Filter Settings")
filter = input.float(0, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len) =>
out = 0.0
switch type
"Exponential Moving Average - EMA" => out := ema(src, len)
"Hull Moving Average - HMA" => out := hma(src, len)
"Linear Regression Value - LSMA (Least Squares Moving Average)" => out := lsma(src, len)
"Linear Weighted Moving Average - LWMA" => out := lwma(src, len)
"Non-Lag Moving Average" => out := nonlagma(src, len)
"Parabolic Weighted Moving Average" => out := pwma(src, len, 2)
"Simple Moving Average - SMA" => out := sma(src, len)
"Sine Weighted Moving Average" => out := swma(src, len)
"Smoothed Moving Average - SMMA" => out := smma(src, len)
"Triangular Moving Average - TMA" => out := tma(src, len)
"Volume Weighted Moving Average - VWMA" => out := vwma(src, len)
out
src := filterop == "Both" or filterop == "Price" and filter > 0 ? stdFilter(src, filterperiod, filter) : src
coeffs = powerOfCosineDesign(type, per, fcut, mult)
half = math.floor(per/2.0)
out = 0.
sum = 0.
for k = 0 to per - 1
if causal
out += nz(src[k]) * array.get(coeffs, k)
else
if (k - half) >= 0 and (k - half) < bar_index
out += nz(src[k - half]) * array.get(coeffs, k)
sum += array.get(coeffs, k)
if sum != 0
out /= sum
out := filterop == "Both" or filterop == "STDFVFIRDFB" and filter > 0 ? stdFilter(out, filterperiod, filter) : out
sig = nz(out[1])
float rng = variant(rngtype, ta.tr, rngper)
upb = out + UpDeviation * rng
dhb = out - DnDeviation * rng
state = 0
if causal
if low < nz(low[1]) and nz(high[1]) > nz(upb[1]) and nz(close[1]) > nz(open[1]) and close < open
state := 1
if high > nz(high[1]) and nz(low[1]) < nz(dhb[1]) and nz(close[1]) < nz(open[1]) and close > open
state := -1
else
state := out > sig ? 1 : -1
pregoLong = state == 1
pregoShort = state == -1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
color colorout = na
colorout := state == 1 ? greencolor : state == -1 ? redcolor : colorout[1]
plot(out, "STDFVFIRDFB", color = colorout, linewidth = 3)
plot(upb, "Up band", color = darkGreenColor)
plot(dhb, "Down band", color = darkRedColor)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "STD-Filtered, Variety FIR Digital Filters w/ ATR Bands [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD-Filtered, Variety FIR Digital Filters w/ ATR Bands [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
End-pointed SSA of Normalized Price Oscillator [Loxx] | https://www.tradingview.com/script/HmHUSpRq-End-pointed-SSA-of-Normalized-Price-Oscillator-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 126 | 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/
// © loxx
//@version=5
indicator("End-pointed SSA of Normalized Price Oscillator [Loxx]",
shorttitle = "EPSSANPO [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
int Maxncomp = 25
int MaxLag = 200
int MaxArrayLength = 1000
// Calculation of the function Sn, needed to calculate the eigenvalues
// Negative determinants are counted there
gaussSn(matrix<float> A, float l, int n)=>
array<float> w = array.new<float>(n, 0)
matrix<float> B = matrix.copy(A)
int count = 0
int cp = 0
float c = 0.
float s1 = 0.
float s2 = 0.
for i = 0 to n - 1
matrix.set(B, i, i, matrix.get(B, i, i) - l)
for k = 0 to n - 2
for i = k + 1 to n - 1
if matrix.get(B, k, k) == 0
for i1 = 0 to n - 1
array.set(w, i1, matrix.get(B, i1, k))
matrix.set(B, i1, k, matrix.get(B, i1, k + 1))
matrix.set(B, i1, k + 1, array.get(w, i1))
cp := cp + 1
c := matrix.get(B, i, k) / matrix.get(B, k, k)
for j = 0 to n - 1
matrix.set(B, i, j, matrix.get(B, i, j) - matrix.get(B, k, j) * c)
count := 0
s1 := 1
for i = 0 to n - 1
s2 := matrix.get(B, i, i)
if s2 < 0
count := count + 1
count
// Calculation of eigenvalues by the bisection method}
// The good thing is that as many eigenvalues are needed, so many will count,
// saves a lot of resources
gaussbisectionl(matrix<float> A, int k, int n)=>
float e1 = 0.
float maxnorm = 0.
float cn = 0.
float a1 = 0.
float b1 = 0.
float c = 0.
for i = 0 to n - 1
cn := 0
for j = 0 to n - 1
cn := cn + matrix.get(A, i, i)
if maxnorm < cn
maxnorm := cn
a1 := 0
b1 := 10 * maxnorm
e1 := 1.0 * maxnorm / 10000000
while math.abs(b1 - a1) > e1
c := 1.0 * (a1 + b1) / 2
if gaussSn(A, c, n) < k
a1 := c
else
b1 := c
float out = (a1 + b1) / 2.0
out
// Calculates eigenvectors for already computed eigenvalues
svector(matrix<float> A, float l, int n, array<float> V)=>
int cp = 0
matrix<float> B = matrix.copy(A)
float c = 0
array<float> w = array.new<float>(n, 0)
for i = 0 to n - 1
matrix.set(B, i, i, matrix.get(B, i, i) - l)
for k = 0 to n - 2
for i = k + 1 to n - 1
if matrix.get(B, k, k) == 0
for i1 = 0 to n - 1
array.set(w, i1, matrix.get(B, i1, k))
matrix.set(B, i1, k, matrix.get(B, i1, k + 1))
matrix.set(B, i1, k + 1, array.get(w, i1))
cp += 1
c := 1.0 * matrix.get(B, i, k) / matrix.get(B, k, k)
for j = 0 to n - 1
matrix.set(B, i, j, matrix.get(B, i, j) - matrix.get(B, k, j) * c)
array.set(V, n - 1, 1)
c := 1
for i = n - 2 to 0
array.set(V, i, 0)
for j = i to n - 1
array.set(V, i, array.get(V, i) - matrix.get(B, i, j) * array.get(V, j))
array.set(V, i, array.get(V, i) / matrix.get(B, i, i))
c += math.pow(array.get(V, i), 2)
for i = 0 to n - 1
array.set(V, i, array.get(V, i) / math.sqrt(c))
// Fast Singular SSA - "Caterpillar" method
// X-vector of the original series
// n-length
// l-lag length
// s-number of eigencomponents
// (there the original series is divided into components, and then restored, here you set how many components you need)
// Y - the restored row (smoothed by the caterpillar)
fastsingular(array<float> X, int n1, int l1, int s1)=>
int n = math.min(MaxArrayLength, n1)
int l = math.min(MaxLag, l1)
int s = math.min(Maxncomp, s1)
matrix<float> A = matrix.new<float>(l, l, 0.)
matrix<float> B = matrix.new<float>(n, l, 0.)
matrix<float> Bn = matrix.new<float>(l, n, 0.)
matrix<float> V = matrix.new<float>(l, n, 0.)
matrix<float> Yn = matrix.new<float>(l, n, 0.)
var array<float> vtarr = array.new<float>(l, 0.)
array<float> ls = array.new<float>(MaxLag, 0)
array<float> Vtemp = array.new<float>(MaxLag, 0)
array<float> Y = array.new<float>(n, 0)
int k = n - l + 1
// We form matrix A in the method that I downloaded from the site of the creators of this matrix S
for i = 0 to l - 1
for j = 0 to l - 1
matrix.set(A, i, j, 0)
for m = 0 to k - 1
matrix.set(A, i, j, matrix.get(A, i, j) + array.get(X, i + m) * array.get(X, m + j))
matrix.set(B, m, j, array.get(X, m + j))
//Find the eigenvalues and vectors of the matrix A
for i = 0 to s - 1
array.set(ls, i, gaussbisectionl(A, l - i, l))
svector(A, array.get(ls, i), l, Vtemp)
for j = 0 to l - 1
matrix.set(V, i, j, array.get(Vtemp, j))
// The restored matrix is formed
for i1 = 0 to s - 1
for i = 0 to k - 1
matrix.set(Yn, i1, i, 0)
for j = 0 to l - 1
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(B, i, j) * matrix.get(V, i1, j))
for i = 0 to l - 1
for j = 0 to k - 1
matrix.set(Bn, i, j, matrix.get(V, i1, i) * matrix.get(Yn, i1, j))
//Diagonal averaging (series recovery)
kb = k
lb = l
for i = 0 to n - 1
matrix.set(Yn, i1, i, 0)
if i < lb - 1
for j = 0 to i
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * (i + 1)))
if (lb - 1 <= i) and (i < kb - 1)
for j = 0 to lb - 1
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * lb))
if kb - 1 <= i
for j = i - kb + 1 to n - kb
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * (n - i)))
// Here, if not summarized, then there will be separate decomposition components
// process by own functions
for i = 0 to n - 1
array.set(Y, i, 0)
for i1 = 0 to s - 1
array.set(Y, i, array.get(Y, i) + matrix.get(Yn, i1, i))
Y
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
lag = input.int(10, "Lag")
ncomp = input.int(2, "Number of Computations", group = "Bands Settings")
ssapernorm = input.int(20, "SSA Period Normalization", group = "Bands Settings")
numbars = input.int(300, "Number of Bars", group = "Bands Settings")
backbars = input.int(400, "Number of Back", group = "Bands Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
showraw = input.bool(false, "Show pre-SSA?", group = "UI Options", tooltip = "This has no value other than to demonstrate the value of the calc before SSA morphing.")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
ma = ta.sma(src, ssapernorm)
dev = ta.stdev(src, ssapernorm) * 3.0
calcno = (src - ma) / (math.max(dev, 0.000001))
out = 0.
arr = array.new_float(numbars + 1, 0)
for i = 0 to numbars - 1
array.set(arr, i, nz(calcno[i]))
if last_bar_index - bar_index < backbars
pv = fastsingular(arr, numbars, lag, ncomp)
out := array.get(pv, 0)
mid = 0
colorout = out > mid ? greencolor : out < mid ? redcolor : color.gray
plot(showraw ? calcno : na, color = color.white)
plot(last_bar_index - bar_index < backbars ? out : na, "EPSSANPO", color = colorout, linewidth = 2)
plot(last_bar_index - bar_index < backbars ? mid : na, "Mid", color = bar_index % 2 ? color.gray : na)
barcolor(last_bar_index - bar_index < backbars and colorbars ? colorout : na)
goLong = ta.crossover(out, mid)
goShort = ta.crossunder(out, mid)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title = "Long", message = "End-pointed SSA of Normalized Price Oscillator [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "End-pointed SSA of Normalized Price Oscillator [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
JV Sessions | https://www.tradingview.com/script/WKvoID6j-JV-Sessions/ | jayantvarade | https://www.tradingview.com/u/jayantvarade/ | 90 | 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/
//Session Local Time DST OFF (UCT+0) DST ON (UTC+0) DST ON 2022 DST OFF 2022 DST ON 2023 DST OFF 2023 DST ON 2024 DST OFF 2024
//London 8am-430pm 0800-1630 0700-1530 March, 27 October, 30 March, 26 October, 29 March, 31 October, 27
//NewYork 930am-4pm 1430-2100 1330-2000 March, 13 November, 6 March, 12 November, 5 March, 10 November, 3
//Tokyo 9am-3pm 0000-0600 0000-0600 N/A N/A N/A N/A N/A N/A
//HongKong 930am-4pm 0130-0800 0130-0800 N/A N/A N/A N/A N/A N/A
//Sydney (NZX+ASX) NZX start 10am, ASX end 4pm 2200-0600 2100-0500 October, 2 April, 3 October, 1 April, 2 October, 6 April, 7
//EU Brinx 800am-900am 0800-0900 0700-0800 March, 27 October, 30 March, 26 October, 29 March, 31 October, 27
//US Brinx 900am-10am 1400-1500 1300-1400 March, 13 November, 6 March, 12 November, 5 March, 10 November, 3
//Frankfurt 800am-530pm 0700-1630 0600-1530 March, 27 October, 30 March, 26 October, 29 March, 31 October, 27
//@version=5
indicator('JV Sessions', overlay=true, max_bars_back=300,max_boxes_count=500, max_lines_count=500, max_labels_count=500)
// Config
label_x_offset = time_close + 5 * timeframe.multiplier * 60 * 1000
// Basic vars (needed in functions)
// Only render intraday
validTimeFrame = timeframe.isintraday == true
// If above the 5 minute, we start drawing yesterday. below, we start today
levelsstart = timeframe.isseconds == true or timeframe.isminutes == true and timeframe.multiplier < 5 ? time('D') : time('D') - 86400 * 1000
//levelsstartbar = ta.barssince(levelsstart)
// Functions
// new_bar: check if we're on a new bar within the session in a given resolution
new_bar(res) =>
ta.change(time(res)) != 0
//Right_Label
r_label(ry, rtext, rstyle, rcolor, valid) =>
var label rLabel = na
if valid and barstate.isrealtime
rLabel := label.new(x=label_x_offset, y=ry, text=rtext, xloc=xloc.bar_time, style=rstyle, textcolor=rcolor, textalign=text.align_right)
label.delete(rLabel[1])
rLabel
//Right_Label
r_label_offset(ry, rtext, rstyle, rcolor, valid, labelOffset) =>
if valid and barstate.isrealtime
rLabel = label.new(x=labelOffset, y=ry, text=rtext, xloc=xloc.bar_time, style=rstyle, textcolor=rcolor, textalign=text.align_right)
label.delete(rLabel[1])
draw_line(x_series, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset) =>
var line x_line = na
if validTimeFrame and new_bar(res) //and barstate.isnew
x_line := line.new(bar_index, x_series, bar_index+1, x_series, extend=xExtend, color=xColor, style=xStyle, width=xWidth)
line.delete(x_line[1])
if not na(x_line) and not new_bar(res)//and line.get_x2(x_line) != bar_index
line.set_x2(x_line, bar_index)
line.set_y1(x_line,x_series)
line.set_y2(x_line,x_series)
if isLabelValid //showADRLabels and validTimeFrame
x_label = label.new(xLabelOffset, x_series, tag, xloc=xloc.bar_time, style=label.style_none, textcolor=xColor)
label.delete(x_label[1])
draw_line_DO(x_series, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset) =>
var line x_line = na
if new_bar(res) and validTimeFrame
line.set_x2(x_line, bar_index)
line.set_extend(x_line, extend.none)
x_line := line.new(bar_index, x_series, bar_index, x_series, extend=xExtend, color=xColor, style=xStyle, width=xWidth)
line.delete(x_line[1])
if not na(x_line) and line.get_x2(x_line) != bar_index
line.set_x2(x_line, bar_index)
if isLabelValid //showADRLabels and validTimeFrame
x_label = label.new(xLabelOffset, x_series, tag, xloc=xloc.bar_time, style=label.style_none, textcolor=xColor)
label.delete(x_label[1])
draw_pivot(pivot_level, res, tag, pivotColor, pivotLabelColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid) =>
var line pivot_line = na
/// market boxes and daily open only on intraday
bool show = timeframe.isminutes and timeframe.multiplier <= 240 and timeframe.multiplier >= 1
time_now_exchange = timestamp(year, month, dayofmonth, hour, minute, second)
bool show_dly = timeframe.isminutes //and timeframe.multiplier < 240
bool show_rectangle9 = input.bool(group='Daily Open', defval=true, title='Show: line ?', inline='dopenconf') and show_dly
bool show_label9 = input.bool(group='Daily Open', defval=true, title='Label?', inline='dopenconf') and show_rectangle9 and show_dly
bool showallDly = input.bool(group='Daily Open', defval=false, title='Show historical daily opens?', inline='dopenconf')
color sess9col = input.color(group='Daily Open', title='Daily Open Color', defval=color.rgb(254, 234, 78, 0), inline='dopenconf1')
string rectStyle = input.string(group='Market sessions', defval='Dashed', title='Line style of Market Session hi/lo line', options=['Dashed', 'Solid'])
sessLineStyle = line.style_dashed
bool show_markets = input.bool(true, group='Market sessions', title='Show Market Sessions?', tooltip='Turn on or off all market sessions') and show
bool show_markets_weekends = input.bool(false, group='Market sessions', title='Show Market Session on Weekends?', tooltip='Turn on or off market sessions in the weekends. Note do not turn this on for exchanges that dont have weekend data like OANDA') and show
string weekend_sessions = ':1234567'
string no_weekend_sessions = ':23456'
bool show_rectangle1 = input.bool(group='Market session: London (0800-1630 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session1conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label1 = input.bool(group='Market session: London (0800-1630 UTC+0) - DST Aware', defval=true, title='Label?', inline='session1conf') and show_rectangle1 and show_markets
bool show_or1 = input.bool(group='Market session: London (0800-1630 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session1conf', tooltip='This controls the shaded area for the session') and show_rectangle1 and show_markets
string sess1Label = input.string(group='Market session: London (0800-1630 UTC+0) - DST Aware', defval='London', title='Name:', inline='session1style')
color sess1col = input.color(group='Market session: London (0800-1630 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(120, 123, 134, 75), inline='session1style')
color sess1colLabel = input.color(group='Market session: London (0800-1630 UTC+0) - DST Aware', title='Label', defval=color.rgb(120, 123, 134, 0), inline='session1style')
string sess1TimeX = '0800-1630'//input.session(group='Market session: London (0800-1630 UTC+0)', defval='0800-1630', title='Time (UTC+0):', inline='session1style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST and times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
sess1Time = show_markets_weekends ? sess1TimeX + weekend_sessions : sess1TimeX + no_weekend_sessions
bool show_rectangle2 = input.bool(group='Market session: New York (1430-2100 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session2conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label2 = input.bool(group='Market session: New York (1430-2100 UTC+0) - DST Aware', defval=true, title='Label?', inline='session2conf') and show_rectangle2 and show_markets
bool show_or2 = input.bool(group='Market session: New York (1430-2100 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session2conf', tooltip='This controls the shaded area for the session') and show_rectangle2 and show_markets
string sess2Label = input.string(group='Market session: New York (1430-2100 UTC+0) - DST Aware', defval='NewYork', title='Name:', inline='session2style')
color sess2col = input.color(group='Market session: New York (1430-2100 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(251, 86, 91, 75), inline='session2style')
color sess2colLabel = input.color(group='Market session: New York (1430-2100 UTC+0) - DST Aware', title='Label', defval=color.rgb(253, 84, 87, 25), inline='session2style')
string sess2TimeX = '1430-2100'//input.session(group='Market session: New York (1430-2100 UTC+0)', defval='1430-2100', title='Time (UTC+0):', inline='session2style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
sess2Time = show_markets_weekends ? sess2TimeX + weekend_sessions : sess2TimeX + no_weekend_sessions
bool show_rectangle3 = input.bool(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session3conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label3 = input.bool(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', defval=true, title='Label?', inline='session3conf') and show_rectangle3 and show_markets
bool show_or3 = input.bool(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session3conf', tooltip='This controls the shaded area for the session') and show_rectangle3 and show_markets
string sess3Label = input.string(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', defval='Tokyo', title='Name:', inline='session3style')
color sess3col = input.color(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(80, 174, 85, 75), inline='session3style')
color sess3colLabel = input.color(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', title='Label', defval=color.rgb(80, 174, 85, 25), inline='session3style')
string sess3TimeX = '0000-0600'//input.session(group='Market session: Tokyo (0000-0600 UTC+0)', defval='0000-0600', title='Time (UTC+0):', inline='session3style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
sess3Time = show_markets_weekends ? sess3TimeX + weekend_sessions : sess3TimeX + no_weekend_sessions
bool show_rectangle4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session4conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', defval=true, title='Label?', inline='session4conf') and show_rectangle4 and show_markets
bool show_or4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session4conf', tooltip='This controls the shaded area for the session') and show_rectangle4 and show_markets
string sess4Label = input.string(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', defval='HongKong', title='Name:', inline='session4style')
color sess4col = input.color(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(128, 127, 23, 75), inline='session4style')
color sess4colLabel = input.color(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', title='Label', defval=color.rgb(128, 127, 23, 25), inline='session4style')
string sess4TimeX = '0130-0800'//input.session(group='Market session: Hong Kong (0130-0800 UTC+0)', defval='0130-0800', title='Time (UTC+0):', inline='session4style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
sess4Time = show_markets_weekends ? sess4TimeX + weekend_sessions : sess4TimeX + no_weekend_sessions
bool show_rectangle5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session5conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', defval=true, title='Label?', inline='session5conf') and show_rectangle5 and show_markets
bool show_or5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session5conf', tooltip='This controls the shaded area for the session') and show_rectangle5 and show_markets
string sess5Label = input.string(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', defval='Sydney', title='Name:', inline='session5style')
color sess5col = input.color(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(37, 228, 123, 75), inline='session5style')
color sess5colLabel = input.color(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', title='Label', defval=color.rgb(37, 228, 123, 25), inline='session5style')
string sess5TimeX = '2200-0600'//input.session(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', defval='2200-0600', title='Time (UTC+0):', inline='session5style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
sess5Time = show_markets_weekends ? sess5TimeX + weekend_sessions : sess5TimeX + no_weekend_sessions
bool show_rectangle6 = input.bool(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session6conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label6 = input.bool(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', defval=true, title='Label?', inline='session6conf') and show_rectangle6 and show_markets
bool show_or6 = input.bool(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session6conf', tooltip='This controls the shaded area for the session') and show_rectangle6 and show_markets
string sess6Label = input.string(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', defval='EU Brinks', title='Name:', inline='session6style')
color sess6col = input.color(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(255, 255, 255, 65), inline='session6style')
color sess6colLabel = input.color(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', title='Label', defval=color.rgb(255, 255, 255, 25), inline='session6style')
string sess6TimeX = '0800-0900'//input.session(group='Market session: EU Brinks (0800-0900 UTC+0)', defval='0800-0900', title='Time (UTC+0):', inline='session6style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
sess6Time = show_markets_weekends ? sess6TimeX + weekend_sessions : sess6TimeX + no_weekend_sessions
bool show_rectangle7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session7conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', defval=true, title='Label?', inline='session7conf') and show_rectangle7 and show_markets
bool show_or7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session7conf', tooltip='This controls the shaded area for the session') and show_rectangle7 and show_markets
string sess7Label = input.string(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', defval='US Brinks', title='Name:', inline='session7style')
color sess7col = input.color(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(255, 255, 255, 65), inline='session7style')
color sess7colLabel = input.color(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', title='Label', defval=color.rgb(255, 255, 255, 25), inline='session7style')
string sess7TimeX = '1400-1500'//input.session(group='Market session: US Brinks (1400-1500 UTC+0)', defval='1400-1500', title='Time (UTC+0):', inline='session7style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
sess7Time = show_markets_weekends ? sess7TimeX + weekend_sessions : sess7TimeX + no_weekend_sessions
bool show_rectangle8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0) - DST Aware', defval=false, title='Show: session?', inline='session8conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and show_markets
bool show_label8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0) - DST Aware', defval=true, title='Label?', inline='session8conf') and show_rectangle8 and show_markets
bool show_or8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session8conf', tooltip='This controls the shaded area for the session') and show_rectangle8 and show_markets
string sess8Label = input.string(group='Market session: Frankfurt (0700-1630 UTC+0) - DST Aware', defval='Frankfurt', title='Name:', inline='session8style')
color sess8col = input.color(group='Market session: Frankfurt (0700-1630 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(253, 152, 39, 75), inline='session8style')
color sess8colLabel = input.color(group='Market session: Frankfurt (0700-1630 UTC+0) - DST Aware', title='Label', defval=color.rgb(253, 152, 39, 25), inline='session8style')
string sess8TimeX = '0700-1630'//input.session(group='Market session: Frankfurt (0700-1630 UTC+0)', defval='0700-1630', title='Time (UTC+0):', inline='session8style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.')
sess8Time = show_markets_weekends ? sess8TimeX + weekend_sessions : sess8TimeX + no_weekend_sessions
bool showPsy = timeframe.isminutes and (timeframe.multiplier == 60 or timeframe.multiplier == 30 or timeframe.multiplier == 15 or timeframe.multiplier == 5 or timeframe.multiplier == 3 or timeframe.multiplier == 1)
bool show_psylevels = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=true, title='Show: Levels?', inline='psyconf') and showPsy
bool show_psylabel = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=true, title='Labels?', inline='psyconf', tooltip="The Psy High/Low will only show on these timeframes: 1h/30min/15min/5min/3min/1min. It is disabled on all others. This is because the calculation requires a candle to start at the correct time for Sydney/Tokyo but in other timeframes the data does not have values at the designated time for the Sydney/Tokyo sessions.") and show_psylevels
bool showallPsy = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=false, title='Show historical psy levels?', inline='psyconf') and show_psylevels
color psycolH = input.color(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', title='Psy Hi Color', defval=color.new(color.orange, 30), inline='psyconf1')
color psycolL = input.color(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', title='Psy Low Color', defval=color.new(color.orange, 30), inline='psyconf1')
string psyType = input.string(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval='crypto', title='Psy calc type', options=['crypto', 'forex'], inline='psyconf12', tooltip="Are you looking at Crypto or Forex? Crypto calculations start with the Sydney session on Saturday night. Forex calculations start with the Tokyo session on Monday morning. Note some exchanges like Oanda do not have sessions on the weekends so you might be forced to select Forex for exchanges like Oanda even when looking at symbols like BITCOIN on Oanda.")
//*****************
// Market sessions
//*****************
splitSessionString(sessXTime) =>
//session stirng looks like this: 0000-0000:1234567 ie start time, end time, day of the week
//we need to parse the sessXTime string into hours and min for start and end times so we can use those in the timestampfunction below
//string times contains "0000-2300" as an example
string times = array.get(str.split(sessXTime, ':'), 0)
//string startTime contains "0000"
string startTime = array.get(str.split(times, '-'), 0)
//string endTime contains "2300"
string endTime = array.get(str.split(times, '-'), 1)
//now we need to get the start hour and start min, sing 0 index - hour is the characters in index 0 and index 1 while min is the chars at index 2 and 3
string[] startTimeChars = str.split(startTime, '')
string[] endTimeChars = str.split(endTime, '')
//so now startHour contains 00 and start min contains 00
string startHour = array.get(startTimeChars, 0) + array.get(startTimeChars, 1)
string startMin = array.get(startTimeChars, 2) + array.get(startTimeChars, 3)
//so now endHour contains 23 and end min contains 00
string endHour = array.get(endTimeChars, 0) + array.get(endTimeChars, 1)
string endMin = array.get(endTimeChars, 2) + array.get(endTimeChars, 3)
[startHour, startMin, endHour, endMin]
calc_session_startend(sessXTime, gmt) =>
[startHour, startMin, endHour, endMin] = splitSessionString(sessXTime)
targetstartTimeX = timestamp(gmt, year, month, dayofmonth, math.round(str.tonumber(startHour)), math.round(str.tonumber(startMin)), 00)
targetendTimeX = timestamp(gmt, year, month, dayofmonth, math.round(str.tonumber(endHour)), math.round(str.tonumber(endMin)), 00)
time_now = timestamp(year, month, dayofmonth, hour, minute, 00)
midnight_exchange = timestamp(year, month, dayofmonth, 00, 00, 00)
//if start hour is greater than end hour we are dealing with a session that starts towards the end of one day
//and ends the next day. ie advance the end time by 24 hours - its the next day
bool adjusted = false
if gmt == 'GMT+0'
if math.round(str.tonumber(startHour)) > math.round(str.tonumber(endHour))
if time_now - targetstartTimeX >= 0
targetendTimeX := targetendTimeX + 24 * 60 * 60 * 1000
adjusted := true
targetendTimeX
if gmt == 'GMT+1'
if math.round(str.tonumber(startHour)) == 0
startHour := '24'
if math.round(str.tonumber(endHour)) == 0
endHour := '24'
if math.round(str.tonumber(startHour))-1 > math.round(str.tonumber(endHour))-1
if time_now - targetstartTimeX >= 0
targetendTimeX := targetendTimeX + 24 * 60 * 60 * 1000
adjusted := true
targetendTimeX
//now is the exchange is at some utc offset and the market session crosses days even when start hour is not greater than end hour
//we still need to adjust the end time.
if targetstartTimeX < midnight_exchange and midnight_exchange < targetendTimeX and not adjusted
targetendTimeX := targetendTimeX + 24 * 60 * 60 * 1000
targetendTimeX
[targetstartTimeX,targetendTimeX]
draw_open_range(sessXTime, sessXcol, show_orX, gmt)=>
if show_orX
// Initialize variables on bar zero only, so they preserve their values across bars.
var hi = float(na)
var lo = float(na)
var box hiLoBox = na
// Detect changes in timeframe.
session = time(timeframe.period, sessXTime, gmt)
bool newTF = session and not session[1]
if newTF
// New bar in higher timeframe; reset values and create new lines and box.
[targetstartTimeX,targetendTimeX] = calc_session_startend(sessXTime, gmt)
sessionDuration = math.round(math.abs(time - targetendTimeX)/(timeframe.multiplier*60*1000))
hi := high
lo := low
hiLoBox := box.new(bar_index, hi, timeframe.multiplier == 1? bar_index : bar_index+sessionDuration, lo, border_color = na, bgcolor = sessXcol)
int(na)
else
if timeframe.multiplier == 1 and (na(session[1]) and not na(session) or session[1] < session)
box.set_right(hiLoBox, bar_index+1)
int(na)
draw_session_hilo(sessXTime, show_rectangleX, show_labelX, sessXcolLabel, sessXLabel, gmt)=>
if show_rectangleX
// Initialize variables on bar zero only, so they preserve their values across bars.
var hi = float(0)
var lo = float(10000000000.0)
var line line_t = na
var line line_b = na
var label line_label = na
// var box hiLoBox = na
// Detect changes in timeframe.
session = time(timeframe.period, sessXTime, gmt)
sessLineStyleX = rectStyle == 'Solid' ? line.style_solid : line.style_dashed
bool newTF = session and not session[1]
hi := newTF ? high : session ? math.max(high, hi[1]) : hi[1]
lo := newTF ? low : session ? math.min(low, lo[1]) : lo[1]
if newTF
beginIndex = bar_index
[targetstartTimeX,targetendTimeX] = calc_session_startend(sessXTime, gmt)
sessionDuration = math.round(math.abs(time - targetendTimeX)/(timeframe.multiplier*60*1000))
line_t := line.new(beginIndex, hi, timeframe.multiplier == 1? bar_index : bar_index+sessionDuration, hi, xloc=xloc.bar_index, style=sessLineStyleX, color=sessXcolLabel)
line_b := line.new(beginIndex, lo, timeframe.multiplier == 1? bar_index : bar_index+sessionDuration, lo, xloc=xloc.bar_index, style=sessLineStyleX, color=sessXcolLabel)
line.delete(line_t[1])
line.delete(line_b[1])
if show_labelX
line_label := label.new(beginIndex, hi, sessXLabel, xloc=xloc.bar_index, textcolor=sessXcolLabel, style=label.style_none, size=size.normal, textalign=text.align_right)
label.delete(line_label[1])
int(na)
else
if na(session[1]) and not na(session) or session[1] < session
if timeframe.multiplier == 1
line.set_x2(line_t,bar_index+1)
line.set_x2(line_b,bar_index+1)
line.set_y1(line_t,hi)
line.set_y2(line_t,hi)
line.set_y1(line_b,lo)
line.set_y2(line_b,lo)
if show_labelX and not na(line_label)
label.set_y(line_label, hi)
int(na)
//*****************************//
// Daylight Savings Time Flags //
//*****************************//
int previousSunday = dayofmonth - dayofweek + 1
bool nyDST = na
bool ukDST = na
bool sydDST = na
if month < 3 or month > 11
nyDST := false
ukDST := false
sydDST := true
else if month > 4 and month < 10
nyDST := true
ukDST := true
sydDST := false
else if month == 3
nyDST := previousSunday >= 8
ukDST := previousSunday >= 24
sydDST := true
else if month == 4
nyDST := true
ukDST := true
sydDST := previousSunday <= 0
else if month == 10
nyDST := true
ukDST := previousSunday <= 24
sydDST := previousSunday >= 0
else // month == 11
nyDST := previousSunday <= 0
ukDST := false
sydDST := true
if ukDST
draw_open_range(sess1Time,sess1col,show_or1,'GMT+1')
draw_session_hilo(sess1Time, show_rectangle1, show_label1, sess1colLabel, sess1Label, 'GMT+1')
else
draw_open_range(sess1Time,sess1col,show_or1,'GMT+0')
draw_session_hilo(sess1Time, show_rectangle1, show_label1, sess1colLabel, sess1Label, 'GMT+0')
if nyDST
draw_open_range(sess2Time,sess2col,show_or2,'GMT+1')
draw_session_hilo(sess2Time, show_rectangle2, show_label2, sess2colLabel, sess2Label, 'GMT+1')
else
draw_open_range(sess2Time,sess2col,show_or2,'GMT+0')
draw_session_hilo(sess2Time, show_rectangle2, show_label2, sess2colLabel, sess2Label, 'GMT+0')
// Tokyo
draw_open_range(sess3Time,sess3col,show_or3,'GMT+0')
draw_session_hilo(sess3Time, show_rectangle3, show_label3, sess3colLabel, sess3Label, 'GMT+0')
// Hong Kong
draw_open_range(sess4Time,sess4col,show_or4,'GMT+0')
draw_session_hilo(sess4Time, show_rectangle4, show_label4, sess4colLabel, sess4Label, 'GMT+0')
if sydDST
draw_open_range(sess5Time,sess5col,show_or5,'GMT+1')
draw_session_hilo(sess5Time, show_rectangle5, show_label5, sess5colLabel, sess5Label, 'GMT+1')
else
draw_open_range(sess5Time,sess5col,show_or5,'GMT+0')
draw_session_hilo(sess5Time, show_rectangle5, show_label5, sess5colLabel, sess5Label, 'GMT+0')
//eu brinks is for london
if ukDST
draw_open_range(sess6Time,sess6col,show_or6,'GMT+1')
draw_session_hilo(sess6Time, show_rectangle6, show_label6, sess6colLabel, sess6Label, 'GMT+1')
else
draw_open_range(sess6Time,sess6col,show_or6,'GMT+0')
draw_session_hilo(sess6Time, show_rectangle6, show_label6, sess6colLabel, sess6Label, 'GMT+0')
//us brinks is ny
if nyDST
draw_open_range(sess7Time,sess7col,show_or7,'GMT+1')
draw_session_hilo(sess7Time, show_rectangle7, show_label7, sess7colLabel, sess7Label, 'GMT+1')
else
draw_open_range(sess7Time,sess7col,show_or7,'GMT+0')
draw_session_hilo(sess7Time, show_rectangle7, show_label7, sess7colLabel, sess7Label, 'GMT+0')
//becuase frankfurt changes with london
if ukDST
draw_open_range(sess8Time,sess8col,show_or8,'GMT+1')
draw_session_hilo(sess8Time, show_rectangle8, show_label8, sess8colLabel, sess8Label, 'GMT+1')
else
draw_open_range(sess8Time,sess8col,show_or8,'GMT+0')
draw_session_hilo(sess8Time, show_rectangle8, show_label8, sess8colLabel, sess8Label, 'GMT+0')
// Daily open
//***********
getdayOpen()=>
in_sessionDly = time('D', '24x7')
bool isDly = ta.change(time('D'))//ta.change(in_sessionDly)//in_sessionDly and not in_sessionDly[1]
var dlyOpen = float(na)
if isDly
dlyOpen := open
dlyOpen
daily_open = getdayOpen()
//this plot is only to show historical values when the option is selected.
plot(show_rectangle9 and validTimeFrame and showallDly ? daily_open : na, color=sess9col, style=plot.style_stepline, linewidth=2, editable=false, title="Daily Open")
if showallDly
//if historical values are selected to be shown - then add a label to the plot
r_label(daily_open, 'Daily Open', label.style_none, sess9col, validTimeFrame and show_label9)
showallDly
else
if show_rectangle9
//othewise we draw the line and label together - showing only todays line.
draw_line_DO(daily_open, 'D', 'Daily Open', sess9col, line.style_solid, 1, extend.none, validTimeFrame and show_label9, label_x_offset)
//London DST Starts Last Sunday of March DST Edns Last Sunday of October
//New York DST Starts 2nd Sunday of March DST Edns 1st Sunday of November
//Sydney DST Start on 1st Sunday of October DST ends 1st Sunday of Arpil
//Frankfurt DST Starts Last Sunday of March DST Edns Last Sunday of October
|
Bull/Bear Candle % Oscillator | https://www.tradingview.com/script/Ag7NKgTE-Bull-Bear-Candle-Oscillator/ | SolCollector | https://www.tradingview.com/u/SolCollector/ | 68 | 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/
// © SolCollector
// BS Computer Science
// Spencer G.
//
// This script will create a plot with a shaded area indirectly representing the
// percentage of candles that were either bullish or bearish from a given sample
// length. The script has 2 modes: 'classic', and 'range'*.
//
// classic - Candle weights are all the same (1); bullish candles are
// candles that had a close above the open, bearish otherwise. The
// oscillator calculation proceeds in 5 steps:
// 1) Find the number of bullish candles in the sample length
// 2) Find the number of bearish candles in the sample length
// 3) Add together (1) and (2) for a total sum
// 4) Determine % bullish and bearish values by dividing (1) and (2)
// by the sum in (3) individually (multiply each by 100%).
// 5) Subtract the bearish percent from bullish percent, plot.
//
// range† - Candle weights are modified by a specific range of the candle;
// the process for calculating the values of bullish and bearish
// candles differs slightly compared to 'classic'. For bullish
// candles, the upper wick (high - close) is subtracted from the
// total range of that candle for its weight. This upper wick value
// is then added to the weights of bearish candles. The same is
// true for the lower wicks being subtracted from the total range
// of bearish candles and being added to the weights of bullish
// candles.
//
// Bullish Weight: bullish candle low to close + lower wicks of
// bearish candles
// Bearish Weight: bearish candle high to close + upper wicks of
// bullish candles
//
// * There is an additional option for the user to modify the weights of the
// candles in either mode by the volume. Volumetric weight is calculated by
// dividing the current candle's volume by the sum of all volume in the sample
// length, then multiplying the value derived by each candle (1 for classic,
// specific candle ranges otherwise) by this weight.
//
// † When 'Volume Weighted' is enabled, this script will employ the
// request.security_lower_tf function to request the highs, lows, and volume of
// all candles at the specified resolution**. The volumetric weight of the upper
// and lower wicks will then be determined by the volume of all the lower time
// frame candles as follows:
//
// upper wicks - volume is added to the upper wick weight when the low of a
// lower timeframe candle is greater than the close of a
// bullish candle at the current resolution. This volume is then
// subtracted from the current bullish candle's volume.***
//
// lower wicks - volume is added to the lower wick weight when the high of
// a lower timeframe candle is less than the close of a bearish
// candle at the current resolution. This volume is then
// subtracted from the current bearish candle's volume.***
//
// The limitation of this implementation would be that the volumetric weight of
// wicks may be 0 if all lower timeframe candles have lows or highs that are
// within the current candle body at the chart's resolution.
//
// ** NOTE: The default resolution is 1 minute candles. FOR HIGHER TIME FRAMES,
// I RECOMMEND USING RESOLUTIONS THAT THE CURRENT RESOLUTION OF THE CHART IS
// DIVISIBLE BY. I believe that using resolutions for which the current chart
// resolution is not divisible by may yield unreliable results.
//
// *** In the original design of this script, low and high values used in these
// statements are the default source values used, this has since been modified
// so that the user may decide which OHLC values to use when determining wick
// weights.
//
// This will create an oscillator that fluctuates between 100 and -100 where
// above 0 means there were more bullish candles and below 0 means there were
// more bearish candles in the sample. Data produced by this oscillator is
// normalized around the 50% value. If there is an even 50/50 split between
// bullish and bearish candles, then the value produced by this oscillator will
// be 0. This oscillator is an indirect representation of the percentage of
// candles in a sample that were bullish or bearish. To find that percentage
// using this oscillator, perform the following:
//
// TYPE = oscillator value >= 0 ? bullish : bearish
// 50% + ((|oscillator value| / 100) * 50)% of candles in the sample were {TYPE}
//
//@version=5
indicator("Bull/Bear Candle % Oscillator", overlay = false, max_bars_back = 300)
// CONSTANT VALUES
var string UPPER_SWITCH = "upper"
var string LOWER_SWITCH = "lower"
i_SampleLength = input.int(defval = 21, title = "Sample Length", minval = 1,
tooltip = "Defines how may candles will be backtraced to calculate a "
+ "percentage for.")
i_BullishColor = input.color(defval = color.green, title = "Bull Color",
inline = "Colors")
i_NeutralColor = input.color(defval = color.white, title = "Neutral Color",
inline = "Colors")
i_BearishColor = input.color(defval = color.red, title = "Bear Color",
tooltip = "These define the colors used to create the color gradient that fills "
+ "the plot line to the zero line in both positive and negative directions.",
inline = "Colors")
i_InvertColors = input.bool(defval = false, title = "Invert Colors")
i_CalculationType = input.string(defval = "Classic", title = "Calculation Type",
options = ["Classic", "Range"], tooltip = "This setting changes the "
+ "behavior of the script regarding how the % bullish/bearish candles is "
+ "performed. There are 2 settings:\n\nClassic - Counters for keeping track of "
+ "the % of bull/bear candles rely on candle color alone.\n\nRange - Bullish "
+ "candles will be weighted based on how large the range is from low to close"
+ " plus the Lower Wicks of bearish candles in the sample. Bearish candles "
+ "will be weighted based on how large the range is from the high to close "
+ "plus the Upper Wicks of bullish candles in the sample.")
i_VolumeWeighted = input.bool(defval = false, title = "Volume Weighted",
tooltip = "Modifies the % calculation by assigning weight to each candle (or "
+ "relevant partitions*) based upon its volume.\n\n*For the 'Range' setting, "
+ "this will cause the script to analyze the weights of 'counter wicks' on each"
+ " candle. Counter Wicks will be: Upper Wicks for bullish candles, and Lower "
+ "Wicks for bearish candles. The volume weight for these wicks will be "
+ "analyzed at the specified 'Slice' resolution, and calculated as follows:\n\n"
+ "Bullish Candles - for every lower timeframe candle where the low is greater "
+ "than the candle's close at the current resolution, volume weight is shifted "
+ "onto the upper wick.\n\nBearish Candles - for every lower timeframe candle "
+ "where the high is less than the candle's close at the current resolution, "
+ "volume weight is shifted onto the lower wick.")
i_SliceResolution = input.timeframe(defval = "1", title = "Wick Slice Resolution",
tooltip = "*Range & Volume Weighted Enabled Only*\n\nDefines the lower timeframe "
+ "resolution that will be used to determine the volumetric weight of upper "
+ "and lower wicks for candles at the current resolution. It is important to"
+ "note that PineScrypt will restrict the number of lower resolution candles "
+ "utilized to 100,000 total. This script uses 3 request.security_lower_tf "
+ "calls: 1 minute slices on a 1D chart will cause this script to not perform "
+ "any calculations past 23 days prior.\n\n**It is recommended to make this "
+ "value one that the current resolution is divisible by for more reliable "
+ "results.**")
i_UpperWickSource = input.source(defval = low, title = "Limiting Value: Upper Wicks",
inline = "WICK SOURCES")
i_LowerWickSource = input.source(defval = high, title = "Lower Wicks",
inline = "WICK SOURCES", tooltip = "*Range & Volume Weighted Enabled Only*\n\n"
+ "These 'limiting' values will determine which OHLC value of intrabar candles "
+ "will be used against the current chart resolution's close to attribute "
+ "volumetric weight to the upper and lower wicks of that candle.\n\nThe "
+ "default values of 'low' and 'high' ensure that this script will only "
+ "attribute the volume of intrabar candles where 100% of the price action "
+ "had occurred in the current resolution candle's wicks.")
i_RestrictMinMaxData = input.bool(defval = false, title = "Restrict Min/Max Data",
inline = "Restriction")
i_MinMaxRestrictVal = input.int(defval = 100, title = "Restriction:",
minval = 20, tooltip = "Reduces the number of candles to back test "
+ "for defining the min/max % of Bearish/Bullish candles (aids in the gradient "
+ "coloration).\n\nIf 'false', this script will back test the whole way to the "
+ "beginning of viewable historic data.", inline = "Restriction")
i_DisplayMinMaxGuide = input.bool(defval = false, title = "Display Min/Max Guide",
tooltip = "Displays the guidelines that marks what the value of the Minimum %"
+ " and Maximum % Bearish/Bullish candles that is currently being used for "
+ "gradient coloration.")
i_ShowConvertedNormalVal = input.bool(defval = false,
title = "Show Converted Normalized Value", tooltip = "Plots a line that "
+ "represents the 'Bull/Bear ±% Line' value converted from the normalized "
+ "value to the actual percent of bullish and bearish candles. Minimum value "
+ "that this line will reach is 50, maximum value is 100. The color used to"
+ "represent bullish and bearish candles correspond to the input values for "
+ "'Bull/Bear Color' (not affected by 'Invert Colors')\n\nEq: 50% + "
+ "((|SIGNAL| / 100) * 50)%")
// Get Wick Vol(ume) is a helper function which will assess how much volume had
// occurred in the wicks at the current candle of the chart's resolution.
//
// @params:
// lowerTFArr - (float[]) The array that contains all the prices at either
// the high or low of all candles in the lower resolution.
// volArr - (float[]) The array that contains all the volumes
// associated with each candle in the lower resolution.
// type - (string) Specifies which boolean case/calculation to be
// used for determining volume of wicks. (must be 'upper' or
// 'lower')
//
// @return:
// volsum - (float) The volume determined to be in the requested wick at
// the current chart resolution's candle.
f_GetWickVol(_lowerTFValArr, _volArr, string _type) =>
float volsum = 0
int arrSize = array.size(_lowerTFValArr)
int count = 0
// Padding for empty case
if nz(arrSize) == 0
na
else
// Iterate through the lower resolution candles.
while count < arrSize
value = array.get(_lowerTFValArr, count)
vol = array.get(_volArr, count)
switch(_type)
// Upper Wicks -> value must be above close to be counted
"upper" =>
if value > close
volsum := volsum + vol
// Lower Wicks -> value must be below close to be counted
"lower" =>
if value < close
volsum := volsum + vol
count := count + 1
// return
volsum
// Convert Normalized Value is a simple helper function to take the SIGNALPERCENT
// value and convert it from its normalized form to the actual % bullish and
// bearish candles that this script aims to represent. This will reveal the true
// percentage of bullish and bearish candles, optionally plotted on the chart.
f_ConvertNormalizedValue(_val) =>
50 + ((math.abs(_val) / 100) * 50)
// Gradient color endpoints
var color BULLCOLOR = i_InvertColors ? i_BearishColor : i_BullishColor
var color BEARCOLOR = i_InvertColors ? i_BullishColor : i_BearishColor
// Modifiable Array to hold historical values of the SIGNALPERCENT below.
// When utilized as a queue, this prevents the use of a for-loop at each candle.
var float[] MODARR = array.new_float(i_MinMaxRestrictVal + 1, na)
// Place holders for the maximum and minimum values of the MODARR
var float HIGHERMOD = 0
var float LOWERMOD = 0
// SignalPercent is the main result of the script: oscillates [-100, 100]
// BULL/BEAR GRADIENT COLOR will fluctuate between i_BullColor - i_NeutralColor -
// i_BearColor based on how close SIGNALPERCENT is to HIGHER/LOWERMOD OR the
// math.max/min of MODARR (i_RestrictMinMaxData enabled)
float SIGNALPERCENT = na
color BULLGRADIENTCOLOR = na
color BEARGRADIENTCOLOR = na
// Grab lower resolution data: volume, upperwick source, lowerwick source
float[] VOLUMELOWTF =
request.security_lower_tf(syminfo.tickerid, i_SliceResolution, volume)
float[] UPPERWICKSOURCELOWTF =
request.security_lower_tf(syminfo.tickerid, i_SliceResolution, i_UpperWickSource)
float[] LOWERWICKSOURCELOWTF =
request.security_lower_tf(syminfo.tickerid, i_SliceResolution, i_LowerWickSource)
// Ignore introductory data
if bar_index > i_SampleLength
body = close - open
cRange = high - low
vol = volume
bullOrBear = body >= 0
upperWick = bullOrBear ? high - close : high - open
lowerWick = bullOrBear ? open - low : close - low
// BullRange - (high - low) - (high - close)
// BearRange - (high - low) - (close - low)
bullRange = cRange - upperWick
bearRange = cRange - lowerWick
// If classic, wick volumes are not considered, determine wick volume by
// lower resolution candles otherwise
upperWickVol = i_CalculationType == "Classic" ? 0 :
f_GetWickVol(UPPERWICKSOURCELOWTF, VOLUMELOWTF, UPPER_SWITCH)
lowerWickVol = i_CalculationType == "Classic" ? 0 :
f_GetWickVol(LOWERWICKSOURCELOWTF, VOLUMELOWTF, LOWER_SWITCH)
// Value of candle:
// classic - 1
// range - if bullish candle: bullRange, bearRange otherwise
value =
i_CalculationType == "Classic" ? 1 : bullOrBear ? bullRange : bearRange
// Find total volume during the sample length
sampleVolSum = math.sum(vol, i_SampleLength)
// For standard volumetric weight, divide current candle's volume by the
// sample volume, if not weighted return 1
standardVolWeight = i_VolumeWeighted ? vol / sampleVolSum : 1
classicValues = value * standardVolWeight
// After determining wick volume (if weighted/range) subtract the associated
// wick volume from current candle volume: this is the volume weight for
// this candle:
// Bullish -> value * adjustedBullVol
// Bearish -> value * adjustedBearVol
adjustedBullVol = i_VolumeWeighted ? (vol - upperWickVol) / sampleVolSum : 1
adjustedBearVol = i_VolumeWeighted ? (vol - lowerWickVol) / sampleVolSum : 1
// Determine the proportion of the wick volumes
bullWickVolWeight = i_VolumeWeighted ? lowerWickVol / sampleVolSum : 1
bearWickVolWeight = i_VolumeWeighted ? upperWickVol / sampleVolSum : 1
// For complex/counter values, calculate based on if the current candle is
// bullish or bearish:
//
// Bullish - Counter value is upperWick * bearWickVolWeight
//
// Bearish - Counter value is lowerWick * bullWickVolWeight
complexValue =
bullOrBear ? value * adjustedBullVol : value * adjustedBearVol
counterValue =
bullOrBear ? upperWick * bearWickVolWeight : lowerWick * bullWickVolWeight
// Multi-purpose summation ternary declaration:
// If the current candle is:
// Bullish - TernaryValA is added to bullish totals, TernaryValB is
// added to bearish totals.
// Bearish - TernaryValB is added to bullish totals, TernaryValA is
// added to bearish totals.
//
// If the calculation type is:
// classic - TernaryValA will be the classicValues calculated above,
// TernaryValB will be 0.
// range - TernaryValA will be the complexValue calculated above,
// TernaryValB will be the counterValue calculated above.
ternaryValA = i_CalculationType == "Classic" ? classicValues : complexValue
ternaryValB = i_CalculationType == "Classic" ? 0 : counterValue
bullSum = math.sum(bullOrBear ? ternaryValA : ternaryValB, i_SampleLength)
bearSum = math.sum(not bullOrBear ? ternaryValA : ternaryValB, i_SampleLength)
// SIGNALPERCENT Calculation
totalSum = bullSum + bearSum
bullPercent = (bullSum / totalSum) * 100
bearPercent = (bearSum / totalSum) * 100
SIGNALPERCENT := bullPercent - bearPercent
// Treat MODARR like a queue
if i_RestrictMinMaxData
array.unshift(MODARR, SIGNALPERCENT)
if array.size(MODARR) > i_MinMaxRestrictVal
throwAwayVal = array.pop(MODARR)
// Determine the change in HIGHER/LOWERMOD based on SIGNALPERCENT
HIGHERMOD := i_RestrictMinMaxData ? array.max(MODARR) :
SIGNALPERCENT > HIGHERMOD ? SIGNALPERCENT : HIGHERMOD
LOWERMOD := i_RestrictMinMaxData ? array.min(MODARR) :
SIGNALPERCENT < LOWERMOD ? SIGNALPERCENT : LOWERMOD
// Generate the color gradient based on the SIGNALPERCENT's relation to
// HIGHER/LOWERMOD
BULLGRADIENTCOLOR :=
color.from_gradient(SIGNALPERCENT, 0, HIGHERMOD, i_NeutralColor, BULLCOLOR)
BEARGRADIENTCOLOR :=
color.from_gradient(math.abs(SIGNALPERCENT), 0, math.abs(LOWERMOD),
i_NeutralColor, BEARCOLOR)
NORMALCONVERT =
i_ShowConvertedNormalVal ? f_ConvertNormalizedValue(SIGNALPERCENT) : na
SIGNALCOLOR = SIGNALPERCENT > 0 ? BULLGRADIENTCOLOR : BEARGRADIENTCOLOR
SIGNALPLOT = plot(SIGNALPERCENT, title = "Bull/Bear ±% Line", color = color.white,
linewidth = 2)
ZEROPLOT = plot(0, title = "Zero Line", color = color.white)
fill(plot1 = ZEROPLOT, plot2 = SIGNALPLOT, color = SIGNALPERCENT > 0 ?
BULLGRADIENTCOLOR : BEARGRADIENTCOLOR, title = "Bull/Bear Gradient")
plot(NORMALCONVERT, title = "Converted Normalized Value Line",
color = SIGNALPERCENT > 0 ? i_BullishColor : i_BearishColor)
plot(HIGHERMOD, title = "Higher Mod Value", color = BULLCOLOR,
display = i_DisplayMinMaxGuide ? display.all : display.none)
plot(LOWERMOD, title = "Lower Mod Value", color = BEARCOLOR,
display = i_DisplayMinMaxGuide ? display.all : display.none)
alertcondition(SIGNALPERCENT[1] > 0 and SIGNALPERCENT < 0, title = "Bull/Bear "
+ "% Line Bearish Flip", message = "Bull/Bear % Line below 0, more bearish "
+ "candles detected in current sample.")
alertcondition(SIGNALPERCENT[1] < 0 and SIGNALPERCENT > 0, title = "Bull/Bear "
+ "% Line Bullish Flip", message = "Bull/Bear % Line above 0, more bullish "
+ "candles detected in current sample.") |
High/Low Historical Volatility Bands [Loxx] | https://www.tradingview.com/script/O5D82c78-High-Low-Historical-Volatility-Bands-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 179 | 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/
// © loxx
//@version=5
indicator("High/Low Historical Volatility Bands [Loxx]",
shorttitle = "HLHVB [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
ema(float src, float per)=>
float alpha = 2.0 / (1.0 + per)
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
sma(float src, float per)=>
float sum = 0
float out = src
for k = 0 to per - 1
sum += nz(src[k])
out := sum / per
out
smma(float src, float per)=>
float alpha = 1.0 / per
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
lwma(float src, float per)=>
float sumw = 0
float sum = 0
float out = 0
for i = 0 to per - 1
float weight = (per - i) * per
sumw += weight
sum += nz(src[i]) * weight
out := sum / sumw
out
pwma(float src, float per, float pow)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = math.pow((per - k), pow)
sumw += weight
sum += nz(src[k]) * weight
out := sum / sumw
out
lsma(float src, float per)=>
float out = 0
out := 3.0 * lwma(src, per) - 2.0 * sma(src, per)
out
hma(float src, float per)=>
int HalfPeriod = math.floor(per / 2)
int HullPeriod = math.floor(math.sqrt(per))
float out = 0
float price1 = 2.0 * lwma(src, HalfPeriod) - lwma(src, per)
out := lwma(price1, HullPeriod)
out
tma(float src, float per)=>
float half = (per + 1.0) / 2.0
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = k + 1
if weight > half
weight := per - k
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
swma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
weight = math.sin((k + 1) * math.pi / (per + 1))
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
vwma(float src, float per)=>
float sum = 0
float sumw = 0
float out = 0
for k = 0 to per - 1
float weight = nz(volume[k])
sumw += weight
sum += weight * nz(src[k])
out := sum / sumw
out
nonlagma(float src, float len)=>
float cycle = 4.0
float coeff = 3.0 * math.pi
float phase = len - 1.0
int _len = int(len * cycle + phase)
float weight = 0.
float alfa = 0.
float out = 0.
float[] alphas = array.new_float(_len, 0)
for k = 0 to _len - 1
float t = 0.
t := k <= phase - 1 ? 1.0 * k / (phase - 1) : 1.0 + (k - phase + 1) * (2.0 * cycle - 1.0) / (cycle * len -1.0)
beta = math.cos(math.pi * t)
float g = 1.0/(coeff * t + 1)
g := t <= 0.5 ? 1 : g
array.set(alphas, k, g * beta)
weight += array.get(alphas, k)
if (weight > 0)
float sum = 0.
for k = 0 to _len - 1
sum += array.get(alphas, k) * nz(src[k])
out := (sum / weight)
out
variant(type, src, len) =>
out = 0.0
switch type
"Exponential Moving Average - EMA" => out := ema(src, len)
"Hull Moving Average - HMA" => out := hma(src, len)
"Linear Regression Value - LSMA (Least Squares Moving Average)" => out := lsma(src, len)
"Linear Weighted Moving Average - LWMA" => out := lwma(src, len)
"Non-Lag Moving Average" => out := nonlagma(src, len)
"Parabolic Weighted Moving Average" => out := pwma(src, len, 2)
"Simple Moving Average - SMA" => out := sma(src, len)
"Sine Weighted Moving Average" => out := swma(src, len)
"Smoothed Moving Average - SMMA" => out := smma(src, len)
"Triangular Moving Average - TMA" => out := tma(src, len)
"Volume Weighted Moving Average - VWMA" => out := vwma(src, len)
=> out := sma(src, len)
out
hvbands(string type, float src, int per, float dev)=>
float hl = high - low
float avg = ta.sma(hl, per)
float sum = 0
for i = 0 to per - 1
sum += math.pow(nz(hl[i]) - avg, 2)
float deviation = math.sqrt(sum / (per - 1))
bufferMe = variant(type, src, per)
bufferUp = bufferMe + deviation * dev
bufferDn = bufferMe - deviation * dev
bufferUpc = 0
bufferDnc = 0
bufferUpc := nz(bufferUpc[1])
bufferDnc := nz(bufferDnc[1])
if bufferUp > nz(bufferUp[1])
bufferUpc := 0
if bufferUp < nz(bufferUp[1])
bufferUpc := 1
if bufferDn> nz(bufferDn[1])
bufferDnc := 0
if bufferDn< nz(bufferDn[1])
bufferDnc := 1
bufferMec = (bufferUpc == 0 and bufferDnc == 0) ? 0 : (bufferUpc == 1 and bufferDnc == 1) ? 1 : 2
[bufferUp, bufferDn, bufferMe, bufferMec, bufferUpc, bufferDnc]
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(40, "Period", group = "Basic Settings")
type = input.string("Hull Moving Average - HMA", "Double Smoothing MA Type", options = ["Exponential Moving Average - EMA"
, "Hull Moving Average - HMA"
, "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA"
, "Non-Lag Moving Average"
, "Parabolic Weighted Moving Average"
, "Simple Moving Average - SMA"
, "Sine Weighted Moving Average"
, "Smoothed Moving Average - SMMA"
, "Triangular Moving Average - TMA"
, "Volume Weighted Moving Average - VWMA"],
group = "Bands Settings")
dev = input.float(1.0, "Deviations", group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
[bufferUp, bufferDn, bufferMe, bufferMec, bufferUpc, bufferDnc] = hvbands(type, src, per, dev)
pregoLong = bufferMec == 0
pregoShort = bufferMec == 1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
colorout = bufferMec == 0 ? greencolor : bufferMec == 1 ? redcolor : color.white
coloroutu = bufferUpc == 0 ? greencolor : bufferUpc == 1 ? redcolor : color.white
coloroutd = bufferDnc == 0 ? greencolor : bufferDnc == 1 ? redcolor : color.white
plot(bufferMe, "Middle", color = colorout, linewidth = 3)
plot(bufferUp, "Up band", color = coloroutu)
plot(bufferDn, "Down band", color = coloroutd)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "High/Low Historical Volatility Bands [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "High/Low Historical Volatility Bands [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Variety MA Cluster Filter [Loxx] | https://www.tradingview.com/script/cr2Ix9Il-Variety-MA-Cluster-Filter-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 171 | 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/
// © loxx
//@version=5
indicator("Variety MA Cluster Filter [Loxx]",
shorttitle="VMACF [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
clusterFilter(float src, float inpma1, float inpma2, int per)=>
inner = src
while true
if nz(inner[1]) > nz(inner[per])
if (nz(inner[1]) < inpma2 and nz(inner[1]) < inpma1)
inner := math.min(inpma2, inpma1)
break
if nz(inner[1]) < inpma2 and nz(inner[1]) > inpma1
inner := inpma2
break
if nz(inner[1]) > inpma2 and nz(inner[1]) < inpma1
inner := inpma1
break
inner := math.max(inpma2, inpma1)
break
else
if nz(inner[1]) > inpma2 and nz(inner[1]) > inpma1
inner := math.max(inpma2, inpma1)
break
if nz(inner[1]) > inpma2 and nz(inner[1]) < inpma1
inner := inpma2
break
if nz(inner[1]) < inpma2 and nz(inner[1]) > inpma1
inner := inpma1
break
inner := math.min(inpma2, inpma1)
break
inner
stdFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
smthtype1 = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption1 = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per1 = input.int(2,'Period', group = "Basic Settings")
type1 = input.string("Simple Moving Average - SMA", "MA1 Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre filt", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Basic Settings")
type2 = input.string("Exponential Moving Average - EMA", "MA2 Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre filt", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Basic Settings")
filterop = input.string("VMACF", "Filter Options", options = ["Price", "VMACF", "Both", "None"], group= "Filter Settings")
filter = input.float(2, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title="* Laguerre filt (LF) Only - Alpha", minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, "* Parabolic Weighted Moving Average (PWMA) Only - Power", minval=0, group = "Moving Average Inputs")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
srcfinal(srcoption, smthtype)=>
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = loxxmas.adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = loxxmas.ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = loxxmas.alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = loxxmas.dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = loxxmas.dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = loxxmas.frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = loxxmas.hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = loxxmas.ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = loxxmas.ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = loxxmas.instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre filt"
[t, s, b] = loxxmas.laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = loxxmas.leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = loxxmas.lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = loxxmas.lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = loxxmas.mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = loxxmas.mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = loxxmas.nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = loxxmas.pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = loxxmas.rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = loxxmas.sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = loxxmas.swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = loxxmas.smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = loxxmas.smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = loxxmas.super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = loxxmas.threepolebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = loxxmas.threepolesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = loxxmas.tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = loxxmas.tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = loxxmas.twopolebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = loxxmas.twopoless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = loxxmas.vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = loxxmas.zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = loxxmas.zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = loxxmas.zlagtema(src, len)
sig := s
trig := t
special := b
trig
src = srcfinal(srcoption1, smthtype1)
ma1 = variant(type1, src, per1)
ma2 = variant(type2, src, per1)
src := filterop == "Both" or filterop == "Price" and filter > 0 ? stdFilter(src, filterperiod, filter) : src
out = clusterFilter(src, ma1, ma2, per1)
out := filterop == "Both" or filterop == "VMACF" and filter > 0 ? stdFilter(out, filterperiod, filter) : out
sig = nz(out[1])
state = out > sig ? 1 : out < sig ? -1 : 0
pregoLong = out > sig and (nz(out[1]) < nz(sig[1]) or nz(out[1]) == nz(sig[1]))
pregoShort = out < sig and (nz(out[1]) > nz(sig[1]) or nz(out[1]) == nz(sig[1]))
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
var color colorout = na
colorout := state == -1 ? redcolor : state == 1 ? greencolor : nz(colorout[1])
plot(out, "Step VMACF", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "Variety MA Cluster Filter [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Variety MA Cluster Filter [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
SSA of Price [Loxx] | https://www.tradingview.com/script/rF9lVLXW-SSA-of-Price-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 58 | 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/
// © loxx
//@version=5
indicator("SSA of Price [Loxx]",
shorttitle = "SSP [Loxx]",
overlay = true,
max_lines_count = 500)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
int Maxncomp = 25
int MaxLag = 200
int MaxArrayLength = 1000
// Calculation of the function Sn, needed to calculate the eigenvalues
// Negative determinants are counted there
gaussSn(matrix<float> A, float l, int n)=>
array<float> w = array.new<float>(n, 0)
matrix<float> B = matrix.copy(A)
int count = 0
int cp = 0
float c = 0.
float s1 = 0.
float s2 = 0.
for i = 0 to n - 1
matrix.set(B, i, i, matrix.get(B, i, i) - l)
for k = 0 to n - 2
for i = k + 1 to n - 1
if matrix.get(B, k, k) == 0
for i1 = 0 to n - 1
array.set(w, i1, matrix.get(B, i1, k))
matrix.set(B, i1, k, matrix.get(B, i1, k + 1))
matrix.set(B, i1, k + 1, array.get(w, i1))
cp := cp + 1
c := matrix.get(B, i, k) / matrix.get(B, k, k)
for j = 0 to n - 1
matrix.set(B, i, j, matrix.get(B, i, j) - matrix.get(B, k, j) * c)
count := 0
s1 := 1
for i = 0 to n - 1
s2 := matrix.get(B, i, i)
if s2 < 0
count := count + 1
count
// Calculation of eigenvalues by the bisection method}
// The good thing is that as many eigenvalues are needed, so many will count,
// saves a lot of resources
gaussbisectionl(matrix<float> A, int k, int n)=>
float e1 = 0.
float maxnorm = 0.
float cn = 0.
float a1 = 0.
float b1 = 0.
float c = 0.
for i = 0 to n - 1
cn := 0
for j = 0 to n - 1
cn := cn + matrix.get(A, i, i)
if maxnorm < cn
maxnorm := cn
a1 := 0
b1 := 10 * maxnorm
e1 := 1.0 * maxnorm / 10000000
while math.abs(b1 - a1) > e1
c := 1.0 * (a1 + b1) / 2
if gaussSn(A, c, n) < k
a1 := c
else
b1 := c
float out = (a1 + b1) / 2.0
out
// Calculates eigenvectors for already computed eigenvalues
svector(matrix<float> A, float l, int n, array<float> V)=>
int cp = 0
matrix<float> B = matrix.copy(A)
float c = 0
array<float> w = array.new<float>(n, 0)
for i = 0 to n - 1
matrix.set(B, i, i, matrix.get(B, i, i) - l)
for k = 0 to n - 2
for i = k + 1 to n - 1
if matrix.get(B, k, k) == 0
for i1 = 0 to n - 1
array.set(w, i1, matrix.get(B, i1, k))
matrix.set(B, i1, k, matrix.get(B, i1, k + 1))
matrix.set(B, i1, k + 1, array.get(w, i1))
cp += 1
c := 1.0 * matrix.get(B, i, k) / matrix.get(B, k, k)
for j = 0 to n - 1
matrix.set(B, i, j, matrix.get(B, i, j) - matrix.get(B, k, j) * c)
array.set(V, n - 1, 1)
c := 1
for i = n - 2 to 0
array.set(V, i, 0)
for j = i to n - 1
array.set(V, i, array.get(V, i) - matrix.get(B, i, j) * array.get(V, j))
array.set(V, i, array.get(V, i) / matrix.get(B, i, i))
c += math.pow(array.get(V, i), 2)
for i = 0 to n - 1
array.set(V, i, array.get(V, i) / math.sqrt(c))
// Fast Singular SSA - "Caterpillar" method
// X-vector of the original series
// n-length
// l-lag length
// s-number of eigencomponents
// (there the original series is divided into components, and then restored, here you set how many components you need)
// Y - the restored row (smoothed by the caterpillar)
fastsingular(array<float> X, int n1, int l1, int s1)=>
int n = math.min(MaxArrayLength, n1)
int l = math.min(MaxLag, l1)
int s = math.min(Maxncomp, s1)
matrix<float> A = matrix.new<float>(l, l, 0.)
matrix<float> B = matrix.new<float>(n, l, 0.)
matrix<float> Bn = matrix.new<float>(l, n, 0.)
matrix<float> V = matrix.new<float>(l, n, 0.)
matrix<float> Yn = matrix.new<float>(l, n, 0.)
var array<float> vtarr = array.new<float>(l, 0.)
array<float> ls = array.new<float>(MaxLag, 0)
array<float> Vtemp = array.new<float>(MaxLag, 0)
array<float> Y = array.new<float>(n, 0)
int k = n - l + 1
// We form matrix A in the method that I downloaded from the site of the creators of this matrix S
for i = 0 to l - 1
for j = 0 to l - 1
matrix.set(A, i, j, 0)
for m = 0 to k - 1
matrix.set(A, i, j, matrix.get(A, i, j) + array.get(X, i + m) * array.get(X, m + j))
matrix.set(B, m, j, array.get(X, m + j))
//Find the eigenvalues and vectors of the matrix A
for i = 0 to s - 1
array.set(ls, i, gaussbisectionl(A, l - i, l))
svector(A, array.get(ls, i), l, Vtemp)
for j = 0 to l - 1
matrix.set(V, i, j, array.get(Vtemp, j))
// The restored matrix is formed
for i1 = 0 to s - 1
for i = 0 to k - 1
matrix.set(Yn, i1, i, 0)
for j = 0 to l - 1
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(B, i, j) * matrix.get(V, i1, j))
for i = 0 to l - 1
for j = 0 to k - 1
matrix.set(Bn, i, j, matrix.get(V, i1, i) * matrix.get(Yn, i1, j))
//Diagonal averaging (series recovery)
kb = k
lb = l
for i = 0 to n - 1
matrix.set(Yn, i1, i, 0)
if i < lb - 1
for j = 0 to i
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * (i + 1)))
if (lb - 1 <= i) and (i < kb - 1)
for j = 0 to lb - 1
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * lb))
if kb - 1 <= i
for j = i - kb + 1 to n - kb
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * (n - i)))
// Here, if not summarized, then there will be separate decomposition components
// process by own functions
for i = 0 to n - 1
array.set(Y, i, 0)
for i1 = 0 to s - 1
array.set(Y, i, array.get(Y, i) + matrix.get(Yn, i1, i))
Y
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
lag = input.int(10, "Lag", group = "Bands Settings")
ncomp = input.int(2, "Number of Computations", group = "Bands Settings")
ssapernorm = input.int(20, "SSA Period Normalization", group = "Bands Settings")
numbars = input.int(300, "Number of Bars", group = "Bands Settings")
colorbars = input.bool(false, "Mute bars?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
var pvlines = array.new_line(0)
if barstate.isfirst
for i = 0 to 500 - 1
array.push(pvlines, line.new(na, na, na, na))
if barstate.islast
arr = array.new_float(numbars + 1, 0)
for i = 0 to numbars - 1
array.set(arr, i, nz(src[i]))
pv = fastsingular(arr, numbars, lag, ncomp)
sizer = array.size(pv)
skipperpv = array.size(pv) >= 2000 ? 8 : array.size(pv) >= 1000 ? 4 : array.size(pv) >= 500 ? 2 : 1
int i = 0
int j = 0
while i < sizer - 1 - skipperpv
if j > array.size(pvlines) - 1
break
colorout = i < array.size(pv) - 2 ? array.get(pv, i) > array.get(pv, i + skipperpv) ? greencolor : redcolor : na
pvline = array.get(pvlines, j)
line.set_xy1(pvline, bar_index - i - skipperpv, array.get(pv, i + skipperpv))
line.set_xy2(pvline, bar_index - i, array.get(pv, i))
line.set_color(pvline, colorout)
line.set_style(pvline, line.style_solid)
line.set_width(pvline, 5)
i += skipperpv
j += 1
barcolor(colorbars ? color.black : na)
|
Fractal-Dimension-Adaptive SMA (FDASMA) w/ DSL [Loxx] | https://www.tradingview.com/script/TLgPBwO5-Fractal-Dimension-Adaptive-SMA-FDASMA-w-DSL-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 261 | 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/
// © loxx
//@version=5
indicator("Fractal-Dimension-Adaptive SMA (FDASMA) w/ DSL [Loxx]",
shorttitle = "FDASMADSL [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
darkGreenColor = #1B7E02
darkRedColor = #93021F
SM02 = 'Slope'
SM04 = 'Levels Crosses'
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
trig
sma(float src, float per)=>
float sum = 0
float out = src
for k = 0 to per - 1
sum += nz(src[k])
out := sum / per
out
fdasma(float src, int per, int speedin) =>
float fmax = ta.highest(src, per)
float fmin = ta.lowest(src, per)
float length = 0
float diff = 0
for i = 1 to per - 1
diff := (nz(src[i]) - fmin) / (fmax - fmin)
if i > 0
length += math.sqrt( math.pow(nz(diff[i]) - nz(diff[i + 1]), 2) + (1 / math.pow(per, 2)))
float fdi = 1 + (math.log(length) + math.log(2)) / math.log(2 * per)
float traildim = 1 / (2 - fdi)
float alpha = traildim / 2
int speed = math.round(speedin * alpha)
float out = sma(src, speed)
out
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(30, title = "Period", minval = 2, group = "Basic Settings")
speed = input.int(20, "Speed", group = "Basic Settings")
signal_length = input.int(9, "Signal Period", group = "Signal/DSL Settings")
sigmatype = input.string("Exponential Moving Average - EMA", "Signal/DSL Smoothing", options = ["Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA"], group = "Signal/DSL Settings")
sigtype = input.string(SM04, "Signal type", options = [SM02, SM04], group = "Signal/DSL Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
filterop = input.string("Both", "Filter Options", options = ["Price", "STDFVFIRDFB", "Both", "None"], group= "Filter Settings")
filter = input.float(0, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
out = fdasma(src, per, speed)
sig = out[1]
levelu = 0., leveld = 0., mid = 0.
levelu := (out > sig) ? variant(sigmatype, out, signal_length) : nz(levelu[1])
leveld := (out < sig) ? variant(sigmatype, out, signal_length) : nz(leveld[1])
state = 0.
if sigtype == SM02
if (out < sig)
state :=-1
if (out > sig)
state := 1
else if sigtype == SM04
if (out < leveld)
state :=-1
if (out > levelu)
state := 1
goLong_pre = sigtype == SM02 ? ta.crossover(out, sig) : ta.crossover(out, levelu)
goShort_pre = sigtype == SM02 ? ta.crossunder(out, sig) : ta.crossunder(out, leveld)
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
colorout = sigtype == SM02 ? contSwitch == -1 ? redcolor : greencolor :
state == 1 ? greencolor : state == -1 ? redcolor : color.gray
plot(out,"FDASMADSL", color = colorout, linewidth = 3)
plot(levelu, "Level Up", color = darkGreenColor)
plot(leveld, "Level Down", color = darkRedColor)
barcolor(colorbars ? colorout : na)
goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="Fractal Dimension Adaptive SMA (FDASMA) w/ DSL [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Fractal Dimension Adaptive SMA (FDASMA) w/ DSL [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Support and resistance zones | https://www.tradingview.com/script/apwMQCag/ | mgruner | https://www.tradingview.com/u/mgruner/ | 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/
// © mgruner
// A simple script to plot support and resistance zones for a given instrument
// The zones input has to come as a string. Each zone consists of a string with: "<low(number)>,<high(number)>,<"S"|"R"|"L">,<"Normal"|"Strong">,<Optional: Comment (without spaces in it>"
// An example for the zones input looks like:
//
// 3919.25,3919.25,L,Normal
// 3897.50,3906.50,R,Normal
// 3891.00,3894.50,S,Strong,My-Comment_without_space
//
// The different zone strings have to be seperated by either new line or space.
// I appreciate any feedback.
//@version=5
indicator(title="Support and resistance zones", overlay=true)
InpZones = input(title="Zones", defval="3919.25,3919.25,L,Normal 3897.50,3906.50,R,Normal 3891.00,3894.50,S,Strong,My-Comment_without_space")
InpResCol = input(title="Resistance-Box Color", defval=color.red, inline="Resistance")
InpResBord = input(title="Resistance-Border Color", defval=color.maroon, inline="Resistance")
InpSupCol = input(title="Support-Box Color", defval=color.green, inline="Support")
InpSupBord = input(title="Support-Border Color", defval=color.olive, inline="Support")
InpLineCol = input(title="Line-Color", defval=color.orange)
InpBorderWidthNormal = input(title="Border-Width Normal", defval=1)
InpBorderWidthStrong = input(title="Border-Width Strong", defval=4)
InpLabelColor = input(title="Label Background-Color", defval=color.gray, inline="Label")
InpLabelText = input(title="Label Text-Color", defval=color.white, inline="Label")
InpLabelOffset = input(title="Label-Offset", defval=100, inline="Label")
InpDaysBack = input(title="Days back to be drawn", defval=2)
fZoneColor(inString) =>
inString == "R" ? InpResCol : inString == "S" ? InpSupCol : color.new(color.gray,60)
fBorderColor(inString) =>
inString == "R" ? InpResBord : inString == "S" ? InpSupBord : InpLineCol
fBorderWidth(inString) =>
inString == "Normal" ? InpBorderWidthNormal : InpBorderWidthStrong
// global variable to track if the labels are on the chart already to prevent overlay on new bars
var bLabelsPainted = false
var LabelsArray = array.new_label(0)
var bBoxesPainted = false
// Create persistent variable to track box identifier
box openBox = na
daysTimeFrame = str.tostring(InpDaysBack) + "D"
lastDay = request.security(syminfo.tickerid, daysTimeFrame, barstate.islast, lookahead = barmerge.lookahead_on)
isNewDay = time("D") != time("D")[1]
ZonesArray = array.new_string(0)
// Show the zones only for today
if isNewDay and lastDay and not bBoxesPainted
ZonesArray := str.split(InpZones," ")
// Do the drawing while iterating through the zones
for i = 0 to (array.size(ZonesArray) == 0 ? na : array.size(ZonesArray) - 1)
/////Split the input string (seperator is ",")
mybox = str.split(array.get(ZonesArray,i),",")
/////get the values from the splitted string
ZoneTop = str.tonumber(array.get(mybox,1))
ZoneBottom = str.tonumber(array.get(mybox,0))
ZoneColor = fZoneColor(array.get(mybox,2))
BorderColor = fBorderColor(array.get(mybox,2))
BorderWidth = fBorderWidth(array.get(mybox,3))
LabelText = ZoneBottom == ZoneTop ? str.tostring(ZoneBottom) : str.tostring(ZoneBottom)+"-" + str.tostring(ZoneTop)
////draw the zone
openBox := box.new(left=bar_index, top=ZoneTop,
right=bar_index + 1, bottom= ZoneBottom,
bgcolor= ZoneColor,
border_width=BorderWidth, extend=extend.right)
box.set_border_color(id=openBox, color=BorderColor)
bBoxesPainted := true
////set a nice label
if barstate.islast and not bLabelsPainted
ZonesArray := str.split(InpZones," ")
// Do the drawing while iterating through the zones
for i = 0 to (array.size(ZonesArray) == 0 ? na : array.size(ZonesArray) - 1)
/////Split the input string (seperator is ",")
mylabeldata = str.split(array.get(ZonesArray,i),",")
/////get the values from the splitted string
ZoneTop = str.tonumber(array.get(mylabeldata,1))
ZoneBottom = str.tonumber(array.get(mylabeldata,0))
Comment = array.size(mylabeldata) == 5 ? array.get(mylabeldata,4) : ""
LabelText = ZoneBottom == ZoneTop ? str.tostring(ZoneBottom) : str.tostring(ZoneBottom)+" - " + str.tostring(ZoneTop) + (Comment == "" ? "" : (" ===> "+ Comment))
mylabel = label.new(bar_index+InpLabelOffset,ZoneBottom+((ZoneTop-ZoneBottom)/2),LabelText,style=label.style_label_left,color=InpLabelColor,textcolor=InpLabelText)
array.push(LabelsArray, mylabel)
bLabelsPainted := true
////move labels forward on new a new bar
if barstate.islast and bLabelsPainted
for i = 0 to (array.size(LabelsArray) == 0 ? na : array.size(LabelsArray) -1 )
label.set_x(array.get(LabelsArray,i),bar_index+InpLabelOffset)
//////done |
Fractal Dimension Index Adaptive Period [Loxx] | https://www.tradingview.com/script/7qV2mmMs-Fractal-Dimension-Index-Adaptive-Period-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
indicator("Fractal Dimension Index Adaptive Period [Loxx]",
shorttitle = "FDIAP [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
fdip(float src, int per, int speedin) =>
float fmax = ta.highest(src, per)
float fmin = ta.lowest(src, per)
float length = 0
float diff = 0
for i = 1 to per - 1
diff := (nz(src[i]) - fmin) / (fmax - fmin)
if i > 0
length += math.sqrt( math.pow(nz(diff[i]) - nz(diff[i + 1]), 2) + (1 / math.pow(per, 2)))
float fdi = 1 + (math.log(length) + math.log(2)) / math.log(2 * per)
float traildim = 1 / (2 - fdi)
float alpha = traildim / 2
int speed = math.round(speedin * alpha)
speed
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(30, title = "Period", minval = 2, group = "Basic Settings")
speed = input.int(20, "Speed", group = "Basic Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
out = fdip(src, per, speed)
plot(out, "FDIAP", color = greencolor, linewidth = 2)
|
End-pointed SSA of FDASMA [Loxx] | https://www.tradingview.com/script/TowkmF7s-End-pointed-SSA-of-FDASMA-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 102 | 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/
// © loxx
//@version=5
indicator("End-pointed SSA of FDASMA [Loxx]",
shorttitle = "EPSSAFDASMA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
int Maxncomp = 25
int MaxLag = 200
int MaxArrayLength = 1000
sma(float src, float per)=>
float sum = 0
float out = src
for k = 0 to per - 1
sum += nz(src[k])
out := sum / per
out
fdasma(float src, int per, int speedin) =>
float fmax = ta.highest(src, per)
float fmin = ta.lowest(src, per)
float length = 0
float diff = 0
for i = 1 to per - 1
diff := (nz(src[i]) - fmin) / (fmax - fmin)
if i > 0
length += math.sqrt( math.pow(nz(diff[i]) - nz(diff[i + 1]), 2) + (1 / math.pow(per, 2)))
float fdi = 1 + (math.log(length) + math.log(2)) / math.log(2 * per)
float traildim = 1 / (2 - fdi)
float alpha = traildim / 2
int speed = math.round(speedin * alpha)
float out = sma(src, speed)
out
// Calculation of the function Sn, needed to calculate the eigenvalues
// Negative determinants are counted there
gaussSn(matrix<float> A, float l, int n)=>
array<float> w = array.new<float>(n, 0)
matrix<float> B = matrix.copy(A)
int count = 0
int cp = 0
float c = 0.
float s1 = 0.
float s2 = 0.
for i = 0 to n - 1
matrix.set(B, i, i, matrix.get(B, i, i) - l)
for k = 0 to n - 2
for i = k + 1 to n - 1
if matrix.get(B, k, k) == 0
for i1 = 0 to n - 1
array.set(w, i1, matrix.get(B, i1, k))
matrix.set(B, i1, k, matrix.get(B, i1, k + 1))
matrix.set(B, i1, k + 1, array.get(w, i1))
cp := cp + 1
c := matrix.get(B, i, k) / matrix.get(B, k, k)
for j = 0 to n - 1
matrix.set(B, i, j, matrix.get(B, i, j) - matrix.get(B, k, j) * c)
count := 0
s1 := 1
for i = 0 to n - 1
s2 := matrix.get(B, i, i)
if s2 < 0
count := count + 1
count
// Calculation of eigenvalues by the bisection method}
// The good thing is that as many eigenvalues are needed, so many will count,
// saves a lot of resources
gaussbisectionl(matrix<float> A, int k, int n)=>
float e1 = 0.
float maxnorm = 0.
float cn = 0.
float a1 = 0.
float b1 = 0.
float c = 0.
for i = 0 to n - 1
cn := 0
for j = 0 to n - 1
cn := cn + matrix.get(A, i, i)
if maxnorm < cn
maxnorm := cn
a1 := 0
b1 := 10 * maxnorm
e1 := 1.0 * maxnorm / 10000000
while math.abs(b1 - a1) > e1
c := 1.0 * (a1 + b1) / 2
if gaussSn(A, c, n) < k
a1 := c
else
b1 := c
float out = (a1 + b1) / 2.0
out
// Calculates eigenvectors for already computed eigenvalues
svector(matrix<float> A, float l, int n, array<float> V)=>
int cp = 0
matrix<float> B = matrix.copy(A)
float c = 0
array<float> w = array.new<float>(n, 0)
for i = 0 to n - 1
matrix.set(B, i, i, matrix.get(B, i, i) - l)
for k = 0 to n - 2
for i = k + 1 to n - 1
if matrix.get(B, k, k) == 0
for i1 = 0 to n - 1
array.set(w, i1, matrix.get(B, i1, k))
matrix.set(B, i1, k, matrix.get(B, i1, k + 1))
matrix.set(B, i1, k + 1, array.get(w, i1))
cp += 1
c := 1.0 * matrix.get(B, i, k) / matrix.get(B, k, k)
for j = 0 to n - 1
matrix.set(B, i, j, matrix.get(B, i, j) - matrix.get(B, k, j) * c)
array.set(V, n - 1, 1)
c := 1
for i = n - 2 to 0
array.set(V, i, 0)
for j = i to n - 1
array.set(V, i, array.get(V, i) - matrix.get(B, i, j) * array.get(V, j))
array.set(V, i, array.get(V, i) / matrix.get(B, i, i))
c += math.pow(array.get(V, i), 2)
for i = 0 to n - 1
array.set(V, i, array.get(V, i) / math.sqrt(c))
// Fast Singular SSA - "Caterpillar" method
// X-vector of the original series
// n-length
// l-lag length
// s-number of eigencomponents
// (there the original series is divided into components, and then restored, here you set how many components you need)
// Y - the restored row (smoothed by the caterpillar)
fastsingular(array<float> X, int n1, int l1, int s1)=>
int n = math.min(MaxArrayLength, n1)
int l = math.min(MaxLag, l1)
int s = math.min(Maxncomp, s1)
matrix<float> A = matrix.new<float>(l, l, 0.)
matrix<float> B = matrix.new<float>(n, l, 0.)
matrix<float> Bn = matrix.new<float>(l, n, 0.)
matrix<float> V = matrix.new<float>(l, n, 0.)
matrix<float> Yn = matrix.new<float>(l, n, 0.)
var array<float> vtarr = array.new<float>(l, 0.)
array<float> ls = array.new<float>(MaxLag, 0)
array<float> Vtemp = array.new<float>(MaxLag, 0)
array<float> Y = array.new<float>(n, 0)
int k = n - l + 1
// We form matrix A in the method that I downloaded from the site of the creators of this matrix S
for i = 0 to l - 1
for j = 0 to l - 1
matrix.set(A, i, j, 0)
for m = 0 to k - 1
matrix.set(A, i, j, matrix.get(A, i, j) + array.get(X, i + m) * array.get(X, m + j))
matrix.set(B, m, j, array.get(X, m + j))
//Find the eigenvalues and vectors of the matrix A
for i = 0 to s - 1
array.set(ls, i, gaussbisectionl(A, l - i, l))
svector(A, array.get(ls, i), l, Vtemp)
for j = 0 to l - 1
matrix.set(V, i, j, array.get(Vtemp, j))
// The restored matrix is formed
for i1 = 0 to s - 1
for i = 0 to k - 1
matrix.set(Yn, i1, i, 0)
for j = 0 to l - 1
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(B, i, j) * matrix.get(V, i1, j))
for i = 0 to l - 1
for j = 0 to k - 1
matrix.set(Bn, i, j, matrix.get(V, i1, i) * matrix.get(Yn, i1, j))
//Diagonal averaging (series recovery)
kb = k
lb = l
for i = 0 to n - 1
matrix.set(Yn, i1, i, 0)
if i < lb - 1
for j = 0 to i
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * (i + 1)))
if (lb - 1 <= i) and (i < kb - 1)
for j = 0 to lb - 1
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * lb))
if kb - 1 <= i
for j = i - kb + 1 to n - kb
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * (n - i)))
// Here, if not summarized, then there will be separate decomposition components
// process by own functions
for i = 0 to n - 1
array.set(Y, i, 0)
for i1 = 0 to s - 1
array.set(Y, i, array.get(Y, i) + matrix.get(Yn, i1, i))
Y
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
speed = input.int(20, "Speed", group = "Basic Settings")
lag = input.int(10, "Lag", group = "Basic Settings")
ncomp = input.int(2, "Number of Computations", group = "Basic Settings")
ssapernorm = input.int(30, "SSA Period Normalization", group = "Basic Settings")
numbars = input.int(330, "Number of Bars", group = "Basic Settings")
backbars = input.int(400, "Number of Back", group = "Basic Settings", tooltip ="How many bars to plot.The higher the number the slower the computation.")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
scrin = fdasma(src, ssapernorm, speed)
out = 0.
sig = 0.
arr = array.new_float(numbars + 1, 0)
for i = 0 to numbars - 1
array.set(arr, i, nz(scrin[i]))
if last_bar_index - bar_index < backbars
pv = fastsingular(arr, numbars, lag, ncomp)
out := array.get(pv, 0)
sig := out[1]
colorout = out > sig ? greencolor : out < sig ? redcolor : color.gray
plot(last_bar_index - bar_index < backbars ? out : na, "EPSSAFDASMA", color = colorout, linewidth = 2)
barcolor(last_bar_index - bar_index < backbars and colorbars ? colorout : na)
goLong = ta.crossover(out, sig)
goShort = ta.crossunder(out, sig)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.auto)
alertcondition(goLong, title = "Long", message = "End-pointed SSA of FDASMA [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "End-pointed SSA of FDASMA [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
FDI-Adaptive Fisher Transform [Loxx] | https://www.tradingview.com/script/Rg90QydP-FDI-Adaptive-Fisher-Transform-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
indicator("FDI-Adaptive Fisher Transform [Loxx]",
overlay = false,
shorttitle="FDIAFT [Loxx]",
timeframe="",
timeframe_gaps=true,
max_bars_back = 3000)
greencolor = #2DD204
redcolor = #D2042D
SM02 = 'Zero-Line Cross'
SM03 = 'Signal Crossover'
fdip(float src, int per, int speedin) =>
float fmax = ta.highest(src, per)
float fmin = ta.lowest(src, per)
float length = 0
float diff = 0
for i = 1 to per - 1
diff := (nz(src[i]) - fmin) / (fmax - fmin)
if i > 0
length += math.sqrt( math.pow(nz(diff[i]) - nz(diff[i + 1]), 2) + (1 / math.pow(per, 2)))
float fdi = 1 + (math.log(length) + math.log(2)) / math.log(2 * per)
float traildim = 1 / (2 - fdi)
float alpha = traildim / 2
int speed = math.round(speedin * alpha)
speed
src = input.source(hl2, "Source", group = "Basic Settings")
per = input.int(30, "Fractal Period Ingest", group = "Basic Settings")
speed = input.int(20, "Speed", group = "Basic Settings")
signalMode = input.string(SM02, 'Signal Type', options=[SM02, SM03], group = "Basic Settings")
fisherOb1 = input.float(2, minval=1, step = 0.1, title='Overbought Level', group = "Basic Settings")
fisherOs1 = input.float(-2, maxval=-1, step = 0.1, title='Oversold Level', group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showsignals = input.bool(true, "Show signals?", group = "UI Options")
masterdom = fdip(src, per, speed)
int len = math.floor(masterdom) < 1 ? 1 : math.floor(masterdom)
len := nz(len, 1)
high_ = ta.highest(hl2, len)
low_ = ta.lowest(hl2, len)
round_(val) => val > .99 ? .999 : val < -.99 ? -.999 : val
value = 0.0
value := round_(.66 * ((hl2 - low_) / (high_ - low_) - .5) + .67 * nz(value[1]))
fish1 = 0.0
fish1 := .5 * math.log((1 + value) / (1 - value)) + .5 * nz(fish1[1])
fish2 = fish1[1]
hth = fisherOb1
lth = fisherOs1
middle = 0.
plot(hth+1.5, color = color.new(color.white, 100), title = "Upper UI Constraint")
plot(lth-1.5, color = color.new(color.white, 100), title = "Lower UI Constraint")
tl = plot(hth+1, color=color.rgb(0, 255, 255, 100), style=plot.style_line, title = "OB Level 2")
tl1 = plot(hth, color=color.rgb(0, 255, 255, 100), style=plot.style_line, title = "OB Level 1")
plot(middle, color=color.new(color.gray, 30), linewidth=1, style=plot.style_circles, title = "Zero")
bl1 = plot(lth, color=color.rgb(255, 255, 255, 100), style=plot.style_line, title = "OS Level 1")
bl = plot(lth-1, color=color.rgb(255, 255, 255, 100), style=plot.style_line, title = "OS Level 2")
fill(tl, tl1, color=color.new(color.gray, 85), title = "Top Boundary Fill Color")
fill(bl, bl1, color=color.new(color.gray, 85), title = "Bottom Boundary Fill Color")
color_out =
signalMode == SM03 ? (fish1 > fish2 ? greencolor : redcolor) :
(fish1 >= 0 and fish1 > fish2 ? greencolor :
fish1 < 0 and fish1 < fish2 ? redcolor : color.gray)
plot(fish1, color = color_out, title='Fisher', linewidth = 3)
plot(fish2, color = color.white, title = "Signal")
barcolor(colorbars ? color_out : na)
goLong = signalMode == SM03 ? ta.crossover(fish1, fish2) : ta.crossover(fish1, 0)
goShort = signalMode == SM03 ? ta.crossunder(fish1, fish2) : ta.crossunder(fish1, 0)
plotshape(goLong and showsignals, title = "Long", color = greencolor, textcolor = greencolor, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(goShort and showsignals, title = "Short", color = redcolor, textcolor = redcolor, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="FDI-Adaptive Fisher Transform [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="FDI-Adaptive Fisher Transform [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Normalized Velocity [Loxx] | https://www.tradingview.com/script/1K0vWSrj-Normalized-Velocity-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 100 | 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/
// © loxx
//@version=5
indicator("Normalized Velocity [Loxx]",
shorttitle='NV [Loxx]',
overlay=false,
timeframe="",
timeframe_gaps=true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
darkGreenColor = #1B7E02
darkRedColor = #93021F
SM02 = 'Slope'
SM03 = 'Middle Crosses'
SM04 = 'Levels Crosses'
moms(float src, float per, float powSlow, float powFast)=>
float suma = 0.0
float sumwa=0
float sumb = 0.0
float sumwb=0
out = 0.
for k = 0 to per - 1
float weight = per - k
suma += nz(src[k]) * math.pow(weight, powSlow)
sumb += nz(src[k]) * math.pow(weight, powFast)
sumwa += math.pow(weight, powSlow)
sumwb += math.pow(weight, powFast)
out := sumb / sumwb - suma / sumwa
out
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(32, "Period", minval=1, group = "Basic Settings")
minMaxPeriod = input.int(50, "Min/Max Period", minval=1, group = "Basic Settings")
LevelUp = input.int(80, "Upper Level", group = "Levels Settings")
LevelDown = input.int(20, "Bottom Level", group = "Levels Settings")
sigtype = input.string(SM03, "Signal type", options = [SM02, SM03, SM04], group = "Signal Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
outmaxminper = (minMaxPeriod > 0) ? minMaxPeriod : per
div = ta.atr(15)
out = src
out := moms(out, per, 1, 2) / div
sig = out[1]
float fmin = ta.lowest(out, outmaxminper)
float fmax = ta.highest(out, outmaxminper)
float rng = fmax - fmin
lvlup = fmin + LevelUp * rng / 100.0
lvldn = fmin + LevelDown * rng / 100.0
mid = fmin + 0.5 * rng
state = 0.
if sigtype == SM02
if (out < sig)
state :=-1
if (out > sig)
state := 1
else if sigtype == SM03
if (out < mid)
state :=-1
if (out > mid)
state := 1
else if sigtype == SM04
if (out < lvldn)
state := -1
if (out > lvlup)
state := 1
colorout = state == 1 ? greencolor : state == -1 ? redcolor : color.gray
plot(out, "Normalized Velocity", color = colorout, linewidth = 2)
plot(lvlup, "Up level", color = bar_index % 2 ? color.gray : na)
plot(lvldn, "Down level", color = bar_index % 2 ? color.gray : na)
plot(mid, "Mid", color = bar_index % 2 ? color.gray : na)
barcolor(colorbars ? colorout: na)
goLong = sigtype == SM02 ? ta.crossover(out, sig) : sigtype == SM03 ? ta.crossover(out, mid) : ta.crossover(out, lvlup)
goShort = sigtype == SM02 ? ta.crossunder(out, sig) : sigtype == SM03 ? ta.crossunder(out, mid) : ta.crossunder(out, lvldn)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Normalized Velocity [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Normalized Velocity [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
FDI-Adaptive Supertrend w/ Floating Levels [Loxx] | https://www.tradingview.com/script/JAtirpgd-FDI-Adaptive-Supertrend-w-Floating-Levels-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 346 | 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/
// © loxx
//@version=5
indicator("FDI-Adaptive Supertrend w/ Floating Levels [Loxx]",
overlay = true,
shorttitle="FDIASTSL [Loxx]",
timeframe="",
timeframe_gaps=true)
greencolor = #2DD204
redcolor = #D2042D
RMA(x, t) =>
EMA1 = x
EMA1 := na(EMA1[1]) ? x : (x - nz(EMA1[1])) * (1/t) + nz(EMA1[1])
EMA1
fdip(float src, int per, int speedin)=>
float fmax = ta.highest(src, per)
float fmin = ta.lowest(src, per)
float length = 0
float diff = 0
for i = 1 to per - 1
diff := (nz(src[i]) - fmin) / (fmax - fmin)
if i > 0
length += math.sqrt( math.pow(nz(diff[i]) - nz(diff[i + 1]), 2) + (1 / math.pow(per, 2)))
float fdi = 1 + (math.log(length) + math.log(2)) / math.log(2 * per)
float traildim = 1 / (2 - fdi)
float alpha = traildim / 2
int speed = math.round(speedin * alpha)
speed
pine_supertrend(float src, float factor, int atrPeriod) =>
float atr = RMA(ta.tr(true), atrPeriod)
float upperBand = src + factor * atr
float lowerBand = src - factor * atr
float prevLowerBand = nz(lowerBand[1])
float prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
float prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := close > upperBand ? -1 : 1
else
direction := close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
[superTrend, direction]
src = input.source(hl2, "Source", group = "Basic Settings")
per = input.int(30, "Fractal Period Ingest", group = "Basic Settings")
speed = input.int(20, "Speed", group = "Basic Settings")
mult = input.float(3.0, "Multiplier", group = "Basic Settings")
adapt = input.bool(true, "Make it adaptive?", group = "Basic Settings")
flLookBack = input.int(25, "Floating Level Lookback Period", group = "Advanced Settings")
flLevelUp = input.float(80, "Floating Levels Up Level %", group = "Advanced Settings")
flLevelDown = input.float(20, "Floating Levels Down Level %", group = "Advanced Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showfloat = input.bool(true, "Show Floating Levels?", group = "UI Options")
showfill = input.bool(true, "Fill Floating Levels?", group = "UI Options")
showsignals = input.bool(true, "Show signals?", group = "UI Options")
masterdom = fdip(src, per, speed)
int len = math.floor(masterdom) < 1 ? 1 : math.floor(masterdom)
len := nz(len, 1)
[supertrend, direction] = pine_supertrend(src, mult, adapt ? len : per)
mini = ta.lowest(supertrend, flLookBack)
maxi = ta.highest(supertrend, flLookBack)
rrange = maxi-mini
flu = mini+flLevelUp*rrange/100.0
fld = mini+flLevelDown*rrange/100.0
flm = mini+0.5*rrange
top = plot(showfloat ? flu : na, "Top float", color = color.new(greencolor, 50), linewidth = 1)
bot = plot(showfloat ? fld : na, "bottom float", color = color.new(redcolor, 50), linewidth = 1)
mid = plot(showfloat ? flm : na, "Mid Float", color = color.new(color.gray, 10), linewidth = 1)
fill(top, mid, title = "Top fill color", color = showfill ? color.new(greencolor, 95) : na)
fill(bot, mid,title = "Bottom fill color", color = showfill ? color.new(redcolor, 95) : na)
barcolor(colorbars ? direction == -1 ? greencolor : redcolor : na)
plot(supertrend, "Supertrend", color = direction == -1 ? greencolor : redcolor, linewidth = 3)
goLong = direction == -1 and direction[1] == 1
goShort = direction == 1 and direction[1] == -1
plotshape(goLong and showsignals, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(goShort and showsignals, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="FDI-Adaptive Supertrend w/ Floating Levels [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="FDI-Adaptive Supertrend w/ Floating Levels [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Smoother Moving Average w/ DSL [Loxx] | https://www.tradingview.com/script/BMrG1Uq7-Smoother-Moving-Average-w-DSL-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 137 | 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/
// © loxx
//@version=5
indicator("Smoother Moving Average w/ DSL [Loxx]",
shorttitle='SMTHMADSL [Loxx]',
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
darkGreenColor = #1B7E02
darkRedColor = #93021F
SM02 = 'Slope'
SM04 = 'Levels Crosses'
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
trig
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(25, "Period", group = "Basic Settings")
signal_length = input.int(9, "Signal Period", group = "Signal/DSL Settings")
sigmatype = input.string("Exponential Moving Average - EMA", "Signal/DSL Smoothing", options = ["Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA"], group = "Signal/DSL Settings")
sigtype = input.string(SM04, "Signal type", options = [SM02, SM04], group = "Signal/DSL Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
[filt, _, _] = loxxmas.smoother(src, per)
out = filt
sig = out[1]
levelu = 0., leveld = 0., mid = 0.
levelu := (out > sig) ? variant(sigmatype, out, signal_length) : nz(levelu[1])
leveld := (out < sig) ? variant(sigmatype, out, signal_length) : nz(leveld[1])
state = 0.
if sigtype == SM02
if (out < sig)
state :=-1
if (out > sig)
state := 1
else if sigtype == SM04
if (out < leveld)
state :=-1
if (out > levelu)
state := 1
goLong_pre = sigtype == SM02 ? ta.crossover(out, sig) : ta.crossover(out, levelu)
goShort_pre = sigtype == SM02 ? ta.crossunder(out, sig) : ta.crossunder(out, leveld)
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
colorout = sigtype == SM02 ? contSwitch == -1 ? redcolor : greencolor :
state == 1 ? greencolor : state == -1 ? redcolor : color.gray
plot(out,"SMTHMADSL", color = colorout, linewidth = 3)
plot(levelu, "Level Up", color = darkGreenColor)
plot(leveld, "Level Down", color = darkRedColor)
barcolor(colorbars ? colorout : na)
goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="Smoother Moving Average w/ DSL [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Smoother Moving Average w/ DSL [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
FDI-Adaptive, Jurik-Filtered, TMA w/ Price Zones [Loxx] | https://www.tradingview.com/script/NqQ5poqX-FDI-Adaptive-Jurik-Filtered-TMA-w-Price-Zones-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 211 | 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/
// © loxx
//@version=5
indicator("FDI-Adaptive, Jurik-Filtered, TMA w/ Price Zones [Loxx]",
shorttitle="FDIAJFTMAPZ [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxjuriktools/1
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
fdip(float src, int per, int speedin)=>
float fmax = ta.highest(src, per)
float fmin = ta.lowest(src, per)
float length = 0
float diff = 0
for i = 1 to per - 1
diff := (nz(src[i]) - fmin) / (fmax - fmin)
if i > 0
length += math.sqrt( math.pow(nz(diff[i]) - nz(diff[i + 1]), 2) + (1 / math.pow(per, 2)))
float fdi = 1 + (math.log(length) + math.log(2)) / math.log(2 * per)
float traildim = 1 / (2 - fdi)
float alpha = traildim / 2
int speed = math.round(speedin * alpha)
speed
calcrng(per)=>
float lsum = (per + 1) * low
float hsum = (per + 1) * high
float sumw = (per + 1)
int k = per
for j = 1 to per
lsum += k * nz(low[j])
hsum += k * nz(high[j])
sumw += k
k -= 1
float out = (hsum / sumw - lsum / sumw)
out
src = input.source(hl2, "Source", group= "Source Settings")
per = input.int(30, "Fractal Period Ingest", group = "Basic Settings")
speed = input.int(20, "Speed", group = "Basic Settings")
smthper = input.int(30, "Jurik Smoothing Period", group = "Jurik Settings")
smthphs = input.float(0., "Jurik Smoothing Phase", group = "Jurik Settings")
rngper = input.int(5, "Range Period", group = "Price Zone Settings")
dev = input.float(1.8, "Deviation", group = "Price Zone Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showsignals = input.bool(true, "Show signals?", group = "UI Options")
fdiper = fdip(src, per, speed)
sum = (fdiper + 1) * src
sumw = (fdiper + 1)
k = fdiper
for j = 1 to fdiper
sum += k * nz(src[j])
sumw += k
k -= 1
tma = loxxjuriktools.jurik_filt(sum / sumw, smthper, smthphs)
sig = tma[1]
rng = calcrng(rngper)
uplvl = tma + dev * rng
dnlvl = tma - dev * rng
colorout = tma > sig ? greencolor : redcolor
plot(tma, "TMA", color = colorout, linewidth = 3)
plot(uplvl, "Upper Channel", color = color.gray, linewidth = 1)
plot(dnlvl, "Lower Channel", color = color.gray, linewidth = 1)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(tma, sig)
goShort = ta.crossunder(tma, sig)
plotshape(goLong and showsignals, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(goShort and showsignals, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="FDI-Adaptive, Jurik-Filtered, TMA w/ Price Zones [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="FDI-Adaptive, Jurik-Filtered, TMA w/ Price Zones [Loxx]]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Price Profile | https://www.tradingview.com/script/gH8mJpct-Price-Profile/ | efe_akm | https://www.tradingview.com/u/efe_akm/ | 26 | 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/
// © efe_akm
//@version=5
indicator("Price Profile", overlay = true, max_boxes_count = 500)
// INPUTS
STARTTIME = input.time(title = "Start Time", defval = timestamp("01 Sep 2022 00:00"), confirm = true)
STOPTIME = input.time(title = "Stop Time", defval = timestamp("10 Sep 2022 00:00"), confirm = true)
BOX_POSITION = input.int(title = "Horizontal Position of the Bars", defval = 5, tooltip = "Shifts position of the horizontal bars to left/right")
BOX_COLORR = input.color(title = "Bar Color", defval = color.new(color.orange, 30))
SHOW_CANDLE_DIFFS = input.bool(true, "Show Candle Differences", tooltip = 'Calculates difference between upper and lower adjacent boxes')
GRANULARITY = input.int(title = "Number of Horizontal Bars", defval = 10, minval = 2 , maxval = 500, group = 'Constant Number of Boxes')
TICK_PER_BOX = input.bool(false, 'Calculate Box Size per Ticks', group = 'Ticks per Box', tooltip = 'Calculates Box Size by a defined number of ticks. Be sure that it creates less than 500 boxes otherwise the indicator may lead to error.')
NUMBER_OF_TICKS = input.int(1000, "Number of Ticks per Box", group = 'Ticks per Box')
// Draw starttime and stoptime
line.new(STARTTIME, low*0.999, STARTTIME , high * 1.0001, extend = extend.both, xloc = xloc.bar_time, color = color.orange)
line.new(STOPTIME, low*0.999, STOPTIME , high * 1.0001, extend = extend.both, xloc = xloc.bar_time, color = color.orange)
// Get bar_index for the left origin of the horizontal bars
var left_bar_index = 999999999999
if time >= STARTTIME
left_bar_index := math.min(left_bar_index, bar_index)
// Create required arrays
var highs = array.new_float(0) // highs of the candles in time window
var lows = array.new_float(0) // lows of the candles in time window
var top_boundaries = array.new_float(GRANULARITY) // top boundaries of horizontal bars
var bottom_boundaries = array.new_float(GRANULARITY) // bottom boundaries of horizontal bars
var candle_counts = array.new_int(GRANULARITY) // candle counts for each horizontal bar
var candle_diffs = array.new_int(GRANULARITY)
// Collect all highs and lows in time window
if time >= STARTTIME and time <= STOPTIME
array.push(highs, high)
array.push(lows, low)
maxx = array.max(highs)
minn = array.min(lows)
// Calculate the indicator
if barstate.islast
// step between horizontal boundaries
step = TICK_PER_BOX ? syminfo.mintick * NUMBER_OF_TICKS : (maxx - minn) / GRANULARITY
granularity = TICK_PER_BOX ? (maxx - minn) / syminfo.mintick / NUMBER_OF_TICKS : GRANULARITY
// Calculate top and bottom of horizontal bars
for i = 0 to granularity - 1
bottom = minn + (i*step)
top = minn + ( (i+1)*step )
array.insert(bottom_boundaries, i, bottom)
array.insert(top_boundaries, i, top)
//Calculate number of candles in that specific horizontal bar
num_of_candles_in_bucket = 0
for j = 0 to array.size(highs) - 1
candle_above_hbar = array.get(lows,j) > top
candle_below_hbar = array.get(highs,j) < bottom
is_candle_in_bucket = not (candle_above_hbar or candle_below_hbar)
num_of_candles_in_bucket += is_candle_in_bucket ? 1 : 0
array.insert(candle_counts, i, num_of_candles_in_bucket)
for i = 0 to granularity - 2
candle_diff = array.get(candle_counts, i+1) - array.get(candle_counts, i)
array.insert(candle_diffs, i, math.abs(candle_diff) )
// Draw Boxes
for i = 0 to granularity - 1
// Draw Candle Counts
horizontal_shift = int(array.size(highs)/10) * BOX_POSITION //to specify horizontal location of the bars
box_left = left_bar_index - horizontal_shift
box_top = array.get(top_boundaries, i)
box_right = box_left + array.get(candle_counts,i)
box_bottom = array.get(bottom_boundaries, i)
box.new(box_left, box_top, box_right, box_bottom, xloc = xloc.bar_index, border_style = line.style_solid, border_color = color.black, border_width = 1, bgcolor = BOX_COLORR)
if SHOW_CANDLE_DIFFS
for i = 0 to granularity - 2
// Draw Candle Diffs
horizontal_shift_1 = int(array.size(highs)/10) * BOX_POSITION //to specify horizontal location of the bars
box_right_1 = left_bar_index - horizontal_shift_1
box_left_1 = box_right_1 - array.get(candle_diffs,i)
box_top_1 = array.get(top_boundaries, i)
box_bottom_1 = array.get(bottom_boundaries, i)
box.new(box_left_1, box_top_1, box_right_1, box_bottom_1, xloc = xloc.bar_index, border_style = line.style_solid, border_color = color.black, border_width = 1, bgcolor = BOX_COLORR)
|
TNT_Upgraded | https://www.tradingview.com/script/ctCJDI0j-TNT-Upgraded/ | Lazylady | https://www.tradingview.com/u/Lazylady/ | 34 | 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/
// © Lazylady
//@version=5
indicator("TNT_Upgraded", overlay = false)
bsp = input(28,title="Body Size Period",group = "Time Periods")
map = input(28,title="Smoothing Period",group = "Time Periods")
fillc = color.black
var bin = 0
var bs = 0.00
////////////////////////
//anchorTime = input.time(timestamp("15 Sep 2022 15:30 -0530"), "Date")
//anchorBarIndex = (time - anchorTime) / (1000 * timeframe.in_seconds(timeframe.period))
//anchorBarsBack = bar_index - anchorBarIndex
timePeriodFactor = time_close(timeframe.period)-time
periodsInDay = 6.25*60*60*1000/timePeriodFactor
// Reset Candle Count to 0 from a particular time interval
if session.isfirstbar
bin := 1
else
bin := bin+1
factor = math.max(bin,bsp)
if timeframe.isintraday
bs := ta.sma(math.abs(close - open),factor)
else
bs := ta.sma(math.abs(close - open),bsp)
///////////////////////
MA = ta.sma(bs,map)
//////////////////
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"Bollinger Bands" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
rsiLengthInput = input.int(27, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
rsiMAInput = input.int(28, minval=1, title="RSI SMA Length", group="RSI MA Settings")
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
///////////////
//TimeFrame Inputs
tf1 = input.timeframe(title="Time Frame 1", defval="5", group="RSI TimeFrame")
tf2 = input.timeframe(title="Time Frame 2", defval="15", group="RSI TimeFrame")
tf3 = input.timeframe(title="Time Frame 3", defval="60", group="RSI TimeFrame")
tfw1 = input(1, title="Time Frame 1 Weight", group="RSI TimeFrame")
tfw2 = input(4, title="Time Frame 2 Weight", group="RSI TimeFrame")
tfw3 = input(9, title="Time Frame 3 Weight", group="RSI TimeFrame")
total = tfw1 + tfw2 + tfw3
//pre-plot
rsi1 = request.security(syminfo.tickerid, tf1, rsi)
rsi2 = request.security(syminfo.tickerid, tf2, rsi)
rsi3 = request.security(syminfo.tickerid, tf3, rsi)
rsif = rsi1*(tfw1/total) + rsi2*(tfw2/total) + rsi3*(tfw3/total)
rsifma = ta.sma(rsif,rsiMAInput)
///////////////
p1 = plot(rsif, "RSI", color=#7E57C2)
rsiUpperBand = hline(60, "RSI Upper Band", color=#787B86)
hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(40, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
p2 = plot(rsifma, title = "RSI MA",color=color.red)
if rsif > rsifma
fillc := color.green
else
fillc := color.red
fill (p1,p2,fillc)
/////////////////
//plot(bs)
//plot(MA,color=color.red)
trendingup = color.new(input.color(color.green, title = "Trending Up", group = "Background Color"),85)
rangebound = color.new(input.color(color.blue, title = "Range Bound", group = "Background Color"),85)
trendingdn = color.new(input.color(color.red, title = "Trending Down", group = "Background Color"),85)
sessioncolor = if bs>MA and rsif > rsifma
trendingup
else if bs>MA and rsif < rsifma
trendingdn
else
rangebound
bgcolor(sessioncolor) |
TSL_adch_1 | https://www.tradingview.com/script/xcXnZkOD-TSL-adch-1/ | adch-1 | https://www.tradingview.com/u/adch-1/ | 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/
// © adch-1
//@version=5
indicator("TSL_adch_1", overlay=true)
a=math.max(high[1],high)
b=math.min(low[1],low)
c=close
d=open[1]
e=math.avg(a,b,c,d)
//e=(a+b+c+d)/4
//e=high[1]
plot(e)
|
Digital Nivesh: Triveni Sangam | https://www.tradingview.com/script/YsEvHPqg-Digital-Nivesh-Triveni-Sangam/ | digitalnivesh | https://www.tradingview.com/u/digitalnivesh/ | 34 | 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/
// © digitalnivesh
//@version=5
indicator("Digital Nivesh: Triveni Sangam",overlay=true)
sLen = input(9,title="SMA length")
mFactor = input(2,title="BB Factor")
bLen = input(20,title="BB Length")
plot(ta.vwap,color=color.red)
plot(ta.sma(high,sLen),color=color.green)
[mid,u,l] = ta.bb(close,bLen,mFactor)
p1= plot(u,color=color.black)
plot(mid,color=color.purple)
p2 = plot(l,color=color.black)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95)) |
End-pointed SSA of Williams %R [Loxx] | https://www.tradingview.com/script/7U7nMQIe-End-pointed-SSA-of-Williams-R-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 244 | 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/
// © loxx
//@version=5
indicator("End-pointed SSA of Williams %R [Loxx]",
shorttitle = "EPSSAWPR [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
int Maxncomp = 25
int MaxLag = 200
int MaxArrayLength = 1000
// Calculation of the function Sn, needed to calculate the eigenvalues
// Negative determinants are counted there
gaussSn(matrix<float> A, float l, int n)=>
array<float> w = array.new<float>(n, 0)
matrix<float> B = matrix.copy(A)
int count = 0
int cp = 0
float c = 0.
float s1 = 0.
float s2 = 0.
for i = 0 to n - 1
matrix.set(B, i, i, matrix.get(B, i, i) - l)
for k = 0 to n - 2
for i = k + 1 to n - 1
if matrix.get(B, k, k) == 0
for i1 = 0 to n - 1
array.set(w, i1, matrix.get(B, i1, k))
matrix.set(B, i1, k, matrix.get(B, i1, k + 1))
matrix.set(B, i1, k + 1, array.get(w, i1))
cp := cp + 1
c := matrix.get(B, i, k) / matrix.get(B, k, k)
for j = 0 to n - 1
matrix.set(B, i, j, matrix.get(B, i, j) - matrix.get(B, k, j) * c)
count := 0
s1 := 1
for i = 0 to n - 1
s2 := matrix.get(B, i, i)
if s2 < 0
count := count + 1
count
// Calculation of eigenvalues by the bisection method}
// The good thing is that as many eigenvalues are needed, so many will count,
// saves a lot of resources
gaussbisectionl(matrix<float> A, int k, int n)=>
float e1 = 0.
float maxnorm = 0.
float cn = 0.
float a1 = 0.
float b1 = 0.
float c = 0.
for i = 0 to n - 1
cn := 0
for j = 0 to n - 1
cn := cn + matrix.get(A, i, i)
if maxnorm < cn
maxnorm := cn
a1 := 0
b1 := 10 * maxnorm
e1 := 1.0 * maxnorm / 10000000
while math.abs(b1 - a1) > e1
c := 1.0 * (a1 + b1) / 2
if gaussSn(A, c, n) < k
a1 := c
else
b1 := c
float out = (a1 + b1) / 2.0
out
// Calculates eigenvectors for already computed eigenvalues
svector(matrix<float> A, float l, int n, array<float> V)=>
int cp = 0
matrix<float> B = matrix.copy(A)
float c = 0
array<float> w = array.new<float>(n, 0)
for i = 0 to n - 1
matrix.set(B, i, i, matrix.get(B, i, i) - l)
for k = 0 to n - 2
for i = k + 1 to n - 1
if matrix.get(B, k, k) == 0
for i1 = 0 to n - 1
array.set(w, i1, matrix.get(B, i1, k))
matrix.set(B, i1, k, matrix.get(B, i1, k + 1))
matrix.set(B, i1, k + 1, array.get(w, i1))
cp += 1
c := 1.0 * matrix.get(B, i, k) / matrix.get(B, k, k)
for j = 0 to n - 1
matrix.set(B, i, j, matrix.get(B, i, j) - matrix.get(B, k, j) * c)
array.set(V, n - 1, 1)
c := 1
for i = n - 2 to 0
array.set(V, i, 0)
for j = i to n - 1
array.set(V, i, array.get(V, i) - matrix.get(B, i, j) * array.get(V, j))
array.set(V, i, array.get(V, i) / matrix.get(B, i, i))
c += math.pow(array.get(V, i), 2)
for i = 0 to n - 1
array.set(V, i, array.get(V, i) / math.sqrt(c))
// Fast Singular SSA - "Caterpillar" method
// X-vector of the original series
// n-length
// l-lag length
// s-number of eigencomponents
// (there the original series is divided into components, and then restored, here you set how many components you need)
// Y - the restored row (smoothed by the caterpillar)
fastsingular(array<float> X, int n1, int l1, int s1)=>
int n = math.min(MaxArrayLength, n1)
int l = math.min(MaxLag, l1)
int s = math.min(Maxncomp, s1)
matrix<float> A = matrix.new<float>(l, l, 0.)
matrix<float> B = matrix.new<float>(n, l, 0.)
matrix<float> Bn = matrix.new<float>(l, n, 0.)
matrix<float> V = matrix.new<float>(l, n, 0.)
matrix<float> Yn = matrix.new<float>(l, n, 0.)
var array<float> vtarr = array.new<float>(l, 0.)
array<float> ls = array.new<float>(MaxLag, 0)
array<float> Vtemp = array.new<float>(MaxLag, 0)
array<float> Y = array.new<float>(n, 0)
int k = n - l + 1
// We form matrix A in the method that I downloaded from the site of the creators of this matrix S
for i = 0 to l - 1
for j = 0 to l - 1
matrix.set(A, i, j, 0)
for m = 0 to k - 1
matrix.set(A, i, j, matrix.get(A, i, j) + array.get(X, i + m) * array.get(X, m + j))
matrix.set(B, m, j, array.get(X, m + j))
//Find the eigenvalues and vectors of the matrix A
for i = 0 to s - 1
array.set(ls, i, gaussbisectionl(A, l - i, l))
svector(A, array.get(ls, i), l, Vtemp)
for j = 0 to l - 1
matrix.set(V, i, j, array.get(Vtemp, j))
// The restored matrix is formed
for i1 = 0 to s - 1
for i = 0 to k - 1
matrix.set(Yn, i1, i, 0)
for j = 0 to l - 1
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(B, i, j) * matrix.get(V, i1, j))
for i = 0 to l - 1
for j = 0 to k - 1
matrix.set(Bn, i, j, matrix.get(V, i1, i) * matrix.get(Yn, i1, j))
//Diagonal averaging (series recovery)
kb = k
lb = l
for i = 0 to n - 1
matrix.set(Yn, i1, i, 0)
if i < lb - 1
for j = 0 to i
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * (i + 1)))
if (lb - 1 <= i) and (i < kb - 1)
for j = 0 to lb - 1
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * lb))
if kb - 1 <= i
for j = i - kb + 1 to n - kb
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * (n - i)))
// Here, if not summarized, then there will be separate decomposition components
// process by own functions
for i = 0 to n - 1
array.set(Y, i, 0)
for i1 = 0 to s - 1
array.set(Y, i, array.get(Y, i) + matrix.get(Yn, i1, i))
Y
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
lag = input.int(10, "Lag", group = "Basic Settings")
ncomp = input.int(2, "Number of Computations", group = "Basic Settings")
ssapernorm = input.int(14, "SSA Period Normalization", group = "Basic Settings")
numbars = input.int(330, "Number of Bars", group = "Basic Settings")
backbars = input.int(400, "Number of Back", group = "Basic Settings", tooltip ="How many bars to plot.The higher the number the slower the computation.")
upband = input.int(-20, "Upper band", group = "Band Settings")
dnband = input.int(-80, "Lower band", group = "Band Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
_pr(length) =>
max = ta.highest(length)
min = ta.lowest(length)
100 * (src - max) / (max - min)
scrin = _pr(ssapernorm)
out = 0.
sig = 0.
arr = array.new_float(numbars + 1, 0)
for i = 0 to numbars - 1
array.set(arr, i, nz(scrin[i]))
if last_bar_index - bar_index < backbars
pv = fastsingular(arr, numbars, lag, ncomp)
out := array.get(pv, 0)
sig := out[1]
plot(last_bar_index - bar_index < backbars ? upband : na, color = bar_index % 2 ? color.gray : na)
plot(last_bar_index - bar_index < backbars ? dnband : na, color = bar_index % 2 ? color.gray : na)
colorout = out > upband ? greencolor : out < dnband ? redcolor : color.gray
plot(last_bar_index - bar_index < backbars ? out : na, "EPSSAWPR", color = colorout, linewidth = 2)
barcolor(last_bar_index - bar_index < backbars and colorbars ? colorout : na)
goLong = ta.crossover(out, upband)
goShort = ta.crossunder(out, dnband)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title = "Long", message = "End-pointed SSA of Williams %R [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "End-pointed SSA of Williams %R [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Reserve Balances with Federal Reserve Banks | https://www.tradingview.com/script/XMJxhkcC-Reserve-Balances-with-Federal-Reserve-Banks/ | Quang47 | https://www.tradingview.com/u/Quang47/ | 32 | 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/
// © Quang47
//@version=5
indicator("Reserve Balances with Federal Reserve Banks", overlay=true, scale=scale.right)
i_res = input.timeframe('D', "Resolution", options=['D', 'W', 'M'])
unit_input = input.string('Millions', options=['Millions', 'Billions', 'Trillions'])
units = unit_input == 'Billions' ? 1e3 : unit_input == 'Millions' ? 1e0 : unit_input == 'Trillions' ? 1e6 : na
fed_res = request.security('FRED:WRESBAL', i_res, close) // millions
fed_out = fed_res / units
var fed_res_offset = 0 // 2-week offset for use with daily charts
if timeframe.isdaily
fed_res_offset := 0
if timeframe.isweekly
fed_res_offset := 0
if timeframe.ismonthly
fed_res_offset := 0
plot(fed_out, title='Reserve Balances', color=color.new(color.yellow,0), style=plot.style_line, linewidth=4, offset=fed_res_offset)
|
Indicator For Trang | https://www.tradingview.com/script/X9TLIQ64-Indicator-For-Trang/ | MikePapinski | https://www.tradingview.com/u/MikePapinski/ | 3 | 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/
// © MikePapinski
//@version=5
indicator("IndicatorForTrang")
plot(close)
|
BTC Twitter Sentiment | https://www.tradingview.com/script/dgFWybBn-BTC-Twitter-Sentiment/ | Powerscooter | https://www.tradingview.com/u/Powerscooter/ | 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/
// © Powerscooter
// Since IntoTheBlock only provides daily sentiment data, this chart might look chunky on lower timeframes, even with smoothing.
//@version=5
indicator("BTC Twitter Sentiment", overlay=false)
//If there's an additional ticker that you'd like to see here, please let me know!
Source = input.string(title="Blockchain", defval="BTC", options=["AAVE","ADA","ALGO","AXS","BAT","BCH","BIT","BTC","CHZ","CRO","CRV","DASH","DOGE","ENS","ETH","FTM","FTT","FXS","GRT","HT","KCS","LDO","LEO","LINK","LTC","MANA","MATIC","MKR","NEXO","OKB","QNT","SAND","SHIB","SNX","UNI","ZEC"], group="Inputs")
smoothing = input.string(title="Smoothing", defval="SMA", options=["SMA", "RMA", "EMA", "WMA"], group="Smoothing Settings")
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)
SmoothLength = input(1, 'MA Length', group="Smoothing Settings")
TwitterPosT = "INTOTHEBLOCK:" + Source + "_TWITTERPOSITIVE"
TwitterNegT = "INTOTHEBLOCK:" + Source + "_TWITTERNEGATIVE"
TwitterNeuT = "INTOTHEBLOCK:" + Source + "_TWITTERNEUTRAL"
TwitterPos = request.security(TwitterPosT, "D", close)
TwitterNeg = request.security(TwitterNegT, "D", close)
TwitterNeu = request.security(TwitterNeuT, "D", close)
//Plotting
ZeroLine = plot(ma_function(0, SmoothLength), color=color.blue, transp=100, editable = false, display=display.none) //We need to make this ZeroLine, as the fill function doesn't accept variable of type int
NegLine = plot(ma_function(TwitterNeg, SmoothLength), "Negative Tweets", color=color.red, display=display.all-display.status_line)
NeuLine = plot(ma_function(TwitterNeu+TwitterNeg, SmoothLength), "Neutral Tweets", color=color.white, display=display.all-display.status_line)
PosLine = plot(ma_function(TwitterNeu+TwitterNeg+TwitterPos, SmoothLength), "Positive Tweets", color=color.green, display=display.all-display.status_line)
//Separate plots that only show the numbers (This is because showing numbers for original plots would show aggregate numbers)
NegNumber = plot(ma_function(TwitterNeg, SmoothLength), "Negative Tweets Number display", color=color.red, display=display.status_line)
NeuNumber = plot(ma_function(TwitterNeu, SmoothLength), "Neutral Tweets Number display", color=color.white, display=display.status_line)
PosNumber = plot(ma_function(TwitterPos, SmoothLength), "Positive Tweets Number display", color=color.green, display=display.status_line)
fill(PosLine, NeuLine, color=color.green,title= "Positive Background", transp=50)
fill(NeuLine, NegLine, color=color.white,title= "Neutral Background", transp=50)
fill(ZeroLine, NegLine, color=color.red,title= "Negative Background", transp=50) |
EMA Ribbon + Stoch (Open) v1 | https://www.tradingview.com/script/GuXHBoqy-EMA-Ribbon-Stoch-Open-v1/ | teguamit_trading | https://www.tradingview.com/u/teguamit_trading/ | 6 | 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/
// © teguamit_trading
//@version=5
indicator("EMA Ribbon + Stoch", overlay=true)
// Inputs
fastMALen = input.int(title="Fast MA Length", defval=5)
medMALen = input.int(title="Medium MA Length", defval=13)
slowMALen = input.int(title="Slow MA Length", defval=21)
ultraslowMALen = input.int(title="200 MA Length", defval=200)
kline = ta.sma(ta.stoch(close,high,low,14),3)
dline = ta.sma(kline,3)
stochLong = kline>dline
stochShort = kline<dline
// Calculate strategy values
fastMA = ta.ema(close, fastMALen)
medMA = ta.ema(close, medMALen)
slowMA = ta.ema(close, slowMALen)
ultraslowMA = ta.ema(close,ultraslowMALen)
// Determine long trading conditions
longCondition1 = ta.crossover(fastMA,medMA)
enterLong = longCondition1 and stochLong
shortCondition1 = ta.crossunder(fastMA,medMA)
enterShort = shortCondition1 and stochShort
//plots
plot(fastMA, color=color.red)
plot(medMA, color=color.blue)
plot(slowMA, color=color.purple)
plot(ultraslowMA, color=color.black)
green = color.green
red=color.red
blue=color.blue
orange=color.orange
bgColour =
enterLong ? green :
enterShort ? red :
na
bgcolor(color=bgColour, transp=85)
if(enterLong)
alert("Buy gold", freq = alert.freq_once_per_bar_close)
if(enterShort)
alert("Sell gold", freq = alert.freq_once_per_bar_close)
|
CFB-Adaptive Trend Cipher Candles [Loxx] | https://www.tradingview.com/script/jfhV0TV0-CFB-Adaptive-Trend-Cipher-Candles-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
indicator('CFB-Adaptive Trend Cipher Candles [Loxx]',
shorttitle = "CFBATCC [Loxx]",
timeframe="",
timeframe_gaps=true,
overlay = true)
import loxx/loxxjuriktools/1 as jf
import loxx/loxxexpandedsourcetypes/4
_corrrelation(x, y, len)=>
float meanx = math.sum(x, len) / len
float meany = math.sum(y, len) / len
float sumxy = 0
float sumx = 0
float sumy = 0
for i = 0 to len - 1
sumxy := sumxy + (nz(x[i]) - meanx) * (nz(y[i]) - meany)
sumx := sumx + math.pow(nz(x[i]) - meanx, 2)
sumy := sumy + math.pow(nz(y[i]) - meany, 2)
sumxy / math.sqrt(sumy * sumx)
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
nlen = input.int(20, "CFB Normal Period", minval = 1, group = "CFB Ingest Settings")
cfb_len = input.int(10, "CFB Depth", maxval = 10, group = "CFB Ingest Settings")
smth = input.int(8, "CFB Smooth Period", minval = 1, group = "CFB Ingest Settings")
slim = input.int(8, "CFB Short Limit", minval = 1, group = "CFB Ingest Settings")
llim = input.int(48, "CFB Long Limit", minval = 1, group = "CFB Ingest Settings")
jcfbsmlen = input.int(5, "Post CFB Jurik Smooth Period", minval = 1, group = "CFB Ingest Settings")
jcfbsmph = input.float(0, "Post CFB Jurik Smooth Phase", group = "CFB Ingest Settings")
CfbSmoothDouble = input.bool(true, "CFB Double Juirk Smoothing?", group = "CFB Ingest Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
cfb_draft = jf.jcfb(src, cfb_len, smth)
cfb_pre =
CfbSmoothDouble ? jf.jurik_filt(jf.jurik_filt(cfb_draft, jcfbsmlen, jcfbsmph), jcfbsmlen, jcfbsmph) :
jf.jurik_filt(cfb_draft, jcfbsmlen, jcfbsmph)
max = ta.highest(cfb_pre, nlen)
min = ta.lowest(cfb_pre, nlen)
denom = max - min
ratio = (denom > 0) ? (cfb_pre - min) / denom : 0.5
out = math.ceil(slim + ratio * (llim - slim))
correlate = _corrrelation(src, bar_index, out)
colorCorrelate =
correlate > 0.95 ? #FFF300 :
correlate > 0.9 ? #80ff5f :
correlate > 0.8 ? #58ff2e :
correlate > 0.6 ? #33fc00 :
correlate > 0.4 ? #29cc00 :
correlate > 0.2 ? #1f9b00 :
correlate > 0.0 ? #156a00 :
correlate < -0.95 ? #FF0EF3 :
correlate < -0.9 ? #ff2e57 :
correlate < -0.8 ? #fc0031 :
correlate < -0.6 ? #cc0028 :
correlate < -0.4 ? #9b001e :
correlate < -0.2 ? #6a0014 :
#6a0014
color_out = color.new(colorCorrelate, 0)
barcolor(color_out)
|
Risk Calculation Table - Amount Based | https://www.tradingview.com/script/Dc2AQIA9-Risk-Calculation-Table-Amount-Based/ | macbedunduc | https://www.tradingview.com/u/macbedunduc/ | 31 | 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/
//Mac bedunduc
//@version=5
indicator('Risk Calculation Table - Amount Based', shorttitle='RRTable', overlay=true)
//Table Settings
//RR and Ticker's decimal
entry = input.price(0.0, 'Entry Price', group='Table Settings')
stop = input.price(0.0, 'SL Price', group='Table Settings')
exit = input.price(0.0, 'TP Price', group='Table Settings')
amount = input(100.0, 'Amount Traded', group='Table Settings')
decimalinput = input.string(defval='0.0', title="Ticker's decimal", tooltip="Type 0 based on the ticker, 0.0 means one number behind decimal, and 0.0000 means four numbers behind decimal",group='Table Settings')
//Manual Table
mtblPos = input.string(title='Table Location', defval='Top Right', options=['Top Right', 'Middle Right', 'Bottom Right', 'Top Center', 'Middle Center', 'Bottom Center', 'Top Left', 'Middle Left', 'Bottom Left'], group='Table Display Settings')
mtblposition = mtblPos == 'Top Right' ? position.top_right : mtblPos == 'Middle Right' ? position.middle_right : mtblPos == 'Bottom Right' ? position.bottom_right : mtblPos == 'Top Center' ? position.top_center : mtblPos == 'Middle Center' ? position.middle_center : mtblPos == 'Bottom Center' ? position.bottom_center : mtblPos == 'Top Left' ? position.top_left : mtblPos == 'Middle Left' ? position.middle_left : position.bottom_left
size = input.string(title='Table Size', defval='Small', options=['Auto', 'Huge', 'Large', 'Normal', 'Small', 'Tiny'], group='Table Display Settings')
_size = size == 'Auto' ? size.auto : size == 'Huge' ? size.huge : size == 'Large' ? size.large : size == 'Normal' ? size.normal : size == 'Small' ? size.small : size.tiny
//plotline
plot(entry > 0 ? entry : na, "Entry Price",color=color.new(color.white,50), style=plot.style_cross, offset=10)
plot(stop > 0 ? stop : na, "StopLoss Price", color=color.new(color.red,50), style=plot.style_cross, offset = 10)
plot(exit > 0 ? exit : na, "TP Price", color=color.new(color.green,50), style=plot.style_cross, offset = 10)
//alarm line
riskcalc = entry > stop ? (((entry-stop)*amount)/entry) : entry < stop ? (((stop - entry)*amount)/entry) : na
tpcalc = exit > entry ? (((exit-entry)*amount)/entry) : exit < entry ? (((entry-exit)*amount)/entry) : na
rrmult = tpcalc / riskcalc
pos = entry > stop ? 'LONG' : entry < stop ? 'SHORT' : na
mcol = entry > stop ? color.green : entry < stop ? color.red : na
//manual table
var mTable = table.new(position=mtblposition, columns=2, rows=9, border_width=1, frame_width=2, frame_color=color.new(#000000, 50), border_color=color.new(#000000, 0))
table.cell(mTable, column=0, row=0, text='Position', text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=0, row=1, text='Entry', text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=0, row=2, text='SL', text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=0, row=3, text='TP', text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=0, row=4, text='Amount', text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=0, row=5, text='SL Risk', text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=0, row=6, text='TP Gain', text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=0, row=7, text='RR Ratio', text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_left, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=1, row=0, text=str.tostring(pos), text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_right, text_valign=text.align_center, bgcolor=mcol)
table.cell(mTable, column=1, row=1, text=str.tostring(entry, decimalinput), text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_right, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=1, row=2, text=str.tostring(stop, decimalinput), text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_right, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=1, row=3, text=str.tostring(exit, decimalinput), text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_right, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=1, row=4, text=str.tostring(amount,'0.0'), text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_right, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=1, row=5, text=str.tostring(riskcalc, '0.00'), text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_right, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=1, row=6, text=str.tostring(tpcalc,'0.00'), text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_right, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
table.cell(mTable, column=1, row=7, text=str.tostring(rrmult,'0.0'+' : 1'), text_color=color.new(#000000,0), text_size=_size, text_halign=text.align_right, text_valign=text.align_center, bgcolor=color.new(#ffffff,0))
|
LuizinTradezone - 9 MME + 20,50,200 MMA | https://www.tradingview.com/script/xqSvCflr/ | wellrats | https://www.tradingview.com/u/wellrats/ | 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/
// © wellrats
//@version=5
indicator("9 MME + 20,50,200 MMA", overlay=true)
//Input Menus
Input1 = input(9, "Primeira EMA")
Input2 = input(20, "Segunda MMA")
Input3 = input(50, "Terceira MMA")
Input4 = input(200, "Quarta MMA")
shortest = ta.ema(close, Input1)
short = ta.sma(close, Input2)
longer = ta.sma(close, Input3)
longest = ta.sma(close, Input4)
//cumulativePeriod = input(20, "VWAP Period")
// typicalPrice = (high + low + close) / 3
// typicalPriceVolume = typicalPrice * volume
// cumulativeTypicalPriceVolume = math.sum(typicalPriceVolume, cumulativePeriod)
// cumulativeVolume = math.sum(volume, cumulativePeriod)
// vwapValue = cumulativeTypicalPriceVolume / cumulativeVolume
// plot(vwapValue, "VWAP", color = color.new(color.aqua, transp=0))
plot(shortest,"Primeira EMA", color = color.new(color.blue, transp=0))
plot(short, "Segunda MMA", color = color.new(color.green, transp=0))
plot(longer, "Terceira MMA", color = color.new(color.orange, transp=0))
plot(longest,"Quarta MMA", color = color.new(color.black, transp=0))
|
Channel Take Profit Tool for Alertatron | https://www.tradingview.com/script/6KxjYM8I-Channel-Take-Profit-Tool-for-Alertatron/ | jordanfray | https://www.tradingview.com/u/jordanfray/ | 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/
// © jordanfray
//@version=5
indicator("Channel Take Profit", overlay=true)
import jordanfray/threengine_global_automation_library/95 as bot
// Colors - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
green = color.new(#2DBD85,0)
lightGreen = color.new(#2DBD85,90)
red = color.new(#E02A4A,0)
blue = color.new(#00A5FF,0)
lightBlue = color.new(#00A5FF,90)
white = color.new(#ffffff,0)
gray = color.new(#AAAAAA,0)
transparent = color.new(#ffffff,100)
// Tooltips
offsetTip = "How far away from the line do you want to trigger Alertatron to close the trade? \n\n Default: 1%"
amountToCloseTip = "What percentage of the open postiion do you want to close? \n\n Default: 50%"
alertatronSecretTip = "The key that is configured in Alertatron that selects which exchange integration you want to use."
exchangeTooltip = "Pick the exchange that your Alertatron API Secret is configured to. This is used to get the right divider between the pair and the base currency."
exchangeCurrencyOverrideTip = "If you want to use a different base currency than the current chart, you can override it here. Be sure it matches the exchange base currency. \n \n Do not include the currency/symbol divider in this."
exchangeCurrencySymbolTip = "If you want to use a different symbol than the current chart, you can override it here. Be sure it matches the exchange symbol. \n \n Do not include the currency/symbol divider in this."
// Inputs
mainLineX1 = input.time(defval=timestamp("01 Jan 2022 00:00"), title="x1", group="Channel Coordinates", confirm=true, inline="point1")
mainLineY1 = input.price(defval=0.0, title="y1", group="Channel Coordinates", confirm=true, inline="point1")
mainLineX2 = input.time(defval=timestamp("01 Jan 2022 00:00"), title="x2", confirm=true, group="Channel Coordinates", inline="point2")
mainLineY2 = input.price(defval=0.0, title="y2", group="Channel Coordinates", confirm=true, inline="point2")
lineOffset = input.float(defval=1.0, title="Offset (%)", group="Channel Coordinates", tooltip=offsetTip)
amoutToClose = input.int(defval=50, title="Amount to Close (%)", step=5, group="Exit Settings", tooltip=amountToCloseTip)
tradeAutomationExchange = input.string(defval="ByBit", options=["ByBit", "FTX.us"], title="Exchange", group="Alertatron Settings", tooltip=exchangeTooltip)
tradeAutomationSecret = input.string(defval="", title="Alertatron API Secret", group="Alertatron Settings", tooltip=alertatronSecretTip)
tradeAutomationCurrencyOverride = input.string(defval="", title="Currency Override", group="Alertatron Settings", tooltip=exchangeCurrencyOverrideTip)
tradeAutomationSymbolOverride = input.string(defval="", title="Symbol Override", group="Alertatron Settings", tooltip=exchangeCurrencySymbolTip)
showDebugTable = input.bool(defval=false, title="Show Debug Table", group="Testing")
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// S T R A T E G Y C A L C U L A T I O N S - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Calulate y-axis locations for top and bottom lines
var float topLineY1 = (mainLineY1 + (mainLineY1*(lineOffset/100)))
var float topLinwY2 = (mainLineY2 + (mainLineY2*(lineOffset/100)))
var float bottomLineY1 = (mainLineY1 - (mainLineY1*(lineOffset/100)))
var float bottomLineY2 = (mainLineY2 - (mainLineY2*(lineOffset/100)))
// Calculate the change between point 1 and 2
chartTimeframeInMinutes = timeframe.in_seconds(timeframe.period)/60
yDelta = mainLineY2 - mainLineY1 // price
xDelta = ((mainLineX2 - mainLineX1)/60000)/chartTimeframeInMinutes // bars
changePerBar = yDelta/xDelta // price change per bar (aka slope)
// Set initial values of
var float maingLineLoc = mainLineY1
var float bottomLineLoc = (mainLineY1 - (mainLineY1*(lineOffset/100)))
var float topLineLoc = (mainLineY1 + (mainLineY1*(lineOffset/100)))
// Subtract the slope from each line's y-axis location each bar beyond the point 1
if time > mainLineX1
maingLineLoc += changePerBar
bottomLineLoc += changePerBar
topLineLoc += changePerBar
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// P L O T S A N D L I N E S - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Plot all three lines but only show the main line
lowerThreshold = plot(bottomLineLoc, title="Lower Threshold", editable=false, display=display.status_line + display.price_scale)
mainLine = plot(maingLineLoc, title="Main Line", color=ta.change(maingLineLoc) ? blue : transparent, linewidth=2, editable=false, display=display.status_line + display.pane + display.price_scale)
upperThreshold = plot(topLineLoc, title="Upper Threshold", editable=false, display=display.status_line + display.price_scale)
// Plot the upper and lower line so they extend beyond the current bar
if barstate.islastconfirmedhistory
topLine = line.new(x1=mainLineX1, y1=topLineY1, x2=mainLineX2, y2=topLinwY2, color=blue, width=1, xloc=xloc.bar_time, style=line.style_solid, extend=extend.right)
bottomLine = line.new(x1=mainLineX1, y1=bottomLineY1, x2=mainLineX2, y2=bottomLineY2, color=blue, width=1, xloc=xloc.bar_time, style=line.style_solid, extend=extend.right)
channelBackground = linefill.new(topLine, bottomLine, lightBlue)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// C L O S E T H E T R A D E - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Exit Criteria
closeLong = ta.crossover(high, bottomLineLoc)
closeShort = ta.crossunder(low, topLineLoc)
// Check to see if currency or symbol should be overridden
string baseCurrency = na
string symbol = na
if tradeAutomationCurrencyOverride != ""
baseCurrency := tradeAutomationCurrencyOverride
else
baseCurrency := bot.getBaseCurrency()
if tradeAutomationSymbolOverride != ""
symbol := tradeAutomationSymbolOverride
else
symbol := bot.getChartSymbol()
// Get alert message
var string exitLongAlertMessage = bot.getAlertatronAlertMessageMarketClosePercentOfPosition(secret=tradeAutomationSecret, symbol=symbol, baseCurrency=baseCurrency, pairDivider=bot.getPairDividerForExchange(tradeAutomationExchange), percent=amoutToClose, side="sell")
var string exitShortAlertMessage = bot.getAlertatronAlertMessageMarketClosePercentOfPosition(secret=tradeAutomationSecret, symbol=symbol, baseCurrency=baseCurrency, pairDivider=bot.getPairDividerForExchange(tradeAutomationExchange), percent=amoutToClose, side="buy")
// Close the trade
var int alertTriggered = 0
if closeLong and time > mainLineX2
if alertTriggered == 0
alert(message=exitLongAlertMessage, freq=alert.freq_once_per_bar)
alertTriggered += 1
if closeShort and time > mainLineX2
if alertTriggered == 0
alert(message=exitShortAlertMessage, freq=alert.freq_once_per_bar)
alertTriggered += 1
// Display shapes when when exit criteria is met
plotshape(time > mainLineX2 and alertTriggered <=1 ? closeLong : na, title="Above Bottom Line", style=shape.triangleup, location=location.abovebar, color=green, display=display.pane)
plotshape(time > mainLineX2 and alertTriggered <=1 ? closeShort : na, title="Below Top Line", style=shape.triangledown, location=location.belowbar, color=red, display=display.pane)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// D E B U G M O D E - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if showDebugTable
var table debug = table.new(position=position.bottom_left, columns=2, rows=100, bgcolor=gray, border_color=gray, border_width=2)
rowCount = 0
table.cell(debug, 0, rowCount, text="exitLongAlertMessage: ", text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
table.cell(debug, 1, rowCount, text=str.tostring(exitLongAlertMessage), text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
rowCount += 1
table.cell(debug, 0, rowCount, text="exitShortAlertMessage: ", text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
table.cell(debug, 1, rowCount, text=str.tostring(exitShortAlertMessage), text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
rowCount += 1
table.cell(debug, 0, rowCount, text="alertTriggered: ", text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
table.cell(debug, 1, rowCount, text=str.tostring(alertTriggered), text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small) |
Opening Range Breakout with Price Targets | https://www.tradingview.com/script/iVglS0oT-Opening-Range-Breakout-with-Price-Targets/ | syntaxgeek | https://www.tradingview.com/u/syntaxgeek/ | 459 | 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/
// © amitgandhinz
// © syntaxgeek
// Thanks to amitgandhinz for the work on this amazing indicator!
// Todo:
// a) clean up all the functions, variables names and reorganize everything to ease maintenance
// b) explore retest flags at orb low and mid
// c) customizable fib, % price targets?
//@version=5
indicator(title="Opening Range Breakout", shorttitle="ORB", overlay=true)
// <inputs>
i_session = input.session("0930-0945", title="Opening Range Time", group="Session")
i_allowPre = input.bool(false, "Enable Premarket Support?", tooltip="Enables support for pre-market based opening range times.", group="Session")
i_timezone = input.string("America/New_York", title="Opening Range Timezone", group="Session")
i_marketType = input.string("24x5", "Market Type", options=["24x5", "24x7"], tooltip="For regular traded markets in nasdaq, s&p, etc use 24x5; for crypto and futures Sunday trading use 24x7")
i_showORBOnlyRTH = input.bool(true, "Show ORB During RTH Only?", group="Display Lines")
i_showORBLabels = input.string("default", "Show ORB labels?", options=["default", "short", "none"], group="Display Lines")
i_showPreviousDayORBs = input.bool(true, "Show ORB ranges on previous days", group="Display Lines")
i_showEntries = input.bool(true, "Show potential ORB Breakouts and Retests (BRB)", group="Display Lines")
i_showORBTargets = input.string("default", title="Price Target Type", options=["default", "fib", "none"], tooltip="Default Price Targets (50%, 100%, etc), Fib Targets (23.6%, 61.8%, 100%, etc) or none.", group="Display Lines")
i_orbTargetsLineWidth = input.int(1, title="Price target line width", minval=1, group="Display Lines")
i_boxBorderSize = input.int(2, title="Box border size", minval=0, group="ORB Box")
i_showShadedBox = input.bool(true, "Shade the ORB Range", group="ORB Box")
i_shadeColor = input.color(color.new(color.teal, 80), "Shaded ORB Range Color", group="ORB Box")
i_alertBreakoutsOnly = input.bool(false, "Alert only on ORB breakouts (not price ticks)", "Alerts")
// </inputs>
// <funcs>
f_tradingDays(_marketType) =>
switch _marketType
"24x5" => ":23456"
"24x7" => ":1234567"
f_drawForSession() => not i_showORBOnlyRTH or (i_showORBOnlyRTH and session.ismarket)
f_timeInRange(_session, _marketType) => not na(time(timeframe.period, _session + f_tradingDays(_marketType), i_timezone)) ? 1 : 0
f_highest(_a, _b) => _a > _b ? _a : _b
f_lowest(_a, _b) => _a > _b ? _b : _a
f_range(_a, _b) =>
v_high = f_highest(_a, _b)
v_low = f_lowest(_a, _b)
v_high - v_low
f_rangeMid(_price1, _price2) =>
v_priceHigh = f_highest(_price1, _price2)
v_priceHigh - (f_range(_price1, _price2) / 2)
// </funcs>
showPriceTargets = false
showFibTargets = false
showLabels = false
showShortLabels = false
if (i_showORBLabels == "default")
showLabels := true
else if (i_showORBLabels == "short")
showLabels := true
showShortLabels := true
if (i_showORBTargets == "default")
showPriceTargets := true
else if (i_showORBTargets == "fib")
showFibTargets := true
in_session = f_timeInRange(i_session, i_marketType)
// Create variables
var orbTitle = "ORB"
var orbHighPrice = 0.0
var orbLowPrice = 0.0
var box dailyBox = na
var inBreakout = false
bool isToday = false
if year(timenow, i_timezone) == year(time, i_timezone) and month(timenow, i_timezone) == month(time, i_timezone) and dayofmonth(timenow, i_timezone) == dayofmonth(time, i_timezone) and (session.ismarket or (i_allowPre and session.ispremarket))
isToday := true
is_first = in_session and not in_session[1] and (session.ismarket or (i_allowPre and session.ispremarket))
if is_first
orbHighPrice := high
orbLowPrice := low
inBreakout := false
else
orbHighPrice := orbHighPrice[1]
orbLowPrice := orbLowPrice[1]
if high > orbHighPrice and in_session
orbHighPrice := high
if low < orbLowPrice and in_session
orbLowPrice := low
bool drawOrbs = i_showPreviousDayORBs or (not i_showPreviousDayORBs and isToday)
drawMidOrb = false
// When a new day start, create a new box for that day.
// Else, during the day, update that day's box.
if (drawOrbs)
if (i_showShadedBox)
if is_first
dailyBox := box.new(left=bar_index, top=orbHighPrice,
right=bar_index + 1, bottom=orbLowPrice,
border_width=i_boxBorderSize)
// If we don't want the boxes to join, the previous box shouldn't
// end on the same bar as the new box starts.
if (not i_showORBOnlyRTH)
box.set_right(dailyBox[1], bar_index[1])
else if (f_drawForSession())
box.set_top(dailyBox, orbHighPrice)
box.set_rightbottom(dailyBox, right=bar_index + 1, bottom=orbLowPrice)
drawMidOrb := true
box.set_bgcolor(dailyBox, i_shadeColor)
box.set_border_color(dailyBox, color.teal)
orbRange = f_range(orbHighPrice, orbLowPrice)
orbMidPrice = f_rangeMid(orbHighPrice, orbLowPrice)
orbHighMidPrice = f_rangeMid(orbHighPrice, orbMidPrice)
orbLowMidPrice = f_rangeMid(orbMidPrice, orbLowPrice)
box.set_text(dailyBox, "Range: " + str.tostring(orbRange))
box.set_text_valign(dailyBox, text.align_bottom)
box.set_text_halign(dailyBox, text.align_right)
box.set_text_size(dailyBox, size.normal)
plot(f_drawForSession() and not in_session and drawOrbs ? orbHighPrice : na, style=plot.style_linebr, color=orbHighPrice[1] != orbHighPrice ? na : color.green, title="ORB High", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and drawOrbs ? orbLowPrice : na , style=plot.style_linebr, color=orbLowPrice[1] != orbLowPrice ? na : color.red, title="ORB Low", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and drawOrbs ? orbHighMidPrice : na, style=plot.style_cross, color=color.gray, title="ORB Mid High", linewidth = 1)
plot(f_drawForSession() and not in_session and drawOrbs ? orbMidPrice : na, style=plot.style_linebr, color=color.white, title="ORB Mid", linewidth = 1)
plot(f_drawForSession() and not in_session and drawOrbs ? orbLowMidPrice : na, style=plot.style_cross, color=color.gray, title="ORB Mid Low", linewidth = 1)
// plot PT for ORB - 50% retracement
plot(f_drawForSession() and not in_session and showPriceTargets and drawOrbs ? orbHighPrice + (orbRange * 1.5): na , style=plot.style_linebr, color=orbHighPrice[1] != orbHighPrice ? na : color.lime, title="ORB High PT 3", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showPriceTargets and drawOrbs ? orbHighPrice + (orbRange * 1.0): na , style=plot.style_linebr, color=orbHighPrice[1] != orbHighPrice ? na : color.blue, title="ORB High PT 2", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showPriceTargets and drawOrbs ? orbHighPrice + (orbRange * 0.5) : na, style=plot.style_linebr, color=orbHighPrice[1] != orbHighPrice ? na : color.purple, title="ORB High PT 1", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showPriceTargets and drawOrbs ? orbLowPrice + (orbRange * -0.5): na , style=plot.style_linebr, color=orbLowPrice[1] != orbLowPrice ? na : color.purple, title="ORB Low PT 1", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showPriceTargets and drawOrbs ? orbLowPrice + (orbRange * -1.0): na , style=plot.style_linebr, color=orbLowPrice[1] != orbLowPrice ? na : color.blue, title="ORB Low PT 2", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showPriceTargets and drawOrbs ? orbLowPrice + (orbRange * -1.5): na , style=plot.style_linebr, color=orbLowPrice[1] != orbLowPrice ? na : color.lime, title="ORB Low PT 3", linewidth=i_orbTargetsLineWidth)
// fib levels
plot(f_drawForSession() and not in_session and showFibTargets ? orbHighPrice + (orbRange * 0.236): na , style=plot.style_linebr, color=orbHighPrice[1] != orbHighPrice ? na : color.aqua, title="FIB 23.6%", linewidth=i_orbTargetsLineWidth)
// plot(f_drawForSession() and not in_session and showFibTargets ? orbHighPrice + (orbRange * 0.382): na , style=plot.style_linebr, color=orbHighPrice[1] != orbHighPrice ? na : color.blue, title="FIB 38.2%", linewidth=i_orbTargetsLineWidth)
// plot(f_drawForSession() and not in_session and showFibTargets ? orbHighPrice + (orbRange * 0.50): na , style=plot.style_linebr, color=orbHighPrice[1] != orbHighPrice ? na : color.lime, title="FIB 50%", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showFibTargets ? orbHighPrice + (orbRange * 0.618): na , style=plot.style_linebr, color=orbHighPrice[1] != orbHighPrice ? na : color.yellow, title="FIB 61.8%", linewidth=i_orbTargetsLineWidth)
// plot(f_drawForSession() and not in_session and showFibTargets ? orbHighPrice + (orbRange * 0.786): na , style=plot.style_linebr, color=orbHighPrice[1] != orbHighPrice ? na : color.orange, title="FIB 78.6%", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showFibTargets ? orbHighPrice + (orbRange * 1): na , style=plot.style_linebr, color=orbHighPrice[1] != orbHighPrice ? na : color.red, title="FIB 100%", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showFibTargets ? orbHighPrice + (orbRange * 1.382): na , style=plot.style_linebr, color=orbHighPrice[1] != orbHighPrice ? na : color.fuchsia, title="FIB 138.2%", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showFibTargets ? orbHighPrice + (orbRange * 1.618): na , style=plot.style_linebr, color=orbHighPrice[1] != orbHighPrice ? na : color.purple, title="FIB 161.8%", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showFibTargets ? orbLowPrice + (orbRange * -0.236): na , style=plot.style_linebr, color=orbLowPrice[1] != orbLowPrice ? na : color.aqua, title="FIB -23.6%", linewidth=i_orbTargetsLineWidth)
// plot(f_drawForSession() and not in_session and showFibTargets ? orbLowPrice + (orbRange * -0.382): na , style=plot.style_linebr, color=orbLowPrice[1] != orbLowPrice ? na : color.blue, title="FIB -38.2%", linewidth=i_orbTargetsLineWidth)
// plot(f_drawForSession() and not in_session and showFibTargets ? orbLowPrice + (orbRange * -0.50): na , style=plot.style_linebr, color=orbLowPrice[1] != orbLowPrice ? na : color.lime, title="FIB -50%", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showFibTargets ? orbLowPrice + (orbRange * -0.618): na , style=plot.style_linebr, color=orbLowPrice[1] != orbLowPrice ? na : color.yellow, title="FIB -61.8%", linewidth=i_orbTargetsLineWidth)
// plot(f_drawForSession() and not in_session and showFibTargets ? orbLowPrice + (orbRange * -0.786): na , style=plot.style_linebr, color=orbLowPrice[1] != orbLowPrice ? na : color.orange, title="FIB -78.6%", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showFibTargets ? orbLowPrice + (orbRange * -1): na , style=plot.style_linebr, color=orbLowPrice[1] != orbLowPrice ? na : color.red, title="FIB -100%", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showFibTargets ? orbLowPrice + (orbRange * -1.382): na , style=plot.style_linebr, color=orbLowPrice[1] != orbLowPrice ? na : color.fuchsia, title="FIB -138.2%", linewidth=i_orbTargetsLineWidth)
plot(f_drawForSession() and not in_session and showFibTargets ? orbLowPrice + (orbRange * -1.618): na , style=plot.style_linebr, color=orbLowPrice[1] != orbLowPrice ? na : color.purple, title="FIB -161.8%", linewidth=i_orbTargetsLineWidth)
drawPriceTargetLabel(fromPrice, level, name, col) =>
if showLabels
finalTitle = not showShortLabels ? orbTitle + " " + name : name
var pt = label.new(bar_index, fromPrice + (orbRange * level), style=label.style_label_lower_left, text=finalTitle, color=col, textcolor=color.white)
if (f_drawForSession())
label.set_xy(pt, bar_index + 2, fromPrice + (orbRange * level))
drawPriceTargetLabel(orbHighPrice, 0, "HIGH", color.green)
drawPriceTargetLabel(orbLowPrice, 0, "LOW", color.red)
drawPriceTargetLabel(orbMidPrice, 0, "MID", color.orange)
if (not in_session and showPriceTargets and isToday and session.ismarket and drawOrbs )
drawPriceTargetLabel(orbHighPrice, 1.5, "PT 150%", color.lime)
drawPriceTargetLabel(orbHighPrice, 1.0, "PT 100%", color.blue)
drawPriceTargetLabel(orbHighPrice, 0.5, "PT 50%", color.purple)
drawPriceTargetLabel(orbLowPrice, -0.5, "PT 50%", color.purple)
drawPriceTargetLabel(orbLowPrice, -1.0, "PT 100%", color.blue)
drawPriceTargetLabel(orbLowPrice, -1.5, "PT 150%", color.lime)
if (not in_session and showFibTargets and isToday and session.ismarket and drawOrbs )
drawPriceTargetLabel(orbHighPrice, 0.236, "FIB 23.6%", color.aqua)
// drawPriceTargetLabel(orbHighPrice, 0.382, "FIB 38.2%", color.blue)
// drawPriceTargetLabel(orbHighPrice, 0.50, "FIB 50%", color.lime)
drawPriceTargetLabel(orbHighPrice, 0.618, "FIB 61.8%", color.yellow)
// drawPriceTargetLabel(orbHighPrice, 0.786, "FIB 78.6%", color.orange)
drawPriceTargetLabel(orbHighPrice, 1, "FIB 100%", color.red)
drawPriceTargetLabel(orbHighPrice, 1.382, "FIB 138.2%", color.fuchsia)
drawPriceTargetLabel(orbHighPrice, 1.618, "FIB 161.8%", color.purple)
drawPriceTargetLabel(orbLowPrice, -0.236, "FIB -23.6%", color.aqua)
// drawPriceTargetLabel(orbLowPrice, -0.382, "FIB -38.2%", color.blue)
// drawPriceTargetLabel(orbLowPrice, -0.50, "FIB -50%", color.lime)
drawPriceTargetLabel(orbLowPrice, -0.618, "FIB -61.8%", color.yellow)
// drawPriceTargetLabel(orbLowPrice, -0.786, "FIB -78.6%", color.orange)
drawPriceTargetLabel(orbLowPrice, -1, "FIB -100%", color.red)
drawPriceTargetLabel(orbLowPrice, -1.382, "FIB -138.2%", color.fuchsia)
drawPriceTargetLabel(orbLowPrice, -1.618, "FIB -161.8%", color.purple)
// candle crossed orb level, next candle stayed above it, current candle also stayed above it, and had volume in there
//volumeSMA = ta.sma(volume, 20)
//bool volumeSpiked = volume[2] > volumeSMA[2] or volume[1] > volumeSMA[1] or volume > volumeSMA
bool highCrossBO = (low[2] < orbHighPrice and close[2] > orbHighPrice and low[1] > orbHighPrice and close[1] > orbHighPrice and close > low[1] and low > orbHighPrice) and session.ismarket
bool lowCrossBO = (high[2] > orbLowPrice and close[2] < orbLowPrice and high[1] < orbLowPrice and close[1] < orbLowPrice and close < high[1] and high < orbLowPrice) and session.ismarket
bool highCross = (not i_alertBreakoutsOnly and ta.cross(close, orbHighPrice)) or (i_alertBreakoutsOnly and highCrossBO)
bool lowCross = (not i_alertBreakoutsOnly and ta.cross(close, orbLowPrice)) or (i_alertBreakoutsOnly and lowCrossBO)
bool isRetestOrbHigh = close[1] > orbHighPrice and low <= orbHighPrice and close >= orbHighPrice
bool isRetestOrbLow = close[1] < orbLowPrice and high >= orbLowPrice and close <= orbLowPrice
bool failedRetest = inBreakout and ((close[1] > orbHighPrice and close < orbHighPrice) or (close[1] < orbLowPrice and close > orbLowPrice))
// show entries
if (i_showEntries and session.ismarket)
if (highCrossBO)
lbl = label.new(bar_index, na)
label.set_color(lbl, color.green)
label.set_textcolor(lbl, color.green)
label.set_text(lbl, "Breakout\n Wait for Retest")
label.set_yloc( lbl,yloc.abovebar)
label.set_style(lbl, label.style_triangledown)
label.set_size(lbl, size.tiny)
inBreakout := true
if (lowCrossBO)
lbl = label.new(bar_index, na)
label.set_color(lbl, color.green)
label.set_textcolor(lbl, color.green)
label.set_text(lbl, "Breakout,\n Wait for Retest")
label.set_yloc( lbl,yloc.belowbar)
label.set_style(lbl, label.style_triangleup)
label.set_size(lbl, size.tiny)
inBreakout := true
if inBreakout and (isRetestOrbHigh or isRetestOrbLow)
// we have our breakout and retest
lbl = label.new(bar_index, na)
label.set_color(lbl, color.green)
label.set_textcolor(lbl, color.white)
label.set_text(lbl, "Retest")
label.set_yloc( lbl,yloc.abovebar)
label.set_style(lbl, label.style_label_down)
label.set_size(lbl, size.tiny)
inBreakout := false
if inBreakout and failedRetest
// we have failed the retest
lbl = label.new(bar_index, na)
label.set_color(lbl, color.red)
label.set_textcolor(lbl, color.white)
label.set_text(lbl, "Failed Retest")
label.set_yloc( lbl,yloc.abovebar)
label.set_style(lbl, label.style_label_down)
label.set_size(lbl, size.tiny)
inBreakout := false
// show alerts
alertcondition(not in_session and (session.ismarket or (i_allowPre and session.ispremarket)) and (highCross or lowCross), title="ORB Level Cross", message="Price crossing ORB Level")
alertcondition(not in_session and (session.ismarket or (i_allowPre and session.ispremarket)) and i_alertBreakoutsOnly and (highCrossBO or lowCrossBO), title="ORB Breakout", message="Price Breaking out of ORB Level, Look for Retest")
if (not in_session and isToday and (session.ismarket or (i_allowPre and session.ispremarket)))
if (not i_alertBreakoutsOnly)
if highCross
alert("Price crossing ORB High Level", alert.freq_once_per_bar)
if lowCross
alert("Price crossing ORB Low Level", alert.freq_once_per_bar)
if (i_alertBreakoutsOnly)
if highCrossBO
alert("Price breaking out of ORB High Level, Look for Retest", alert.freq_once_per_bar)
if lowCrossBO
alert("Price breaking out of ORB Low Level, Look for Retest", alert.freq_once_per_bar) |
ABC 123 Harmonic Ratio Custom Range Interactive | https://www.tradingview.com/script/hVk0dICJ-ABC-123-Harmonic-Ratio-Custom-Range-Interactive/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 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/
// © RozaniGhani-RG
// Credits to Scott M Carney, author of Harmonic Trading : Volume One
// Harmonic Trading Ratios - Page 18
//@version=5
indicator('ABC 123 Harmonic Ratio Custom Range Interactive', shorttitle = 'AHR_CRI', overlay = true, precision = 3)
// —— Import {
import RozaniGhani-RG/PriceTimeInteractive/2 as pti
import RozaniGhani-RG/DeleteArrayObject/1 as obj
import RozaniGhani-RG/HarmonicCalculation/1 as calc
import RozaniGhani-RG/HarmonicSwitches/1 as sw
// }
// —— Content {
// 0. Input
// 1. Initialization
// 2. TRADE IDENTIFICATION - Harmonic Trading System Part 1
// 3. Draw XABCD Pattern (Trade Identification)
// 4. Table
// 5. Construct
// }
// —— 0. Input {
// ———— 1) TIME POINTS {
int point_A = timestamp('2022-07')
int point_B = timestamp('2022-08')
int point_C = timestamp('2022-09')
int time_A = input.time(point_A, 'Point A', group = '1) TIME POINTS', inline = 'A', confirm = true, tooltip = 'Point A must BEFORE Point A')
int time_B = input.time(point_B, 'Point B', group = '1) TIME POINTS', inline = 'B', confirm = true, tooltip = 'Point B must BEFORE Point C')
int time_C = input.time(point_C, 'Point C', group = '1) TIME POINTS', inline = 'C', confirm = true, tooltip = 'Point C must AFTER Point B')
// }
// ———— 2) TABLE DISPLAY {
T8 = '1) Tick to show table\n2) Small font size recommended for mobile app or multiple layout'
T9 = 'Table must be tick before change table position'
i_b_table = input.bool(true, 'Show Table |', group = '2) TABLE DISPLAY', inline = 'Table1')
i_s_font = input.string('normal', 'Font size', group = '2) TABLE DISPLAY', inline = 'Table1', options = ['tiny', 'small', 'normal', 'large', 'huge'], tooltip = T8)
i_s_Y = input.string('bottom', 'Table Position', group = '2) TABLE DISPLAY', inline = 'Table2', options = ['top', 'middle', 'bottom'])
i_s_X = input.string('left', '', group = '2) TABLE DISPLAY', inline = 'Table2', options = ['left', 'center', 'right'], tooltip = T9)
// }
// ———— 3) OTHERS {
i_f_pro = input.float( 2.240, 'Last Projection', group = '3) OTHERS', options = [2.24, 2.618, 3.140, 3.618], tooltip = 'Only applicable')
i_s_label = input.string('ABC', 'Label', group = '3) OTHERS', options = ['ABC', '123'], tooltip = 'Use number or alphabet for label')
i_s_helper = input.string('All', 'Show Helper', group = '3) OTHERS', options = ['All', 'Direction label', 'Range', 'None'])
i_b_col = input.bool( true, 'Use trend color', group = '3) OTHERS', tooltip = 'Show Trend color if true\nTrue : Lime (Bullish), Red (Bearish)\n False : Blue')
i_b_currency = input.bool( true, 'Show Currency', group = '3) OTHERS')
// }
// }
// —— 1. Initialization {
P = 'PRIMARY', PD = 'PRIMARY DERIVED', SD = 'SECONDARY DERIVED', SE = 'SECONDARY DERIVED EXTREME'
SW = switch i_f_pro
2.240 => SD
2.618 => SE
3.140 => SE
3.618 => SE
// }
// —— 2. TRADE IDENTIFICATION - Harmonic Trading System Part 1 {
// ———— 2.1 Get Price from Point A to Point C {
[high_A, low_A, close_A] = pti.hlc_time(time_A)
[high_B, low_B, close_B] = pti.hlc_time(time_B)
[high_C, low_C, _ ] = pti.hlc_time(time_C)
// }
// ———— 2.2 Determine Point A is lower or higher than Point B {
bool A_lower_B = close_A < close_B
[pr_A, pr_B, pr_C] = switch A_lower_B
// Output : pr_A, pr_B, pr_C
true => [ low_A, high_B, low_C]
=> [high_A, low_B, high_C]
[ style0, style1, col_dir] = sw.TupleSwitchStyleColor(A_lower_B)
[str_dir, str_A, str_B] = sw.TupleSwitchString( A_lower_B)
// }
// ———— 2.3 Get ratio and difference for price and time {
y_AB = calc.PriceDiff( pr_B, pr_A), time_AB = calc.TimeDiff( time_B, time_A)
y_BC = calc.PriceDiff( pr_C, pr_B), time_BC = calc.TimeDiff( time_C, time_B), y_ABC = y_BC / y_AB, time_ABC = calc.TimeDiff(time_C, time_A)
// }
// ———— 2.4 Variables for Point C {
bool bool_ret = math.abs(y_ABC) >= 0.382 and math.abs(y_ABC) <= 0.930
bool bool_pro = math.abs(y_ABC) >= 1.073 and math.abs(y_ABC) <= i_f_pro
var bool_ratio = array.new_bool(2)
bool_ratio.set(0, bool_ret)
bool_ratio.set(1, bool_pro)
// }
// ———— 2.5 Verify ratio {
// 0 1 2 3 4 5 6
float_ret = array.from(0.382, 0.500, 0.618, 0.707, 0.786, 0.886, 0.930)
float_pro = array.from(1.073, 1.130, 1.270, 1.410, 1.618, 2.000, i_f_pro)
str_ret = array.from( SD, SD, P, SD, PD, PD)
str_pro = array.from( PD, PD, SD, P, SD, SW)
ret_min = float_ret.copy(), ret_min.remove(0)
ret_max = float_ret.copy(), ret_max.remove(6)
pro_min = float_pro.copy(), pro_min.pop()
pro_max = float_pro.copy(), pro_max.shift()
int int_index = na
if bool_ratio.includes(true)
int_index := bool_ratio.indexof(bool_ratio.includes(true))
str_BB = switch int_index
0 => 'RETRACEMENT'
1 => 'PROJECTION'
float_ratio = switch bool_ratio.indexof(bool_ratio.includes(true))
0 => float_ret
1 => float_pro
float_min = switch bool_ratio.indexof(bool_ratio.includes(true))
0 => ret_min
1 => pro_min
float_max = switch bool_ratio.indexof(bool_ratio.includes(true))
0 => ret_max
1 => pro_max
str_ratio = switch bool_ratio.indexof(bool_ratio.includes(true))
0 => str_ret
1 => str_pro
f_bool(int _index) => math.abs(y_ABC) >= float_ratio.get(_index) and math.abs(y_ABC) < float_ratio.get(_index + 1)
f_rng(int _index) => str.tostring(float_ratio.get(_index), '0.000') + '; ' + str.tostring(float_ratio.get(_index + 1), '0.000')
var bool_rng = array.new_bool(6)
var str_rng = array.new_string(6)
for i = 0 to 5
bool_rng.set(i, f_bool(i))
str_rng.set(i, f_rng(i))
// }
float ratio_min = na
float ratio_max = na
float price_min = na
float price_max = na
if bool_ratio.includes(true)
ratio_min := float_ratio.get(bool_rng.indexof(bool_rng.includes(true)))
ratio_max := float_ratio.get(bool_rng.indexof(bool_rng.includes(true)) + 1)
price_min := calc.AbsoluteRange(pr_B, y_AB, ratio_min)
price_max := calc.AbsoluteRange(pr_B, y_AB, ratio_max)
harmonic = switch str_BB
'RETRACEMENT' => math.min(ratio_min, ratio_max)
'PROJECTION' => math.max(ratio_min, ratio_max)
// ———— 2.6 Overall pattern average for price and time {
y_AC = calc.PriceAverage(pr_C, pr_A), x_AC = calc.TimeAverage(time_A, time_C)
// }
// }
// —— 3. Draw ABC Pattern (Trade Identification) {
// ———— 3.1 Initialize arrays {
str_123 = array.from( '1', '2', '3')
str_ABC = array.from( 'A', 'B', 'C')
arr_pr = array.from( pr_A, pr_B, pr_C)
arr_time = array.from(time_A, time_B, time_C)
y_ratio = array.from( y_AC)
x_ratio = array.from( x_AC)
str_arr = switch i_s_label
'ABC' => str_ABC
'123' => str_123
arr_ratio = array.from(str.tostring(math.abs(y_ABC), '0.000'))
var label_ABC = array.new_label(3), obj.delete(label_ABC)
var ratio_ABC = array.new_label(1), obj.delete(ratio_ABC)
var solid_ABC = array.new_line(2), obj.delete(solid_ABC)
var dot_ABC = array.new_line(1), obj.delete( dot_ABC)
var fill_ABC = array.new_linefill(1), obj.delete( fill_ABC)
var label_rng = array.new_label(1), obj.delete(label_rng)
var hlabel_AC = array.new_label(2), obj.delete(hlabel_AC)
var hline_AC = array.new_line(2), obj.delete( hline_AC)
string txt = na
string str_C = na
if bool_ratio.includes(true)
txt := str_dir + ' ' + str_BB + '\n' +
str_ratio.get(bool_rng.indexof(bool_rng.includes(true))) + ' (' + str.tostring(harmonic, '0.000') + ')'
str_C := str_rng.get(bool_rng.indexof(bool_rng.includes(true)))
else
txt := str_dir + ' ' + str_BB + '\n' + arr_ratio.get(0)
// }
// ———— 3.2 ABC custom functions {
f_label_ABC(int _x, color _col = color.blue) =>
label.new(
x = arr_time.get(_x),
y = arr_pr.get(_x),
text = str_arr.get(_x),
xloc = xloc.bar_time,
color = color.new(color.blue, 100),
style = _x % 2 ? style1 : style0,
textcolor = i_b_col ? col_dir : _col)
f_ratio_ABC(int _x, color _col = color.blue) =>
label.new(
x = x_ratio.get(_x),
y = y_ratio.get(_x),
text = arr_ratio.get(_x),
xloc = xloc.bar_time,
style = label.style_label_center,
textcolor = i_b_col ? color.black : color.white,
color = i_b_col ? col_dir : _col)
f_hlabel(float _ratio, float _y, int _int, color _col = color.blue) =>
label.new(
x = time_A,
y = _y,
text = str.tostring(_ratio, '0.000') + ' (' + str.tostring(_y, '#.000') + ')',
xloc = xloc.bar_time,
style = _int % 2 ? label.style_label_upper_right : label.style_label_lower_right,
color = color.new(_col, 100),
textcolor = i_b_col ? col_dir : _col)
f_line(int _x1, int _y1, int _x2, int _y2, bool _bool = true, int _width = 1, int _transp = 0) =>
_style = switch _bool
true => line.style_solid
false => line.style_dotted
line.new(
x1 = arr_time.get(_x1),
y1 = arr_pr.get(_y1),
x2 = arr_time.get(_x2),
y2 = arr_pr.get(_y2),
xloc = xloc.bar_time,
color = i_b_col ? color.new(col_dir, _transp) : color.new(color.blue, _transp),
style = _style,
width = _width)
f_hline(float _y, int _width = 1, int _transp = 0) =>
line.new(
x1 = time_A,
y1 = _y,
x2 = time_C,
y2 = _y,
xloc = xloc.bar_time,
color = i_b_col ? color.new(col_dir, _transp) : color.new(color.blue, _transp),
style = line.style_solid,
width = _width)
f_fill_ABC(int _x1 = 0, int _x2 = 0, color _col = color.blue) =>
linefill.new(solid_ABC.get(_x1), dot_ABC.get(_x2), i_b_col ? color.new(col_dir, 80) : color.new(_col, 80))
f_label_rng(string _txt, color _col = color.blue) =>
label.new(
x = time_A,
y = pr_B,
text = _txt,
xloc = xloc.bar_time,
style = label.style_label_right,
color = color.new(_col, 100),
textcolor = i_b_col ? col_dir : _col)
// }
// }
// —— 4. Table {
// ———— 4.1 Table variable {
var table_ABC = table.new(position = i_s_Y + '_' + i_s_X, columns =7, rows = 6, border_color = color.new(color.blue, 100), border_width = 1)
row_0 = array.from('POINT', 'RATIO', 'SPEC', 'PRICE')
column_1 = array.from( str_A, str_B, str_C)
column_3 = array.from( pr_A, pr_B, pr_C)
// 0, 1, 2, 3
// }
// ———— 4.2 Table custom functions {
f_cell(int _column, int _row, string _text, color _col1 = color.black, color _col2 = color.white, bool halign = true) =>
table_ABC.cell(_column, _row, _text, text_color = _col1, text_size = i_s_font,
text_halign = halign ? text.align_right : text.align_center, bgcolor = _col2)
// }
// }
// —— 5. Construct {
if barstate.islast
for x = 0 to 2
label_ABC.set(x, f_label_ABC(x))
for x = 0 to 1
solid_ABC.set(x, f_line(x, x, x + 1, x + 1, true, 4))
ratio_ABC.set(0, f_ratio_ABC(0))
dot_ABC.set( 0, f_line(0, 0, 0 + 2, 0 + 2, false))
fill_ABC.set( 0, f_fill_ABC())
if array.includes(bool_ratio, true)
if i_s_helper == 'All' or i_s_helper == 'Direction label'
label_rng.set(0, f_label_rng(txt))
if i_s_helper == 'All' or i_s_helper == 'Range'
hline_AC.set( 0, f_hline(price_min))
hline_AC.set( 1, f_hline(price_max))
hlabel_AC.set(0, f_hlabel(ratio_min, price_min, 0))
hlabel_AC.set(1, f_hlabel(ratio_max, price_max, 1))
if i_b_table
if bool_ratio.includes(true)
f_cell(0, 0, txt, color.black, col_dir)
table_ABC.merge_cells(0, 0, 3, 0)
for i = 0 to 3
f_cell(i, 1, array.get(row_0, i), color.white, color.blue, false)
for i = 0 to 2
f_cell(0, i + 2, str_arr.get(i), (i + 1) % 3 ? col_dir : color.black, (i + 1) % 3 ? color.black : col_dir, false)
f_cell(1, i + 2, column_1.get(i), (i + 1) % 3 ? col_dir : color.black, (i + 1) % 3 ? color.black : col_dir, false)
f_cell(3, i + 2, calc.PriceCurrency(i_b_currency, column_3.get(i)), (i + 1) % 3 ? col_dir : color.black, (i + 1) % 3 ? color.black : col_dir, false)
f_cell(2, 2, '', color.white, color.black)
table_ABC.merge_cells(2, 2, 2, 3)
f_cell(2, 4, arr_ratio.get(0), color.black, col_dir, false)
plot(i_s_label == 'ABC' ? pr_A : na, 'A', color.new(col_dir, 100))
plot(i_s_label == 'ABC' ? pr_B : na, 'B', color.new(col_dir, 100))
plot(i_s_label == 'ABC' ? pr_C : na, 'C', color.new(col_dir, 100))
plot(i_s_label == '1' ? pr_A : na, '1', color.new(col_dir, 100))
plot(i_s_label == '2' ? pr_B : na, '2', color.new(col_dir, 100))
plot(i_s_label == '3' ? pr_C : na, '3', color.new(col_dir, 100))
plot( price_min, 'Min', color.new(color.blue, 100))
plot( price_max, 'Max', color.new(color.blue, 100))
// }
|
ATR Trailing Stop Loss [V5] | https://www.tradingview.com/script/YqSnK3KQ-ATR-Trailing-Stop-Loss-V5/ | BentonBuilding | https://www.tradingview.com/u/BentonBuilding/ | 136 | 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/
// © BentonBuilding
//@version=5
indicator("ATR Trailing Stop Loss", 'ATR TS', overlay = true, timeframe = '')
atr_p_inp = input.int(5, 'ATR length', 1, 1000000, 1)
atr_m_inp = input.float(3.5, 'ATR mult.', 0.01, 1000000, 0.05)
gold_ent = input.bool (true, 'Gold Entry Directional Confluence', tooltip = 'Requirs Gold Sell Signals To Be On A Red Bar And Gold Buy Signal To Be On A Green Bar')
atr = ta.atr(atr_p_inp)
ts = atr_m_inp * atr
float atr_ts = na
if (close > nz(atr_ts[1], 0)) and (close[1] > nz(atr_ts[1], 0))
atr_ts := (math.max(nz(atr_ts[1]), close - ts))
else
if (close < nz(atr_ts[1], 0)) and (close[1] < nz(atr_ts[1], 0))
atr_ts := (math.min(nz(atr_ts[1]), close + ts))
else
if (close > nz(atr_ts[1], 0))
atr_ts := (close - ts)
else
atr_ts := (close + ts)
float pos = na
if (close[1] < nz(atr_ts[1], 0)) and (close > nz(atr_ts[1], 0))
pos := (1)
else
if (close[1] > nz(atr_ts[1], 0)) and (close < nz(atr_ts[1], 0))
pos := (-1)
else
pos := (nz(pos[1], 0))
color _color = na
if (pos == -1)
_color := (color.red)
else
if (pos == 1)
_color := (color.green)
else
_color := (color.blue)
plot (atr_ts, color=_color, title="ATR Trailing Stop")
plotshape (pos, 'UP/DOWN', location = location.bottom, color = _color)
long_trig = (close < atr_ts)[1] and (close > atr_ts)
shrt_trig = (close > atr_ts)[1] and (close < atr_ts)
long_gold = (close > atr_ts) and (low < atr_ts) and not ((close > atr_ts) and (low < atr_ts))[1] and (gold_ent == true ? (close > open) : true)
shrt_gold = (close < atr_ts) and (high > atr_ts) and not ((close < atr_ts) and (high > atr_ts))[1] and (gold_ent == true ? (close < open) : true)
plotshape (long_trig, 'Long', shape.triangleup, location.belowbar, color.green, size = size.small)
plotshape (shrt_trig, 'Short', shape.triangledown, location.abovebar, color.red, size = size.small)
plotshape (long_gold, 'Gold Long', shape.triangleup, location.belowbar, color.yellow, size = size.small)
plotshape (shrt_gold, 'Gold Short', shape.triangledown, location.abovebar, color.yellow, size = size.small)
alertcondition (long_trig, 'Long', 'Green Triangles Below Price')
alertcondition (shrt_trig, 'Short', 'Red Triangles Above Price')
alertcondition ( (pos == 1), 'Long Condition', 'Moving In The Bullish Direction')
alertcondition ( (pos == -1), 'Short Condition', 'Moving In The Bearish Direction')
alertcondition (long_gold, 'Gold Long', 'Gold Triangles Below Price')
alertcondition (shrt_gold, 'Gold Short', 'Gold Triangles Above Price')
|
HMA-Kahlman Trend & Trendlines (v.2) | https://www.tradingview.com/script/MiloJegS-HMA-Kahlman-Trend-Trendlines-v-2/ | capissimo | https://www.tradingview.com/u/capissimo/ | 377 | 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/
// © capissimo
//@version=5
indicator('HMA-Kahlman Trend & Trendlines (v.2-2)', '', true, precision=2)
// This is an upgrade to HMA-Kahlman Trend & Trendlines script (https://www.tradingview.com/script/Pi7EVefr-hma-kahlman-trend-trendlines/).
// This gives more flexibility because you can play around with 2 parameters to Kalman function (Sharpness and K (aka. step size)).
//== HMA-Kahlman Trend Module
//-- Inputs
base = input.source(close, 'Dataset')
lag = input.int (40, 'Lookback', 2)
nrep = input.bool (false, 'Non-Repainting', inline='b')
labels = input.bool (true, 'Labels', inline='b')
k = input.bool (true, 'Kalman', inline='b')
//-- Constants
var buy = '🡅' , var sell = '🡇'
//-- Variables
var int state = 0
//-- Functions
cGreen(g) => g>9 ? #006400 : g>8 ? #1A741A : g>7 ? #338333 : g>6 ? #4D934D : g>5 ? #66A266 : g>4 ? #80B280 : g>3 ? #99C199 : g>2 ? #B3D1B3 : g>1? #CCE0CC : #E6F0E6
cRed(g) => g>9 ? #E00000 : g>8 ? #E31A1A : g>7 ? #E63333 : g>6 ? #E94D4D : g>5 ? #EC6666 : g>4 ? #F08080 : g>3 ? #F39999 : g>2 ? #F6B3B3 : g>1? #F9CCCC : #FCE6E6
cAqua(g) => g>9 ? #0080FFff : g>8 ? #0080FFe5 : g>7 ? #0080FFcc : g>6 ? #0080FFb2 : g>5 ? #0080FF99 : g>4 ? #0080FF7f : g>3 ? #0080FF66 : g>2 ? #0080FF4c : g>1 ? #0080FF33 : #00C0FF19
cPink(g) => g>9 ? #FF0080ff : g>8 ? #FF0080e5 : g>7 ? #FF0080cc : g>6 ? #FF0080b2 : g>5 ? #FF008099 : g>4 ? #FF00807f : g>3 ? #FF008066 : g>2 ? #FF00804c : g>1 ? #FF008033 : #FF008019
hma3() => p = lag/2, ta.wma(ta.wma(close, p/3)*3 - ta.wma(close, p/2) - ta.wma(close, p), p)
klmf(x) =>
sharpness = input.float(0.5, 'Sharpness', step=.05)
k = input.float(10.0, 'K', step=.05) //-- step size
var float velocity = 0.0
var float kf = 0.0
float distance = x - nz(kf[1], x)
float error = nz(kf[1], x) + distance * math.sqrt(sharpness*k/100)
velocity := nz(velocity[1], 0) + distance*k/100
kf := error + velocity
//-- Logic
float ds = request.security('', '', base)[nrep?1:0]
float a = k ? klmf(ds) : ta.hma(ds, lag)
float b = k ? klmf(hma3()) : hma3()
float avg = math.avg(a,b)
color c = avg>avg[1] ? color.lime : color.red
bool crossdn = c==color.red //a > b and a[1] < b[1]
bool crossup = c==color.lime //b > a and b[1] < a[1]
state := crossup ? 1 : crossdn ? -1 : nz(state[1])
//-- Visuals
fill(plot(a,'', color.new(c,75), 1), plot(b,'',color.new(c,55),1), color.new(c, 55))
plot(avg, '', avg>avg[1]?cAqua(6):cPink(6), 1)
plotshape(labels and ta.change(state) and state==1 ? a : na, '', shape.labelup, location.belowbar, na, 0, buy, cAqua(10), size=size.small)
plotshape(labels and ta.change(state) and state==-1 ? a : na, '', shape.labeldown, location.abovebar, na, 0, sell, cPink(10), size=size.small)
//== Trendlines Module, see https://www.tradingview.com/script/mpeEgn5J-Trendlines-JD/
//-- Inputs
tlmod = input.bool(false, '===Trendlines Module===')
l1 = input.int (2, 'Pivots Lookback Window', 1)
//-- Functions
trendline(input_function, delay, only_up) => // Calculate line coordinates (Ax,Ay) - (Bx,By)
var int Ax = 0, var int Bx = 0, var float By = 0.0, var float slope = 0.0
Ay = fixnan(input_function)
if ta.change(Ay)!=0
Ax := time[delay], By:= Ay[1], Bx := Ax[1]
slope := ((Ay-By)/(Ax-Bx))
else
Ax := Ax[1], Bx := Bx[1], By := By[1]
var line trendline=na, var int Axbis=0, var float Aybis=0.0, var bool xtend=true
extension_time = 0
Axbis := Ax + extension_time
Aybis := (Ay + extension_time*slope)
if tlmod and ta.change(Ay)!=0
line_color = slope*time<0?(only_up?na:color.red):(only_up?color.lime:na)
if not na(line_color)
trendline = line.new(Bx,By,Axbis, Aybis, xloc.bar_time, extend=xtend?extend.none:extend.none, color=line_color, style=line.style_dotted, width=1)
line.delete(trendline[1])
slope
pivot(len) =>
high_point = ta.pivothigh(high, len,len/2)
low_point = ta.pivotlow(low, len,len/2)
slope_high = trendline(high_point, len/2,false)
slope_low = trendline(low_point, len/2,true)
[high_point, low_point, slope_high, slope_low]
//-- Logic
[high_point1, low_point1, slope_high1, slope_low1] = pivot(l1)
color_high1 = slope_high1 * time<0 ? color.red : na
color_low1 = slope_low1 * time>0 ? color.lime : na
//-- Visuals
plot(tlmod ? high_point1 : na, '', color_high1, 2, offset=-l1/2)
plot(tlmod ? low_point1 : na, '', color_low1, 2, offset=-l1/2) |
MACD strategy + Trailstop indicator | https://www.tradingview.com/script/sd5rmSDu-MACD-strategy-Trailstop-indicator/ | Bretzay | https://www.tradingview.com/u/Bretzay/ | 138 | 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/
// © Bretzay
//@version=5
indicator("MACD strategy + SuperTrend",overlay=true,timeframe_gaps = false, timeframe = "")
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Inputs-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Validation inputs :
int emalength = input(200,title="EMAlength",tooltip="Choose the length of the EMA") //EMA LENGTH
color bullmc = input(title="Bullish trend",defval=color.new(color.green,70)) //Confirmation background color
color bearmc = input(title="Bullish trend",defval=color.new(color.red,70)) //Confirmation background color
bool filter = input.bool(title="EMA Filter ?",defval = true,tooltip = "We filter noise by don't taking signals if one of the 14 candle before the signal closes on the other side of the EMA.") //EMA Filter
bool background = input.bool(title="Background confirmation ?",defval=true,tooltip = "It makes appear (or not) the background on each place where there's a cross over in your filtering settings.") // Confirmation Background
bool TSFilter = input.bool(title="Only Supertrend ?",defval=false)
//Risk inputs
//RR = input.float(title="Risk Reward", tooltip = "Choose your Risk to Reward ratio", group = "Risk",minval=0,defval=1.5,step=0.1)
//SL Inputs (ATR)
float Mult = input.float(title="ATR Multiplier", tooltip="Increase of decrease the SL range from price", group="ATR",defval=3,step=0.1)
int atrLength = input.int(title="ATR Length", defval=10, minval=1,group="ATR")
// MACD Inputs
int fast_length = input(title="Fast Length", defval=12,group="MACD")
int slow_length = input(title="Slow Length", defval=26,group="MACD")
src = input(title="Source", defval=close,group="MACD")
int signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9,group="MACD")
string sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"],group="MACD")
string sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"],group="MACD")
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Calculating-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Super Trend Indicator
[supertrend, direction] = ta.supertrend(Mult, atrLength)
bodyMiddle = plot((open + close) / 2, display=display.none)
// MACD
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
// Validating trend
MACD = ta.macd(close,12,26,9)
EMA = ta.ema(close,emalength)
//Filters for moves close to EMA
closeunder = if close[14]<EMA or close[13]<EMA or close[12]<EMA or close[11]<EMA or close[10]<EMA or close[9]<EMA or close[8]<EMA or close[7]<EMA or close[6]<EMA or close[5]<EMA or close[4]<EMA or close[3]<EMA or close[2]<EMA or close[1]<EMA
false
else
true
closeabove = if close[14]>EMA or close[13]>EMA or close[12]>EMA or close[11]>EMA or close[10]>EMA or close[9]>EMA or close[8]>EMA or close[7]>EMA or close[6]>EMA or close[5]>EMA or close[4]>EMA or close[3]>EMA or close[2]>EMA or close[1]>EMA
false
else
true
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Strategy-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Calculate the TrailStop
ATR = ta.atr(atrLength)
Stop = Mult * ATR
//Is the market in bull/bear and MACD confirmation
var Bull = ta.crossover(macd, signal) and close > EMA and macd < 0 and closeunder
var Bear = ta.crossunder(macd, signal) and close < EMA and macd > 0 and closeabove
if filter == true
Bull := ta.crossover(macd, signal) and close > EMA and macd < 0 and closeunder
Bear := ta.crossunder(macd, signal) and close < EMA and macd > 0 and closeabove
else
Bull := ta.crossover(macd, signal) and close > EMA and macd < 0
Bear := ta.crossunder(macd, signal) and close < EMA and macd > 0
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Trail Stop-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Trailstop movement
// SELL TRAIL STOP
HL = (high+low)/2
var SellATR = 0.00
SellATR := if close < SellATR[1] and close[1] < SellATR[1]
math.min(SellATR[1], HL[1]+Stop)
else
HL+Stop
// BUY TRAIL STOP
var BuyATR = 0.00
BuyATR := if close > BuyATR[1] and close[1] > BuyATR[1]
math.max(BuyATR[1], HL[1]-Stop)
else
HL-Stop
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------Filtering TrailStop for Visual Improvement------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var Scl = color.new(color.red,0)
var Bcl = color.new(color.green,0)
if TSFilter == false and close < EMA and direction < 0
Scl:=color.new(color.red,0) //Selling color = Red trail stop
Bcl:=color.new(color.green,100) //Buying color = Green trail stop
else if TSFilter == false and close > EMA and direction > 0
Scl:=color.new(color.red,100) //Selling color = Red trail stop
Bcl:=color.new(color.green,0) //Buying color = Green trail stop
else
Scl:=color.new(color.red,100) //Selling color = Red trail stop
Bcl:=color.new(color.green,100) //Buying color = Green trail stop
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Showing-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//What appear on screen
bgcolor(background ? Bull ? color(bullmc) : Bear ? color(bearmc) : na : na, title = "Confirmation background color")
plot(EMA,"EMA")
Dtrend = plot(SellATR,color=Scl,title="Only change 0 and 1 (Trailing Stop)",style=plot.style_linebr)
Utrend = plot(BuyATR,color=Bcl,title="Only change 0 (Trailing Stop)",style=plot.style_linebr)
// Super Trend Indicator
upTrend = plot(close > EMA ? direction < 0 ? supertrend : na : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(close < EMA ? direction < 0? na : supertrend : na, "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)
|
Relative Volume Indicator | https://www.tradingview.com/script/GniGSDgt/ | Kaspricci | https://www.tradingview.com/u/Kaspricci/ | 108 | 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/
// © Kaspricci
//@version=5
indicator("Relative Volume Indicator", shorttitle="Volume%")
toolTipLength = "Define the number of bars to find the highest volume"
toolTipThreshold = "Set a threshold to differentiate high and low volume. Value between 0 and 1."
toolTipSmoothhing = "Define the length for applying simple movering average to volume."
volLength = input.int(240, title="Length", minval=1, tooltip=toolTipLength)
volSmthLength = input.int(3, title="Smoothing", minval=1, tooltip=toolTipSmoothhing)
volThreshold = input.float(0.2, title="Threshold", minval=0.01, maxval=1, step=0.05, tooltip=toolTipThreshold)
vh = ta.highest(volume, volLength)
val = math.round(ta.sma(volume / vh, volSmthLength), 2)
barColor = val < volThreshold ? color.silver : color.teal
plot(val, color=barColor, style=plot.style_columns, title="Volume")
hline(volThreshold, color=color.gray, linestyle=hline.style_dashed, title="Threshold")
hline(1, color=color.new(color.white, 100), title="Upper Limit") // blind line to avoid automatic scaling
|
STD/C-Filtered, Power-of-Cosine FIR Filter [Loxx] | https://www.tradingview.com/script/HFWCtbZ2-STD-C-Filtered-Power-of-Cosine-FIR-Filter-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 53 | 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/
// © loxx
//@version=5
indicator("STD/C-Filtered, Power-of-Cosine FIR Filter [Loxx]",
shorttitle = "STDCFPOCFIRF [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
powerOfCosineDesign(int per, int order)=>
float[] coeffs = array.new<float>(per, 0)
float coeff = 1
for i = 0 to per - 1
N = per + 1
ni = i + 1
X = ni / N
switch order
2 =>
coeff := (1 - math.cos(2.0 * math.pi * X)) / 2
4 =>
coeff := (3 -
4 * math.cos(2.0 * math.pi * X) +
math.cos(4.0 * math.pi * X)) / 8
6 =>
coeff := (10 -
15 * math.cos(2.0 * math.pi * X) +
6 * math.cos(4.0 * math.pi * X) -
math.cos(6.0 * math.pi * X)) / 32
8 =>
coeff := (35 -
56 * math.cos(2.0 * math.pi * X) +
28 * math.cos(4.0 * math.pi * X) -
8 * math.cos(6.0 * math.pi * X) +
math.cos(8.0 * math.pi * X)) / 128
10 =>
coeff := (126 -
210 * math.cos(2.0 * math.pi * X) +
120 * math.cos(4.0 * math.pi * X) -
45 * math.cos(6.0 * math.pi * X) +
10 * math.cos(8.0 * math.pi * X) -
math.cos(10.0 * math.pi * X)) / 512
12 =>
coeff := (462 -
792 * math.cos(2.0 * math.pi * X) +
495 * math.cos(4.0 * math.pi * X) -
220 * math.cos(6.0 * math.pi * X) +
66 * math.cos(8.0 * math.pi * X) -
12 * math.cos(10.0 * math.pi * X) +
math.cos(12.0 * math.pi * X)) / 2048
14 =>
coeff := (1716 -
3003 * math.cos(2.0 * math.pi * X) +
2002 * math.cos(4.0 * math.pi * X) -
1001 * math.cos(6.0 * math.pi * X) +
364 * math.cos(8.0 * math.pi * X) -
91 * math.cos(10.0 * math.pi * X) +
14 * math.cos(12.0 * math.pi * X) -
math.cos(14.0 * math.pi * X)) / 8192
16 =>
coeff := (6435 -
11440 * math.cos(2.0 * math.pi * X) +
8008 * math.cos(4.0 * math.pi * X) -
4368 * math.cos(6.0 * math.pi * X) +
1820 * math.cos(8.0 * math.pi * X) -
560 * math.cos(10.0 * math.pi * X) +
120 * math.cos(12.0 * math.pi * X) -
16 * math.cos(14.0 * math.pi * X) +
math.cos(16.0 * math.pi * X)) / 32768
=>
coeff := (1 - math.cos(2.0 * math.pi * X)) / 2
array.set(coeffs, i, coeff)
[coeffs, array.sum(coeffs)]
clutterFilt(float src, float threshold)=>
bool out = math.abs(ta.roc(src, 1)) > threshold
out
stdFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("HAB Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(14, "Period", group = "Basic Settings")
type = input.int(2, "Alpha", minval = 2, step = 2, maxval = 16, group = "Basic Settings")
sth = input.float(0.1, "Clutter Filter Threshold", group = "Basic Settings", step = 0.001)
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
showdeadzones = input.bool(false, "Show dead zones?", group= "UI Options")
filterop = input.string("Both", "Filter Options", options = ["Price", "STDCFPOCFIRF", "Both", "None"], group= "Filter Settings")
filter = input.float(0, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? stdFilter(src, filterperiod, filter) : src
[coeffs, coeffsSum] = powerOfCosineDesign(per, type)
float dSum = 0
for k = 0 to array.size(coeffs) - 1
dSum += nz(src[k]) * array.get(coeffs, k)
out = coeffsSum != 0 ? dSum / coeffsSum : 0
out := filterop == "Both" or filterop == "STDCFPOCFIRF" and filter > 0 ? stdFilter(out, filterperiod, filter) : out
sig = nz(out[1])
filtTrend = clutterFilt(out, sth)
state = filtTrend ? (out > sig ? 1 : out < sig ? -1 : 0) : 0
pregoLong = state == 1
pregoShort =state == -1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
color colorout = na
colorout := filtTrend ? (state == 1 ? greencolor : state == -1 ? redcolor : showdeadzones ? color.gray : colorout[1]) : showdeadzones ? color.gray : colorout[1]
plot(out, "STDCFPOCFIRF", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "STD/C-Filtered, Power-of-Cosine FIR Filter [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD/C-Filtered, Power-of-Cosine FIR Filter [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}") |
MultiTF 6 MA | https://www.tradingview.com/script/wW4KMX6V-MultiTF-6-MA/ | Jxjay | https://www.tradingview.com/u/Jxjay/ | 18 | 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/
// © Jxjay
//@version=5
indicator("MultiTF 6 MA", shorttitle='MTF6MA', overlay=true ,max_lines_count = 100, max_labels_count = 100)
COLOR_01 = #ffffff //1
COLOR_02 = #ffee99 //5
COLOR_03 = #ffff00 //15
COLOR_04 = #ffaa00 //30
COLOR_05 = #ffffff //1h
COLOR_06 = #ffee99 //2h
COLOR_07 = #ffff00 //4h
COLOR_08 = #ffaa00 //6h
COLOR_09 = #ff6600 //8h
COLOR_10 = #ff0000 //12h
COLOR_11 = #ffffff //1d
COLOR_12 = #ffee99 //2d
COLOR_13 = #ffff00 //3d
COLOR_14 = #ffaa00 //1w
COLOR_15 = #ff6600 //1mo
OPACITY = 50
var realTimeLabels = array.new_label()
var realTimeLines = array.new_line()
deleteRealtimeDrawings() =>
i = 0
while i < array.size(realTimeLabels)
label.delete(array.get(realTimeLabels,i))
array.remove(realTimeLabels, i)
while i < array.size(realTimeLines)
line.delete(array.get(realTimeLines,i))
array.remove(realTimeLines, i)
deleteRealtimeDrawings()
fnc = input.string(title="MA type", defval="EMA", options=["EMA", "SMA", "WMA", "HMA", "RMA", "SWMA", "ALMA", "VWMA", "VWAP"])
srcInput = input.source(close, "Source")
show_len1 = input.bool(defval=true, title="1:", group="Lengths", inline="len1")
len1 = input.int(defval=21, title="Len", group="Lengths", inline="len1")
lw1 = input.int(defval=2, title="Width", group="Lengths", inline="len1", minval=1, maxval=4, step=1)
show_len2 = input.bool(defval=true, title="2:", group="Lengths", inline="len2")
len2 = input.int(defval=34, title="Len", group="Lengths", inline="len2")
lw2 = input.int(defval=1, title="Width", group="Lengths", inline="len2", minval=1, maxval=4, step=1)
show_len3 = input.bool(defval=false, title="3:", group="Lengths", inline="len3")
len3 = input.int(defval=55, title="Len", group="Lengths", inline="len3")
lw3 = input.int(defval=1, title="Width", group="Lengths", inline="len3", minval=1, maxval=4, step=1)
c1m = input.color(defval=color.new(COLOR_01, OPACITY), title="1m", group="TimeFrame Settings", inline="1m")
show_1m_1 = input.bool(defval=true, title="Len1", group="TimeFrame Settings", inline="1m")
show_1m_2 = input.bool(defval=true, title="Len2", group="TimeFrame Settings", inline="1m")
show_1m_3 = input.bool(defval=true, title="Len3", group="TimeFrame Settings", inline="1m")
show_1m = show_1m_1 or show_1m_2 or show_1m_3
c5m = input.color(defval=color.new(COLOR_02, OPACITY), title="5m", group="TimeFrame Settings", inline="5m")
show_5m_1 = input.bool(defval=true, title="Len1", group="TimeFrame Settings", inline="5m")
show_5m_2 = input.bool(defval=true, title="Len2", group="TimeFrame Settings", inline="5m")
show_5m_3 = input.bool(defval=true, title="Len3", group="TimeFrame Settings", inline="5m")
show_5m = show_5m_1 or show_5m_2 or show_5m_3
c15m = input.color(defval=color.new(COLOR_03, OPACITY), title="15m", group="TimeFrame Settings", inline="15m")
show_15m_1 = input.bool(defval=true, title="Len1", group="TimeFrame Settings", inline="15m")
show_15m_2 = input.bool(defval=true, title="Len2", group="TimeFrame Settings", inline="15m")
show_15m_3 = input.bool(defval=true, title="Len3", group="TimeFrame Settings", inline="15m")
show_15m = show_15m_1 or show_15m_2 or show_15m_3
c30m = input.color(defval=color.new(COLOR_04, OPACITY), title="30m", group="TimeFrame Settings", inline="30m")
show_30m_1 = input.bool(defval=true, title="Len1", group="TimeFrame Settings", inline="30m")
show_30m_2 = input.bool(defval=true, title="Len2", group="TimeFrame Settings", inline="30m")
show_30m_3 = input.bool(defval=true, title="Len3", group="TimeFrame Settings", inline="30m")
show_30m = show_30m_1 or show_30m_2 or show_30m_3
c1h = input.color(defval=color.new(COLOR_05, OPACITY), title="1H", group="TimeFrame Settings", inline="1h")
show_1h_1 = input.bool(defval=true, title="Len1", group="TimeFrame Settings", inline="1h")
show_1h_2 = input.bool(defval=true, title="Len2", group="TimeFrame Settings", inline="1h")
show_1h_3 = input.bool(defval=true, title="Len3", group="TimeFrame Settings", inline="1h")
show_1h = show_1h_1 or show_1h_2 or show_1h_3
c2h = input.color(defval=color.new(COLOR_06, OPACITY), title="2H", group="TimeFrame Settings", inline="2h")
show_2h_1 = input.bool(defval=true, title="Len1", group="TimeFrame Settings", inline="2h")
show_2h_2 = input.bool(defval=true, title="Len2", group="TimeFrame Settings", inline="2h")
show_2h_3 = input.bool(defval=true, title="Len3", group="TimeFrame Settings", inline="2h")
show_2h = show_2h_1 or show_2h_2 or show_2h_3
c4h = input.color(defval=color.new(COLOR_07, OPACITY), title="4H", group="TimeFrame Settings", inline="4h")
show_4h_1 = input.bool(defval=true, title="Len1", group="TimeFrame Settings", inline="4h")
show_4h_2 = input.bool(defval=true, title="Len2", group="TimeFrame Settings", inline="4h")
show_4h_3 = input.bool(defval=true, title="Len3", group="TimeFrame Settings", inline="4h")
show_4h = show_4h_1 or show_4h_2 or show_4h_3
c6h = input.color(defval=color.new(COLOR_08, OPACITY), title="6H", group="TimeFrame Settings", inline="6h")
show_6h_1 = input.bool(defval=false, title="Len1", group="TimeFrame Settings", inline="6h")
show_6h_2 = input.bool(defval=false, title="Len2", group="TimeFrame Settings", inline="6h")
show_6h_3 = input.bool(defval=false, title="Len3", group="TimeFrame Settings", inline="6h")
show_6h = show_6h_1 or show_6h_2 or show_6h_3
c8h = input.color(defval=color.new(COLOR_09, OPACITY), title="8H", group="TimeFrame Settings", inline="8h")
show_8h_1 = input.bool(defval=false, title="Len1", group="TimeFrame Settings", inline="8h")
show_8h_2 = input.bool(defval=false, title="Len2", group="TimeFrame Settings", inline="8h")
show_8h_3 = input.bool(defval=false, title="Len3", group="TimeFrame Settings", inline="8h")
show_8h = show_8h_1 or show_8h_2 or show_8h_3
c12h = input.color(defval=color.new(COLOR_10, OPACITY), title="12H", group="TimeFrame Settings", inline="12h")
show_12h_1 = input.bool(defval=false, title="Len1", group="TimeFrame Settings", inline="12h")
show_12h_2 = input.bool(defval=false, title="Len2", group="TimeFrame Settings", inline="12h")
show_12h_3 = input.bool(defval=false, title="Len3", group="TimeFrame Settings", inline="12h")
show_12h = show_12h_1 or show_12h_2 or show_12h_3
c1D = input.color(defval=color.new(COLOR_11, OPACITY), title="1D", group="TimeFrame Settings", inline="1d")
show_1d_1 = input.bool(defval=true, title="Len1", group="TimeFrame Settings", inline="1d")
show_1d_2 = input.bool(defval=true, title="Len2", group="TimeFrame Settings", inline="1d")
show_1d_3 = input.bool(defval=true, title="Len3", group="TimeFrame Settings", inline="1d")
show_1d = show_1d_1 or show_1d_2 or show_1d_3
c2D = input.color(defval=color.new(COLOR_12, OPACITY), title="2D", group="TimeFrame Settings", inline="2d")
show_2d_1 = input.bool(defval=false, title="Len1", group="TimeFrame Settings", inline="2d")
show_2d_2 = input.bool(defval=false, title="Len2", group="TimeFrame Settings", inline="2d")
show_2d_3 = input.bool(defval=false, title="Len3", group="TimeFrame Settings", inline="2d")
show_2d = show_2d_1 or show_2d_2 or show_2d_3
c3D = input.color(defval=color.new(COLOR_13, OPACITY), title="3D", group="TimeFrame Settings", inline="3d")
show_3d_1 = input.bool(defval=false, title="Len1", group="TimeFrame Settings", inline="3d")
show_3d_2 = input.bool(defval=false, title="Len2", group="TimeFrame Settings", inline="3d")
show_3d_3 = input.bool(defval=false, title="Len3", group="TimeFrame Settings", inline="3d")
show_3d = show_3d_1 or show_3d_2 or show_3d_3
c1W = input.color(defval=color.new(COLOR_14, OPACITY), title="1W", group="TimeFrame Settings", inline="1w")
show_1w_1 = input.bool(defval=true, title="Len1", group="TimeFrame Settings", inline="1w")
show_1w_2 = input.bool(defval=true, title="Len2", group="TimeFrame Settings", inline="1w")
show_1w_3 = input.bool(defval=true, title="Len3", group="TimeFrame Settings", inline="1w")
show_1w = show_1w_1 or show_1w_2 or show_1w_3
c1M = input.color(defval=color.new(COLOR_15, OPACITY), title="1M", group="TimeFrame Settings", inline="1mo")
show_1mo_1 = input.bool(defval=true, title="Len1", group="TimeFrame Settings", inline="1mo")
show_1mo_2 = input.bool(defval=true, title="Len2", group="TimeFrame Settings", inline="1mo")
show_1mo_3 = input.bool(defval=true, title="Len3", group="TimeFrame Settings", inline="1mo")
show_1mo = show_1mo_1 or show_1mo_2 or show_1mo_3
show_extend = input.bool(defval=true, title="Extend lines")
show_label = input.bool(defval=true, title="Show labels")
// pstyle = plot.style_stepline
pstyle = plot.style_line
future_intervals = 20
draw_by = 5
MovAvgType(averageType, averageSource, averageLength) =>
switch str.upper(averageType)
"SMA" => ta.sma(averageSource, averageLength)
"EMA" => ta.ema(averageSource, averageLength)
"WMA" => ta.wma(averageSource, averageLength)
"HMA" => ta.hma(averageSource, averageLength)
"RMA" => ta.rma(averageSource, averageLength)
"SWMA" => ta.swma(averageSource)
"ALMA" => ta.alma(averageSource, averageLength, 0.85, 6)
"VWMA" => ta.vwma(averageSource, averageLength)
"VWAP" => ta.vwap(averageSource)
=> runtime.error("Moving average type '" + averageType +
"' not found!"), na
estimate_future(data, future_intervals_draw, do_full_estimation = true) =>
dd1 = data - data[1]
dd2 = data[1] - data[2]
future = array.new_float()
i=1
float current_val = na
array.push(future, data)
while i <= future_intervals_draw and do_full_estimation
change = dd2-(dd2-dd1)*i*math.pow(0.8,i)
new_val = nz(current_val, data) + change
array.push(future, new_val)
current_val := new_val
i += 1
future
get_line_data(src, len, future_intervals_draw, do_full_estimation = true) =>
data = MovAvgType(fnc,src,len)
time_diff = time-time[1]
time_current = time
time_next = time+time_diff
future = estimate_future(data, future_intervals_draw, do_full_estimation)
[data, time_diff, time_next, future]
get_lines_data(src, l1, l2, l3, future_intervals_draw, isDisplayable = true, do_full_estimation = true) =>
if isDisplayable == false
[na,na,na,na,na,na,na,na,na,na]
[data1, time_diff1, time_next1, future1] = get_line_data(src, l1, future_intervals_draw, do_full_estimation)
[data2, time_diff2, time_next2, future2] = get_line_data(src, l2, future_intervals_draw, do_full_estimation)
[data3, time_diff3, time_next3, future3] = get_line_data(src, l3, future_intervals_draw, do_full_estimation)
[data1, future1, data2, future2, data3, future3, time_diff1, time_next1]
is_displayable(tf) =>
disp = false
disp1 = false
disp2 = false
disp3 = false
if tf == "1"
time_disp = ( timeframe.isseconds or (timeframe.isminutes and timeframe.multiplier == 1) )
disp := show_1m and time_disp
disp1 := show_1m_1 and time_disp
disp2 := show_1m_2 and time_disp
disp3 := show_1m_3 and time_disp
if tf == "5"
time_disp = ( timeframe.isseconds or (timeframe.isminutes and timeframe.multiplier <= 5) )
disp := show_5m and time_disp
disp1 := show_5m_1 and time_disp
disp2 := show_5m_2 and time_disp
disp3 := show_5m_3 and time_disp
if tf == "15"
time_disp = ( timeframe.isseconds or (timeframe.isminutes and timeframe.multiplier <= 15) )
disp := show_15m and time_disp
disp1 := show_15m_1 and time_disp
disp2 := show_15m_2 and time_disp
disp3 := show_15m_3 and time_disp
if tf == "30"
time_disp = ( timeframe.isseconds or (timeframe.isminutes and timeframe.multiplier <= 30) )
disp := show_30m and time_disp
disp1 := show_30m_1 and time_disp
disp2 := show_30m_2 and time_disp
disp3 := show_30m_3 and time_disp
if tf == "60"
time_disp = ( timeframe.isseconds or (timeframe.isminutes and timeframe.multiplier <= 60) )
disp := show_1h and time_disp
disp1 := show_1h_1 and time_disp
disp2 := show_1h_2 and time_disp
disp3 := show_1h_3 and time_disp
if tf == "120"
time_disp = ( timeframe.isminutes and timeframe.multiplier <= 120 )
disp := show_2h and time_disp
disp1 := show_2h_1 and time_disp
disp2 := show_2h_2 and time_disp
disp3 := show_2h_3 and time_disp
if tf == "240"
time_disp = ( timeframe.isminutes and timeframe.multiplier <= 240 )
disp := show_4h and time_disp
disp1 := show_4h_1 and time_disp
disp2 := show_4h_2 and time_disp
disp3 := show_4h_3 and time_disp
if tf == "360"
time_disp = ( timeframe.isminutes and timeframe.multiplier <= 360 )
disp := show_6h and time_disp
disp1 := show_6h_1 and time_disp
disp2 := show_6h_2 and time_disp
disp3 := show_6h_3 and time_disp
if tf == "480"
time_disp = ( timeframe.isminutes and timeframe.multiplier <= 480 )
disp := show_8h and time_disp
disp1 := show_8h_1 and time_disp
disp2 := show_8h_2 and time_disp
disp3 := show_8h_3 and time_disp
if tf == "720"
time_disp = ( timeframe.isminutes and timeframe.multiplier <= 720 )
disp := show_12h and time_disp
disp1 := show_12h_1 and time_disp
disp2 := show_12h_2 and time_disp
disp3 := show_12h_3 and time_disp
if tf == "1D"
time_disp = ( timeframe.isminutes or timeframe.isdaily and timeframe.multiplier == 1 )
disp := show_1d and time_disp
disp1 := show_1d_1 and time_disp
disp2 := show_1d_2 and time_disp
disp3 := show_1d_3 and time_disp
if tf == "2D"
time_disp = ( timeframe.isminutes or timeframe.isdaily and timeframe.multiplier <= 2 )
disp := show_2d and time_disp
disp1 := show_2d_1 and time_disp
disp2 := show_2d_2 and time_disp
disp3 := show_2d_3 and time_disp
if tf == "3D"
time_disp = ( timeframe.isminutes or timeframe.isdaily and timeframe.multiplier <= 3 )
disp := show_3d and time_disp
disp1 := show_3d_1 and time_disp
disp2 := show_3d_2 and time_disp
disp3 := show_3d_3 and time_disp
if tf == "1W"
time_disp = ( timeframe.isminutes or timeframe.isdaily or timeframe.isweekly )
disp := show_1w and time_disp
disp1 := show_1w_1 and time_disp
disp2 := show_1w_2 and time_disp
disp3 := show_1w_3 and time_disp
if tf == "1M"
time_disp = ( timeframe.isminutes or timeframe.isdaily or timeframe.isweekly or timeframe.ismonthly)
disp := show_1mo and time_disp
disp1 := show_1mo_1 and time_disp
disp2 := show_1mo_2 and time_disp
disp3 := show_1mo_3 and time_disp
[disp, disp1, disp2, disp3]
get_tf_by_order(order) =>
o_move = 0
ret = "0"
found = false
if not show_1m
o_move := o_move +1
if order == 1 - o_move
ret := "1"
found := true
if not show_5m
o_move := o_move +1
if order == 2 - o_move and not found
ret := "5"
found := true
if not show_15m
o_move := o_move +1
if order == 3 - o_move and not found
ret := "15"
found := true
if not show_30m
o_move := o_move +1
if order == 4 - o_move and not found
ret := "30"
found := true
if not show_1h
o_move := o_move +1
if order == 5 - o_move and not found
ret := "60"
found := true
if not show_2h
o_move := o_move +1
if order == 6 - o_move and not found
ret := "120"
found := true
if not show_4h
o_move := o_move +1
if order == 7 - o_move and not found
ret := "240"
found := true
if not show_6h
o_move := o_move +1
if order == 8 - o_move and not found
ret := "360"
found := true
if not show_8h
o_move := o_move +1
if order == 9 - o_move and not found
ret := "480"
found := true
if not show_12h
o_move := o_move +1
if order == 10 - o_move and not found
ret := "720"
found := true
if not show_1d
o_move := o_move +1
if order == 11 - o_move and not found
ret := "1D"
found := true
if not show_2d
o_move := o_move +1
if order == 12 - o_move and not found
ret := "2D"
found := true
if not show_3d
o_move := o_move +1
if order == 13 - o_move and not found
ret := "3D"
found := true
if not show_1w
o_move := o_move +1
if order == 14 - o_move and not found
ret := "1W"
found := true
if not show_1mo
o_move := o_move +1
if order == 15 - o_move and not found
ret := "1M"
found := true
ret
get_tf_name_by_order(order) =>
o_move = 0
ret = "0"
found = false
if not show_1m
o_move := o_move +1
if order == 1 - o_move and not found
ret := "1m"
found := true
if not show_5m
o_move := o_move +1
if order == 2 - o_move and not found
ret := "5m"
found := true
if not show_15m
o_move := o_move +1
if order == 3 - o_move and not found
ret := "15m"
found := true
if not show_30m
o_move := o_move +1
if order == 4 - o_move and not found
ret := "30m"
found := true
if not show_1h
o_move := o_move +1
if order == 5 - o_move and not found
ret := "1H"
found := true
if not show_2h
o_move := o_move +1
if order == 6 - o_move and not found
ret := "2H"
found := true
if not show_4h
o_move := o_move +1
if order == 7 - o_move and not found
ret := "4H"
found := true
if not show_6h
o_move := o_move +1
if order == 8 - o_move and not found
ret := "6H"
found := true
if not show_8h
o_move := o_move +1
if order == 9 - o_move and not found
ret := "8H"
found := true
if not show_12h
o_move := o_move +1
if order == 10 - o_move and not found
ret := "12H"
found := true
if not show_1d
o_move := o_move +1
if order == 11 - o_move and not found
ret := "1D"
found := true
if not show_2d
o_move := o_move +1
if order == 12 - o_move and not found
ret := "2D"
found := true
if not show_3d
o_move := o_move +1
if order == 13 - o_move and not found
ret := "3D"
found := true
if not show_1w
o_move := o_move +1
if order == 14 - o_move and not found
ret := "1W"
found := true
if not show_1mo
o_move := o_move +1
if order == 15 - o_move and not found
ret := "1M"
found := true
ret
get_color_by_order(order) =>
o_move = 0
ret = c1M
found = false
if not show_1m
o_move := o_move +1
if order == 1 - o_move and not found
ret := c1m
found := true
if not show_5m
o_move := o_move +1
if order == 2 - o_move and not found
ret := c5m
found := true
if not show_15m
o_move := o_move +1
if order == 3 - o_move and not found
ret := c15m
found := true
if not show_30m
o_move := o_move +1
if order == 4 - o_move and not found
ret := c30m
found := true
if not show_1h
o_move := o_move +1
if order == 5 - o_move and not found
ret := c1h
found := true
if not show_2h
o_move := o_move +1
if order == 6 - o_move and not found
ret := c2h
found := true
if not show_4h
o_move := o_move +1
if order == 7 - o_move and not found
ret := c4h
found := true
if not show_6h
o_move := o_move +1
if order == 8 - o_move and not found
ret := c6h
found := true
if not show_8h
o_move := o_move +1
if order == 9 - o_move and not found
ret := c8h
found := true
if not show_12h
o_move := o_move +1
if order == 10 - o_move and not found
ret := c12h
found := true
if not show_1d
o_move := o_move +1
if order == 11 - o_move and not found
ret := c1D
found := true
if not show_2d
o_move := o_move +1
if order == 12 - o_move and not found
ret := c2D
found := true
if not show_3d
o_move := o_move +1
if order == 13 - o_move and not found
ret := c3D
found := true
if not show_1w
o_move := o_move +1
if order == 14 - o_move and not found
ret := c1W
found := true
// if not show_1mo
// o_move := o_move +1
// if order == 10 - o_move and not found
// ret := "1M"
ret
get_ratio_by_order(order) =>
3
identify_tf_order(tf) =>
( timeframe.isseconds or (timeframe.isminutes and timeframe.multiplier == 1) ) ? 1
: (timeframe.isminutes and timeframe.multiplier > 1 and timeframe.multiplier <= 5) ? 2
: (timeframe.isminutes and timeframe.multiplier > 5 and timeframe.multiplier <= 15) ? 3
: (timeframe.isminutes and timeframe.multiplier > 15 and timeframe.multiplier <= 30) ? 4
: (timeframe.isminutes and timeframe.multiplier > 30 and timeframe.multiplier <= 60) ? 5
: (timeframe.isminutes and timeframe.multiplier > 60 and timeframe.multiplier <= 120) ? 6
: (timeframe.isminutes and timeframe.multiplier > 120 and timeframe.multiplier <= 240) ? 7
: (timeframe.isminutes and timeframe.multiplier > 240 and timeframe.multiplier <= 360) ? 8
: (timeframe.isminutes and timeframe.multiplier > 360 and timeframe.multiplier <= 480) ? 9
: (timeframe.isminutes and timeframe.multiplier > 480 and timeframe.multiplier <= 720) ? 10
: (timeframe.isminutes and timeframe.multiplier > 720 or timeframe.isdaily and timeframe.multiplier == 1 ) ? 11
: (timeframe.isminutes or timeframe.isdaily and timeframe.multiplier == 2 ) ? 12
: (timeframe.isminutes or timeframe.isdaily and timeframe.multiplier == 3 ) ? 13
: (timeframe.isdaily and timeframe.multiplier > 3 or timeframe.isweekly and timeframe.multiplier == 1 ) ? 14
: 15
get_tf_params(tf, instance) =>
tf_order = identify_tf_order(tf)
disp_order = tf_order + instance - 1
[get_tf_by_order(disp_order), get_tf_name_by_order(disp_order), get_color_by_order(disp_order), get_ratio_by_order(disp_order) ]
draw_label(interval_name, len, fnc, label_shift, y, cm, display = false) =>
if display and show_label
_lab = label.new(text=interval_name+ " " + str.tostring(len) + " " + fnc ,x = bar_index+label_shift, y=y, style=label.style_label_left)
label.set_textcolor(id=_lab, textcolor=cm)
label.set_color(id=_lab, color=color.new(color.black, 100))
array.push(realTimeLabels, _lab)
draw_future_line(x1, y1, x2, y2, lw, cm) =>
_line = line.new(
x1 = x1, y1 = y1, x2 = x2, y2 = y2,
xloc=xloc.bar_time, style=line.style_dotted, width=lw, color=cm
)
array.push(realTimeLines, _line)
draw_future_lines(future, future_intervals_draw, time_next, time_diff, lw, cm, display = false) =>
fid = future_intervals_draw
if fid < draw_by
fid := draw_by
if display and show_extend
i=draw_by
while i+draw_by-1 < array.size(future) and i <= fid
x1 = i<draw_by+1?time:time_next+time_diff*(i-draw_by-1)
y1 = array.get(future, i-draw_by)
x2 = time_next+time_diff*(i-1)
y2 = array.get(future, i)
draw_future_line(x1, y1, x2, y2, lw, cm)
i+=draw_by
label_shift = 5
label_shift_change = 4
future_intervals_draw = future_intervals
[intrvl, interval_name, cm, ratio_to_prev] = get_tf_params(timeframe.period, 1)
[isDisplayable, isDisplayable1, isDisplayable2, isDisplayable3] = is_displayable(intrvl)
[data1, future1, data2, future2, data3, future3, time_diff, time_next] = request.security(syminfo.tickerid, isDisplayable?intrvl:timeframe.period, get_lines_data(srcInput,len1,len2,len3, future_intervals_draw,isDisplayable, barstate.islast))
plot(isDisplayable and isDisplayable1 and show_len1 ?data1:na, color=cm, linewidth = lw1, style=pstyle)
plot(isDisplayable and isDisplayable2 and show_len2 ?data2:na, color=cm, linewidth = lw2, style=pstyle)
plot(isDisplayable and isDisplayable3 and show_len3 ?data3:na, color=cm, linewidth = lw3, style=pstyle)
if barstate.islast and isDisplayable
f1 = array.new_float()
i=0
while i < array.size(future1)
array.push(f1, array.get(future1, i))
i += 1
f2 = array.new_float()
i:=0
while i < array.size(future2)
array.push(f2, array.get(future2, i))
i += 1
f3 = array.new_float()
i:=0
while i < array.size(future3)
array.push(f3, array.get(future3, i))
i += 1
draw_future_lines(f1, future_intervals_draw, time_next, time_diff, lw1, cm, show_len1 and isDisplayable1)
draw_future_lines(f2, future_intervals_draw, time_next, time_diff, lw2, cm, show_len2 and isDisplayable2)
draw_future_lines(f3, future_intervals_draw, time_next, time_diff, lw3, cm, show_len3 and isDisplayable3)
draw_label(interval_name, len1, fnc, label_shift, data1, cm, show_len1 and isDisplayable1)
draw_label(interval_name, len2, fnc, label_shift, data2, cm, show_len2 and isDisplayable2)
draw_label(interval_name, len3, fnc, label_shift, data3, cm, show_len3 and isDisplayable3)
label_shift += label_shift_change
if true
[intrvl, _interval_name, _cm, _ratio_to_prev] = get_tf_params(timeframe.period, 2)
interval_name := _interval_name
cm := _cm
ratio_to_prev := _ratio_to_prev
[_isDisplayable, _isDisplayable1, _isDisplayable2, _isDisplayable3] = is_displayable(intrvl)
isDisplayable := _isDisplayable
isDisplayable1 := _isDisplayable1
isDisplayable2 := _isDisplayable2
isDisplayable3 := _isDisplayable3
if isDisplayable
future_intervals_draw := math.ceil(future_intervals_draw/2.5) + draw_by
[_data1, _future1, _data2, _future2, _data3, _future3, _time_diff, _time_next] = request.security(syminfo.tickerid, isDisplayable?intrvl:timeframe.period, get_lines_data(srcInput,len1,len2,len3, future_intervals_draw,isDisplayable, barstate.islast))
data1 := _data1
future1 := _future1
data2 := _data2
future2 := _future2
data3 := _data3
future3 := _future3
time_diff := _time_diff
time_next := _time_next
plot(isDisplayable and isDisplayable1 and show_len1 ?data1:na, color=cm, linewidth = lw1, style=pstyle)
plot(isDisplayable and isDisplayable2 and show_len2 ?data2:na, color=cm, linewidth = lw2, style=pstyle)
plot(isDisplayable and isDisplayable3 and show_len3 ?data3:na, color=cm, linewidth = lw3, style=pstyle)
if barstate.islast and isDisplayable
f1 = array.new_float()
i=0
while i < array.size(future1)
array.push(f1, array.get(future1, i))
i += 1
f2 = array.new_float()
i:=0
while i < array.size(future2)
array.push(f2, array.get(future2, i))
i += 1
f3 = array.new_float()
i:=0
while i < array.size(future3)
array.push(f3, array.get(future3, i))
i += 1
draw_future_lines(f1, future_intervals_draw, time_next, time_diff, lw1, cm, show_len1 and isDisplayable1)
draw_future_lines(f2, future_intervals_draw, time_next, time_diff, lw2, cm, show_len2 and isDisplayable2)
draw_future_lines(f3, future_intervals_draw, time_next, time_diff, lw3, cm, show_len3 and isDisplayable3)
draw_label(interval_name, len1, fnc, label_shift, data1, cm, show_len1 and isDisplayable1)
draw_label(interval_name, len2, fnc, label_shift, data2, cm, show_len2 and isDisplayable2)
draw_label(interval_name, len3, fnc, label_shift, data3, cm, show_len3 and isDisplayable3)
label_shift += label_shift_change
if true
[intrvl, _interval_name, _cm, _ratio_to_prev] = get_tf_params(timeframe.period, 3)
interval_name := _interval_name
cm := _cm
ratio_to_prev := _ratio_to_prev
[_isDisplayable, _isDisplayable1, _isDisplayable2, _isDisplayable3] = is_displayable(intrvl)
isDisplayable := _isDisplayable
isDisplayable1 := _isDisplayable1
isDisplayable2 := _isDisplayable2
isDisplayable3 := _isDisplayable3
if isDisplayable
future_intervals_draw := math.ceil(future_intervals_draw/2.5) + draw_by
[_data1, _future1, _data2, _future2, _data3, _future3, _time_diff, _time_next] = request.security(syminfo.tickerid, isDisplayable?intrvl:timeframe.period, get_lines_data(srcInput,len1,len2,len3, future_intervals_draw,isDisplayable, barstate.islast))
data1 := _data1
future1 := _future1
data2 := _data2
future2 := _future2
data3 := _data3
future3 := _future3
time_diff := _time_diff
time_next := _time_next
plot(isDisplayable and isDisplayable1 and show_len1 ?data1:na, color=cm, linewidth = lw1, style=pstyle)
plot(isDisplayable and isDisplayable2 and show_len2 ?data2:na, color=cm, linewidth = lw2, style=pstyle)
plot(isDisplayable and isDisplayable3 and show_len3 ?data3:na, color=cm, linewidth = lw3, style=pstyle)
if barstate.islast and isDisplayable
f1 = array.new_float()
i=0
while i < array.size(future1)
array.push(f1, array.get(future1, i))
i += 1
f2 = array.new_float()
i:=0
while i < array.size(future2)
array.push(f2, array.get(future2, i))
i += 1
f3 = array.new_float()
i:=0
while i < array.size(future3)
array.push(f3, array.get(future3, i))
i += 1
draw_future_lines(f1, future_intervals_draw, time_next, time_diff, lw1, cm, show_len1 and isDisplayable1)
draw_future_lines(f2, future_intervals_draw, time_next, time_diff, lw2, cm, show_len2 and isDisplayable2)
draw_future_lines(f3, future_intervals_draw, time_next, time_diff, lw3, cm, show_len3 and isDisplayable3)
draw_label(interval_name, len1, fnc, label_shift, data1, cm, show_len1 and isDisplayable1)
draw_label(interval_name, len2, fnc, label_shift, data2, cm, show_len2 and isDisplayable2)
draw_label(interval_name, len3, fnc, label_shift, data3, cm, show_len3 and isDisplayable3)
label_shift += label_shift_change
if true
[intrvl, _interval_name, _cm, _ratio_to_prev] = get_tf_params(timeframe.period, 4)
interval_name := _interval_name
cm := _cm
ratio_to_prev := _ratio_to_prev
[_isDisplayable, _isDisplayable1, _isDisplayable2, _isDisplayable3] = is_displayable(intrvl)
isDisplayable := _isDisplayable
isDisplayable1 := _isDisplayable1
isDisplayable2 := _isDisplayable2
isDisplayable3 := _isDisplayable3
if isDisplayable
future_intervals_draw := math.ceil(future_intervals_draw/2.5) + draw_by
[_data1, _future1, _data2, _future2, _data3, _future3, _time_diff, _time_next] = request.security(syminfo.tickerid, isDisplayable?intrvl:timeframe.period, get_lines_data(srcInput,len1,len2,len3, future_intervals_draw,isDisplayable, barstate.islast))
data1 := _data1
future1 := _future1
data2 := _data2
future2 := _future2
data3 := _data3
future3 := _future3
time_diff := _time_diff
time_next := _time_next
plot(isDisplayable and isDisplayable1 and show_len1 ?data1:na, color=cm, linewidth = lw1, style=pstyle)
plot(isDisplayable and isDisplayable2 and show_len2 ?data2:na, color=cm, linewidth = lw2, style=pstyle)
plot(isDisplayable and isDisplayable3 and show_len3 ?data3:na, color=cm, linewidth = lw3, style=pstyle)
if barstate.islast and isDisplayable
f1 = array.new_float()
i=0
while i < array.size(future1)
array.push(f1, array.get(future1, i))
i += 1
f2 = array.new_float()
i:=0
while i < array.size(future2)
array.push(f2, array.get(future2, i))
i += 1
f3 = array.new_float()
i:=0
while i < array.size(future3)
array.push(f3, array.get(future3, i))
i += 1
draw_future_lines(f1, future_intervals_draw, time_next, time_diff, lw1, cm, show_len1 and isDisplayable1)
draw_future_lines(f2, future_intervals_draw, time_next, time_diff, lw2, cm, show_len2 and isDisplayable2)
draw_future_lines(f3, future_intervals_draw, time_next, time_diff, lw3, cm, show_len3 and isDisplayable3)
draw_label(interval_name, len1, fnc, label_shift, data1, cm, show_len1 and isDisplayable1)
draw_label(interval_name, len2, fnc, label_shift, data2, cm, show_len2 and isDisplayable2)
draw_label(interval_name, len3, fnc, label_shift, data3, cm, show_len3 and isDisplayable3)
label_shift += label_shift_change
if true
[intrvl, _interval_name, _cm, _ratio_to_prev] = get_tf_params(timeframe.period, 5)
interval_name := _interval_name
cm := _cm
ratio_to_prev := _ratio_to_prev
[_isDisplayable, _isDisplayable1, _isDisplayable2, _isDisplayable3] = is_displayable(intrvl)
isDisplayable := _isDisplayable
isDisplayable1 := _isDisplayable1
isDisplayable2 := _isDisplayable2
isDisplayable3 := _isDisplayable3
if isDisplayable
future_intervals_draw := math.ceil(future_intervals_draw/2.5) + draw_by
[_data1, _future1, _data2, _future2, _data3, _future3, _time_diff, _time_next] = request.security(syminfo.tickerid, isDisplayable?intrvl:timeframe.period, get_lines_data(srcInput,len1,len2,len3, future_intervals_draw,isDisplayable, barstate.islast))
data1 := _data1
future1 := _future1
data2 := _data2
future2 := _future2
data3 := _data3
future3 := _future3
time_diff := _time_diff
time_next := _time_next
plot(isDisplayable and isDisplayable1 and show_len1 ?data1:na, color=cm, linewidth = lw1, style=pstyle)
plot(isDisplayable and isDisplayable2 and show_len2 ?data2:na, color=cm, linewidth = lw2, style=pstyle)
plot(isDisplayable and isDisplayable3 and show_len3 ?data3:na, color=cm, linewidth = lw3, style=pstyle)
if barstate.islast and isDisplayable
f1 = array.new_float()
i=0
while i < array.size(future1)
array.push(f1, array.get(future1, i))
i += 1
f2 = array.new_float()
i:=0
while i < array.size(future2)
array.push(f2, array.get(future2, i))
i += 1
f3 = array.new_float()
i:=0
while i < array.size(future3)
array.push(f3, array.get(future3, i))
i += 1
draw_future_lines(f1, future_intervals_draw, time_next, time_diff, lw1, cm, show_len1 and isDisplayable1)
draw_future_lines(f2, future_intervals_draw, time_next, time_diff, lw2, cm, show_len2 and isDisplayable2)
draw_future_lines(f3, future_intervals_draw, time_next, time_diff, lw3, cm, show_len3 and isDisplayable3)
draw_label(interval_name, len1, fnc, label_shift, data1, cm, show_len1 and isDisplayable1)
draw_label(interval_name, len2, fnc, label_shift, data2, cm, show_len2 and isDisplayable2)
draw_label(interval_name, len3, fnc, label_shift, data3, cm, show_len3 and isDisplayable3)
label_shift += label_shift_change
if true
[intrvl, _interval_name, _cm, _ratio_to_prev] = get_tf_params(timeframe.period, 6)
interval_name := _interval_name
cm := _cm
ratio_to_prev := _ratio_to_prev
[_isDisplayable, _isDisplayable1, _isDisplayable2, _isDisplayable3] = is_displayable(intrvl)
isDisplayable := _isDisplayable
isDisplayable1 := _isDisplayable1
isDisplayable2 := _isDisplayable2
isDisplayable3 := _isDisplayable3
if isDisplayable
future_intervals_draw := math.ceil(future_intervals_draw/2.5) + draw_by
[_data1, _future1, _data2, _future2, _data3, _future3, _time_diff, _time_next] = request.security(syminfo.tickerid, isDisplayable?intrvl:timeframe.period, get_lines_data(srcInput,len1,len2,len3, future_intervals_draw,isDisplayable, barstate.islast))
data1 := _data1
future1 := _future1
data2 := _data2
future2 := _future2
data3 := _data3
future3 := _future3
time_diff := _time_diff
time_next := _time_next
plot(isDisplayable and isDisplayable1 and show_len1 ?data1:na, color=cm, linewidth = lw1, style=pstyle)
plot(isDisplayable and isDisplayable2 and show_len2 ?data2:na, color=cm, linewidth = lw2, style=pstyle)
plot(isDisplayable and isDisplayable3 and show_len3 ?data3:na, color=cm, linewidth = lw3, style=pstyle)
if barstate.islast and isDisplayable
f1 = array.new_float()
i=0
while i < array.size(future1)
array.push(f1, array.get(future1, i))
i += 1
f2 = array.new_float()
i:=0
while i < array.size(future2)
array.push(f2, array.get(future2, i))
i += 1
f3 = array.new_float()
i:=0
while i < array.size(future3)
array.push(f3, array.get(future3, i))
i += 1
draw_future_lines(f1, future_intervals_draw, time_next, time_diff, lw1, cm, show_len1 and isDisplayable1)
draw_future_lines(f2, future_intervals_draw, time_next, time_diff, lw2, cm, show_len2 and isDisplayable2)
draw_future_lines(f3, future_intervals_draw, time_next, time_diff, lw3, cm, show_len3 and isDisplayable3)
draw_label(interval_name, len1, fnc, label_shift, data1, cm, show_len1 and isDisplayable1)
draw_label(interval_name, len2, fnc, label_shift, data2, cm, show_len2 and isDisplayable2)
draw_label(interval_name, len3, fnc, label_shift, data3, cm, show_len3 and isDisplayable3)
label_shift += label_shift_change
|
Deviation Scaled Moving Average w/ DSL [Loxx] | https://www.tradingview.com/script/MXTaXJdU-Deviation-Scaled-Moving-Average-w-DSL-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 289 | 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/
// © loxx
//@version=5
indicator("Deviation Scaled Moving Average w/ DSL [Loxx]",
shorttitle='DSMAWDSL [Loxx]',
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
darkGreenColor = #1B7E02
darkRedColor = #93021F
SM02 = 'Slope'
SM04 = 'Levels Crosses'
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
trig
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(25, "Period", group = "Basic Settings")
signal_length = input.int(9, "Signal Period", group = "Signal/DSL Settings")
sigmatype = input.string("Exponential Moving Average - EMA", "Signal/DSL Smoothing", options = ["Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA"], group = "Signal/DSL Settings")
sigtype = input.string(SM04, "Signal type", options = [SM02, SM04], group = "Signal/DSL Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
[filt, _, _] = loxxmas.super(ta.change(close, 2), per)
rms = 0.
for k = 0 to per - 1
rms += math.pow(nz(filt[k]), 2)
rms := math.sqrt(rms / per)
scaledfit = filt / rms
alpha = math.abs(scaledfit) * 5 / per
out = 0.
out := nz(out[1]) + alpha * (src - nz(out[1]))
sig = out[1]
levelu = 0., leveld = 0., mid = 0.
levelu := (out > sig) ? variant(sigmatype, out, signal_length) : nz(levelu[1])
leveld := (out < sig) ? variant(sigmatype, out, signal_length) : nz(leveld[1])
state = 0.
if sigtype == SM02
if (out < sig)
state :=-1
if (out > sig)
state := 1
else if sigtype == SM04
if (out < leveld)
state :=-1
if (out > levelu)
state := 1
goLong_pre = sigtype == SM02 ? ta.crossover(out, sig) : ta.crossover(out, levelu)
goShort_pre = sigtype == SM02 ? ta.crossunder(out, sig) : ta.crossunder(out, leveld)
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
colorout = sigtype == SM02 ? contSwitch == -1 ? redcolor : greencolor :
state == 1 ? greencolor : state == -1 ? redcolor : color.gray
plot(out,"Pips-Stepped, Adaptive-ER DSEMA", color = colorout, linewidth = 3)
plot(levelu, "Level Up", color = darkGreenColor)
plot(leveld, "Level Down", color = darkRedColor)
barcolor(colorbars ? colorout : na)
goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="Deviation Scaled Moving Average w/ DSL [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Deviation Scaled Moving Average w/ DSL [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Money Flow Index modifier | https://www.tradingview.com/script/KGKXxoiq/ | mentalOil86068 | https://www.tradingview.com/u/mentalOil86068/ | 13 | 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/
// © mentalOil86068
//@version=5
indicator(title="Money Flow Index", shorttitle="MFI", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
length = input.int(title="Length", defval=14, minval=1, maxval=2000)
src = hlc3
mf = ta.mfi(src, length)
plot(mf, "MF", color=#7E57C2)
overbought=hline(80, title="Overbought", color=#787B86)
hline(80, title="Overbought", color=#787B86)
hline(80, title="Overbought", color=#787B86)
hline(50, "Middle Band", color=color.new(#787B86, 50))
oversold=hline(20, title="Oversold", color=#787B86)
hline(20, title="Oversold", color=#787B86)
hline(20, title="Oversold", color=#787B86)
fill(overbought, oversold, color=color.rgb(126, 87, 194, 90), title="Background") |
Williams %R (v.4) | https://www.tradingview.com/script/oeOL32mb-Williams-R-v-4/ | capissimo | https://www.tradingview.com/u/capissimo/ | 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/
// © capissimo
//@version=5
indicator("Williams %R (v.4)", "W%R-4", false, format=format.price, precision=2, timeframe="", timeframe_gaps=true)
// This is an upgrade and an update of my Williams %R indicator modification.
// As before this implementation is enhanced with CCI in the form of background colors.
// These colors can be used as a confirmation signal and indication of a current trend.
// Thee also can be employed in deciding when to enter/exit the market.
// Besides, added is a scaling function and Lower/Upper Bound inputs.
//-- Inputs
base = input.source(close, 'Dataset')
lkb = input.int (12, 'Lookback', 1)
nonrep = input.bool (true, 'Non-Repainting')
lbound = input.float (20, 'Lower Bound [0..50]', 0, 50) / 100
ubound = input.float (80, 'Upper Bound [51..100]', 51, 100) / 100
feature = input.string('CCI', 'Feature', ['CCI','EMA','VWAP','LSMA','Vidya'], inline='f')
flag = input.int (20, 'Lag', 1, inline='f')
//-- Functions
lsma(ds, p) => 3*ta.wma(ds,p) - 2*ta.sma(ds,p)
vidya(ds, p) =>
mom = ta.change(ds)
upSum = math.sum(math.max(mom, 0), p)
downSum = math.sum(-math.min(mom, 0), p)
out = (upSum - downSum) / (upSum + downSum)
cmo = math.abs(out)
alpha = 2 / (p + 1)
vidya = 0.0
vidya := ds * alpha * cmo + nz(vidya[1]) * (1 - alpha * cmo)
scale(x, p) => lo = ta.lowest(x, p), (x - lo) / (ta.highest(x, p) - lo)
minimax(X, p, min, max) =>
hi = ta.highest(X, p), lo = ta.lowest(X, p)
(max - min) * (X - lo)/(hi - lo) + min
green(g) => g>9 ? #006400 : g>8 ? #1A741A : g>7 ? #338333 : g>6 ? #4D934D : g>5 ? #66A266 : g>4 ? #80B280 : g>3 ? #99C199 : g>2 ? #B3D1B3 : g>1? #CCE0CC : #E6F0E6
red(g) => g>9 ? #E00000 : g>8 ? #E31A1A : g>7 ? #E63333 : g>6 ? #E94D4D : g>5 ? #EC6666 : g>4 ? #F08080 : g>3 ? #F39999 : g>2 ? #F6B3B3 : g>1? #F9CCCC : #FCE6E6
//-- Logic
float ds = request.security('', '', base)[nonrep?1:0]
float r = scale(ds, lkb)
float cci = ta.cci(ds, lkb) / 100
float ls = minimax(lsma(ds, lkb), flag, -1, 1)
float vwp = minimax(ta.vwap(ds), flag, -1, 1)
float vid = minimax(vidya(ds, lkb), flag, -1, 1)
float ema = minimax(ta.ema(ds, lkb), flag, -1, 1)
float f = feature=='LSMA' ? ls : feature=='Vidya' ? vid : feature=='EMA' ? ema : feature=='VWAP' ? vwp : cci
color clr = r >= 0.5 ? green(9) : red(9)
//-- Visuals
bgcolor(f>ubound ? green(2) : f<lbound ? red(2) : na)
hline(ubound, '', color.gray)
hline(.5, '', color.black)
hline(lbound, '', color.gray)
plot(r, '', clr, 2)
|
Machine Learning: kNN (New Approach) | https://www.tradingview.com/script/3lZg4gmr-Machine-Learning-kNN-New-Approach/ | capissimo | https://www.tradingview.com/u/capissimo/ | 1,926 | 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/
// © capissimo
//@version=5
indicator("Machine Learning: kNN (New Approach)", '', true, format=format.price, precision=2, timeframe="", timeframe_gaps=true)
// kNN is a very robust and simple method for data classification and prediction. It is very
// effective if the training data is large. However, it is distinguished by difficulty at
// determining its main parameter, K (a number of nearest neighbors), beforehand. The
// computation cost is also quite high because we need to compute distance of each instance
// to all training samples. Nevertheless, in algorithmic trading KNN is reported to perform
// on a par with such techniques as SVM and Random Forest. It is also widely used in the area
// of data science.
// The input data is just a long series of prices over time without any particular features.
// The value to be predicted is just the next bar's price. The way that this problem is
// solved for both nearest neighbor techniques and for some other types of prediction
// algorithms is to create training records by taking, for instance, 10 consecutive prices
// and using the first 9 as predictor values and the 10th as the prediction value.
// Doing this way, given 100 data points in your time series you could create 10 different
// training records. It's possible to create even more training records than 10 by creating
// a new record starting at every data point. For instance, you could take the first 10 data
// points and create a record. Then you could take the 10 consecutive data points starting at
// the second data point, the 10 consecutive data points starting at the third data point, etc.
// By default, shown are only 10 initial data points as predictor values and the 6th as the
// prediction value.
// Here is a step-by-step workthrough on how to compute K nearest neighbors (KNN) algorithm for
// quantitative data:
// 1. Determine parameter K = number of nearest neighbors.
// 2. Calculate the distance between the instance and all the training samples. As we are
// dealing with one-dimensional distance, we simply take absolute value from the instance to
// value of x (| x – v |).
// 3. Rank the distance and determine nearest neighbors based on the K'th minimum distance.
// 4. Gather the values of the nearest neighbors.
// 5. Use average of nearest neighbors as the prediction value of the instance.
// The original logic of the algorithm was slightly modified, and as a result at approx. N=17
// the resulting curve nicely approximates that of the sma(20). See the description below.
// Beside the sma-like MA this algorithm also gives you a hint on the direction of the next bar
// move.
//-- Inputs
TF = input.timeframe('5', 'Resolution', ['1','3','5','10','15','30','45','60','120','180','240','480','D','W','M'])
N = input.int (10, '# of Data Points [2:n]', 2)
K = input.int (100, '# of Nearest Neighbors (K) [1:252]', 1, 252)
ADJ = input.bool (true, 'Adjust Prediction', inline='b')
REP = input.bool (false, 'Non-Repainting', inline='b')
ADDON = input.string ('Z-Score', 'Add-On', ['None','Pivot Point','Z-Score'])
LAGP = input.int (5, 'Pivot Point Lag [2:n] if selected', 2)
LAGZ = input.int (20, 'Z-Score Lag [2:n] if selected', 2)
DISP = input.string ('Both', 'Show Outcomes', ['Curve','Predict','Both'])
ODS = input.source (hlcc4, 'Projection Base')
//-- Functions
knn(data) => //-- calculate nearest neighbors (if any)
nearest_neighbors = array.new_float(0)
distances = array.new_float(0)
for i = 0 to N-1
float d = math.abs(data[i] - data[i+1])
//-- euclidean will do just as well
// float d = math.sqrt(math.pow(data[i] - data[i+1], 2))
array.push(distances, d)
int size = array.size(distances)
//-- The original logic was too funky, imho :-)
// float new_neighbor = d<array.min(distances, size>K?K:0)?data[i+1]:0
// if new_neighbor > 0
// array.push(nearest_neighbors, new_neighbor)
//-- The following logic reasonably smooths the outcome!
float new_neighbor = d<array.min(distances, size>K?K:0)?data[i+1]:data[i]
array.push(nearest_neighbors, new_neighbor)
nearest_neighbors
predict(neighbors, data) => //-- predict the expected price and calculate next bar's direction
float prediction = array.avg(neighbors)
int direction = prediction < data[ADJ?0:1] ? 1 : prediction > data[ADJ?0:1] ? -1 : 0
[prediction, direction]
green(g) => g>9 ? #006400 : g>8 ? #1A741A : g>7 ? #338333 : g>6 ? #4D934D : g>5 ? #66A266 : g>4 ? #80B280 : g>3 ? #99C199 : g>2 ? #B3D1B3 : g>1? #CCE0CC : #E6F0E6
red(g) => g>9 ? #E00000 : g>8 ? #E31A1A : g>7 ? #E63333 : g>6 ? #E94D4D : g>5 ? #EC6666 : g>4 ? #F08080 : g>3 ? #F39999 : g>2 ? #F6B3B3 : g>1? #F9CCCC : #FCE6E6
ordinary_color(dir) =>
dir==1?green(9):dir==-1?red(9):na
pivot_color(h,l, p, dir) =>
ph = ta.highestbars(h, LAGP)==0 ? h : na
pl = ta.lowestbars(l, LAGP)==0 ? l : na
ph and dir==1 ? green(9) : pl and dir==-1 ? red(9):na
zscore_color(data, p, dir) =>
zs = (data - ta.sma(data, p)) / ta.stdev(data, p) // standardize
zs/(p/5)>0 and dir==1 ? green(9) : zs/(p/5)<0 and dir==-1 ? red(9) : na
//-- Logic
rep = REP?1:0
[O,H,L,C] = request.security('', TF, [open,high[rep],low[rep],close[rep]])
nn = knn(C)
[pred,dir] = predict(nn, C)
clr = ADDON=='Z-Score'?zscore_color(C, LAGZ, dir):ADDON=='Pivot Point'?pivot_color(H,L,LAGP, dir):ordinary_color(dir)
//-- Visuals
//plot(ta.sma(close,20))
plot(DISP=='Curve' or DISP=='Both' ? pred : na, 'kNN Curve', clr, 3, offset=0)
plot(DISP=='Predict' or DISP=='Both' ? ODS : na, 'Prediction', clr, 5, plot.style_circles, offset=2, show_last=1)
|
TNT | https://www.tradingview.com/script/oYpe9ghq-TNT/ | Lazylady | https://www.tradingview.com/u/Lazylady/ | 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/
// © Lazylady
//@version=5
indicator("TNT", overlay = true)
bsp = input(28,title="Body Size Period",group = "Time Periods")
map = input(28,title="Smoothing Period",group = "Time Periods")
bs = ta.sma(math.abs(close - open),bsp)
MA = ta.sma(bs,map)
//plot(bs)
//plot(MA,color=color.red)
trending = color.new(input.color(color.green, title = "Trending", group = "Background Color"),85)
rangebound = color.new(input.color(color.red, title = "Range Bound", group = "Background Color"),85)
sessioncolor = if bs>MA
trending
else
rangebound
bgcolor(sessioncolor) |
STD/C-Filtered, N-Order Power-of-Cosine FIR Filter [Loxx] | https://www.tradingview.com/script/g6voZmXO-STD-C-Filtered-N-Order-Power-of-Cosine-FIR-Filter-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 71 | 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/
// © loxx
//@version=5
indicator("STD/C-Filtered, N-Order Power-of-Cosine FIR Filter [Loxx]",
shorttitle = "STDCFNOPOCFIRF [Loxx]",
overlay = true, max_lines_count = 500)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
//Factorial calcuation
fact(int n)=>
float out = 1
for i = 1 to n
out *= i
out
//-----------------------------------------------/
// Binomial Expansions Using Pascal’s Triangle of
// Power-of-CosineFamily of FIR Digtial Filters
//-----------------------------------------------/
powerOfCosineDesign(int per, int order)=>
// Create alpha0 which equals the prevoius Pascal Traingle
// order's maximum of the left side; that is, the middle
// value of pervious order of the Pascal's triangle
float ppastri = 0
var float[] pastri = array.new<float>(order + 1, 0.)
int pdepth = order - 1
for k = 0 to order / 2 - 1
ppastri := nz(fact(pdepth) / (fact(pdepth - k) * fact(k)), 1)
// Get all values from Pascal's triangle from row = order
// maximum of the left side, that is, the middle
// value of Pascal's triangle
for k = 0 to order
array.set(pastri, k, nz(fact(order) / (fact(order - k) * fact(k)), 1))
// We are only worried about the left side of Pascal values
// slice array to get those values
array<float> outpastri = array.slice(pastri, 0, order / 2)
// Invert array to order numers correctly for kernel calculation
array.reverse(outpastri)
float[] coeffs = array.new<float>(per, 0)
int N = per + 1
for i = 0 to per - 1
int ni = i + 1
float X = ni / N
int sign = -1
float coeff = ppastri
for k = 0 to array.size(outpastri) - 1
coeff += sign * array.get(outpastri, k) * math.cos((k + 1) * 2 * math.pi * X)
sign *= -1
coeff := coeff / (array.sum(outpastri) + ppastri)
array.set(coeffs, i, coeff)
[coeffs, array.sum(coeffs)]
clutterFilt(float src, float threshold)=>
bool out = math.abs(ta.roc(src, 1)) > threshold
out
stdFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * ta.stdev(src, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcoption = input.string("HAB Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(14, "Period", group = "Basic Settings")
type = input.int(2, "Alpha", minval = 2, step = 2, maxval = 50, group = "Basic Settings")
sth = input.float(0, "Clutter Filter Threshold", group = "Basic Settings", step = 0.001)
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group= "UI Options")
showdeadzones = input.bool(false, "Show dead zones?", group= "UI Options")
filterop = input.string("Both", "Filter Options", options = ["Price", "STDCFNOPOCFIRF", "Both", "None"], group= "Filter Settings")
filter = input.float(0, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? stdFilter(src, filterperiod, filter) : src
[coeffs, coeffsSum] = powerOfCosineDesign(per, type)
float dSum = 0
for k = 0 to array.size(coeffs) - 1
dSum += nz(src[k]) * array.get(coeffs, k)
out = coeffsSum != 0 ? dSum / coeffsSum : 0
out := filterop == "Both" or filterop == "STDCFNOPOCFIRF" and filter > 0 ? stdFilter(out, filterperiod, filter) : out
sig = nz(out[1])
filtTrend = clutterFilt(out, sth)
state = filtTrend ? (out > sig ? 1 : out < sig ? -1 : 0) : 0
pregoLong = state == 1
pregoShort =state == -1
contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])
goLong = pregoLong and nz(contsw[1]) == -1
goShort = pregoShort and nz(contsw[1]) == 1
color colorout = na
colorout := filtTrend ? (state == 1 ? greencolor : state == -1 ? redcolor : showdeadzones ? color.gray : colorout[1]) : showdeadzones ? color.gray : colorout[1]
plot(out, "STDCFNOPOCFIRF", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title = "Long", message = "STD/C-Filtered, N-Order Power-of-Cosine FIR Filter [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD/C-Filtered, N-Order Power-of-Cosine FIR Filter [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Day_Week_High_Low | https://www.tradingview.com/script/BJ3siUBA-Day-Week-High-Low/ | sankettatiya | https://www.tradingview.com/u/sankettatiya/ | 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/
// ©sankettatiya My Contact No 8378987574
//@version=5
indicator(title="Day_Week_High_Low", shorttitle="D_W_H_L", overlay=true)
D_High = request.security(syminfo.tickerid, 'D', high[1])
D_Low = request.security(syminfo.tickerid, 'D', low[1])
W_High = request.security(syminfo.tickerid, 'W', high[1])
W_Low = request.security(syminfo.tickerid, 'W', low[1])
plot(D_High, title="Pre.Day High",style=plot.style_line, color=color.rgb(42, 241, 108),linewidth=1)
plot(W_High, title="Pre.Wk High",style=plot.style_line, color=color.rgb(12, 179, 40), linewidth=1)
plot(D_Low, title="Pre.Day Low",style=plot.style_line, color=#ff7a52, linewidth=1)
plot(W_Low, title="Pre.Wk Low",style=plot.style_line, color=color.rgb(124, 8, 70), linewidth=1) |
GAIN MORE GURU 7 EMA | https://www.tradingview.com/script/2hwy3tFI-GAIN-MORE-GURU-7-EMA/ | gurucharanrao | https://www.tradingview.com/u/gurucharanrao/ | 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/
// © gurucharanrao
//@version=5
indicator("GAIN MORE GURU 7 EMA", overlay=true)
Lenthema1 = input.int(title = "EMA1", defval = 7, minval =1, maxval =500)
Lenthema2 = input.int(title = "EMA2", defval = 25, minval =1, maxval =500)
Lenthema3 = input.int(title = "EMA3", defval = 50, minval =1, maxval =500)
Lenthema4 = input.int(title = "EMA4", defval = 99, minval =1, maxval =500)
Lenthema5 = input.int(title = "EMA5", defval = 150, minval =1, maxval =500)
Lenthema6 = input.int(title = "EMA6", defval = 200, minval =1, maxval =500)
Lenthema7 = input.int(title = "EMA7", defval = 300, minval =1, maxval =500)
/// EMA INDICATOR
EMA1 = ta.ema(close,Lenthema1)
EMA2 = ta.ema(close,Lenthema2)
EMA3 = ta.ema(close,Lenthema3)
EMA4 = ta.ema(close,Lenthema4)
EMA5 = ta.ema(close,Lenthema5)
EMA6 = ta.ema(close,Lenthema6)
EMA7 = ta.ema(close,Lenthema7)
/// PLOT
plot(EMA1, color = color.new(color.green,1))
plot(EMA2, color = color.new(color.orange,2))
plot(EMA3, color = color.new(color.silver,3))
plot(EMA4, color = color.new(color.fuchsia,4))
plot(EMA5, color = color.new(color.maroon,5))
plot(EMA6, color = color.new(color.blue,6))
plot(EMA7, color = color.new(color.red,7))
|
double Bollinger Bands | https://www.tradingview.com/script/ZV5q9Mq1-double-Bollinger-Bands/ | alixnet | https://www.tradingview.com/u/alixnet/ | 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/
// © alixnet
//@version=5
indicator(shorttitle="2BB", title="double Bollinger Bands", overlay=true, timeframe="", timeframe_gaps=true)
length = input.int(20, minval=1)
src = input(close, title="Source")
mult = input.float(1.0, minval=0.001, maxval=50, title="StdDev 1")
mult2 = input.float(2.0, minval=0.001, maxval=50, title="StdDev 2")
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
dev2 = mult2 * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
upper2 = basis + dev2
lower2 = basis - dev2
offset = input.int(0, "Offset", minval = -500, maxval = 500)
plot(basis, "Basis", color=#FF6D00, offset = offset)
p1 = plot(upper, "Upper", color=#2962FF, offset = offset)
p2 = plot(lower, "Lower", color=#2962FF, offset = offset)
p3 = plot(upper2, "Upper", color=#2453d4, offset = offset)
p4 = plot(lower2, "Lower", color=#2453d4, offset = offset)
fill(p1, p3, title = "Background", color=color.rgb(33, 150, 243, 85))
fill(p2, p4, title = "Background", color=color.rgb(33, 150, 243, 85))
|
Stablecoin Dominance (USDT, USDC & BUSD) Credits to lysergik | https://www.tradingview.com/script/ms8z0sfg-Stablecoin-Dominance-USDT-USDC-BUSD-Credits-to-lysergik/ | itzvenom95 | https://www.tradingview.com/u/itzvenom95/ | 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/
// © lysergik
//@version=5
indicator(title="Aggregated Stablecoin Dominance",
shorttitle="AggrStableDom", format=format.percent, precision=3)
// data sources \\
usdt = request.security('USDT.D', timeframe.period, close)
usdc = request.security('USDC.D', timeframe.period, close)
busd = request.security('(BUSD_MARKETCAP*100)/CRYPTOCAP:TOTAL', timeframe.period, close)
usdt_o = request.security('USDT.D', timeframe.period, open)
usdc_o = request.security('USDC.D', timeframe.period, open)
busd_o = request.security('(BUSD_MARKETCAP*100)/CRYPTOCAP:TOTAL', timeframe.period, open)
usdt_h = request.security('USDT.D', timeframe.period, high)
usdc_h = request.security('USDC.D', timeframe.period, high)
busd_h = request.security('(BUSD_MARKETCAP*100)/CRYPTOCAP:TOTAL', timeframe.period, high)
usdt_l = request.security('USDT.D', timeframe.period, low)
usdc_l = request.security('USDC.D', timeframe.period, low)
busd_l = request.security('(BUSD_MARKETCAP*100)/CRYPTOCAP:TOTAL', timeframe.period, low)
// inputs \\
use_candles = input.bool(false, 'Use Candles Instead', group='Total Dominance')
heikin = input.bool(true, 'Heikin Candles', group='Total Dominance')
use_fma = input.bool(true, 'Show Fast Moving Average', group='Moving Averages')
use_sma = input.bool(true, 'Show Slow Moving Average', group='Moving Averages')
predict_ema = input.bool(true, 'Show MA Prediction', group='Moving Averages')
f_length = input.int(21, 'Fast MA Length', minval=2, group='Moving Averages')
s_length = input.int(50, 'Slow MA Length', minval=2, group='Moving Averages')
ema = input.bool(true, 'Use EMA instead of SMA', group='Moving Averages')
col = input.bool(true, 'Color MAs to Reflect the Trend', group='Color')
colInvert = input.bool(false, 'Invert MA Coloring', group='Color')
bb = input.bool(false, 'Use Bollinger Bands', group='Bollinger Bands')
bb_sig = input.bool(false, 'Show Bollinger Bands Multi-Signals (beta)', group='Bollinger Bands')
length = input.int(21, minval=1, group='Bollinger Bands')
mult = input.float(2.618, minval=0.001, maxval=50, group='Bollinger Bands')
// math \\
totalDom = usdt + usdc + busd
totalDom_o = usdt_o + usdc_o + busd_o
totalDom_h = usdt_h + usdc_h + busd_h
totalDom_l = usdt_l + usdc_l + busd_l
// === CANDLES ===
src(_src) =>
Close = not heikin ? totalDom : math.avg(totalDom_o, totalDom_h, totalDom_l, totalDom)
Open = float(na)
Open := not heikin ? totalDom_o : na(Open[1]) ? (totalDom_o + totalDom) / 2 : (nz(Open[1]) + nz(Close[1])) / 2
High = not heikin ? totalDom_h : math.max(totalDom_h, math.max(Open, Close))
Low = not heikin ? totalDom_l : math.min(totalDom_l, math.min(Open, Close))
HL2 = not heikin ? math.avg(totalDom_l, totalDom_h) : math.avg(High, Low)
HLC3 = not heikin ? math.avg(totalDom_l, totalDom_h, totalDom) : math.avg(High, Low, Close)
OHLC4 = not heikin ? math.avg(totalDom_o, totalDom_h, totalDom_l, totalDom) : math.avg(Open, High, Low, Close)
Price = _src == 'close' ? Close : _src == 'open' ? Open : _src == 'high' ? High : _src == 'low' ? Low : _src == 'hl2' ? HL2 : _src == 'hlc3' ? HLC3 : OHLC4
Source = math.round(Price / syminfo.mintick) * syminfo.mintick // PineCoders method for aligning Pine prices with chart instrument prices
src = math.avg(totalDom_h,totalDom_l,totalDom)
basis = ta.vwma(src, length)
dev = mult * ta.stdev(src, length)
upper_1= basis + (0.236*dev)
upper_2= basis + (0.382*dev)
upper_3= basis + (0.5*dev)
upper_4= basis + (0.618*dev)
upper_5= basis + (0.764*dev)
upper_6= basis + (1*dev)
lower_1= basis - (0.236*dev)
lower_2= basis - (0.382*dev)
lower_3= basis - (0.5*dev)
lower_4= basis - (0.618*dev)
lower_5= basis - (0.764*dev)
lower_6= basis - (1*dev)
fMA = 0.00
sMA = 0.00
string predict_type = "EMA"
if ema
fMA := ta.ema(totalDom, f_length)
sMA := ta.ema(totalDom, s_length)
predict_type := "EMA"
else
fMA := ta.sma(totalDom, f_length)
sMA := ta.sma(totalDom, s_length)
predict_type := "SMA"
ma(_type, _src, _len) =>
if _type == "EMA"
ta.ema(_src, _len)
else if _type == "SMA"
ta.sma(_src, _len)
ma_prediction(_type, _src, _period, _offset) => (ma(_type, _src, _period - _offset) * (_period - _offset) + _src * _offset) / _period
longemapredictor_1 = ma_prediction(predict_type, totalDom, s_length, 1)
longemapredictor_2 = ma_prediction(predict_type, totalDom, s_length, 2)
longemapredictor_3 = ma_prediction(predict_type, totalDom, s_length, 3)
longemapredictor_4 = ma_prediction(predict_type, totalDom, s_length, 4)
longemapredictor_5 = ma_prediction(predict_type, totalDom, s_length, 5)
shortemapredictor_1 = ma_prediction(predict_type, totalDom, f_length, 1)
shortemapredictor_2 = ma_prediction(predict_type, totalDom, f_length, 2)
shortemapredictor_3 = ma_prediction(predict_type, totalDom, f_length, 3)
shortemapredictor_4 = ma_prediction(predict_type, totalDom, f_length, 4)
shortemapredictor_5 = ma_prediction(predict_type, totalDom, f_length, 5)
// logic \\
isBullish = totalDom <= fMA ? true : false
slowIsBelow = sMA < fMA ? true : false
isBelow(_v2, _v1) =>
out = false
if _v1 > _v2
out := true
BB_bullCross = (ta.crossunder(src,upper_6)) or (ta.crossover(src, lower_4) or ta.crossunder(src, basis)) ? true : false
BB_bearCross = (ta.crossover(src,lower_6)) or (ta.crossunder(src, upper_4) or ta.crossover(src, basis)) ? true : false
// front-end \\
f_plot = plot(use_fma ? fMA : na, 'Fast Moving Average', color=col ? color.black : color.blue, linewidth=2)
s_plot = plot(use_sma ? sMA : na, 'Slow Moving Average', color=color.white, linewidth=2)
dom_plot = plot(totalDom, 'Combined Dominance', color=use_candles ? na : color.white, trackprice=true)
barColor = not use_candles ? na : src('close') >= src('open') ? color.purple : color.teal
plotcandle(src('open'), src('high'), src('low'), src('close'),
'Candles', color=barColor, wickcolor=not use_candles ? na : color.new(color.white, 50), bordercolor=na)
color fastCol =
not colInvert ? (isBullish and col ? color.rgb(0,255,0,70) : not isBullish and col ? color.rgb(255,0,0,70) : na) :
(isBullish and col ? color.rgb(255,0,0,70) : not isBullish and col ? color.rgb(0,255,0,70) : na)
color slowCol =
not colInvert ? (slowIsBelow and col ? color.new(color.purple,75) : not slowIsBelow and col ? color.new(color.aqua,75) : na) :
(slowIsBelow and col ? color.new(color.aqua,75) : not slowIsBelow and col ? color.new(color.purple,75) : na)
fill(dom_plot, f_plot, color=fastCol)
fill(f_plot, s_plot, color=slowCol)
plot(usdt, 'USDT Dominance', color=color.aqua, display=display.none)
plot(usdc, 'USDC Dominance', color=color.purple, display=display.none)
plot(busd, 'BUSD Dominance', color=color.yellow, display=display.none)
plot(bb ? basis : na, color=color.white, linewidth=2, style=plot.style_stepline)
p1 = plot(bb ? upper_1 : na, color=color.white, linewidth=1, title="0.236", display=display.none)
p2 = plot(bb ? upper_2 : na, color=color.aqua, linewidth=1, title="0.382", display=display.none)
p3 = plot(bb ? upper_3 : na, color=color.white, linewidth=1, title="0.5", display=display.none)
p4 = plot(bb ? upper_4 : na, color=color.orange, linewidth=1, title="0.618")
p5 = plot(bb ? upper_5 : na, color=color.white, linewidth=1, title="0.764", display=display.none)
p6 = plot(bb ? upper_6 : na, color=color.gray, linewidth=2, title="1")
p13 = plot(bb ? lower_1 : na, color=color.white, linewidth=1, title="0.236", display=display.none)
p14 = plot(bb ? lower_2 : na, color=color.aqua, linewidth=1, title="0.382", display=display.none)
p15 = plot(bb ? lower_3 : na, color=color.white, linewidth=1, title="0.5", display=display.none)
p16 = plot(bb ? lower_4 : na, color=color.orange, linewidth=1, title="0.618")
p17 = plot(bb ? lower_5 : na, color=color.white, linewidth=1, title="0.764", display=display.none)
p18 = plot(bb ? lower_6 : na, color=color.gray, linewidth=2, title="1")
plot(predict_ema and use_sma ? longemapredictor_1 : na, color=isBelow(shortemapredictor_1, longemapredictor_1) ? color.white : color.gray,
linewidth=2, style=plot.style_cross, offset=1, show_last=1, editable=false)
plot(predict_ema and use_sma ? longemapredictor_2 : na, color=isBelow(shortemapredictor_2, longemapredictor_2) ? color.white : color.gray,
linewidth=2, style=plot.style_cross, offset=2, show_last=1, editable=false)
plot(predict_ema and use_sma ? longemapredictor_3 : na, color=isBelow(shortemapredictor_3, longemapredictor_3) ? color.white : color.gray,
linewidth=2, style=plot.style_cross, offset=3, show_last=1, editable=false)
plot(predict_ema and use_sma ? longemapredictor_4 : na, color=isBelow(shortemapredictor_4, longemapredictor_4) ? color.white : color.gray,
linewidth=2, style=plot.style_cross, offset=4, show_last=1, editable=false)
plot(predict_ema and use_sma ? longemapredictor_5 : na, color=isBelow(shortemapredictor_5, longemapredictor_5) ? color.white : color.gray,
linewidth=2, style=plot.style_cross, offset=5, show_last=1, editable=false)
plot(predict_ema and use_fma ? shortemapredictor_1 : na, color=isBelow(shortemapredictor_1, longemapredictor_1) ? color.aqua : color.purple,
linewidth=2, style=plot.style_cross, offset=1, show_last=1, editable=false)
plot(predict_ema and use_fma ? shortemapredictor_2 : na, color=isBelow(shortemapredictor_2, longemapredictor_2) ? color.aqua : color.purple,
linewidth=2, style=plot.style_cross, offset=2, show_last=1, editable=false)
plot(predict_ema and use_fma ? shortemapredictor_3 : na, color=isBelow(shortemapredictor_3, longemapredictor_3) ? color.aqua : color.purple,
linewidth=2, style=plot.style_cross, offset=3, show_last=1, editable=false)
plot(predict_ema and use_fma ? shortemapredictor_4 : na, color=isBelow(shortemapredictor_4, longemapredictor_4) ? color.aqua : color.purple,
linewidth=2, style=plot.style_cross, offset=4, show_last=1, editable=false)
plot(predict_ema and use_fma ? shortemapredictor_5 : na, color=isBelow(shortemapredictor_5, longemapredictor_5) ? color.aqua : color.purple,
linewidth=2, style=plot.style_cross, offset=5, show_last=1, editable=false)
var line realLine = na
varip lineVis = false
if use_candles and
((lineVis == false and not barstate.isconfirmed) or
(barstate.isrealtime and barstate.islast and not barstate.isconfirmed))
line.delete(id=realLine)
realLine := line.new(x1=bar_index[1], y1=totalDom, x2=bar_index, y2=totalDom, width=1, extend=extend.both)
line.set_color(id=realLine, color=totalDom > totalDom_o ? color.purple : totalDom < totalDom_o ? color.teal : color.white)
line.set_style(id=realLine, style=line.style_dashed)
if barstate.isconfirmed
line.delete(id=realLine)
lineVis := false
// Table
var table TA_Display = table.new(position.bottom_right, 14, 4)
if barstate.islast
table.cell(TA_Display, 0, 0, 'TOTAL', text_color=color.white, text_size=size.auto, bgcolor=color.black)
table.cell(TA_Display, 1, 0, str.format('{0}%', totalDom), text_color=ta.change(totalDom) > 0 ? color.red : color.green, text_size=size.auto, bgcolor=color.black)
table.cell(TA_Display, 0, 1, 'USDT', text_color=color.white, text_size=size.auto, bgcolor=color.black)
table.cell(TA_Display, 1, 1, str.format('{0}%', usdt), text_color=ta.change(usdt) > 0 ? color.red : color.green, text_size=size.auto, bgcolor=color.black)
table.cell(TA_Display, 0, 2, 'USDC', text_color=color.white, text_size=size.auto, bgcolor=color.black)
table.cell(TA_Display, 1, 2, str.format('{0}%', usdc), text_color=ta.change(usdc) > 0 ? color.red : color.green, text_size=size.auto, bgcolor=color.black)
table.cell(TA_Display, 0, 3, 'BUSD', text_color=color.white, text_size=size.auto, bgcolor=color.black)
table.cell(TA_Display, 1, 3, str.format('{0}%', busd), text_color=ta.change(busd) > 0 ? color.red : color.green, text_size=size.auto, bgcolor=color.black)
// Signals
plotshape(BB_bullCross and bb_sig ? upper_6 : na, 'BB Bull Cross', style=shape.xcross,
color=color.lime, location=location.absolute, size=size.tiny)
plotshape(BB_bearCross and bb_sig ? lower_6 : na, 'BB Bear Cross', style=shape.xcross,
color=color.red, location=location.absolute, size=size.tiny) |
ATR Trend Bands [Misu] | https://www.tradingview.com/script/PtnKi3nX-ATR-Trend-Bands-Misu/ | Fontiramisu | https://www.tradingview.com/u/Fontiramisu/ | 1,253 | 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/
// ©Misu
//@version=5
indicator("ATR Trend Bands [Misu]", overlay = true, shorttitle="ATR TB [Misu]")//, initial_capital=50000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// import Fontiramisu/fontLib/86 as fontilab
import Fontiramisu/fontilab/11 as fontilab
// ] -------- Input --------------- [
src = input.source(close, "Source", group="Settings")
len = input.int(5, "Length Atr", group = "Settings")
mult = input.float(7.6, "Multiplier Atr", step = 0.1, group = "Settings")
colorbars = input.bool(true, "Color Bars", group = "UI Settings")
showlmidbs = input.bool(true, "Show Label", group = "UI Settings")
// ] -------- Vars --------------- [
// Cond Vars.
// _bodyHi = math.max(close, open)
// _bodyLo = math.min(close, open)
// _body = _bodyHi - _bodyLo
// _bodyAvg = ta.ema(_body, len)
// ] -------- Logic ----------------- [
deltaAtr = mult * ta.atr(len)
[midb, upperb, lowerb] = fontilab.getTrendBands(src, deltaAtr)
trendUp = midb > nz(midb[1])
trendDown = midb < nz(midb[1])
lastState = 0
lastState := nz(lastState[1])
lastState := trendUp ? 1 : trendDown ? -1 : nz(lastState[1])
buyCond = trendUp and nz(lastState[1]) == -1
sellCond = trendDown and nz(lastState[1]) == 1
// ] -------- Strategy Part ------------ [
// if buyCond
// strategy.entry("L", strategy.long, alert_message="Buy Signal")
// if sellCond
// strategy.entry("S", strategy.short, alert_message="Sell Signal")
// ] -------- Plot Part --------------- [
var color colorTrend = na
colorTrend := midb < nz(midb[1]) ? color.red : midb > nz(midb[1]) ? color.green : nz(colorTrend[1])
barcolor(colorbars ? colorTrend : na)
plot(upperb, "Upper Band", color = colorTrend, linewidth = 2)
plot(lowerb, "Lower Band", color = colorTrend, linewidth = 2)
if showlmidbs and buyCond
label.new(x = bar_index, y = low - (ta.atr(30) * 0.3), xloc = xloc.bar_index, text = "L", style = label.style_label_up, color = color.green, size = size.small, textcolor = color.white, textalign = text.align_center)
else if showlmidbs and sellCond
label.new(x = bar_index, y = high + (ta.atr(30) * 0.3), xloc = xloc.bar_index, text = "S", style = label.style_label_down, color = color.red, size = size.small, textcolor = color.white, textalign = text.align_center)
// ] -------- Alerts ----------------- [
alertcondition(buyCond, title = "Long", message = "ATR Trend Bands [Misu]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(sellCond, title = "Short", message = "ATR Trend Bands [Misu]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
// ]
|
SuperTrend Momentum Chart | https://www.tradingview.com/script/IFe7NHnf-SuperTrend-Momentum-Chart/ | VonnyFX | https://www.tradingview.com/u/VonnyFX/ | 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/
// © VonnyFX
//@version=5
indicator("SuperTrend Momentum Chart", shorttitle="SuperTrend Momentum Chart", max_bars_back=5000, overlay=true)
// User inputs
factor = input.float(1, "Factor", step = 0.05, group="Smart Momentum", inline="x")
atrLength = input.int(2, "ATR Length", step = 1, group="Smart Momentum", inline="x")
timeFrameAmount = input.int(title= "Amount of Time Frames", defval=8, group="Higher Time Frame Inputs", minval=0, maxval=8)
res = input.timeframe(title= "TimeFrame #1", defval="3", group="Higher Time Frame Inputs", inline="x")
res2 = input.timeframe(title= "TimeFrame #2", defval="5", group="Higher Time Frame Inputs", inline="x")
res3 = input.timeframe(title= "TimeFrame #3", defval="15", group="Higher Time Frame Inputs", inline="x")
res4 = input.timeframe(title= "TimeFrame #4", defval="60", group="Higher Time Frame Inputs", inline="x")
res5 = input.timeframe(title= "TimeFrame #5", defval="240", group="Higher Time Frame Inputs", inline="x")
res6 = input.timeframe(title= "TimeFrame #6", defval="1D", group="Higher Time Frame Inputs", inline="x")
res7 = input.timeframe(title= "TimeFrame #7", defval="1W", group="Higher Time Frame Inputs", inline="x")
res8 = input.timeframe(title= "TimeFrame #8", defval="1M", group="Higher Time Frame Inputs", inline="x")
textColor = input.color(title="HTF Text Color", defval=#000000, group="Display Inputs" , inline="y")
textSizex = input.string(title="Text Size", group="Display Inputs", inline="y", defval="Normal", options=["Tiny", "Small", "Normal", "Large", "Huge"])
momentumSwitch = input.bool(true, title="[Momentum Switch]", inline="y", group="Display Inputs")
bullColor = input.color(title="Bullish Color", defval=#22ad23, group="Display Inputs" , inline="b")
bullSwitchColor = input.color(title="Bullish Switch Color", defval=#ffe900, group="Display Inputs" , inline="b")
bearColor = input.color(title="Bearish Color", defval=#e10000, group="Display Inputs" , inline="s")
bearSwitchColor = input.color(title="Bearish Switch Color", defval=#0006ff, group="Display Inputs" , inline="s")
chartPositionx = input.string(title="Chart Position",group="Display Inputs", defval="Top Right",
options=["Top Right", "Top Center", "Top Left", "Middle Right", "Middle Center", "Middle Left", "Bottom Right", "Bottom Center", "Bottom Left"])
// Dynamic TimeFrame Text change
timeFrameText = (res == "1" ? res +"m": res == "3" ? res +"m": res == "5" ? res +"m": res == "15" ? res +"m": res == "30" ? res +"m": res == "45" ? res +"m":
res == "60" ? " 1" +"H ": res == "120" ? " 2" +"H ": res == "180" ? " 3" +"H ": res == "240" ? " 4" +"H ":
res == "1D" ? " D ": res == "3D" ? " 3D ": res == "1W" ? " W ": res == "2W" ? " 2W ": res == "1M" ? " M ": res == "2M" ? " 2M ": res == "3M" ? " 3M ": res == "6M" ? " 6M ": res == "12M" ? " 12M ": res == "30" ? "30": "30s")
transparent = timeFrameAmount >= 1 ? 0 : 100
//--------------------------------------------------------------------------
timeFrameText2 = (res2 == "1" ? res2 +"m": res2 == "3" ? res2 +"m": res2 == "5" ? res2 +"m": res2 == "15" ? res2 +"m": res2 == "30" ? res2 +"m": res2 == "45" ? res2 +"m":
res2 == "60" ? " 1" +"H ": res2 == "120" ? " 2" +"H ": res2 == "180" ? " 3" +"H ": res2 == "240" ? " 4" +"H ":
res2 == "1D" ? " D ": res2 == "3D" ? " 3D ": res2 == "1W" ? " W ": res2 == "2W" ? " 2W ": res2 == "1M" ? " M ": res2 == "2M" ? " 2M ": res2 == "3M" ? " 3M ": res2 == "6M" ? " 6M ": res2 == "12M" ? " 12M ": res == "30S" ? " 30S ": na)
transparent2 = timeFrameAmount >= 2 ? 0 : 100
//--------------------------------------------------------------------------
timeFrameText3 = (res3 == "1" ? res3 +"m": res3 == "3" ? res3 +"m": res3 == "5" ? res3 +"m": res3 == "15" ? res3 +"m": res3 == "30" ? res3 +"m": res3 == "45" ? res3 +"m":
res3 == "60" ? " 1" +"H ": res3 == "120" ? " 2" +"H ": res3 == "180" ? " 3" +"H ": res3 == "240" ? " 4" +"H ":
res3 == "1D" ? " D ": res3 == "3D" ? " 3D ": res3 == "1W" ? " W ": res3 == "2W" ? " 2W ": res3 == "1M" ? " M ": res3 == "2M" ? " 2M ": res3 == "3M" ? " 3M ": res3 == "6M" ? " 6M ": res3 == "12M" ? " 12M ": res == "30S" ? " 30S ": na)
transparent3 = timeFrameAmount >= 3 ? 0 : 100
//--------------------------------------------------------------------------
timeFrameText4 = (res4 == "1" ? res4 +"m": res4 == "3" ? res4 +"m": res4 == "5" ? res4 +"m": res4 == "15" ? res4 +"m": res4 == "30" ? res4 +"m": res4 == "45" ? res4 +"m":
res4 == "60" ? " 1" +"H ": res4 == "120" ? " 2" +"H ": res4 == "180" ? " 3" +"H ": res4 == "240" ? " 4" +"H ":
res4 == "1D" ? " D ": res4 == "3D" ? " 3D ": res4 == "1W" ? " W ": res4 == "2W" ? " 2W ": res4 == "1M" ? " M ": res4 == "2M" ? " 2M ": res4 == "3M" ? " 3M ": res4 == "6M" ? " 6M ": res4 == "12M" ? " 12M ": res == "30S" ? " 30S ": na)
transparent4 = timeFrameAmount >= 4 ? 0 : 100
//--------------------------------------------------------------------------
timeFrameText5 = (res5 == "1" ? res5 +"m": res5 == "3" ? res5 +"m": res5 == "5" ? res5 +"m": res5 == "15" ? res5 +"m": res5 == "30" ? res5 +"m": res5 == "45" ? res5 +"m":
res5 == "60" ? " 1" +"H ": res5 == "120" ? " 2" +"H ": res5 == "180" ? " 3" +"H ": res5 == "240" ? " 4" +"H ":
res5 == "1D" ? " D ": res5 == "3D" ? " 3D ": res5 == "1W" ? " W ": res5 == "2W" ? " 2W ": res5 == "1M" ? " M ": res5 == "2M" ? " 2M ": res5 == "3M" ? " 3M ": res5 == "6M" ? " 6M ": res5 == "12M" ? " 12M ": res == "30S" ? " 30S ": na)
transparent5 = timeFrameAmount >= 5 ? 0 : 100
//--------------------------------------------------------------------------
timeFrameText6 = (res6 == "1" ? res6 +"m": res6 == "3" ? res6 +"m": res6 == "5" ? res6 +"m": res6 == "15" ? res6 +"m": res6 == "30" ? res6 +"m": res6 == "45" ? res6 +"m":
res6 == "60" ? " 1" +"H ": res6 == "120" ? " 2" +"H ": res6 == "180" ? " 3" +"H ": res6 == "240" ? " 4" +"H ":
res6 == "1D" ? " D ": res6 == "3D" ? " 3D ": res6 == "1W" ? " W ": res6 == "2W" ? " 2W ": res6 == "1M" ? " M ": res6 == "2M" ? " 2M ": res6 == "3M" ? " 3M ": res6 == "6M" ? " 6M ": res6 == "12M" ? " 12M ": res == "30S" ? " 30S ": na)
transparent6 = timeFrameAmount >= 6 ? 0 : 100
//--------------------------------------------------------------------------
timeFrameText7 = (res7 == "1" ? res7 +"m": res7 == "3" ? res7 +"m": res7 == "5" ? res7 +"m": res7 == "15" ? res7 +"m": res7 == "30" ? res7 +"m": res7 == "45" ? res7 +"m":
res7 == "60" ? " 1" +"H ": res7 == "120" ? " 2" +"H ": res7 == "180" ? " 3" +"H ": res7 == "240" ? " 4" +"H ":
res7 == "1D" ? " D ": res7 == "3D" ? " 3D ": res7 == "1W" ? " W ": res7 == "2W" ? " 2W ": res7 == "1M" ? " M ": res7 == "2M" ? " 2M ": res7 == "3M" ? " 3M ": res7 == "6M" ? " 6M ": res7 == "12M" ? " 12M ": res == "30S" ? " 30S ": na)
transparent7 = timeFrameAmount >= 7 ? 0 : 100
//--------------------------------------------------------------------------
timeFrameText8 = (res8 == "1" ? res8 +"m": res8 == "3" ? res8 +"m": res8 == "5" ? res8 +"m": res8 == "15" ? res8 +"m": res8 == "30" ? res8 +"m": res8 == "45" ? res8 +"m":
res8 == "60" ? " 1" +"H ": res8 == "120" ? " 2" +"H ": res8 == "180" ? " 3" +"H ": res8 == "240" ? " 4" +"H ":
res8 == "1D" ? " D ": res8 == "3D" ? " 3D ": res8 == "1W" ? " W ": res8 == "2W" ? " 2W ": res8 == "1M" ? " M ": res8 == "2M" ? " 2M ": res8 == "3M" ? " 3M ": res8 == "6M" ? " 6M ": res8 == "12M" ? " 12M ": res == "30S" ? " 30S ": na)
transparent8 = timeFrameAmount >= 8 ? 0 : 100
//--------------------------------------------------------------------------
// Dynamic Table Position using user input string
var chartPosition = position.top_right
if chartPositionx == "Top Right"
chartPosition := position.top_right
if chartPositionx == "Top Center"
chartPosition := position.top_center
if chartPositionx == "Top Left"
chartPosition := position.top_left
if chartPositionx == "Middle Right"
chartPosition := position.middle_right
if chartPositionx == "Middle Center"
chartPosition := position.middle_center
if chartPositionx == "Middle Left"
chartPosition := position.middle_left
if chartPositionx == "Bottom Right"
chartPosition := position.bottom_right
if chartPositionx == "Bottom Center"
chartPosition := position.bottom_center
if chartPositionx == "Bottom Left"
chartPosition := position.bottom_left
//--------------------------------------------------------------------------
// Dynamic Table Position using user input string
var textSize = size.tiny
if textSizex == "Tiny"
textSize := size.tiny
if textSizex == "Small"
textSize := size.small
if textSizex == "Normal"
textSize := size.normal
if textSizex == "Large"
textSize := size.large
if textSizex == "Huge"
textSize := size.huge
//--------------------------------------------------------------------------
//Wait for candle to close before you show signal or change in realtime
closeRrealtime = true
barState = (closeRrealtime == true) ? barstate.isconfirmed : barstate.isrealtime
// Get SuperTrend Values
[supertrend, direction] = ta.supertrend(factor, atrLength)
// Get Higher time Frame and insert SuperTrend
htfSuperTrend = request.security(syminfo.tickerid, res, supertrend[barState ? 0 : 1])
htfSuperTrend2 = request.security(syminfo.tickerid, res2, supertrend[barState ? 0 : 1])
htfSuperTrend3 = request.security(syminfo.tickerid, res3, supertrend[barState ? 0 : 1])
htfSuperTrend4 = request.security(syminfo.tickerid, res4, supertrend[barState ? 0 : 1])
htfSuperTrend5 = request.security(syminfo.tickerid, res5, supertrend[barState ? 0 : 1])
htfSuperTrend6 = request.security(syminfo.tickerid, res6, supertrend[barState ? 0 : 1])
htfSuperTrend7 = request.security(syminfo.tickerid, res7, supertrend[barState ? 0 : 1])
htfSuperTrend8 = request.security(syminfo.tickerid, res8, supertrend[barState ? 0 : 1])
htfClose = request.security(syminfo.tickerid, res, close[barState ? 0 : 1])
htfClose2 = request.security(syminfo.tickerid, res2, close[barState ? 0 : 1])
htfClose3 = request.security(syminfo.tickerid, res3, close[barState ? 0 : 1])
htfClose4 = request.security(syminfo.tickerid, res4, close[barState ? 0 : 1])
htfClose5 = request.security(syminfo.tickerid, res5, close[barState ? 0 : 1])
htfClose6 = request.security(syminfo.tickerid, res6, close[barState ? 0 : 1])
htfClose7 = request.security(syminfo.tickerid, res7, close[barState ? 0 : 1])
htfClose8 = request.security(syminfo.tickerid, res8, close[barState ? 0 : 1])
//Prepare a table
var table myHTFTable = table.new(chartPosition, 2, 4, border_width=1)
//Draw table
if barState
table.cell(myHTFTable, column = 0, row = 0 ,text=timeFrameText, text_size=textSize, text_color=textColor,
bgcolor= htfClose > htfSuperTrend and htfClose[1] < htfSuperTrend[1] and momentumSwitch ? color.new(bullSwitchColor,transparent) : htfClose < htfSuperTrend and htfClose[1] > htfSuperTrend[1] and momentumSwitch ? color.new(bearSwitchColor,transparent) :
htfClose > htfSuperTrend ? color.new(bullColor,transparent) : color.new(bearColor,transparent))
table.cell(myHTFTable, column = 0, row = 1 ,text=timeFrameText3, text_size=textSize, text_color=textColor,
bgcolor= htfClose3 > htfSuperTrend3 and htfClose3[1] < htfSuperTrend3[1] and momentumSwitch ? color.new(bullSwitchColor,transparent3) : htfClose3 < htfSuperTrend3 and htfClose3[1] > htfSuperTrend3[1] and momentumSwitch ? color.new(bearSwitchColor,transparent3) :
htfClose3 > htfSuperTrend3 ? color.new(bullColor,transparent3) :color.new(bearColor,transparent3))
table.cell(myHTFTable, column = 0, row = 2 ,text=timeFrameText5, text_size=textSize, text_color=textColor,
bgcolor= htfClose5 > htfSuperTrend5 and htfClose5[1] < htfSuperTrend5[1] and momentumSwitch ? color.new(bullSwitchColor,transparent5) : htfClose2 < htfSuperTrend5 and htfClose5[1] > htfSuperTrend5[1] and momentumSwitch ? color.new(bearSwitchColor,transparent5) :
htfClose5 > htfSuperTrend5 ? color.new(bullColor,transparent5) : color.new(bearColor,transparent5))
table.cell(myHTFTable, column = 0, row = 3 ,text=timeFrameText7, text_size=textSize, text_color=textColor,
bgcolor= htfClose7 > htfSuperTrend7 and htfClose7[1] < htfSuperTrend7[1] and momentumSwitch ? color.new(bullSwitchColor,transparent7) : htfClose7 < htfSuperTrend7 and htfClose7[1] > htfSuperTrend7[1] and momentumSwitch ? color.new(bearSwitchColor,transparent7) :
htfClose7 > htfSuperTrend7 ? color.new(bullColor,transparent7) : color.new(bearColor,transparent7))
if barState
table.cell(myHTFTable, column = 1, row = 0 ,text=timeFrameText2, text_size=textSize, text_color=textColor,
bgcolor= htfClose2 > htfSuperTrend2 and htfClose2[1] < htfSuperTrend2[1] and momentumSwitch ? color.new(bullSwitchColor,transparent2) : htfClose2 < htfSuperTrend2 and htfClose2[1] > htfSuperTrend2[1] and momentumSwitch ? color.new(bearSwitchColor,transparent2) :
htfClose2 > htfSuperTrend2 ? color.new(bullColor,transparent2) : color.new(bearColor,transparent2))
table.cell(myHTFTable, column = 1, row = 1 ,text=timeFrameText4, text_size=textSize, text_color=textColor,
bgcolor=htfClose4 > htfSuperTrend4 and htfClose4[1] < htfSuperTrend4[1] and momentumSwitch ? color.new(bullSwitchColor,transparent4) : htfClose4 < htfSuperTrend4 and htfClose4[1] > htfSuperTrend4[1] and momentumSwitch ? color.new(bearSwitchColor,transparent4) :
htfClose4 > htfSuperTrend4 ? color.new(bullColor,transparent4) : color.new(bearColor,transparent4))
table.cell(myHTFTable, column = 1, row = 2 ,text=timeFrameText6, text_size=textSize, text_color=textColor,
bgcolor= htfClose6 > htfSuperTrend6 and htfClose6[1] < htfSuperTrend6[1] and momentumSwitch ? color.new(bullSwitchColor,transparent6) : htfClose6 < htfSuperTrend6 and htfClose6[1] > htfSuperTrend6[1] and momentumSwitch ? color.new(bearSwitchColor,transparent6) :
htfClose6 > htfSuperTrend6 ? color.new(bullColor,transparent6) : color.new(bearColor,transparent6))
table.cell(myHTFTable, column = 1, row = 3 ,text=timeFrameText8, text_size=textSize, text_color=textColor,
bgcolor= htfClose8 > htfSuperTrend8 and htfClose8[1] < htfSuperTrend8[1] and momentumSwitch ? color.new(bullSwitchColor,transparent8) : htfClose8 < htfSuperTrend8 and htfClose8[1] > htfSuperTrend8[1] and momentumSwitch ? color.new(bearSwitchColor,transparent8) :
htfClose8 > htfSuperTrend8 ? color.new(bullColor,transparent8) : color.new(bearColor,transparent8))
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.