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
|
---|---|---|---|---|---|---|---|---|
mentfx Triple M | https://www.tradingview.com/script/5LgKUJl7-mentfx-Triple-M/ | mentfx50 | https://www.tradingview.com/u/mentfx50/ | 287 | 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/
// © mentfx050
//@version=4
study("mentfx Triple M","mentfx Triple M", overlay = true, max_lines_count = 500)
showhigh = input(true, title = "--------Show High wick--------", inline = "0")
showlow = input(true, title = "--------Show Low wick--------", inline = "0")
linewidth1 = input(3, "High wick linewidth", inline = "witdth")
linewidth2 = input(3, "Low wick linewidth", inline = "witdth")
linecolor1 = input(color.red, "High wick Color", inline = "line color")
linecolor2 = input(color.green, "Low wick Color", inline = "line color")
Highwick = high > high[1] and close < high[1]
Lowwick = low < low[1] and close > low[1]
Highwickbar = 0, Lowwickbar = 0
Highwickhigh = 0.0, Lowwicklow = 0.0
Highbody = 0.0, Lowbody = 0.0
Highwickbar := valuewhen(Highwick, bar_index, 0)
Highwickhigh := valuewhen(Highwick, high, 0)
Highbody := valuewhen(Highwick, max(close, open), 0)
Lowwickbar := valuewhen(Lowwick, bar_index, 0)
Lowwicklow := valuewhen(Lowwick, low, 0)
Lowbody := valuewhen(Lowwick, min(close, open), 0)
highline = not showhigh ? na : line.new(Highwickbar, Highwickhigh, Highwickbar, Highbody, xloc = xloc.bar_index, color = linecolor1, width = linewidth1, style=line.style_solid)
lowline = not showlow ? na : line.new(Lowwickbar, Lowwicklow, Lowwickbar, Lowbody, xloc = xloc.bar_index, color = linecolor2, width = linewidth2, style=line.style_solid)
// line.delete(highline[1])
// line.delete(lowline[1])
|
PSAR-Support Resistance | https://www.tradingview.com/script/bKiQGkyL-PSAR-Support-Resistance/ | traderharikrishna | https://www.tradingview.com/u/traderharikrishna/ | 445 | 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/
// © traderharikrishna
//@version=5
indicator("PSAR-Support Resistance",overlay = true)
mt=input.timeframe('',title='S/R timeframe')
sh=input.int(10,title='Shift S/R Forward/Backward')
start = input.float(title="Start", step=0.01, defval=0.02)
increment = input.float(title="Increment", step=0.01, defval=0.02)
maximum = input.float(title="Maximum", step=0.01, defval=0.2)
sar=request.security(syminfo.tickerid,mt,ta.sar(start,increment,maximum))
plot(sar,style=plot.style_circles,linewidth=1,color=color.yellow)
dir = sar < close ? 1 : -1
buy= dir == 1 and dir[1] == -1
sell=dir == -1 and dir[1] == 1
alertcondition(buy,title='SAR BUY',message='PSAR/Buy Signal')
alertcondition(sell,title='SAR SELL',message='PSAR/Sell Signal')
alertcondition(buy or sell,title='SAR BUY/SELL',message='PSAR/Buy/Sell Signal')
h=ta.valuewhen(buy,close,0)
l=ta.valuewhen(sell,close,0)
buyalert=open>h and close>h and open[1]<h
sellalert=open<l and close<l and open[1]>h
//co=open>h and close>h?color.rgb(6, 217, 240):open<l and close<l?color.rgb(237, 20, 143):color.rgb(242, 231, 8)
//barcolor(color=co)
y=ta.valuewhen(buy,close[0],0)
u=plot(y,color=color.rgb(10, 187, 196),linewidth=1,title='SAR High',offset=sh)
z=ta.valuewhen(sell,close[0],0)
d=plot(z,color=color.rgb(240, 6, 127),linewidth=1,title='SAR Low',offset=sh)
fill(u,d,color=y>z?color.rgb(76, 175, 79, 78):color.rgb(255, 82, 82, 77))
plotshape(buy? sar : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=#06b5e5, textcolor=color.white)
plotshape(sell? sar : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.rgb(249, 11, 106), textcolor=color.white)
malen=input.int(5,title='Moving Average Length')
matype=input.string('ema',title='Moving Average',options=['hma','ema','wma','sma'])
ma1=matype=='wma'?ta.wma(close,malen):matype=='ema'?ta.ema(close,malen):matype=='hma'?ta.hma(close,malen):matype=='sma'?ta.sma(close,malen):ta.ema(close,malen)
plot(ma1,linewidth=2,color=#06ebf3e3,title='Moving Average')
malen2=input.int(22,title='Moving Average Length')
matype2=input.string('ema',title='Moving Average',options=['hma','ema','wma','sma'])
ma2=matype2=='wma'?ta.wma(close,malen2):matype2=='ema'?ta.ema(close,malen2):matype2=='hma'?ta.hma(close,malen2):matype2=='sma'?ta.sma(close,malen2):ta.ema(close,malen2)
plot(ma2,linewidth=2,color=#f10b3df1,title='Moving Average2')
[macd,signal,hist]=ta.macd (close,12,26,9)
buycx=hist>0 and ta.crossover (ma1,ma2)
sellcx=hist <0 and ta.crossunder(ma1,ma2)
plotshape (buycx,title='MA-Buy',location=location.belowbar,style=shape.triangleup, color=#03800acc,size=size.tiny)
plotshape (sellcx,title='MA-Sell', location = location.abovebar, style =shape.triangledown, color= #ff0404,size=size.tiny)
|
Range Detection | https://www.tradingview.com/script/fS8ZHolP-Range-Detection/ | HasanRifat | https://www.tradingview.com/u/HasanRifat/ | 791 | 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/
// © HasanRifat
//@version=5
indicator("Range Detection", "Range", overlay = true, max_lines_count = 500)
minimum_lemgth = input.int(defval = 10, title = "Minimum candles to show range")
var candleLow = low
var candleHigh = high
var candleOpen = open
var candleClose = close
var insideCandles = 1
var label counterLabel = na
if high > candleHigh and close < candleHigh
candleHigh := high
if low < candleLow and close > candleLow
candleLow := low
breakoutCandle = close > candleHigh or close < candleLow
if breakoutCandle and barstate.isconfirmed
candleLow := low
candleHigh := high
candleOpen := open
candleClose := close
insideCandles := 1
if close <= candleHigh and close >= candleLow
insideCandles := insideCandles + 1
if insideCandles >= (minimum_lemgth+1)
counterLabel := label.new(bar_index, high, "Length: " +str.tostring(insideCandles - 1), yloc = yloc.abovebar, size = size.large, textcolor = color.white)
label.delete(counterLabel[1])
break_index = ta.valuewhen(breakoutCandle, bar_index, 0)
upperLine = insideCandles >= (minimum_lemgth+1) ? line.new(break_index, candleHigh, bar_index, candleHigh, color = candleOpen < candleClose ? color.green : color.red, width = 2) : na
lowerLine = insideCandles >= (minimum_lemgth+1) ? line.new(break_index, candleLow, bar_index, candleLow, color = candleOpen < candleClose ? color.green : color.red, width = 2) : na
if not breakoutCandle
line.delete(lowerLine[1])
line.delete(upperLine[1])
linefill.new(upperLine, lowerLine, color = candleOpen < candleClose ? color.new(color.green, 90) : color.new(color.red, 90))
bullish_break = close > candleHigh[1] and barstate.isconfirmed and insideCandles[1] >= (minimum_lemgth+1)
bearish_break = close < candleLow[1] and barstate.isconfirmed and insideCandles[1] >= (minimum_lemgth+1)
alertcondition(bullish_break, "Bullish Breakout", "Bullish Breakout")
alertcondition(bearish_break, "Bearish Breakout", "Bearish Breakout")
|
Wave Generator (WG) | https://www.tradingview.com/script/o2AETaam-Wave-Generator-WG/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 28 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("Wave Generator")
n = bar_index
max(source)=>
var float max = na
src = array.new<float>()
array.push(src, source)
max := math.max(nz(max[1]), array.get(src, 0))
min(source)=>
var float min = na
src = array.new<float>()
array.push(src, source)
min := math.min(nz(min[1]), array.get(src, 0))
min_max(src)=>
((src - min(src))/(max(src) - min(src)) - 0.5) * 2
f_sine_wave(_wave_height, _wave_duration, _phase_shift, _phase_shift_2) =>
_pi = math.pi
_w = 2 * _pi / _wave_duration
_sine_wave = _wave_height * math.sin(_w * n + _phase_shift + _phase_shift_2)
_sine_wave
triangle_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift) =>
_pi = math.pi
sine_waves = array.new<float>()
for i = 1 to _num_harmonics
array.push(sine_waves, f_sine_wave(_wave_height / math.pow(2 * i - 1, 2), _wave_duration / (2 * i - 1), (i - 1) * _pi, int(_phase_shift) * _pi))
_triangle_wave = array.avg(sine_waves)
min_max(_triangle_wave)
saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift_2) =>
_pi = math.pi
sine_waves = array.new<float>()
for i = 1 to _num_harmonics
array.push(sine_waves, f_sine_wave(_wave_height / (i), _wave_duration / (i), i * _phase_shift_2 * _pi, 0))
_saw_wave = array.avg(sine_waves)
min_max(_saw_wave)
ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift_2) =>
_pi = math.pi
sine_waves = array.new<float>()
for i = 1 to _num_harmonics
array.push(sine_waves, f_sine_wave(_wave_height / (i), _wave_duration / (i), i * _phase_shift_2 * _pi, 66))
_ramp_saw_wave = array.sum(sine_waves)
min_max(_ramp_saw_wave)
square_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift_2) =>
_pi = math.pi
sine_waves = array.new<float>()
for i = 1 to _num_harmonics
array.push(sine_waves, f_sine_wave(_wave_height / (2 * i - 1), _wave_duration / (2 * i - 1), (i * 2 - 1) * _phase_shift_2 * _pi, 0))
_square_wave = array.avg(sine_waves)
min_max(_square_wave)
wave_select(style, _wave_height, _wave_duration, _num_harmonics, _phase_shift_2)=>
switch style
"Sine" => f_sine_wave(_wave_height, _wave_duration, 0, _phase_shift_2)
"Triangle" => triangle_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift_2)
"Saw" => saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift_2)
"Ramp Saw" => ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift_2)
"Square" => square_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift_2)
fun = input.int(217, "Fundimental", 1)
harmonics = input.int(1024)
_phase_shift_2 = input.float(0, "Phase Rotation", step = 0.5)
style = input.string("Sine", "Wave Select", ["Sine","Triangle","Saw","Ramp Saw","Square"])
wave = wave_select(style, 1, fun, harmonics, _phase_shift_2)
plot(wave) |
VHF Adaptive Linear Regression KAMA | https://www.tradingview.com/script/TNv7h9fC-VHF-Adaptive-Linear-Regression-KAMA/ | simwai | https://www.tradingview.com/u/simwai/ | 96 | 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/
// © simwai
//@version=5
indicator('VHF Adaptive Linear Regression KAMA', 'AL_K', true)
// -- Input --
string resolution = input.timeframe(defval='', title='Resolution', group='General', inline='1')
int kamaLength = input.int(89, minval=6, title='KAMA Length', group='General', inline='2')
float kamaFactor1 = input.float(0.66, step=0.01, title='KAMA Factor 1', group='General', inline='3')
float kamaFactor2 = input.float(0.0645, step=0.001, title='KAMA Factor 2', group='General', inline='3')
string smoothingMethod = input.string('T3', 'Choose Smoothing Method', ['Hann Window', 'T3', 'None'], group='General', inline='4')
float smoothingLength = input.float(3, minval=2, title='Smoothing Length', group='General', inline='4')
bool isVhfEnabled = input.bool(true, 'Enable VHF Adaptiveness', group='General', inline='5')
bool isLinRegEnabled = input.bool(false, 'Enable Linear Regression', group='General', inline='6')
bool isSignalPlotEnabled = input.bool(true, 'Enable Signal Plot', group='General', inline='7')
// Gradient Color Schemas
var string SH1 = 'Red –> Green'
var string SH2 = 'Purple –> Blue'
var string SH3 = 'Yellow –> Dark Green'
var string SH4 = 'White –> Black'
var string SH5 = 'White –> Blue'
var string SH6 = 'White –> Red'
var string SH7 = 'Rainbow'
var color[] colors = array.new_color(na)
bool isGradientEnabled = input.bool(true, 'Enable Gradient', group='Gradient', inline='1')
bool isGradientInverted = input.bool(false, 'Invert Colors', group='Gradient', inline='1')
string gradientScheme = input.string(SH1, 'Choose Color Scheme', options = [SH1, SH2, SH3, SH4, SH5, SH6, SH7], group='Gradient', inline='2')
int gradientLookback = input.int(14, 'Gradient Lookback', group='Gradient', inline='3')
// -- Colors --
color maximumYellowRed = color.rgb(255, 203, 98) // yellow
color rajah = color.rgb(242, 166, 84) // orange
color magicMint = color.rgb(171, 237, 198)
color lightPurple = color.rgb(193, 133, 243)
color languidLavender = color.rgb(232, 215, 255)
color maximumBluePurple = color.rgb(181, 161, 226)
color skyBlue = color.rgb(144, 226, 244)
color lightGray = color.rgb(214, 214, 214)
color quickSilver = color.rgb(163, 163, 163)
color mediumAquamarine = color.rgb(104, 223, 153)
color carrotOrange = color.rgb(239, 146, 46)
// -- Functions --
// Kaufman's Adaptive Moving Average (KAMA)
kama(float _src, int _period) =>
if (bar_index > _period)
tmpVal = 0.0
len = math.max(_period, 1) // add this line to ensure length is always greater than 0
tmpVal := nz(tmpVal[1]) + math.pow(((math.sum(math.abs(_src - _src[1]), len) != 0) ? (math.abs(_src - _src[_period]) / math.sum(math.abs(_src - _src[1]), len)) : 0) * (kamaFactor1 - kamaFactor2) + kamaFactor2, 2) * (_src - nz(tmpVal[1]))
tmpVal
// Credits to @LucF, https://www.pinecoders.com/faq_and_code/#how-can-i-rescale-an-indicator-from-one-scale-to-another
// Rescales series with known min/max to the color array size.
rescale(_src, _min, _max) =>
var int _size = array.size(colors) - 1
int _colorStep = int(_size * (_src - _min)) / int(math.max(_max - _min, 10e-10))
_colorStep := _colorStep > _size ? _size : _colorStep < 0 ? 0 : _colorStep
int(_colorStep)
colGrad(_src, _min, _max) => array.get(colors, rescale(_src, _min, _max))
// Hann Window Smoothing – Credits to @cheatcountry
doHannWindow(float _series, float _hannWindowLength) =>
sum = 0.0, coef = 0.0
for i = 1 to _hannWindowLength
cosine = 1 - math.cos(2 * math.pi * i / (_hannWindowLength + 1))
sum := sum + (cosine * nz(_series[i - 1]))
coef := coef + cosine
h = coef != 0 ? sum / coef : 0
// T3 - Credits to @loxx
t3(float _src, float _length, float hot=1, string clean='T3')=>
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 + (_length - 1.0) / 2.0)
else
alpha := 2.0 / (1.0 + _length)
_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
atr(src, length, _high, _low, _close) =>
tr = math.max(math.max(_high - _low, math.abs(_high - nz(_close[1]))), math.abs(_low - nz(_close[1])))
atr = ta.ema(tr, length)
// -- Calculation --
[_close, _low, _high] = request.security(syminfo.tickerid, resolution, [close[1], high[1], low[1]], barmerge.gaps_off, barmerge.lookahead_on)
if (smoothingMethod == 'T3')
_close := t3(_close, smoothingLength)
_low := t3(_low, smoothingLength)
_high := t3(_high, smoothingLength)
if (smoothingMethod == 'Hann Window')
_close := doHannWindow(_close, smoothingLength)
_low := doHannWindow(_low, smoothingLength)
_high := doHannWindow(_high, smoothingLength)
int kamaLookback = 3
int _kamaLength = kamaLength
if (isVhfEnabled)
vhfNoise = 0.
vhfDiff = (_close > nz(_close[1])) ? _close - nz(_close[1]) : nz(_close[1]) - _close
vhfNoise := nz(vhfNoise[1]) - nz(vhfDiff[kamaLength]) + vhfDiff
HCP = ta.highest(_close, kamaLength)
LCP = ta.lowest(_close, kamaLength)
vhf = (HCP - LCP) / vhfNoise
int peradapt = math.round(kamaLength * vhf * 2.0)
_kamaLength := peradapt
float kama = isLinRegEnabled ? ta.linreg(kama(_close, _kamaLength), 5, 2) : kama(_close, _kamaLength)
// If you wanna expirement with different calculations like I did:
// float kamaSlope = (kama[kamaLookback] - kama) / (ta.highest(kama, kamaLookback) - ta.lowest(kama, kamaLookback))
// kamaSlope := isLinRegEnabled ? ta.linreg(kamaSlope, kamaLength, 1) : kamaSlope
// float kamaSlope = 5 / (kama[5] - kama)
// float kamaSlope = ta.roc(kama, kamaLookback)
// float kamaSlope = (bar_index[1] - bar_index) / (kama[1] - kama)
float maDiff = kama - ta.sma(kama, gradientLookback)
float kamaSlope = math.atan(maDiff / atr(kama, gradientLookback, _high, _low, _close)) * (180 / math.pi)
bool enterLong = ta.crossover(_close, kama) and ta.crossover(kama, kama[1]) and kamaSlope > 0.5
bool enterShort = ta.crossunder(_close, kama) and ta.crossunder(kama, kama[1]) and kamaSlope < -0.5
plotshape(enterLong, title='ENTER LONG', style=shape.triangleup, color=magicMint, size=size.tiny, location=location.belowbar)
plotshape(enterShort, title='ENTER SHORT', style=shape.triangledown, color=rajah, size=size.tiny, location=location.abovebar)
alertcondition(enterLong, 'Enter Long', 'Adaptive Fisherized KAMA – Enter Long')
alertcondition(enterShort, 'Enter Short', 'Adaptive Fisherized KAMA – Enter Short')
// Gradient - Credits @e2e4mfck
// Fill the array with colors only on the first iteration of the script
if barstate.isfirst and isGradientEnabled
if gradientScheme == SH1
array.push(colors, #ff0000), array.push(colors, #ff2c00), array.push(colors, #fe4200), array.push(colors, #fc5300), array.push(colors, #f96200), array.push(colors, #f57000), array.push(colors, #f07e00), array.push(colors, #ea8a00), array.push(colors, #e39600), array.push(colors, #dca100), array.push(colors, #d3ac00), array.push(colors, #c9b600), array.push(colors, #bfc000), array.push(colors, #b3ca00), array.push(colors, #a6d400), array.push(colors, #97dd00), array.push(colors, #86e600), array.push(colors, #71ee00), array.push(colors, #54f700), array.push(colors, #1eff00)
else if gradientScheme == SH2
array.push(colors, #ff00d4), array.push(colors, #f71fda), array.push(colors, #ef2ee0), array.push(colors, #e63ae5), array.push(colors, #de43ea), array.push(colors, #d44bee), array.push(colors, #cb52f2), array.push(colors, #c158f6), array.push(colors, #b75df9), array.push(colors, #ac63fb), array.push(colors, #a267fe), array.push(colors, #966bff), array.push(colors, #8b6fff), array.push(colors, #7e73ff), array.push(colors, #7276ff), array.push(colors, #6479ff), array.push(colors, #557bff), array.push(colors, #437eff), array.push(colors, #2e80ff), array.push(colors, #0082ff)
else if gradientScheme == SH3
array.push(colors, #fafa6e), array.push(colors, #e0f470), array.push(colors, #c7ed73), array.push(colors, #aee678), array.push(colors, #97dd7d), array.push(colors, #81d581), array.push(colors, #6bcc86), array.push(colors, #56c28a), array.push(colors, #42b98d), array.push(colors, #2eaf8f), array.push(colors, #18a48f), array.push(colors, #009a8f), array.push(colors, #00908d), array.push(colors, #008589), array.push(colors, #007b84), array.push(colors, #0c707d), array.push(colors, #196676), array.push(colors, #215c6d), array.push(colors, #275263), array.push(colors, #2a4858)
else if gradientScheme == SH4
array.push(colors, #ffffff), array.push(colors, #f0f0f0), array.push(colors, #e1e1e1), array.push(colors, #d2d2d2), array.push(colors, #c3c3c3), array.push(colors, #b5b5b5), array.push(colors, #a7a7a7), array.push(colors, #999999), array.push(colors, #8b8b8b), array.push(colors, #7e7e7e), array.push(colors, #707070), array.push(colors, #636363), array.push(colors, #575757), array.push(colors, #4a4a4a), array.push(colors, #3e3e3e), array.push(colors, #333333), array.push(colors, #272727), array.push(colors, #1d1d1d), array.push(colors, #121212), array.push(colors, #000000)
else if gradientScheme == SH5
array.push(colors, #ffffff), array.push(colors, #f4f5fa), array.push(colors, #e9ebf5), array.push(colors, #dee1f0), array.push(colors, #d3d7eb), array.push(colors, #c8cde6), array.push(colors, #bdc3e1), array.push(colors, #b2b9dd), array.push(colors, #a7b0d8), array.push(colors, #9ca6d3), array.push(colors, #919dce), array.push(colors, #8594c9), array.push(colors, #7a8bc4), array.push(colors, #6e82bf), array.push(colors, #6279ba), array.push(colors, #5570b5), array.push(colors, #4768b0), array.push(colors, #385fab), array.push(colors, #2557a6), array.push(colors, #004fa1)
else if gradientScheme == SH6
array.push(colors, #ffffff), array.push(colors, #fff4f1), array.push(colors, #ffe9e3), array.push(colors, #ffded6), array.push(colors, #ffd3c8), array.push(colors, #fec8bb), array.push(colors, #fdbdae), array.push(colors, #fbb2a1), array.push(colors, #f8a794), array.push(colors, #f69c87), array.push(colors, #f3917b), array.push(colors, #f0856f), array.push(colors, #ec7a62), array.push(colors, #e86e56), array.push(colors, #e4634a), array.push(colors, #df563f), array.push(colors, #db4933), array.push(colors, #d63a27), array.push(colors, #d0291b), array.push(colors, #cb0e0e)
else if gradientScheme == SH7
array.push(colors, #E50000), array.push(colors, #E6023B), array.push(colors, #E70579), array.push(colors, #E908B7), array.push(colors, #E00BEA), array.push(colors, #A70DEB), array.push(colors, #6E10ED), array.push(colors, #3613EE), array.push(colors, #162DEF), array.push(colors, #1969F1), array.push(colors, #1CA4F2), array.push(colors, #1FDFF4), array.push(colors, #22F5D2), array.push(colors, #25F69C), array.push(colors, #28F867), array.push(colors, #2CF933), array.push(colors, #5DFA2F), array.push(colors, #96FC32), array.push(colors, #CDFD35), array.push(colors, #FFF938)
// Invert colors in array
if isGradientInverted
array.reverse(colors)
// Colorize the bounded source
color plotColor = isGradientEnabled ? colGrad(kamaSlope, -20, 20) : kamaSlope > 0 ? skyBlue : maximumBluePurple
plot(kama, linewidth=2, color=plotColor, title='KAMA') |
RSI Multi Symbol/Time Frame Detector | https://www.tradingview.com/script/Xg5cUjgF-RSI-Multi-Symbol-Time-Frame-Detector/ | MirNader_ | https://www.tradingview.com/u/MirNader_/ | 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/
// © MirNader_
//@version=5
indicator("RSI Multi Symbol/Time Frame Detector" , overlay = true)
// Create a string variable "Gr1" to be used as a group name for the time frames input
string Gr1 = " RSI Time Frames "
// Create four string variables to be used as input options for the time frames
string tf1_1 = input.timeframe('5' , "Time Frame 1️⃣" , group = Gr1 )
string tf1_2 = input.timeframe('15' , "Time Frame 2️⃣" , group = Gr1 )
string tf1_3 = input.timeframe('60' , "Time Frame 3️⃣" , group = Gr1 )
string tf1_4 = input.timeframe('240' , "Time Frame 4️⃣" , group = Gr1 )
// Create a string variable "Gr2" to be used as a group name for the symbols input
string Gr2 = "RSI Symbols"
// Create three string variables to be used as input options for the symbols
string sym1 = input.symbol("SP:SPX" , "Symbol 1️⃣" , group = Gr2 )
string sym2 = input.symbol("OANDA:EURUSD" , "Symbol 2️⃣" , group = Gr2 )
string sym3 = input.symbol("OANDA:NZDUSD" , "Symbol 3️⃣" , group = Gr2 )
// Create a string variable "Gr3" to be used as a group name for the RSI settings input
string Gr3 = "RSI Settings"
// Create two integer variables to be used as input options for the RSI settings
int rsiLengthInput = input.int(14, minval=1, title="RSI Length" , group=Gr3)
float rsiSourceInput = input.source(close, "Source" , group=Gr3)
// Create a string variable "Gr4" to be used as a group name for the MA settings input
string Gr4 = "MA Settings"
// Create three variables to be used as input options for the MA settings
string maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group=Gr4)
int maLengthInput = input.int(14, title="MA Length" , group=Gr4)
float bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev" , group=Gr4)
// Define a function for the moving average calculation
ma(source, length, type) =>
switch type
// If the type is "SMA", return the simple moving average calculation
"SMA" => ta.sma(source, length)
// If the type is "Bollinger Bands", return the simple moving average calculation
"Bollinger Bands" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
// If the type is "EMA", return the exponential moving average calculation
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
// Calculate relative strength index and its moving average
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))
rsiMA = ma(rsi, maLengthInput, maTypeInput)
// Request security data for multiple symbols and time frames
float rsi1_1 = request.security(sym1 , tf1_1 , rsi[1] , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
float rsi1_2 = request.security(sym1 , tf1_2 , rsi[1] , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
float rsi1_3 = request.security(sym1 , tf1_3 , rsi[1] , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
float rsi1_4 = request.security(sym1 , tf1_4 , rsi[1] , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
float rsi2_1 = request.security(sym2 , tf1_1 , rsi[1] , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
float rsi2_2 = request.security(sym2 , tf1_2 , rsi[1] , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
float rsi2_3 = request.security(sym2 , tf1_3 , rsi[1] , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
float rsi2_4 = request.security(sym2 , tf1_4 , rsi[1] , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
float rsi3_1 = request.security(sym3 , tf1_1 , rsi[1] , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
float rsi3_2 = request.security(sym3 , tf1_2 , rsi[1] , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
float rsi3_3 = request.security(sym3 , tf1_3 , rsi[1] , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
float rsi3_4 = request.security(sym3 , tf1_4 , rsi[1] , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
// Plot Table
var RSI_table = table.new(
"middle" + "_" + 'right', columns=5, rows=24, bgcolor=color.rgb(255, 82, 82, 100),
frame_color=color.gray, frame_width = 1, border_color=color.new(color.green, 70), border_width = 1)
Cell = 0
// Header
table.cell (RSI_table , 0, 0, text = "Multi Time Frame / Symbol RSI Check",text_color = color.black , text_size = size.tiny)
table.merge_cells(RSI_table , 0, Cell, 4, Cell)
Cell := 02
table.cell (RSI_table , 0, Cell, text = "Symbol" , text_color = color.black , text_size = size.tiny)
table.cell (RSI_table , 1, Cell, text = str.tostring(tf1_1 ) + ' Minute' , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
table.cell (RSI_table , 2, Cell, text = str.tostring(tf1_2 ) + ' Minute' , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
table.cell (RSI_table , 3, Cell, text = str.tostring(tf1_3 ) + ' Minute' , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
table.cell (RSI_table , 4, Cell, text = str.tostring(tf1_4 ) + ' Minute' , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
Cell := 03
table.cell (RSI_table , 0, Cell, text = str.tostring(sym1 ) , text_color = color.black , text_size = size.tiny)
table.cell (RSI_table , 1, Cell, text = str.tostring(rsi1_1 , '#' ) , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
table.cell (RSI_table , 2, Cell, text = str.tostring(rsi1_2 , '#' ) , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
table.cell (RSI_table , 3, Cell, text = str.tostring(rsi1_3 , '#' ) , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
table.cell (RSI_table , 4, Cell, text = str.tostring(rsi1_4 , '#' ) , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
Cell := 04
table.cell (RSI_table , 0, Cell, text = str.tostring(sym2 ) , text_color = color.black , text_size = size.tiny)
table.cell (RSI_table , 1, Cell, text = str.tostring(rsi2_1 , '#' ) , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
table.cell (RSI_table , 2, Cell, text = str.tostring(rsi2_2 , '#' ) , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
table.cell (RSI_table , 3, Cell, text = str.tostring(rsi2_3 , '#' ) , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
table.cell (RSI_table , 4, Cell, text = str.tostring(rsi2_4 , '#' ) , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
Cell := 05
table.cell (RSI_table , 0, Cell, text = str.tostring(sym3 ) , text_color = color.black , text_size = size.tiny)
table.cell (RSI_table , 1, Cell, text = str.tostring(rsi3_1 , '#' ) , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
table.cell (RSI_table , 2, Cell, text = str.tostring(rsi3_2 , '#' ) , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
table.cell (RSI_table , 3, Cell, text = str.tostring(rsi3_3 , '#' ) , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
table.cell (RSI_table , 4, Cell, text = str.tostring(rsi3_4 , '#' ) , text_color = color.black , bgcolor = color.rgb(54, 58, 69, 100), text_size = size.tiny)
//End |
Urika Confirmation Indicator | https://www.tradingview.com/script/tAWhCTLc-Urika-Confirmation-Indicator/ | DrZy | https://www.tradingview.com/u/DrZy/ | 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/
// @version=5
//@author ApoZee
//
// Reference: Idea from Ichimoku and Donchian Indicators
// v01, February 2023
//
indicator(title = "Urika Confirmation Indicator", shorttitle="UCI Alert", overlay = true)
fastLength = input.int(5, title="Signal Length", minval = 1)
slowLength = input.int(15, title="Slow Length", minval = 1)
highCalc = ta.highest(high[1], slowLength)
signalCal = (ta.highest(high, fastLength) + ta.lowest(low, fastLength))/2
lowCalc = ta.lowest(low[1], slowLength)
slowCal = math.avg(highCalc, lowCalc)
//color
whiteC = color.new(#ffffff, transp = 70)
redC = color.new(#ee0800, transp = 70)
//Plotting lines
signalLine = plot(signalCal, title = "Signal Line", color = whiteC, linewidth = 2)
slowLine = plot(slowCal, title = "Slow Line", color = redC, linewidth = 2)
//fillings
fillColor = signalCal > slowCal ? color.new(#0ebb23, transp = 70) : color.new(#ee08aa, transp =70)
fill(signalLine, slowLine, color = fillColor)
xUp = ta.crossover(signalCal, slowCal)
xDn = ta.crossunder(signalCal, slowCal)
// Alert condition: DPO crosses above 0
if xUp
alert("Buy", alert.freq_once_per_bar_close)
if xDn
alert("Sell", alert.freq_once_per_bar_close)
plotshape(xUp, "LE", shape.triangleup, location.belowbar, color.white, size = size.tiny)
plotshape(xDn, "LE", shape.triangledown, location.abovebar, color.yellow, size = size.tiny)
//plotchar(xUp, "Long", "▲", location.bottom, color = color.green, size = size.tiny)
//plotchar(xDn, "Short", "▼", location.top, color = color.red, size = size.tiny) |
Volume scaled Price + auto colour change light/dark mode | https://www.tradingview.com/script/FgOLPLJv-Volume-scaled-Price-auto-colour-change-light-dark-mode/ | fikira | https://www.tradingview.com/u/fikira/ | 144 | study | 5 | MPL-2.0 | fi(ki)=>'ra' // © fikira 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('Volume scaled Price', overlay= false, precision= 3, format= format.volume)
_='
--- ––––––––––––––––––––– ---[ settings ]--- ––––––––––––––––––––– ---'
src = input.string('candles', 'Option' , options= [ 'candles' , 'volume' ])
shw = input.string('percentile nearest rank', 'Lines', options= ['percentile nearest rank', 'BB', 'SMA'])
len = input.int ( 100 , 'length' , minval = 1 )
mlt = input.float ( 2 , 'mult' , minval = 0.1 , tooltip= 'for BB' )
prc = input.int ( 90 , '% perc. nearest rank' , minval = 1 , maxval = 99 )
w = input.bool ( false , 'show wick' )
_='
--- ––––––––––––––––––––– ---[ colors ]--- ––––––––––––––––––––– ---'
cPuD = input.color(#089981 , 'Candle ' , group='Colours (Dark theme)' , inline='1')
cPdD = input.color(#f23645 , '' , group='Colours (Dark theme)' , inline='1')
cVuD = input.color(#91e8cb , 'Volume' , group='Colours (Dark theme)' , inline='2')
cVdD = input.color(#ff984e , '' , group='Colours (Dark theme)' , inline='2')
cBsD = input.color(#eafd43 , 'Base ' , group='Colours (Dark theme)' , inline='3')
cB_D = input.color(#f1ffffa9, 'Line ', group='Colours (Dark theme)' , inline='4')
cPuL = input.color(#388e3c , 'Candle ' , group='Colours (Light theme)', inline='1')
cPdL = input.color(#b22833 , '' , group='Colours (Light theme)', inline='1')
cVuL = input.color(#26c6da , 'Volume' , group='Colours (Light theme)', inline='2')
cVdL = input.color(#f57f17 , '' , group='Colours (Light theme)', inline='2')
cBsL = input.color(#4d10c6 , 'Base ' , group='Colours (Light theme)', inline='3')
cB_L = input.color(#574eff , 'Line ', group='Colours (Light theme)', inline='4')
_='
--- ––––––––––––––––––––– ---[ colour ]--- ––––––––––––––––––––– ---'
r = color.r(chart.bg_color)
g = color.g(chart.bg_color)
b = color.b(chart.bg_color)
isDark = r < 80 and g < 80 and b < 80
sCn = src == 'candles'
upC = close > open
col = upC ? sCn ? isDark ? cPuD : cPuL : isDark ? cVuD : cVuL : sCn ? isDark ? cPdD : cPdL : isDark ? cVdD : cVdL
m = upC ? open : close
o = open - m
h = high - m
l = low - m
c = close - m
z = math.max(o, c)
a = math.min(o, c)
plotcandle(sCn ? o : 0, sCn ? w ? h : z : volume, sCn ? w ? l : a : 0, sCn ? c : volume, title= '', color= col, wickcolor= col, bordercolor= col, display= display.all - display.status_line)
prP = ta.percentile_nearest_rank( z , len, prc)
prP_ = ta.percentile_nearest_rank( z , len, 100 - prc)
smaP = ta.sma ( z , len )
[baseP, upP, loP] = ta.bb ( z , len, mlt)
prV = ta.percentile_nearest_rank(volume, len, prc)
prV_ = ta.percentile_nearest_rank(volume, len, 100 - prc)
smaV = ta.sma (volume, len )
[baseV, upV, loV] = ta.bb (volume, len, mlt)
basePlot =
sCn ?
shw == 'percentile nearest rank' ? na :
shw == 'BB' ? baseP : smaP :
shw == 'percentile nearest rank' ? na :
shw == 'BB' ? baseV : smaV
plot2 =
sCn ?
shw == 'percentile nearest rank' ? prP :
shw == 'BB' ? upP : na :
shw == 'percentile nearest rank' ? prV :
shw == 'BB' ? upV : na
plot3 =
sCn ?
shw == 'percentile nearest rank' ? prP_ :
shw == 'BB' ? loP : na :
shw == 'percentile nearest rank' ? prV_ :
shw == 'BB' ? loV : na
p1 = plot(basePlot, title= 'Base' , color= isDark ? cBsD : cBsL , display= display.all - display.status_line)
p2 = plot(plot2 , title= 'Upper', color= isDark ? cB_D : cB_L , display= display.all - display.status_line)
p3 = plot(plot3 , title= 'Lower', color= isDark ? cB_D : cB_L , display= display.all - display.status_line)
fill(p2, p3, color= shw == 'percentile nearest rank' ? isDark ? color.new(cB_D, 93) : color.new(cB_L, 93) : na)
var line zero = line.new(na, 0, na, 0, style=line.style_dotted, color=isDark ? color.white :
color.black, extend=extend.both), zero.set_x1(bar_index), zero.set_x2(zero.get_x1() + 1)
//hline(0, color= isDark ? color.white : color.black, linestyle=hline.style_solid)
plot(0, color= isDark ? color.white : color.black, style= plot.style_line)
dvP = volume > volume[1] and z < z[1] and z < prP_ and volume > prV
dvV = volume < volume[1] and z > z[1] and z > prP and volume < prV_
bgcolor(dvP ? color.new(color.silver, 90) : dvV ? color.new(color.orange, 90) : na)
//pr100= ta.percentile_nearest_rank( z , len, 100), plot(pr100)
|
wick CE; plot candle wick and tail midpoint lines | https://www.tradingview.com/script/taoEj9vY-wick-CE-plot-candle-wick-and-tail-midpoint-lines/ | twingall | https://www.tradingview.com/u/twingall/ | 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/
// © twingall
//
//@version=5
indicator("wick CE", overlay = true, max_bars_back = 5000, max_lines_count = 500)
showWickCE=input.bool(true, 'wick CE', tooltip = "CE = consequent encroachment\n\nThe mid-point line of the wick or the tail")
mult = input.int(1, "Minimum Wick Size", minval = 0, tooltip = "Minimum wick size based on multiples of the chart symbol's mintick value.\n\nToggle on this checkbox to show the symbol's mintick value in the top right corner.\n\nIncrease this number to filter out smaller wicks.", inline = '1')
showMintick = input.bool(false, "show Symbol's Mintick Value", inline = '1')
showBodyMT=input.bool(false, 'body MT', inline ='2', tooltip = "MT = Mean Threshold\n\nThe mid-point line of the candle body")
MTcolor = input.color(color.blue, '| color:', inline ='2')
show75pctRetrace = input.bool(false, "75% retrace", inline ='3')
show25pctRetrace = input.bool(false, "25% retrace", inline ='3')
_75pctCol = input.color(color.red, "| color", inline ='3', tooltip = "For example, a 75% retrace:\n\nrepresents a 75% retrace up into the high to low range (if bearish candle)\n\n..or a 75% retrace down into the low to high range (if it was a bullish candle)")
lookback = input.int(20, "bars back", inline = '1', group = 'lookback')
showCurrentBar=input.bool(true, 'show current bar', inline = '1', group = 'lookback')
inputLinestyle = input.string('dotted', "line style", options = ['dashed','solid', 'dotted','arrow left'], inline = '2', group = 'line formatting')
lineColor = input.color(color.new(color.purple, 15),'color', inline = '2', group = 'line formatting')
lineWidth = input.int(1, "width", minval =1, maxval =6, inline = '2', group = 'line formatting')
linestyle= inputLinestyle=='dashed'?line.style_dashed:inputLinestyle=='solid'? line.style_solid:inputLinestyle=='dotted'?line.style_dotted:inputLinestyle=='arrow left'?line.style_arrow_left:na
extendBars=input.int(0, 'extend lines by X bars', group = 'line formatting')
isBull = close>=open?1:0
bodyHigh = close>=open?close:open
bodyLow = close>=open?open:close
wickCE = showWickCE and high-bodyHigh > mult*syminfo.mintick? bodyHigh+((high-bodyHigh)/2):na
tailCE= showWickCE and bodyLow-low > mult*syminfo.mintick? bodyLow-((bodyLow-low)/2):na
bodyMT = showBodyMT?(isBull?open+(close-open)/2:close+(open-close)/2):na
_75pctLvl = show75pctRetrace?(isBull?low+((high-low)/4):high-((high-low)/4)):na
_25pctLvl = show25pctRetrace?(isBull?high-((high-low)/4):low+((high-low)/4)):na
if bar_index+(lookback-1) >= last_bar_index
line.new(bar_index-1, wickCE[1], bar_index+extendBars, wickCE[1], color=lineColor, style = linestyle)
line.new(bar_index-1, tailCE[1], bar_index+extendBars, tailCE[1], color=lineColor, style = linestyle)
line.new(bar_index-1, bodyMT[1], bar_index+extendBars, bodyMT[1], color=MTcolor, style = linestyle)
line.new(bar_index-1, _75pctLvl[1], bar_index+extendBars, _75pctLvl[1], color=_75pctCol, style = linestyle)
line.new(bar_index-1, _25pctLvl[1], bar_index+extendBars, _25pctLvl[1], color=_75pctCol, style = linestyle)
if barstate.islast and showCurrentBar
line.new(bar_index, wickCE, bar_index+2, wickCE, color=lineColor, style = linestyle)
line.new(bar_index, tailCE, bar_index+2, tailCE, color=lineColor, style = linestyle)
line.new(bar_index, _75pctLvl, bar_index+2, _75pctLvl, color=_75pctCol, style = linestyle)
line.new(bar_index, _25pctLvl, bar_index+2, _25pctLvl, color=_75pctCol, style = linestyle)
var table Table = table.new(position.top_right, 4,4, bgcolor = color.yellow)
if showMintick
table.cell(Table, 0,0, "mintick = " +str.tostring (syminfo.mintick)) |
Sonarlab - Psych/Whole Number Levels | https://www.tradingview.com/script/RLhZUTyg-Sonarlab-Psych-Whole-Number-Levels/ | Sonarlab | https://www.tradingview.com/u/Sonarlab/ | 530 | 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/
// © ClayeWeight
// Enjoy the Free Script!
//@version=5
indicator("Psych/Whole Number Levels", overlay = true)
_grp = "Sonarlab.io"
_v = input.string("v1.1", title="Version", options=["v1.1"], group=_grp)
// -----------
_fx = "Forex & Indices & BTC/ETH"
show_250pip = input.bool(true, title="Show 250 pip levels", group=_fx)
pip250_line_count = input.int(5, title="Line Count", group=_fx)
pip250_line_style = input.string("Solid", title="Line Style", options=["Solid", "Dashed", "Dotted"], inline="style250", group=_fx)
line_style250 = pip250_line_style == "Solid" ? line.style_solid : pip250_line_style == "Dashed" ? line.style_dashed : line.style_dotted
pip250_color = input.color(#b22833, title="", inline="style250", group=_fx)
// -----------
show_100pip = input.bool(true, title="Show 100 pip levels", group=_fx)
pip100_line_count = input.int(5, title="Line Count", group=_fx)
pip100_line_style = input.string("Dashed", title="Line Style", options=["Solid", "Dashed", "Dotted"], inline="style", group=_fx)
line_style100 = pip100_line_style == "Solid" ? line.style_solid : pip100_line_style == "Dashed" ? line.style_dashed : line.style_dotted
pip100_color = input.color(#1848cc, title="", inline="style", group=_fx)
// -----------
show_intraday_pip = input.bool(true, title="Show Intra Day Pip Levels", group=_fx)
intraday_line_count = input.int(5, title="Line Count", group=_fx)
intraday_line_style = input.string("Dotted", title="Line Style", options=["Solid", "Dashed", "Dotted"], inline="stylefx", group=_fx)
line_styleintraday = intraday_line_style == "Solid" ? line.style_solid : intraday_line_style == "Dashed" ? line.style_dashed : line.style_dotted
intraday_color = input.color(#fbc02d, title="", inline="stylefx", group=_fx)
// -----------
_alert = "Alerts"
alert_intraday = input.bool(true, title="Alert Intra Day Levels", group=_alert)
alert_100 = input.bool(true, title="Alert 100 Pip Levels", group=_alert)
alert_250 = input.bool(true, title="Alert 250 Pip Levels", group=_alert)
// --------------------
step = syminfo.mintick * 1000
step100 = step
step250 = step * 2.5
var intradayLevelLines = array.new_line()
var levelLines100 = array.new_line()
var levelLines250 = array.new_line()
remove_lines(_lines) =>
for l in _lines
line.delete(l)
print_line(showBool, lineArray, total, step, stepAdd, multi, col, style) =>
if showBool
for n = 0 to total - 1
stepUp = syminfo.type == 'forex' or syminfo.type == 'crypto' ? math.ceil(close / step) * step + (n * multi) : int(close / step) * step + stepAdd + (n * multi)
stepUp := syminfo.type == 'forex' and show_intraday_pip ? stepUp + stepAdd * step : stepUp
stepDn = syminfo.type == 'forex' or syminfo.type == 'crypto' ? math.floor(close / step) * step - (n * multi) : int(close / step) * step + stepAdd - (n * multi)
stepDn := syminfo.type == 'forex' and show_intraday_pip ? stepDn + stepAdd * step : stepDn
array.push(lineArray, line.new(bar_index, stepUp, bar_index - 1, stepUp, xloc=xloc.bar_index, extend=extend.both, color=col, width=1, style=style))
array.push(lineArray, line.new(bar_index, stepDn, bar_index - 1, stepDn, xloc=xloc.bar_index, extend=extend.both, color=col, width=1, style=style))
alert_me(lineLevels) =>
for l in lineLevels
if open < line.get_y1(l) and close > line.get_y1(l)
alert("Price is above " + str.tostring(line.get_y1(l)) )
break
if open > line.get_y1(l) and close < line.get_y1(l)
alert("Price is below " + str.tostring(line.get_y1(l)) )
break
if alert_250
alert_me(levelLines250)
if alert_100
alert_me(levelLines100)
if alert_intraday
alert_me(intradayLevelLines)
if barstate.islast
remove_lines(intradayLevelLines)
remove_lines(levelLines100)
remove_lines(levelLines250)
if syminfo.type == 'forex'
print_line(show_250pip, levelLines250, pip250_line_count, step250, 0, step250, pip250_color, line_style250)
print_line(show_100pip, levelLines100, pip100_line_count, step100, 0, step100, pip100_color, line_style100)
if timeframe.isintraday
print_line(show_intraday_pip, intradayLevelLines, intraday_line_count, step, 0.2, step, intraday_color, line_styleintraday)
print_line(show_intraday_pip, intradayLevelLines, intraday_line_count, step, 0.5, step, intraday_color, line_styleintraday)
print_line(show_intraday_pip, intradayLevelLines, intraday_line_count, step, 0.8, step, intraday_color, line_styleintraday)
if syminfo.type == 'index' or syminfo.type == 'cfd'
print_line(show_250pip, levelLines250, pip250_line_count, 1000, 500, 250, pip250_color, line_style250)
print_line(show_100pip, levelLines100, pip100_line_count, 100, 0, 100, pip100_color, line_style100)
if syminfo.type == 'crypto'
if str.startswith(syminfo.ticker, "BTC")
print_line(show_100pip, levelLines100, pip100_line_count, 1000, 0, 1000, pip100_color, line_style100)
print_line(show_250pip, levelLines250, pip250_line_count, 1500, 0, 1500, pip250_color, line_style250)
if timeframe.isintraday
print_line(show_intraday_pip, intradayLevelLines, intraday_line_count, 250, 0, 250, intraday_color, line_styleintraday)
if str.startswith(syminfo.ticker, "ETH")
print_line(show_100pip, levelLines100, pip100_line_count, 100, 0, 100, pip100_color, line_style100)
print_line(show_250pip, levelLines250, pip250_line_count, 250, 0, 250, pip250_color, line_style250)
if timeframe.isintraday
print_line(show_intraday_pip, intradayLevelLines, intraday_line_count, 50, 0, 50, intraday_color, line_styleintraday) |
Stochastic Oversold / Overbought Multi Time Frame on Candle | https://www.tradingview.com/script/BeeqJZgP-Stochastic-Oversold-Overbought-Multi-Time-Frame-on-Candle/ | MirNader_ | https://www.tradingview.com/u/MirNader_/ | 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/
// © MirNader_
//@version=5
indicator(title="Stochastic Oversold / Overbought Multi Time Frame on Candle", overlay = true )
// The user can select the %K Length and %K Smoothing for the Stochastic oscillator calculation.
string Gr1 = "Stochastic Overaly "
// periodK - %K Length
int periodK = input.int(14 , "%K Length" , minval=1 , group = Gr1)
// smoothK - %K Smoothing
int smoothK = input.int(1 , "%K Smoothing" , minval=1 , group = Gr1)
string Gr2 = "Stochastic Time Frame 1️⃣ "
// showtf1 - Boolean to show/hide the first time frame signal
bool showtf1 = input.bool(true , "" , inline = "01" , group = Gr2)
// tf1 - First time frame (15 minutes)
string tf1 = input.timeframe('15' , "Time Frame 1️⃣" , inline = "01" , group = Gr2)
// colortf1 - Color for the first time frame signal
color colortf1 = input.color(color.yellow , "" , inline = "01" , group = Gr2)
// overtf1 - Overbought threshold for the first time frame
float overtf1 = input.float(80 , " K > " , inline = "02" , group = Gr2)
// undertf1 - Oversold threshold for the first time frame
float undertf1 = input.float(20 , " or K < " , inline = "02" , group = Gr2)
string Gr3 = "Stochastic Time Frame 2️⃣ "
// showtf2 - Boolean to show/hide the second time frame signal
bool showtf2 = input.bool(false , "" , inline = "01" , group = Gr3)
// tf2 - Second time frame (1 hour)
string tf2 = input.timeframe('60' , "Time Frame 2️⃣" , inline = "01" , group = Gr3)
// colortf2 - Color for the second time frame signal
color colortf2 = input.color(color.red , "" , inline = "01" , group = Gr3)
// overtf2 - Overbought threshold for the second time frame
float overtf2 = input.float(80 , "K > " , inline = "02" , group = Gr3)
// undertf2 - Oversold threshold for the second time frame
float undertf2 = input.float(20 , " or K < " , inline = "02" , group = Gr3)
string Gr4 = "Stochastic Time Frame 3️⃣ "
// showtf3 - Boolean to show/hide the third time frame signal
bool showtf3 = input.bool(false , "" , inline = "01" , group = Gr4)
// tf3 - Third time frame (4 hours)
string tf3 = input.timeframe('240' , "Time Frame 3️⃣" , inline = "01" , group = Gr4)
// colortf3 - Color for the third time frame signal
color colortf3 = input.color(color.black , "" , inline = "01" , group = Gr4)
// overtf3 - Overbought threshold for the third time frame
float overtf3 = input.float(80 , "K > " , inline = "02" , group = Gr4)
// undertf3 - Oversold threshold for the third time frame
float undertf3 = input.float(20 , " or K < " , inline = "02" , group = Gr4)
// Define the TimeframeFuction to return the stochastic signal for the selected time frame
// request the security data for the selected symbol and time frame, with lookahead to handle bar merging
TimeframFuction(_symbol, _res, _src) =>
request.security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)
// Calculate the Stochastic %K
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
// Get the stochastic signal for each of the three timeframes
ktf1 = TimeframFuction(syminfo.tickerid, tf1, k)
ktf2 = TimeframFuction(syminfo.tickerid, tf2, k)
ktf3 = TimeframFuction(syminfo.tickerid, tf3, k)
// Color the bars based on whether the Stochastic %K is above or below the overbought/oversold thresholds for each time frame
// showtf1 - If the first time frame is selected to be shown, color the bars based on the overbought/oversold thresholds for ktf1
barcolor(showtf1 ? ktf1 > overtf1 or ktf1 < undertf1 ? colortf1 : na : na)
// showtf2 - If the second time frame is selected to be shown, color the bars based on the overbought/oversold thresholds for ktf2
barcolor(showtf2 ? ktf2 > overtf2 or ktf2 < undertf2 ? colortf2 : na : na)
// showtf3 - If the third time frame is selected to be shown, color the bars based on the overbought/oversold thresholds for ktf3
barcolor(showtf3 ? ktf3 > overtf3 or ktf3 < undertf3 ? colortf3 : na : na)
//End |
TOMMAR | https://www.tradingview.com/script/FrYXA8Dw-TOMMAR/ | Tommy_Trader | https://www.tradingview.com/u/Tommy_Trader/ | 214 | 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/
// © Tommy_Trader
//@version=5
indicator(title="TOMMAR_2.0.1", shorttitle="TOMMAR_2.0.1", overlay=true)
//input
source = input.source(close, 'Source')
MAtype = input.string('EMA', 'MA Type', options=['EMA', 'HMA', 'RMA', 'SMA', 'VWMA', 'WMA', 'DEMA', 'LSMA', 'PSAR', 'SWMA', 'TEMA', 'SMMA'])
Signal_ON = input.bool(true, 'Trend Light')
Proj_ON = input.bool(false, 'MA Projection')
MA1ON = input.bool(true, '1st MA', group='1st MA')
MA2ON = input.bool(true, '2nd MA', group='2nd MA')
MA3ON = input.bool(true, '3rd MA', group='3rd MA')
MA4ON = input.bool(true, '4th MA', group='4th MA')
MA5ON = input.bool(true, '5th MA', group='5th MA')
//MA6ON = input.bool(true, '6th MA', group='6th MA')
// MA7ON = input.bool(true, '7th MA', group='7th MA')
// MA8ON = input.bool(true, '8th MA', group='8th MA')
//MALON = MA8ON ? MA8ON : MA7ON ? MA7ON : MA6ON ? MA6ON : MA5ON ? MA5ON : MA4ON ? MA4ON : MA3ON ? MA3ON : MA2ON ? MA2ON : MA1ON ? MA1ON : na
MA1len = input.int(25, 'length', group='1st MA')
MA2len = input.int(50, 'length', group='2nd MA')
MA3len = input.int(100, 'length', group='3rd MA')
MA4len = input.int(200, 'length', group='4th MA')
MA5len = input.int(400, 'length', group='5th MA')
//MA6len = input.int(150, 'length', group='6th MA')
// MA7len = input.int(176, 'length', group='7th MA')
// MA8len = input.int(200, 'length', group='8th MA')
MALlen = MA5ON ? MA5len : MA4ON ? MA4len : MA3ON ? MA3len : MA2ON ? MA2len : MA1ON ? MA1len : na
getMA(float _source, simple int _length) =>
switch MAtype
'EMA' => ta.ema(_source, _length)
'HMA' => ta.hma(_source, _length)
'RMA' => ta.rma(_source, _length)
'SMA' => ta.sma(_source, _length)
'VWMA' => ta.vwma(_source, _length)
'WMA' => ta.wma(_source, _length)
'DEMA' => 2 * ta.ema(_source, _length) - ta.ema(ta.ema(_source, _length), _length)
'LSMA' => 3 * ta.wma(_source, _length) - 2 * ta.sma(_source, _length)
'SWMA' => ta.swma(_source)
'TEMA' => 3 * ta.ema(_source, _length) - 3 * ta.ema(ta.ema(_source, _length), _length) + ta.ema(ta.ema(ta.ema(_source, _length), _length), _length)
'PSAR' => ta.sar(_length/10, _length/10, _length*10)
'SMMA' =>
smma = 0.0
smma := na(smma[1]) ? ta.sma(_source, _length) : (smma[1] * (_length - 1) + _source) / _length
smma
MMA1 = MA1ON ? getMA(source, MA1len) : na
MMA2 = MA2ON ? getMA(source, MA2len) : na
MMA3 = MA3ON ? getMA(source, MA3len) : na
MMA4 = MA4ON ? getMA(source, MA4len) : na
MMA5 = MA5ON ? getMA(source, MA5len) : na
//MMA6 = MA6ON ? getMA(source, MA6len) : na
// MMA7 = MA7ON ? getMA(source, MA7len) : na
// MMA8 = MA8ON ? getMA(source, MA8len) : na
MMAL = getMA(source, MALlen)
leadMAColor = ta.change(MMA1) >=0 and MMA1>MMAL ? #089981 : ta.change(MMA1) <0 and MMA1<MMAL ? #e57373 : ta.change(MMA1) <=0 and MMA1<MMAL ? #e57373 : ta.change(MMA1)>=0 and MMA1<MMAL ? #089981 : #e3bb38
maColor(ma, maRef) => ta.change(ma)>=0 and MMA1>maRef ? #089981 : ta.change(ma)<=0 and MMA1<maRef ? #e57373 : ta.change(ma)>=0 and MMA1<maRef ? #089981 : #e3bb38
plot(MMA1, title='MA1', color=leadMAColor, linewidth=1)
plot(MMA2, title='MA2', color=maColor(MMA1, MMAL), linewidth=1)
plot(MMA3, title='MA3', color=maColor(MMA2, MMAL), linewidth=1)
plot(MMA4, title='MA4', color=maColor(MMA3, MMAL), linewidth=1)
plot(MMA5, title='MA5', color=maColor(MMA4, MMAL), linewidth=1)
//plot(MMA6, title='MA6', color=maColor(MMA5, MMAL), linewidth=1)
// plot(MMA7, title='MA7', color=maColor(MMA6, MMAL), linewidth=1)
// plot(MMA8, title='MA8', color=maColor(MMA7, MMAL), linewidth=1)
Long = Signal_ON and MMA1 > MMA2 and MMA2 > MMA3 and MMA3 > MMA4 and MMA4 > MMA5 ? MMA5
: Signal_ON and MMA1 > MMA2 and MMA2 > MMA3 and MMA3 > MMA4 and na(MMA5) ? MMA4
: Signal_ON and MMA1 > MMA2 and MMA2 > MMA3 and na(MMA4) ? MMA3
: Signal_ON and MMA1 > MMA2 and na(MMA3) ? MMA2
: Signal_ON and na(MMA2) ? MMA1
: na
Short = Signal_ON and MMA1 < MMA2 and MMA2 < MMA3 and MMA3 < MMA4 and MMA4 < MMA5 ? MMA5
: Signal_ON and MMA1 < MMA2 and MMA2 < MMA3 and MMA3 < MMA4 and na(MMA5) ? MMA4
: Signal_ON and MMA1 < MMA2 and MMA2 < MMA3 and na(MMA4) ? MMA3
: Signal_ON and MMA1 < MMA2 and na(MMA3) ? MMA2
: Signal_ON and na(MMA2) ? MMA1
: na
// Long = Signal_ON and MMA1 > MMA2 and MMA2 > MMA3 and MMA3 > MMA4 and MMA4 > MMA5 and MMA5 > MMA6 and MMA6 > MMA7 and MMA7 > MMA8 ? MMAL : na
// Short = Signal_ON and MMA1 < MMA2 and MMA2 < MMA3 and MMA3 < MMA4 and MMA4 < MMA5 and MMA5 < MMA6 and MMA6 < MMA7 and MMA7 < MMA8 ? MMAL : na
plotshape(Long, title = 'Long', style=shape.circle, location=location.absolute, color=#089981, size=size.tiny)
plotshape(Short, title = 'Short', style=shape.circle, location=location.absolute, color=#e57373, size=size.tiny)
// Projection //
ma_proj(_source_, _length_, offset) =>
(getMA(_source_, _length_ - offset) * (_length_ - offset) + _source_ * offset) / _length_
MMA1_1 = MA1ON and Proj_ON ? ma_proj(source, MA1len, 2) : na
MMA1_2 = MA1ON and Proj_ON ? ma_proj(source, MA1len, 4) : na
MMA1_3 = MA1ON and Proj_ON ? ma_proj(source, MA1len, 6) : na
MMA1_4 = MA1ON and Proj_ON ? ma_proj(source, MA1len, 8) : na
MMA1_5 = MA1ON and Proj_ON ? ma_proj(source, MA1len, 10) : na
MMA2_1 = MA2ON and Proj_ON ? ma_proj(source, MA2len, 2) : na
MMA2_2 = MA2ON and Proj_ON ? ma_proj(source, MA2len, 4) : na
MMA2_3 = MA2ON and Proj_ON ? ma_proj(source, MA2len, 6) : na
MMA2_4 = MA2ON and Proj_ON ? ma_proj(source, MA2len, 8) : na
MMA2_5 = MA2ON and Proj_ON ? ma_proj(source, MA2len, 10) : na
MMA3_1 = MA3ON and Proj_ON ? ma_proj(source, MA3len, 2) : na
MMA3_2 = MA3ON and Proj_ON ? ma_proj(source, MA3len, 4) : na
MMA3_3 = MA3ON and Proj_ON ? ma_proj(source, MA3len, 6) : na
MMA3_4 = MA3ON and Proj_ON ? ma_proj(source, MA3len, 8) : na
MMA3_5 = MA3ON and Proj_ON ? ma_proj(source, MA3len, 10) : na
MMA4_1 = MA4ON and Proj_ON ? ma_proj(source, MA4len, 2) : na
MMA4_2 = MA4ON and Proj_ON ? ma_proj(source, MA4len, 4) : na
MMA4_3 = MA4ON and Proj_ON ? ma_proj(source, MA4len, 6) : na
MMA4_4 = MA4ON and Proj_ON ? ma_proj(source, MA4len, 8) : na
MMA4_5 = MA4ON and Proj_ON ? ma_proj(source, MA4len, 10) : na
MMA5_1 = MA5ON and Proj_ON ? ma_proj(source, MA5len, 2) : na
MMA5_2 = MA5ON and Proj_ON ? ma_proj(source, MA5len, 4) : na
MMA5_3 = MA5ON and Proj_ON ? ma_proj(source, MA5len, 6) : na
MMA5_4 = MA5ON and Proj_ON ? ma_proj(source, MA5len, 8) : na
MMA5_5 = MA5ON and Proj_ON ? ma_proj(source, MA5len, 10) : na
plot(MMA1_1, color=leadMAColor, linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(MMA1_2, color=leadMAColor, linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(MMA1_3, color=leadMAColor, linewidth=1, style=plot.style_circles, offset=6, show_last=1)
plot(MMA1_4, color=leadMAColor, linewidth=1, style=plot.style_circles, offset=8, show_last=1)
plot(MMA1_5, color=leadMAColor, linewidth=1, style=plot.style_circles, offset=10, show_last=1)
plot(MMA2_1, color=maColor(MMA1, MMAL), linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(MMA2_2, color=maColor(MMA1, MMAL), linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(MMA2_3, color=maColor(MMA1, MMAL), linewidth=1, style=plot.style_circles, offset=6, show_last=1)
plot(MMA2_4, color=maColor(MMA1, MMAL), linewidth=1, style=plot.style_circles, offset=8, show_last=1)
plot(MMA2_5, color=maColor(MMA1, MMAL), linewidth=1, style=plot.style_circles, offset=10, show_last=1)
plot(MMA3_1, color=maColor(MMA2, MMAL), linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(MMA3_2, color=maColor(MMA2, MMAL), linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(MMA3_3, color=maColor(MMA2, MMAL), linewidth=1, style=plot.style_circles, offset=6, show_last=1)
plot(MMA3_4, color=maColor(MMA2, MMAL), linewidth=1, style=plot.style_circles, offset=8, show_last=1)
plot(MMA3_5, color=maColor(MMA2, MMAL), linewidth=1, style=plot.style_circles, offset=10, show_last=1)
plot(MMA4_1, color=maColor(MMA3, MMAL), linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(MMA4_2, color=maColor(MMA3, MMAL), linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(MMA4_3, color=maColor(MMA3, MMAL), linewidth=1, style=plot.style_circles, offset=6, show_last=1)
plot(MMA4_4, color=maColor(MMA3, MMAL), linewidth=1, style=plot.style_circles, offset=8, show_last=1)
plot(MMA4_5, color=maColor(MMA3, MMAL), linewidth=1, style=plot.style_circles, offset=10, show_last=1)
plot(MMA5_1, color=maColor(MMA4, MMAL), linewidth=1, style=plot.style_circles, offset=2, show_last=1)
plot(MMA5_2, color=maColor(MMA4, MMAL), linewidth=1, style=plot.style_circles, offset=4, show_last=1)
plot(MMA5_3, color=maColor(MMA4, MMAL), linewidth=1, style=plot.style_circles, offset=6, show_last=1)
plot(MMA5_4, color=maColor(MMA4, MMAL), linewidth=1, style=plot.style_circles, offset=8, show_last=1)
plot(MMA5_5, color=maColor(MMA4, MMAL), linewidth=1, style=plot.style_circles, offset=10, show_last=1)
|
Historical Federal Fund Futures Curve | https://www.tradingview.com/script/uI2QAqzL-Historical-Federal-Fund-Futures-Curve/ | BadDerivativesTrader | https://www.tradingview.com/u/BadDerivativesTrader/ | 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/
// Based upon the code of of @ BarefootJoey, @ longfiat, @ OpptionsOnly
// Editor: @BadDerivativesTrader
// @version=5
indicator('Historical Federal Fund Futures Curve', overlay=false)
primarycol = input.color(color.rgb(255, 255, 255), "Primary color")
secondcol = input.color(color.gray, "Secondary color")
width = input(8, 'Spacing between labels', tooltip="Measured in bars")
size = input.string(size.small, "Label Size", options=[size.tiny, size.small, size.normal, size.large, size.huge])
lb = input.int(7, "Lookback for Historical Curve 1", minval=1)
lb2 = input.int(30, "Lookback for Historical Curve 2", minval=1)
percentdecimals = input.int(defval=3, title='% Decimals', minval=0, maxval=10)
symbols = 12
ff_jan = 100 - request.security('ZQF2024', "D", close) // instead of "D" the original script used timeframe.period
ff_dec = 100 - request.security('ZQZ2023', "D", close)
ff_nov = 100 - request.security('ZQX2023', "D", close)
ff_oct = 100 - request.security('ZQV2023', "D", close)
ff_sep = 100 - request.security('ZQU2023', "D", close)
ff_aug = 100 - request.security('ZQQ2023', "D", close)
ff_jul = 100 - request.security('ZQN2023', "D", close)
ff_jun = 100 - request.security('ZQM2023', "D", close)
ff_may = 100 - request.security('ZQK2023', "D", close)
ff_apr = 100 - request.security('ZQJ2023', "D", close)
ff_mar = 100 - request.security('ZQH2023', "D", close)
ff_feb = 100 - request.security('ZQG2023', "D", close)
pos(idx) =>
bar_index - (symbols - idx) * width
truncatepercent(number, percentdecimals) =>
factor = math.pow(10, percentdecimals)
int(number * factor) / factor
draw_label(idx, src, txt, tip, col) =>
var label la = na
label.delete(la)
la := label.new(pos(idx), src, text=txt, color=color.new(color.black,100), style=label.style_label_up, textcolor=col, size=size, tooltip=tip)
la
draw_line(idx1, src1, idx2, src2) =>
var line li = na
line.delete(li)
li := line.new(pos(idx1), src1, pos(idx2), src2, color=primarycol, width=2)
li
draw_line2(idx1, src1, idx2, src2) =>
var line li = na
line.delete(li)
li := line.new(pos(idx1), src1, pos(idx2), src2, style=line.style_dotted, color=color.new(primarycol,33), width=2)
li
draw_line3(idx1, src1, idx2, src2) =>
var line li = na
line.delete(li)
li := line.new(pos(idx1), src1, pos(idx2), src2, style=line.style_dotted, color=color.new(primarycol,66), width=2)
li
draw_label(0, ff_feb, 'Feb-23' ,"Current: " + str.tostring(truncatepercent(ff_feb,percentdecimals)) + (ff_feb>ff_feb[1]?" % & rising":" % & falling") + "\n" + str.tostring(lb) + " days ago: " + str.tostring(truncatepercent(ff_feb[lb],percentdecimals)) + " %\n" + str.tostring(lb2) + " days ago: " + str.tostring(truncatepercent(ff_feb[lb2],percentdecimals)) + " %",secondcol)
draw_label(1, ff_mar, 'Mar-23' ,"Current: " + str.tostring(truncatepercent(ff_mar,percentdecimals)) + (ff_mar>ff_mar[1]?" % & rising":" % & falling") + "\n" + str.tostring(lb) + " days ago: " + str.tostring(truncatepercent(ff_mar[lb],percentdecimals)) + " %\n" + str.tostring(lb2) + " days ago: " + str.tostring(truncatepercent(ff_mar[lb2],percentdecimals)) + " %",secondcol)
draw_label(2, ff_apr, 'Apr-23' ,"Current: " + str.tostring(truncatepercent(ff_apr,percentdecimals)) + (ff_apr>ff_apr[1]?" % & rising":" % & falling") + "\n" + str.tostring(lb) + " days ago: " + str.tostring(truncatepercent(ff_apr[lb],percentdecimals)) + " %\n" + str.tostring(lb2) + " days ago: " + str.tostring(truncatepercent(ff_apr[lb2],percentdecimals)) + " %",primarycol)
draw_label(3, ff_may, 'May-23' ,"Current: " + str.tostring(truncatepercent(ff_may,percentdecimals)) + (ff_may>ff_may[1]?" % & rising":" % & falling") + "\n" + str.tostring(lb) + " days ago: " + str.tostring(truncatepercent(ff_may[lb],percentdecimals)) + " %\n" + str.tostring(lb2) + " days ago: " + str.tostring(truncatepercent(ff_may[lb2],percentdecimals)) + " %",secondcol)
draw_label(4, ff_jun, 'Jun-23' ,"Current: " + str.tostring(truncatepercent(ff_jun,percentdecimals)) + (ff_jun>ff_jun[1]?" % & rising":" % & falling") + "\n" + str.tostring(lb) + " days ago: " + str.tostring(truncatepercent(ff_jun[lb],percentdecimals)) + " %\n" + str.tostring(lb2) + " days ago: " + str.tostring(truncatepercent(ff_jun[lb2],percentdecimals)) + " %",secondcol)
draw_label(5, ff_jul, 'Jul-23' ,"Current: " + str.tostring(truncatepercent(ff_jul,percentdecimals)) + (ff_jul>ff_jul[1]?" % & rising":" % & falling") + "\n" + str.tostring(lb) + " days ago: " + str.tostring(truncatepercent(ff_jul[lb],percentdecimals)) + " %\n" + str.tostring(lb2) + " days ago: " + str.tostring(truncatepercent(ff_jul[lb2],percentdecimals)) + " %",primarycol)
draw_label(6, ff_aug, 'Aug-23' ,"Current: " + str.tostring(truncatepercent(ff_aug,percentdecimals)) + (ff_aug>ff_aug[1]?" % & rising":" % & falling") + "\n" + str.tostring(lb) + " days ago: " + str.tostring(truncatepercent(ff_aug[lb],percentdecimals)) + " %\n" + str.tostring(lb2) + " days ago: " + str.tostring(truncatepercent(ff_aug[lb2],percentdecimals)) + " %",secondcol)
draw_label(7, ff_sep, 'Sep-23' ,"Current: " + str.tostring(truncatepercent(ff_sep,percentdecimals)) + (ff_sep>ff_sep[1]?" % & rising":" % & falling") + "\n" + str.tostring(lb) + " days ago: " + str.tostring(truncatepercent(ff_sep[lb],percentdecimals)) + " %\n" + str.tostring(lb2) + " days ago: " + str.tostring(truncatepercent(ff_sep[lb2],percentdecimals)) + " %",secondcol)
draw_label(8, ff_oct, 'Oct-23' ,"Current: " + str.tostring(truncatepercent(ff_oct,percentdecimals)) + (ff_oct>ff_oct[1]?" % & rising":" % & falling") + "\n" + str.tostring(lb) + " days ago: " + str.tostring(truncatepercent(ff_oct[lb],percentdecimals)) + " %\n" + str.tostring(lb2) + " days ago: " + str.tostring(truncatepercent(ff_oct[lb2],percentdecimals)) + " %",secondcol)
draw_label(9, ff_nov, 'Nov-23' ,"Current: " + str.tostring(truncatepercent(ff_nov,percentdecimals)) + (ff_nov>ff_nov[1]?" % & rising":" % & falling") + "\n" + str.tostring(lb) + " days ago: " + str.tostring(truncatepercent(ff_nov[lb],percentdecimals)) + " %\n" + str.tostring(lb2) + " days ago: " + str.tostring(truncatepercent(ff_nov[lb2],percentdecimals)) + " %",primarycol)
draw_label(10, ff_dec, 'Dec-23' ,"Current: " + str.tostring(truncatepercent(ff_dec,percentdecimals)) + (ff_dec>ff_dec[1]?" % & rising":" % & falling") + "\n" + str.tostring(lb) + " days ago: " + str.tostring(truncatepercent(ff_dec[lb],percentdecimals)) + " %\n" + str.tostring(lb2) + " days ago: " + str.tostring(truncatepercent(ff_dec[lb2],percentdecimals)) + " %",secondcol)
draw_label(11, ff_jan, 'Jan-24' ,"Current: " + str.tostring(truncatepercent(ff_jan,percentdecimals)) + (ff_jan>ff_jan[1]?" % & rising":" % & falling") + "\n" + str.tostring(lb) + " days ago: " + str.tostring(truncatepercent(ff_jan[lb],percentdecimals)) + " %\n" + str.tostring(lb2) + " days ago: " + str.tostring(truncatepercent(ff_jan[lb2],percentdecimals)) + " %",primarycol)
a = draw_line(0, ff_feb, 1, ff_mar)
b = draw_line(1, ff_mar, 2, ff_apr)
c = draw_line(2, ff_apr, 3, ff_may)
d = draw_line(3, ff_may, 4, ff_jun)
e = draw_line(4, ff_jun, 5, ff_jul)
f = draw_line(5, ff_jul, 6, ff_aug)
g = draw_line(6, ff_aug, 7, ff_sep)
h = draw_line(7, ff_sep, 8, ff_oct)
i = draw_line(8, ff_oct, 9, ff_nov)
j = draw_line(9, ff_nov, 10, ff_dec)
k = draw_line(10, ff_dec, 11, ff_jan)
a2 = draw_line2(0, ff_feb[lb], 1, ff_mar[lb])
b2 = draw_line2(1, ff_mar[lb], 2, ff_apr[lb])
c2 = draw_line2(2, ff_apr[lb], 3, ff_may[lb])
d2 = draw_line2(3, ff_may[lb], 4, ff_jun[lb])
e2 = draw_line2(4, ff_jun[lb], 5, ff_jul[lb])
f2 = draw_line2(5, ff_jul[lb], 6, ff_aug[lb])
g2 = draw_line2(6, ff_aug[lb], 7, ff_sep[lb])
h2 = draw_line2(7, ff_sep[lb], 8, ff_oct[lb])
i2 = draw_line2(8, ff_oct[lb], 9, ff_nov[lb])
j2 = draw_line2(9, ff_nov[lb], 10, ff_dec[lb])
k2 = draw_line2(10, ff_dec[lb], 11, ff_jan[lb])
a3 = draw_line3(0, ff_feb[lb2], 1, ff_mar[lb2])
b3 = draw_line3(1, ff_mar[lb2], 2, ff_apr[lb2])
c3 = draw_line3(2, ff_apr[lb2], 3, ff_may[lb2])
d3 = draw_line3(3, ff_may[lb2], 4, ff_jun[lb2])
e3 = draw_line3(4, ff_jun[lb2], 5, ff_jul[lb2])
f3 = draw_line3(5, ff_jul[lb2], 6, ff_aug[lb2])
g3 = draw_line3(6, ff_aug[lb2], 7, ff_sep[lb2])
h3 = draw_line3(7, ff_sep[lb2], 8, ff_oct[lb2])
i3 = draw_line3(8, ff_oct[lb2], 9, ff_nov[lb2])
j3 = draw_line3(9, ff_nov[lb2], 10, ff_dec[lb2])
k3 = draw_line3(10, ff_dec[lb2], 11, ff_jan[lb2])
// Labels
var label langle = na
langle := label.new(pos(11), y=ff_jan[lb], size=size.small, text=str.tostring(lb,"#") + " day", color=color.new(color.white,100), style=label.style_label_left, textcolor=color.new(primarycol,33))
label.delete(langle[1])
var label langle2 = na
langle2 := label.new(pos(11), y=ff_jan[lb2], size=size.small, text=str.tostring(lb2,"#") + " day", color=color.new(color.white,100), style=label.style_label_left, textcolor=color.new(primarycol,66))
label.delete(langle2[1])
var label langle3 = na
langle3 := label.new(pos(11), y=ff_jan, size=size.small, text="Current", color=color.new(color.white,100), style=label.style_label_left, textcolor=color.new(primarycol,0))
label.delete(langle3[1])
cctxtbb = (ff_nov > ff_nov[lb]) and (ff_apr > ff_apr[lb]) ? "Bear" : (ff_nov < ff_nov[lb]) and (ff_apr < ff_apr[lb]) ? "Bull" : "Undetermined"
cctxtst = (ff_nov - ff_apr) > (ff_nov[lb] - ff_apr[lb]) ? "Steepening" : (ff_nov - ff_apr) < (ff_nov[lb] - ff_apr[lb]) ? "Flattening" : na
cctxttt = ((ff_nov > ff_nov[lb]) and (ff_apr > ff_apr[lb])) and ((ff_nov - ff_apr) < (ff_nov[lb] - ff_apr[lb])) ? "Fed tightening. Market expects slower growth. Overheating: Seek commodities, high-yield bonds, & cyclical value. Expect: Rate hikes." : // Bear Flattening = Overheat
((ff_nov > ff_nov[lb]) and (ff_apr > ff_apr[lb])) and ((ff_nov - ff_apr) > (ff_nov[lb] - ff_apr[lb])) ? "Fed tightening. Market expects faster growth. Recovery: Seek stocks, corporate bonds, & cyclical growth." : //Bear Steepening = Recovery
((ff_nov < ff_nov[lb]) and (ff_apr < ff_apr[lb])) and ((ff_nov - ff_apr) > (ff_nov[lb] - ff_apr[lb])) ? "Fed loosening. Market expects faster growth. Reflation: Seek bonds, government bonds, & defensive growth. Expect: Rate cuts. " : // Bull Steepening = Reflation
((ff_nov < ff_nov[lb]) and (ff_apr < ff_apr[lb])) and ((ff_nov - ff_apr) < (ff_nov[lb] - ff_apr[lb])) ? "Fed loosening. Market expects slower growth. Stagflation: Seek cash (money market), inflation-linked bonds, & defensive value." : // Bull Flattening = Stagflation
na
position2 = input.string(position.top_center, "Curve Analysis Info Panel Position", [position.top_right, position.middle_right, position.bottom_right, position.bottom_left, position.middle_left, position.top_left, position.bottom_center, position.top_center]) //, group=grtk)
var table Ticker3 = na
Ticker3 := table.new(position2, 1, 3)
if barstate.islast
table.cell(Ticker3, 0, 0,
text = cctxtbb + " " + cctxtst,
text_size = size,
text_color = cctxtbb == "Bear" ? color.new(color.red,20) : cctxtbb == "Bull" ? color.new(color.green,20) : color.new(color.gray,20),
tooltip = cctxttt) |
Gaps + Imbalances + Wicks (MTF) - By Leviathan | https://www.tradingview.com/script/KLiE8iyE-Gaps-Imbalances-Wicks-MTF-By-Leviathan/ | LeviathanCapital | https://www.tradingview.com/u/LeviathanCapital/ | 2,426 | 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/
// © LeviathanCapital
//@version=5
indicator("Gaps + Imbalances + Wicks (MTF) - By Leviathan", overlay=true, max_boxes_count = 500, max_lines_count = 500)
// General Settings
boxtype = input.string('Imbalance', 'Zone Type ', options=['Imbalance', 'Gap', 'Wick'], group = 'General Settings', inline='1')
tfinput = input.timeframe('', ' - ', group = 'General Settings', inline='1')
showmiddleline = input.bool(true, 'Middle Line ', inline='ln', group = 'General Settings')
showbottomline = input.bool(true, 'Bottom Line ', inline='ln', group = 'General Settings')
showtopline = input.bool(true, 'Top Line ', inline='ln', group = 'General Settings')
showup = input.bool(true, 'UP Zones ', inline='appup', group = 'General Settings')
showdown = input.bool(true, 'DOWN Zones ', inline='appdown', group = 'General Settings')
upcol1 = input.color(#90bff965, ' ', inline='appup', group = 'General Settings')
upbordercol = input.color(color.rgb(76, 175, 79, 100), '', inline='appup', group = 'General Settings')
uptextcol = input.color(color.gray, '', inline='appup', group = 'General Settings')
downcol1 = input.color(#9575cd65, ' ', inline='appdown', group = 'General Settings')
downbordercol = input.color(color.rgb(255, 82, 82, 100), '', inline='appdown', group = 'General Settings')
downtextcol = input.color(color.gray, '', inline='appdown', group = 'General Settings')
extendtilfilled = input.bool(true, '', group = 'General Settings', inline='fill')
filledtype = input.string('Touch', 'Fill Condition ', options=['Touch', 'Full Fill', 'Half Fill'], group = 'General Settings', inline='fill')
lookback = input.bool(true, '', inline='lb', group = 'General Settings')
daysBack = input.float(150, 'Lookback (D) ', group = 'General Settings',inline='lb')
hidefilled = input.bool(false, 'Hide Filled Levels', inline='hd', group='General Settings')
showboxes = input.bool(true, 'Show Boxes', inline='hd', group='General Settings')
conditiontype = input.string('ATR', 'Filter Type ', options=['Percentage', 'ATR', 'None'], group = 'Filter Settings')
atrlength = input.int(30, 'ATR Length + Mult.', step=1, group = 'Filter Settings', inline='atr')
atrmult = input.float(1, '', step=0.1, group = 'Filter Settings', inline='atr')
pctcond = input.float(0.30, 'Percentage + Mult.', step=0.1, group = 'Filter Settings', inline='pct')
pctmult = input.float(1, '', step=0.1, group = 'Filter Settings', inline='pct')
showboxtext = input.bool(true, ' ', group = 'Zone Labels', inline='txt')
textType = input.string('Labels + Timeframe', '', group = 'Zone Labels', options = ['Labels', 'Volume','Labels + Timeframe', 'Labels + Timeframe + Volume'], inline='txt')
textsize = input.string('Size: Tiny', '', options = ['Size: Normal','Size: Large', 'Size: Small', 'Size: Tiny', 'Size: Auto' ], inline='txt', group = 'Zone Labels' )
textvalign = input.string('Center','Position ', options = ['Center', 'Top', 'Bottom'], inline='pos', group = 'Zone Labels')
texthalign = input.string('Middle','', options = ['Middle', 'Right', 'Left'], inline='pos', group = 'Zone Labels')
imbtext = input.string("IMB", title='Imbalance Label', group = 'Zone Labels')
gaptext = input.string("GAP", title='Gap Label', group = 'Zone Labels')
wicktext = input.string('WICK', title='Wick Label', group = 'Zone Labels')
actionbool = input.bool(false, '', inline='act', group='Other Settings')
actiondel = input.string('Stop Zone','', options = ['Stop Zone', 'Delete Zone'], inline='act', group='Other Settings')
nmbars = input.int(3500, 'after', inline='act', group='Other Settings', tooltip = 'Delete/Stop Zone after X number of candles')
linestyle = input.string('Dotted', 'Line Style', ['Solid', 'Dashed', 'Dotted'], inline='l', group='Other Settings')
lineCol = input.color(color.rgb(178, 181, 190, 31), '', inline='l', group='Other Settings')
nbars = input.int(4, 'Zone Length', group='Other Settings', tooltip = 'Length of the zone (in bars) if Fill Condition is turned off')
maxBoxes = input.int(499, 'Max Zones', minval=1, maxval=500, group = 'Other Settings')
// Requesting HTF data
[o, h, l, c] = request.security(syminfo.tickerid, tfinput, [open, high, low, close])
[o1, h1, l1, c1] = request.security(syminfo.tickerid, tfinput, [open[1], high[1], low[1], close[1]])
[o2, h2, l2, c2] = request.security(syminfo.tickerid, tfinput, [open[2], high[2], low[2], close[2]])
t = request.security(syminfo.tickerid, tfinput, time)
tvol = request.security(syminfo.tickerid, tfinput, volume)
atr = request.security(syminfo.tickerid, tfinput, ta.atr(atrlength))
bool new = ta.change(time(tfinput))
// Distances in %
upimbdist = (l-h2) / h2 * 100
downimbdist = (l2-h) / h * 100
upgapdist = (l-h1) / h1 * 100
downgapdist = (l1-h) / h * 100
upwickdist = (h1-math.max(o1, c1)) / math.max(o1, c1) * 100
downwickdist = (math.min(o1, c1)-l1) / l1 * 100
// Candle body size and the size of lower&upper wicks
bodysize = math.abs(o1-c1)
upperWickSize = h1 - math.max(o1, c1)
lowerWickSize = math.min(o1, c1) - l1
// Hide boxes (transparency to 100)
clear = color.rgb(0,0,0,100)
color upcol = showboxes ? upcol1 : clear
color downcol = showboxes ? downcol1 : clear
// Volume
float labeltype = 0
if boxtype=='Imbalance' or boxtype=='Wick'
labeltype := tfinput==timeframe.period ? tvol[1] : tvol[2]
if boxtype=='Gap'
labeltype := tfinput==timeframe.period ? tvol[0] : tvol[1]
// Calculating inRange, used for lookback in days
MSPD = 24 * 60 * 60 * 1000
lastBarDate = timestamp(year(timenow), month(timenow), dayofmonth(timenow), hour(timenow), minute(timenow), second(timenow))
thisBarDate = timestamp(year, month, dayofmonth, hour, minute, second)
daysLeft = math.abs(math.floor((lastBarDate - thisBarDate) / MSPD))
inRange = lookback ? (daysLeft < daysBack) : true
// Timeframe labels
timeframelabel(tfinput) =>
switch tfinput
'' => timeframe.period + (timeframe.isminutes ? 'm' : na)
'1' => '1m'
'2' => '2m'
'3' => '3m'
'4' => '4m'
'5' => '5m'
'10' => '10m'
'15' => '15m'
'30' => '30m'
'60' => '1H'
'120' => '2H'
'240' => '4H'
'480' => '8H'
'720' => '12H'
=> tfinput
// Box Text
var string imbboxtext = na, var string gapboxtext = na, var string wickboxtext = na
if showboxtext and textType == 'Labels'
imbboxtext := str.tostring(imbtext)
gapboxtext := str.tostring(gaptext)
wickboxtext := str.tostring(wicktext)
if showboxtext and textType == 'Volume'
imbboxtext := str.tostring(labeltype, format.volume)
gapboxtext := str.tostring(labeltype, format.volume)
wickboxtext := str.tostring(labeltype, format.volume)
if showboxtext and textType == 'Labels + Timeframe'
imbboxtext := str.tostring(imbtext) + ' • ' + str.tostring(timeframelabel(tfinput))
gapboxtext := str.tostring(gaptext) + ' • ' + str.tostring(timeframelabel(tfinput))
wickboxtext := str.tostring(wicktext) + ' • ' + str.tostring(timeframelabel(tfinput))
if showboxtext and textType == 'Labels + Timeframe + Volume'
imbboxtext := str.tostring(imbtext) + ' • ' + str.tostring(timeframelabel(tfinput)) + ' • ' + str.tostring(labeltype, format.volume)
gapboxtext := str.tostring(gaptext) + ' • ' + str.tostring(timeframelabel(tfinput)) + ' • ' + str.tostring(labeltype, format.volume)
wickboxtext := str.tostring(wicktext) + ' • ' + str.tostring(timeframelabel(tfinput)) + ' • ' + str.tostring(labeltype, format.volume)
// Line style and text label appearance
lineStyle(x) =>
switch x
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
switchhalign(texthalign) =>
switch texthalign
'Middle' => text.align_center
'Right' => text.align_right
'Left' => text.align_left
switchvalign(textvalign) =>
switch textvalign
'Center' => text.align_center
'Top' => text.align_top
'Bottom' => text.align_bottom
switchtextsize(textsize) =>
switch textsize
'Size: Normal' => size.normal
'Size: Small' => size.small
'Size: Tiny' => size.tiny
'Size: Auto' => size.auto
'Size: Large' => size.large
// Conditions for Imbalances, Gaps and Wicks
var bool condition = na, var bool condition2 = na, var bool condition3 = na, var bool condition4 = na, var bool condition5 = na, var bool condition6 = na
if conditiontype == 'Percentage'
condition := upimbdist>(pctcond*pctmult)
condition2 := downimbdist>(pctcond*pctmult)
condition3 := upgapdist>(pctcond*pctmult)
condition4 := downgapdist>(pctcond*pctmult)
condition5 := upwickdist>(pctcond*pctmult)
condition6 := downwickdist>(pctcond*pctmult)
if conditiontype == 'ATR'
condition := (l-h2)>(atrmult*atr)
condition2 := (l2-h)>(atrmult*atr)
condition3 := (l-h1)>(atrmult*atr)
condition4 := (l1-h)>(atrmult*atr)
condition5 := (h1-math.max(o1, c1))>(atrmult*atr)
condition6 := (math.min(o1, c1)-l1)>(atrmult*atr)
if conditiontype == 'None'
condition := true
condition2 := true
condition3 := true
condition4 := true
condition5 := true
condition6 := true
// Drawing Boxes and Lines
var boxes = array.new_box(), var topLines = array.new_line(), var middleLines = array.new_line(), var bottomLines = array.new_line()
if boxtype == 'Imbalance' and (l > h2) and showup and condition and inRange and new
imbboxUP = box.new(t[2], l, time, h2, bgcolor = upcol, border_color=upbordercol,border_width = 1, text=imbboxtext, text_size = switchtextsize(textsize), text_halign = switchhalign(texthalign), text_valign = switchvalign(textvalign), text_color = uptextcol,xloc = xloc.bar_time)
topLine = showtopline ? line.new(t[2], l, time, l, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
bottomLine = showbottomline ? line.new(t[2], h2, time, h2, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
middleLine = showmiddleline ? line.new(t[2], (l + h2)/2, time, (l + h2)/2, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
array.push(topLines, topLine)
array.push(middleLines, middleLine)
array.push(bottomLines, bottomLine)
array.push(boxes, imbboxUP)
if boxtype == 'Imbalance' and (h < l2) and showdown and condition2 and inRange and new
imbboxDOWN = box.new(t[2], h, time, l2, bgcolor = downcol, border_color=downbordercol,border_width = 1, text=imbboxtext, text_size = switchtextsize(textsize), text_halign = switchhalign(texthalign), text_valign = switchvalign(textvalign), text_color = downtextcol, xloc = xloc.bar_time)
topLine = showtopline ? line.new(t[2], l2, time, l2, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
bottomLine = showbottomline ? line.new(t[2], h, time, h, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
middleLine = showmiddleline ? line.new(t[2], (h+l2)/2, time, (h+l2)/2, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
array.push(topLines, topLine)
array.push(middleLines, middleLine)
array.push(bottomLines, bottomLine)
array.push(boxes, imbboxDOWN)
if boxtype == 'Gap' and l > h1 and showup and condition3 and inRange and new
gapboxUP = box.new(t[1], l, time, h1, bgcolor = upcol, border_color=upbordercol, border_width = 1, text=gapboxtext, text_size = switchtextsize(textsize), text_halign = switchhalign(texthalign), text_valign = switchvalign(textvalign), text_color = uptextcol, xloc = xloc.bar_time)
topLine = showtopline ? line.new(t[1], l, time, l, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
bottomLine = showbottomline ? line.new(t[1], h1, time, h1, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
middleLine = showmiddleline ? line.new(t[1], (l+h1)/2, time, (l+h1)/2, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
array.push(topLines, topLine)
array.push(middleLines, middleLine)
array.push(bottomLines, bottomLine)
array.push(boxes, gapboxUP)
if boxtype == 'Gap' and h < l1 and showdown and condition4 and inRange and new
gapboxDOWN = box.new(t[1], l1, time, h, bgcolor = downcol, border_color=downbordercol,border_width = 1, text=gapboxtext, text_size = switchtextsize(textsize), text_halign = switchhalign(texthalign), text_valign = switchvalign(textvalign), text_color = downtextcol, xloc = xloc.bar_time)
topLine = showtopline ? line.new(t[1], l1, time, l1, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
bottomLine = showbottomline ? line.new(t[1], h, time, h, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
middleLine = showmiddleline ? line.new(t[1], (h+l1)/2, time, (h+l1)/2, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
array.push(topLines, topLine)
array.push(middleLines, middleLine)
array.push(bottomLines, bottomLine)
array.push(boxes, gapboxDOWN)
if boxtype == 'Wick' and upperWickSize>(bodysize/6) and showup and condition5 and inRange and new
wickboxUP = box.new(t[1], h1, time, math.max(o1, c1), bgcolor = upcol, border_color=upbordercol,border_width = 1, text=wickboxtext, text_size = switchtextsize(textsize), text_halign = switchhalign(texthalign), text_valign = switchvalign(textvalign), text_color = uptextcol, xloc = xloc.bar_time)
topLine = showtopline ? line.new(t[1], math.max(h1, math.max(o1, c1)), time, math.max(h1, math.max(o1, c1)), color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
bottomLine = showbottomline ? line.new(t[1], math.min(h1, math.max(o1, c1)), time, math.min(h1, math.max(o1, c1)), color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
middleLine = showmiddleline ? line.new(t[1], (h1+math.max(o1, c1))/2, time, (h1+math.max(o1, c1))/2, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
array.push(topLines, topLine)
array.push(middleLines, middleLine)
array.push(bottomLines, bottomLine)
array.push(boxes, wickboxUP)
if boxtype == 'Wick' and lowerWickSize>(bodysize/6) and showdown and condition6 and inRange and new
wickboxDOWN = box.new(t[1], math.min(o1, c1), time, l1, bgcolor = downcol, border_color=downbordercol,border_width = 1, text=wickboxtext, text_size = switchtextsize(textsize), text_halign = switchhalign(texthalign), text_valign = switchvalign(textvalign), text_color = downtextcol, xloc = xloc.bar_time)
topLine = showtopline ? line.new(t[1], math.max(l1, math.min(o1, c1)), time, math.max(l1, math.min(o1, c1)), color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
bottomLine = showbottomline ? line.new(t[1], math.min(l1, math.min(o1, c1)), time, math.min(l1, math.min(o1, c1)), color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
middleLine = showmiddleline ? line.new(t[1], (l1+math.min(o1, c1))/2, time, (l1+math.min(o1, c1))/2, color=lineCol, style=lineStyle(linestyle), xloc = xloc.bar_time) : na
array.push(topLines, topLine)
array.push(middleLines, middleLine)
array.push(bottomLines, bottomLine)
array.push(boxes, wickboxDOWN)
// Looping over the arrays and updating objects
size = array.size(boxes)
if size > 0
for i = 0 to size - 1
j = size - 1 - i
box = array.get(boxes, j)
topLine = array.get(topLines, j)
middleLine = array.get(middleLines, j)
bottomLine = array.get(bottomLines, j)
level = box.get_bottom(box)
level2 = box.get_top(box)
level3 = (level2+level)/2
// Defining fill conditions for zones and lines
var bool filled = na
unifill = (high > level and low < level) or (high > level2 and low < level2)
if filledtype == 'Touch'
filled := (high > level and low < level) or (high > level2 and low < level2)
if filledtype == 'Half Fill'
filled := (high > level3 and low < level3)
if filledtype == 'Full Fill'
for imbboxUP in boxes
filled := (high > level2 and low < level2)
for imbboxDOWN in boxes
filled := (high > level and low < level)
for gapboxUP in boxes
filled := (high > level2 and low < level2)
for gapboxDOWN in boxes
filled := (high > level and low < level)
for wickboxUP in boxes
filled := (high > level2 and low < level2)
for wickboxDOWN in boxes
filled := (high > level and low < level)
if hidefilled and filled
line.delete(topLine)
line.delete(middleLine)
line.delete(bottomLine)
box.delete(box)
array.remove(boxes, j)
array.remove(topLines, j)
array.remove(middleLines, j)
array.remove(bottomLines, j)
continue
if filled and extendtilfilled
array.remove(boxes, j)
array.remove(topLines, j)
array.remove(middleLines, j)
array.remove(bottomLines, j)
continue
box.set_right(box, time+1)
line.set_x2(topLine, time+1)
line.set_x2(middleLine, time+1)
line.set_x2(bottomLine, time+1)
if not filled and not extendtilfilled
array.remove(boxes, j)
array.remove(topLines, j)
array.remove(middleLines, j)
array.remove(bottomLines, j)
continue
box.set_right(box, time+nbars)
line.set_x2(topLine, time+nbars)
line.set_x2(middleLine, time+nbars)
line.set_x2(bottomLine, time+nbars)
if not filled and actionbool and actiondel == 'Delete Zone' and ((box.get_right(box)-box.get_left(box)) > nmbars)
line.delete(topLine)
line.delete(middleLine)
line.delete(bottomLine)
box.delete(box)
if not filled and actionbool and actiondel == 'Stop Zone' and ((box.get_right(box)-box.get_left(box)) > nmbars)
array.remove(boxes, j)
array.remove(topLines, j)
array.remove(middleLines, j)
array.remove(bottomLines, j)
continue
box.set_right(box, time)
line.set_x2(topLine, time)
line.set_x2(middleLine, time)
line.set_x2(bottomLine, time)
// Deleting if the array is too big
if array.size(boxes) >= maxBoxes
int i = 0
while array.size(boxes) >= maxBoxes
box = array.get(boxes, i)
topLine = array.get(topLines, i)
middleLine = array.get(middleLines, i)
bottomLine = array.get(bottomLines, i)
line.delete(topLine)
line.delete(middleLine)
line.delete(bottomLine)
box.delete(box)
array.remove(boxes, i)
array.remove(topLines, i)
array.remove(middleLines, i)
array.remove(bottomLines, i)
i += 1 |
Global Net Liquidity - SPX Fair Value | https://www.tradingview.com/script/Wp8FgaHC-Global-Net-Liquidity-SPX-Fair-Value/ | dharmatech | https://www.tradingview.com/u/dharmatech/ | 416 | 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/
// © dharmatech
//@version=5
indicator("Global Net Liquidity - SPX Fair Value", overlay = true)
line_fed = request.security("FRED:WALCL", "D", close, currency = currency.USD)
line_japan = request.security("FRED:JPNASSETS * FX_IDC:JPYUSD", "D", close, currency = currency.USD)
line_china = request.security("CNCBBS * FX_IDC:CNYUSD", "D", close, currency = currency.USD)
line_uk = request.security("GBCBBS * FX:GBPUSD", "D", close, currency = currency.USD)
line_ecb = request.security("ECBASSETSW * FX:EURUSD", "D", close, currency = currency.USD)
line_rrp = request.security("RRPONTSYD", "D", close, currency = currency.USD)
line_tga = request.security("WTREGEN", "D", close, currency = currency.USD)
total = (line_fed + line_japan + line_china + line_uk + line_ecb - line_rrp - line_tga)
// spx_fv = total / 1000 / 1000 / 1000 * 0.3 - 4500 + 100
// spx_fv = total / 1000 / 1000 / 1000 * 0.275 - 3650
// spx_fv = total / 1000 / 1000 / 1000 * 0.27 - 3550
// spx_fv = total / 1000 / 1000 / 1000 * 0.26 - 3250
spx_fv = total / 1000 / 1000 / 1000 * 0.25 - 2950
upper = spx_fv + 400
lower = spx_fv - 400
// plot(series=total, title = 'Global Net Liquidity', color = color.orange)
plot(series=upper, title = 'Upper Band', color = color.red)
plot(series=spx_fv, title = 'Fair Value', color = color.orange)
plot(series=lower, title = 'Lower Band', color = color.green) |
Trend crossier | https://www.tradingview.com/script/gEsbWhwZ-Trend-crossier/ | Arivadis | https://www.tradingview.com/u/Arivadis/ | 93 | 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/
// © Arivadis
//@version=5
indicator("Trend crossier",overlay = true, max_bars_back = 500)
vector_step = input.int(40, "step for each range for vector")
vector_length = input.int(7, title = "ranges inside each vector")
ema_length = input.int(7, "Ema for vector")
Vector_counter(source)=>
vector_array = array.new_float(0, na)
ema_vector = ta.ema(source, ema_length)
counter_ = 0
step_vect_var = 1
array_var = array.new_float(0, na)
while counter_ < vector_length
array.push(vector_array, source[step_vect_var])
counter_ += 1
step_vect_var += vector_step
while array.size(vector_array) > 2
for i = array.size(vector_array) - 1 to 1
array.push(array_var, math.avg(array.get(vector_array, i), array.get(vector_array, i- 1)))
for i = array.size(vector_array) - 1 to 1
if i < array.size(array_var) - 1
array.set(vector_array, i, array.get(array_var, i))
else
array.remove(vector_array, i)
for i = array.size(array_var) - 1 to 1
array.remove(array_var, i)
diff4 = array.get(vector_array,0) - array.get(vector_array,1)
step = input.int(100, minval = 1, title = "Length every step")
free_space = input.int(10, minval = 1, title = "Give some space to reach max/min")
timeframe = input.int(240, title = "Input high timeframe", options = [60, 240,1440])
timeframe_low = input.int(15, title = "Input low timeframe", options = [5, 15, 30, 60])
close4 = request.security(syminfo.tickerid, str.tostring(timeframe) , Vector_counter(close))
close_low = request.security(syminfo.tickerid, str.tostring(timeframe_low) , Vector_counter(close))
vect_mid = Vector_counter(close)
vect_high = close4
vect_low = close_low
lines_min_to_level = input.int(1, title = "how many lines mean as 1 level (1 + N)")
plot_all_levels = input.bool(false, "Plot every level???")
mult = input.float(2, minval = 1.0, title = 'adr mult')
var plot_lines = 10
float line_1_h = ta.highest(close4, step)[free_space]
float line_1_l = ta.lowest(close4, step)[free_space]
float line_2_h = ta.highest(close4, step)[step+free_space]
float line_2_l = ta.lowest(close4, step)[step]
float line_3_h = ta.highest(close4, step)[step*2 +free_space]
float line_3_l = ta.lowest(close4, step)[step*2 +free_space]
float line_4_h = ta.highest(close4, step)[step*3 +free_space]
float line_4_l = ta.lowest(close4, step)[step*3 +free_space]
float line_5_h = ta.highest(close4, step)[step*4 +free_space]
float line_5_l = ta.lowest(close4, step)[step*4 +free_space]
float line_6_h = ta.highest(close4, step)[step*5 +free_space]
float line_6_l = ta.lowest(close4, step)[step*5 +free_space]
float line_7_h = ta.highest(close4, step)[step*6 +free_space]
float line_7_l = ta.lowest(close4, step)[step*6 +free_space]
float line_8_h = ta.highest(close4, step)[step*7 +free_space]
float line_8_l = ta.lowest(close4, step)[step*7 +free_space]
float line_9_h = ta.highest(close4, step)[step*8 +free_space]
float line_9_l = ta.lowest(close4, step)[step*8 +free_space]
float line_10_h = ta.highest(close4, step)[step*9 +free_space]
float line_10_l = ta.lowest(close4, step)[step*9 +free_space]
line_above = line_1_h + (line_1_h * 0.010)
line_below = line_1_l + (line_1_l * 0.010)
SMA = ta.sma(close, 7)
plot(SMA, title = "SMA")
croosing_counter = 0.0
if SMA > line_1_h
croosing_counter += 0.33
if SMA > line_1_l
croosing_counter += 0.33
if SMA > line_2_h
croosing_counter += 0.33
if SMA > line_2_l
croosing_counter += 0.33
if SMA > line_3_h
croosing_counter += 0.33
if SMA > line_3_l
croosing_counter += 0.33
if SMA > line_4_h
croosing_counter += 0.33
if SMA > line_4_l
croosing_counter += 0.33
if SMA > line_5_h
croosing_counter += 0.33
if SMA > line_5_l
croosing_counter += 0.33
if SMA > line_6_h
croosing_counter += 0.33
if SMA > line_6_l
croosing_counter += 0.33
if SMA > line_7_h
croosing_counter += 0.33
if SMA > line_7_l
croosing_counter += 0.33
if SMA > line_8_h
croosing_counter += 0.33
if SMA > line_8_l
croosing_counter += 0.33
if SMA > line_9_h
croosing_counter += 0.33
if SMA > line_9_l
croosing_counter += 0.33
if SMA > line_above
croosing_counter += 0.33
if SMA > line_below
croosing_counter += 0.33
float line_1_h_ = ta.highest(close, step)[free_space]
float line_1_l_ = ta.lowest(close, step)[free_space]
float line_2_h_ = ta.highest(close, step)[step+free_space]
float line_2_l_ = ta.lowest(close, step)[step]
float line_3_h_ = ta.highest(close, step)[step*2 +free_space]
float line_3_l_ = ta.lowest(close, step)[step*2 +free_space]
float line_4_h_ = ta.highest(close, step)[step*3 +free_space]
float line_4_l_ = ta.lowest(close, step)[step*3 +free_space]
float line_5_h_ = ta.highest(close, step)[step*4 +free_space]
float line_5_l_ = ta.lowest(close, step)[step*4 +free_space]
float line_6_h_ = ta.highest(close, step)[step*5 +free_space]
float line_6_l_ = ta.lowest(close, step)[step*5 +free_space]
float line_7_h_ = ta.highest(close, step)[step*6 +free_space]
float line_7_l_ = ta.lowest(close, step)[step*6 +free_space]
float line_8_h_ = ta.highest(close, step)[step*7 +free_space]
float line_8_l_ = ta.lowest(close, step)[step*7 +free_space]
float line_9_h_ = ta.highest(close, step)[step*8 +free_space]
float line_9_l_ = ta.lowest(close, step)[step*8 +free_space]
float line_10_h_ = ta.highest(close, step)[step*9 +free_space]
float line_10_l_ = ta.lowest(close, step)[step*9 +free_space]
line_above_ = line_1_h_ + (line_1_h_ * 0.010)
line_below_ = line_1_l_ + (line_1_l_ * 0.010)
if SMA > line_1_h_
croosing_counter += 0.17
if SMA > line_1_l_
croosing_counter += 0.17
if SMA > line_2_h_
croosing_counter += 0.17
if SMA > line_2_l_
croosing_counter += 0.17
if SMA > line_3_h_
croosing_counter += 0.17
if SMA > line_3_l_
croosing_counter += 0.17
if SMA > line_4_h_
croosing_counter += 0.17
if SMA > line_4_l_
croosing_counter += 0.17
if SMA > line_5_h_
croosing_counter += 0.17
if SMA > line_5_l_
croosing_counter += 0.17
if SMA > line_6_h_
croosing_counter += 0.17
if SMA > line_6_l_
croosing_counter += 0.17
if SMA > line_7_h_
croosing_counter += 0.17
if SMA > line_7_l_
croosing_counter += 0.17
if SMA > line_8_h_
croosing_counter += 0.17
if SMA > line_8_l_
croosing_counter += 0.17
if SMA > line_9_h_
croosing_counter += 0.17
if SMA > line_9_l_
croosing_counter += 0.17
if SMA > line_above_
croosing_counter += 0.17
if SMA > line_below_
croosing_counter += 0.17
var table atrDisplay = table.new(position.top_right, 1, 1, bgcolor = color.gray, frame_width = 2, frame_color = color.black)
table.cell(atrDisplay, 0, 0, str.tostring(croosing_counter, format.mintick), text_color = color.white)
// computing the strong lines of trend
levels = array.new_float(0)
array.push(levels, line_1_h)
array.push(levels, line_1_l)
array.push(levels, line_2_h)
array.push(levels, line_2_l)
array.push(levels, line_3_h)
array.push(levels, line_3_l)
array.push(levels, line_4_h)
array.push(levels, line_4_l)
array.push(levels, line_5_h)
array.push(levels, line_5_l)
array.push(levels, line_6_h)
array.push(levels, line_6_l)
array.push(levels, line_7_h)
array.push(levels, line_7_l)
array.push(levels, line_8_h)
array.push(levels, line_8_l)
array.push(levels, line_9_h)
array.push(levels, line_9_l)
array.push(levels, line_above)
array.push(levels, line_below)
array.push(levels, line_1_h_)
array.push(levels, line_1_l_)
array.push(levels, line_2_h_)
array.push(levels, line_2_l_)
array.push(levels, line_3_h_)
array.push(levels, line_3_l_)
array.push(levels, line_4_h_)
array.push(levels, line_4_l_)
array.push(levels, line_5_h_)
array.push(levels, line_5_l_)
array.push(levels, line_6_h_)
array.push(levels, line_6_l_)
array.push(levels, line_7_h_)
array.push(levels, line_7_l_)
array.push(levels, line_8_h_)
array.push(levels, line_8_l_)
array.push(levels, line_9_h_)
array.push(levels, line_9_l_)
array.push(levels, line_above_)
array.push(levels, line_below_)
array.sort(levels, order = order.ascending)
ADR = ta.sma((high - low) * mult, step * 10)
the_level_array = array.new_int(0)
counter = 1
if array.size(levels) > 0
for i = 0 to array.size(levels) - 2 by 1
val = array.get(levels, i)
val2 = array.get(levels, i+1)
if val + ADR > val2
array.push(the_level_array, counter)
else
counter += 1
array.push(the_level_array, 0)
strong_levels_array = array.new_float(0)
counter_of_level_power = array.new_int(0)
if array.size(the_level_array) > 0
for i = 0 to array.get(the_level_array, array.size(the_level_array) - 1) by 1
counter_ = 0
summ_of_levels = 0.0
for j = 0 to array.size(the_level_array) - 1
if array.get(the_level_array, j) == i and array.get(the_level_array, j) != 0
counter_ += 1
summ_of_levels += array.get(levels, j)
if counter_ >= lines_min_to_level
array.push(strong_levels_array, summ_of_levels / counter_)
array.push(counter_of_level_power, counter_)
counter_ := 0
summ_of_levels := 0.0
val = array.size(strong_levels_array) > 0 ? array.size(strong_levels_array) - 1 : na
var last_strong_array = array.new_line(0)
if array.size(last_strong_array) > 0
for i = 0 to array.size(last_strong_array) - 1
line.delete(array.get(last_strong_array, i))
array.clear(last_strong_array)
if array.size(strong_levels_array) > 0
for x = 0 to array.size(strong_levels_array) - 1 by 1
mid = array.get(strong_levels_array, x)
with_ = array.get(counter_of_level_power, x)
with = 1
trans = 0
if with_ > 2 and with_ < 4
trans := 70
with := 6
else if with_ >= 4 and with_ < 6
trans := 50
with := 6
else
trans := 30
with := 6
array.push(last_strong_array, line.new(x1=bar_index, y1=mid, x2=bar_index - 1, y2=mid, extend=extend.both, color=color.new(color.aqua, trans),width =with ))
var all_lines = array.new_line(0)
if array.size(all_lines) > 0
for i = 0 to array.size(all_lines) - 1
line.delete(array.get(all_lines, i))
array.clear(all_lines)
if plot_all_levels and array.size(levels) > 0
for x = 0 to (array.size(levels) > 0 ? array.size(levels) - 1 : na) by 1
mid = array.get(levels, x)
array.push(all_lines, line.new(x1=bar_index, y1=mid, x2=bar_index - 1, y2=mid, extend=extend.both, color=color.new(color.blue, 60),style = line.style_solid, width=2))
line_vect_mid = line.new(bar_index, high, bar_index + vector_step, high + vect_mid, xloc=xloc.bar_index,extend = extend.none ,color = color.new(#81cc20, 60), width = 2)
line_vect_high = line.new(bar_index, high + (high * 0.005), bar_index + vector_step,high + vect_high + (high * 0.005), xloc=xloc.bar_index,extend = extend.none ,color = color.new(#8422c5, 60), width = 4)
line_vect_low = line.new(bar_index, high - (high * 0.005), bar_index + vector_step,high + vect_low - (high * 0.005),xloc=xloc.bar_index,extend = extend.none ,color = color.new(color.rgb(183, 50, 50), 60), width = 1)
line.delete(line_vect_mid[1])
line.delete(line_vect_high[1])
line.delete(line_vect_low[1]) |
Global Net Liquidity - Dow Jones Global Fair Value | https://www.tradingview.com/script/WEV1uSi7-Global-Net-Liquidity-Dow-Jones-Global-Fair-Value/ | dharmatech | https://www.tradingview.com/u/dharmatech/ | 86 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dharmatech
//@version=5
indicator("Global Net Liquidity - Dow Jones Global Fair Value Bands", overlay = true)
line_fed = request.security("FRED:WALCL", "D", close, currency = currency.USD)
line_japan = request.security("FRED:JPNASSETS * FX_IDC:JPYUSD", "D", close, currency = currency.USD)
line_china = request.security("CNCBBS * FX_IDC:CNYUSD", "D", close, currency = currency.USD)
line_uk = request.security("GBCBBS * FX:GBPUSD", "D", close, currency = currency.USD)
line_ecb = request.security("ECBASSETSW * FX:EURUSD", "D", close, currency = currency.USD)
line_rrp = request.security("RRPONTSYD", "D", close, currency = currency.USD)
line_tga = request.security("WTREGEN", "D", close, currency = currency.USD)
total = (line_fed + line_japan + line_china + line_uk + line_ecb - line_rrp - line_tga)
fv = total / 1000 / 1000 / 1000 * 0.03 - 350
upper = fv + 30
lower = fv - 45
plot(series=upper, title = 'Upper Band', color = color.red)
plot(series=fv, title = 'Fair Value', color = color.orange)
plot(series=lower, title = 'Lower Band', color = color.green) |
Global Net Liquidity | https://www.tradingview.com/script/hky2sJKD-Global-Net-Liquidity/ | dharmatech | https://www.tradingview.com/u/dharmatech/ | 945 | 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/
// © dharmatech
//@version=5
indicator("Global Net Liquidity", overlay = false)
line_fed = request.security("FRED:WALCL", "D", close, currency = currency.USD)
line_japan = request.security("FRED:JPNASSETS * FX_IDC:JPYUSD", "D", close, currency = currency.USD)
line_china = request.security("CNCBBS * FX_IDC:CNYUSD", "D", close, currency = currency.USD)
line_uk = request.security("GBCBBS * FX:GBPUSD", "D", close, currency = currency.USD)
line_ecb = request.security("ECBASSETSW * FX:EURUSD", "D", close, currency = currency.USD)
line_rrp = request.security("RRPONTSYD", "D", close, currency = currency.USD)
line_tga = request.security("WTREGEN", "D", close, currency = currency.USD)
total = (line_fed + line_japan + line_china + line_uk + line_ecb - line_rrp - line_tga)
plot(series=total, title = 'Global Net Liquidity', color = color.orange)
|
Opening Range & Daily and Weekly Pivots | https://www.tradingview.com/script/OdK0iJkh-Opening-Range-Daily-and-Weekly-Pivots/ | StockJustice | https://www.tradingview.com/u/StockJustice/ | 221 | 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/
// © StockJustice
//@version=5
indicator('Opening Range & Daily and Weekly Pivots', shorttitle='ORB + Pivots', overlay=true)
YesterdayHigh = request.security(syminfo.tickerid, 'D', high[1], lookahead=barmerge.lookahead_on)
YesterdayLow = request.security(syminfo.tickerid, 'D', low[1], lookahead=barmerge.lookahead_on)
LastWeekHigh = request.security(syminfo.tickerid, 'W', high[1], lookahead=barmerge.lookahead_on)
LastWeekLow = request.security(syminfo.tickerid, 'W', low[1], lookahead=barmerge.lookahead_on)
today = year == year(timenow) and month == month(timenow) and dayofmonth == dayofmonth(timenow)
plot(today ? YesterdayHigh : na, style=plot.style_circles, color=color.new(color.green, 0), linewidth=2)
plot(today ? YesterdayLow : na, style=plot.style_circles, color=color.new(color.red, 0), linewidth=2)
plot(dayofweek==dayofweek(timenow) ? LastWeekHigh : na, style=plot.style_circles, color=color.new(#3912e7, 0), linewidth=2)
plot(dayofweek==dayofweek(timenow) ? LastWeekLow : na, style=plot.style_circles, color=color.new(color.purple, 0), linewidth=2)
alertcondition(close > YesterdayHigh, title='Breakout Above Yesterday High', message='We are now trading higher than the previous daily high.')
alertcondition(close < YesterdayLow, title='Breakdown Below Yesterday Low', message='We are now trading lower than the previous daily low.')
alertcondition(close > LastWeekHigh, title='Breakout Above Last Week High', message='We are now trading higher than the last week high.')
alertcondition(close < LastWeekLow, title='Breakdown Below Last Week Low', message='We are now trading lower than the last week low.')
inputMax = input(30, title= "ORB total time (minutes)")
sessionInput = input.session("0930-1000", title="ORB Timeframe")
t = time(timeframe.period, sessionInput)
hide = (timeframe.isintraday and timeframe.multiplier <= inputMax)
in_session = not na(t)
is_first = in_session and not in_session[1]
var float orb_high = 0.0
var float orb_low = 0.0
if is_first
orb_high := high
orb_low := low
else
orb_high := orb_high[1]
orb_low := orb_low[1]
if high > orb_high and in_session
orb_high := high
if low < orb_low and in_session
orb_low := low
plot(hide ? orb_high : na, style=plot.style_circles, color = close > orb_high ? color.rgb(168, 255, 17) : color.blue, title = "ORB High", linewidth = 1)
plot(hide ? orb_low : na, style=plot.style_circles, color = close < orb_low ? color.rgb(199, 55, 125) : color.white, title = "ORB Low", linewidth = 1)
alertcondition(close > orb_high, title='Breakout Above ORB High', message='Price has broken above the opening range.')
alertcondition(close < orb_low, title='Breakdown Below ORB Low', message='Price has broken below the opening range.')
//// |
WON Weeklies | https://www.tradingview.com/script/orHYD05E-WON-Weeklies/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 204 | 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/
// © Amphibiantrading
//@version=5
indicator("WON Weeklies", overlay = true)
//inputs
var g_5weeks = "5 Weeks or More Up"
showUpWeks = input(true, 'Highlight 5 or more weeks up in a row', group = g_5weeks)
boxBgCol = input(color.new(color.blue,90), 'Box Background Color',group = g_5weeks)
boxBorderCol = input(color.blue, 'Box Border Color',group = g_5weeks)
var g_3wt = '3 Weeks Tight'
twtBg = input(false, "Color background if 3WT", group = g_3wt, inline = 'a')
circleClose = input(true, "Circles around tight closes",group = g_3wt, inline ='b')
circleClo = input(color.new(color.aqua,70), "",group = g_3wt, inline = 'b')
bgCol = input(color.new(color.aqua,70), "",group = g_3wt, inline = 'a')
tightMax = input.float(1.5, "Tight Close Max", minval = .25, maxval = 3, step = .25, group = g_3wt)
// 5 or more weeks in a row up
// declare variables for box inputs
var int startindex = na
var float lowestlow = na
var float highesthigh = na
var box five_weeks = na
var fiveWeekBool = false
// define positive close and make sure it is confirned
closeup = close > close[1] and timeframe.isweekly and barstate.isconfirmed
closedown = close < close[1] and timeframe.isweekly and barstate.isconfirmed
// declare counter and start variable
var start_counter = false
var counter = 0
//start the counter
start_counter := closeup ? true : false
counter := start_counter ? counter + 1 : counter
//declare arrays to get the low and high values
var lows = array.new<float>(5)
var highs = array.new<float>(5)
if counter == 5
lows := array.from(low[4], low[3], low[2], low[1], low)
highs := array.from(high[4], high[3], high[2], high[1], high)
// reassign the box variables to get get the highs, lows and start bar_index
lowestlow := array.min(lows)
highesthigh := array.max(highs)
startindex := counter >= 5 ? bar_index - 4 : na
//plot the box
if counter == 5 and na(five_weeks) and showUpWeks
five_weeks := box.new(startindex, highesthigh, bar_index, lowestlow, border_color = boxBorderCol, border_style = line.style_dotted, bgcolor = boxBgCol)
fiveWeekBool := true
// change box variables if more than 5 weeks up in a row
if closeup and not na(five_weeks) and showUpWeks
box.set_right(five_weeks, bar_index)
box.set_top(five_weeks, math.max(high, highesthigh))
// reset the counters
start_counter := closedown ? false : start_counter
counter := not start_counter ? 0 : counter
// reset the arrays and box
if counter == 0
array.clear(lows)
array.clear(highs)
five_weeks := na
fiveWeekBool := false
// 3 Weeks Tight
//calculate 3wt
percentchangefirst = ((close - close[1]) / close[1]) * 100
percentchangesecond = ((close[1] - close[2]) / close[2]) * 100
twt = math.abs(percentchangefirst) <= tightMax and math.abs(percentchangesecond) <= tightMax and timeframe.isweekly
//create label circles
if twt and circleClose
label.new(bar_index[1], close[1], style = label.style_circle, color=circleClo)
// color the background
bgcolor(twt and twtBg and not twt[1]? bgCol : na)
bgcolor(twt and twtBg and not twt[1]? bgCol : na, offset = -1)
bgcolor(twt and twtBg and not twt[1]? bgCol : na, offset = -2)
bgcolor(twt and twt[1] and twtBg? bgCol : na )
//alerts
alertcondition(twt, '3 Weeks Tight', '{{ticker}} 3 Weeks Tight')
alertcondition(fiveWeekBool and not fiveWeekBool[1], '5 Weeks Up', '{{ticker}} up 5 weeks in a row')
|
Volume and vPOC Insights | https://www.tradingview.com/script/lEWxr7lT-Volume-and-vPOC-Insights/ | Texmoonbeam | https://www.tradingview.com/u/Texmoonbeam/ | 639 | 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/
// © Texmoonbeam
//@version=5
indicator("Volume and vPOC Insights", overlay = true, max_boxes_count = 100, max_lines_count = 100, max_labels_count = 500, max_bars_back = 5000)
// hide candles where volume is not top x% based on lookback
// for shown candles show position.top_center
// optional draw lines from nPOC to next touch level
//Inputs
groupVis = "Visual settings"
lookback = input.int(defval=200, title="Lookback", minval = 1, maxval = 5000, group=groupVis)
hidecol = input.color(color.new(color.white, 30), "Hide Candle Colour", group=groupVis)
vol = input.float(defval=70, title="% of Highest Volume", minval=0, maxval = 100, group=groupVis, tooltip="This setting will cause any candle whose volume is less than x % of the highest within the lookback, to be obscured")
showrange = input.bool(defval = false, title="Show untapped highs/lows of volume candles", group=groupVis, inline = "1")
extendnpoc = input.bool(defval = false, title="Extend (naked) vPOCs", group=groupVis, inline = "2")
showema = input.bool(defval = false, title="Show EMA using vPOC prices", group=groupVis, inline = "3")
length = input.int(defval=50, title="Length", minval = 1, maxval = 999, group=groupVis, inline = "3")
i_vpocCol = input.color(color.teal, "VPOC ", group=groupVis, inline = "4")
i_vpocThresholdCol = input.color(color.maroon, "Threshold exceeded", group=groupVis, inline = "4")
line_style = input.string(line.style_solid, 'Line Style', options=[line.style_solid, line.style_dotted, line.style_dashed], group=groupVis, inline = "5")
line_width = input.int(defval=1, title="Line Width", minval = 1, maxval = 10, group=groupVis, inline = "5")
//POC inputs // credit quantifytools
groupPoc = "VPOC settings"
i_source = input.source(close, "Source for VPOC price", group=groupPoc, tooltip="E.g. With close as source, a point of control is calculated using LTF close.")
i_vpocThreshold = input.int(50, "Threshold % for VPOC highlight", maxval=100, minval=1, group=groupPoc)
//Timeframe inputs // credit quantifytools
groupTf = "Timeframe settings"
i_tf1 = input.timeframe("1", "LTF for charts <= 30 min", group=groupTf, tooltip="E.g. Lower timeframe data is fetched from 1 minute timeframe when viewing charts at or below 30 min. The lower the chosen timeframe, the more precision you get, but with the cost of less historical data and slower loading time.")
i_tf2 = input.timeframe("3", "LTF for charts > 30 min & <= 3 hours", group=groupTf)
i_tf3 = input.timeframe("15", "LTF for charts > 3 hours & <= 8 hours", group=groupTf)
i_tf4 = input.timeframe("60", "LTF for charts > 8 hours & <= 1D", group=groupTf)
i_tf5 = input.timeframe("120", "LTF for charts > 1D & <= 3D", group=groupTf)
i_tf6 = input.timeframe("240", "LTF for charts > 3D", group=groupTf)
//LTF data // credit quantifytools
//Current timeframe in minutes
currentTimeframe = timeframe.in_seconds(timeframe.period) / 60
//Dynamic timeframe
dynTf = currentTimeframe <= 30 ? i_tf1 : currentTimeframe > 30 and currentTimeframe <= 180 ? i_tf2 :
currentTimeframe > 180 and currentTimeframe <= 480 ? i_tf3 : currentTimeframe > 480 and currentTimeframe <= 1440 ? i_tf4 :
currentTimeframe > 1440 and currentTimeframe <= 4320 ? i_tf5 : currentTimeframe > 4320 ? i_tf6 : na
//Function to fetch LTF data // credit quantifytools
ltfStats() =>
volpart = na(volume) == false ? volume : 0
[i_source, volpart]
[ltfSrc, ltfVolume] = request.security_lower_tf(syminfo.tickerid, dynTf, ltfStats())
//VPOC // credit quantifytools
//Max volume from LTF volume array
maxVolume = array.max(ltfVolume)
//Array index of max volume
indexOfMaxVolume = array.indexof(ltfVolume, maxVolume)
//Price at max volume (VPOC)
maxVol = array.size(ltfSrc) > 0 ? array.get(ltfSrc, indexOfMaxVolume) : na
vpocThresholdMet = maxVolume >= (volume * (i_vpocThreshold / 100)) and barstate.isconfirmed
vpocColor = vpocThresholdMet ? i_vpocThresholdCol : i_vpocCol
vh = ta.highest(volume, lookback)
plotcandle(open, high, low, close, title='Noise', color = volume < (vh/100)*vol ? hidecol : color.new(color.white, 100), wickcolor=volume < (vh/100)*vol ? hidecol : color.new(color.white, 100), bordercolor=volume < (vh/100)*vol ? hidecol : color.new(color.white, 100))
plotshape(na(volume) == false and volume > (vh/100)*vol ? maxVol : na, title="VPOC", style=shape.cross, text="", color=vpocColor, location=location.absolute, size=size.tiny, textcolor=color.white)
// Lines for ema, Vol and vPOC
vema = ta.ema(maxVol, length)
plot(showema ? vema : na, color=i_vpocCol)
var npoclines = array.new_line()
var npocfloat = array.new_float()
var npoctime = array.new_int()
var npoctimetemp = array.new_int()
var npocfloattemp = array.new_float()
var npochighlines = array.new_line()
var npochigh = array.new_float()
var npochightime = array.new_int()
var npochightemp = array.new_float()
var npochightimetemp = array.new_int()
var npoclowlines = array.new_line()
var npoclow = array.new_float()
var npoclowtime = array.new_int()
var npoclowtemp = array.new_float()
var npoclowtimetemp = array.new_int()
arrayadd(n, arr1, arr2) =>
array.push(arr2, array.get(arr1, n))
if (array.size(npoclines) > 0)
for x = array.size((npoclines))-1 to 0
delline1 = array.remove(npoclines, x)
line.delete(delline1)
//label.new(x=time, y=high, text="deleted", xloc=xloc.bar_time, color=color.white, style=label.style_none, textcolor=color.green, size=size.normal, textalign=text.align_right)
if (array.size(npochighlines) > 0)
for x = array.size((npochighlines))-1 to 0
delline2 = array.remove(npochighlines, x)
line.delete(delline2)
if (array.size(npoclowlines) > 0)
for x = array.size((npoclowlines))-1 to 0
delline3 = array.remove(npoclowlines, x)
line.delete(delline3)
if (array.size((npocfloat)) > 0)
for x = array.size((npocfloat))-1 to 0
if array.get(npoctime, x) < time and not((high > array.get(npocfloat, x) and low <= array.get(npocfloat, x)) or (low < array.get(npocfloat, x) and high >= array.get(npocfloat, x)))
//label.new(x=time, y=high, text="added", xloc=xloc.bar_time, color=color.white, style=label.style_none, textcolor=color.green, size=size.normal, textalign=text.align_right)
arrayadd(x, npocfloat, npocfloattemp)
arrayadd(x, npoctime, npoctimetemp)
npocfloat := array.copy(npocfloattemp)
array.clear(npocfloattemp)
npoctime := array.copy(npoctimetemp)
array.clear(npoctimetemp)
if (array.size((npochigh)) > 0)
for x = array.size((npochigh))-1 to 0
if array.get(npochightime, x) < time and not((high > array.get(npochigh, x) and low <= array.get(npochigh, x)) or (low < array.get(npochigh, x) and high >= array.get(npochigh, x)))
//label.new(x=time, y=high, text="added", xloc=xloc.bar_time, color=color.white, style=label.style_none, textcolor=color.green, size=size.normal, textalign=text.align_right)
arrayadd(x, npochigh, npochightemp)
arrayadd(x, npochightime, npochightimetemp)
npochigh := array.copy(npochightemp)
array.clear(npochightemp)
npochightime := array.copy(npochightimetemp)
array.clear(npochightimetemp)
if (array.size((npoclow)) > 0)
for x = array.size((npoclow))-1 to 0
if array.get(npoclowtime, x) < time and not((high > array.get(npoclow, x) and low <= array.get(npoclow, x)) or (low < array.get(npoclow, x) and high >= array.get(npoclow, x)))
//label.new(x=time, y=low, text="added", xloc=xloc.bar_time, color=color.white, style=label.style_none, textcolor=color.green, size=size.normal, textalign=text.align_right)
arrayadd(x, npoclow, npoclowtemp)
arrayadd(x, npoclowtime, npoclowtimetemp)
npoclow := array.copy(npoclowtemp)
array.clear(npoclowtemp)
npoclowtime := array.copy(npoclowtimetemp)
array.clear(npoclowtimetemp)
if (extendnpoc == true and volume >= (vh/100)*vol and maxVol > 0 )
array.push(npocfloat, maxVol)
array.push(npoctime, time)
if (showrange == true and volume >= (vh/100)*vol and maxVol > 0 )
array.push(npochigh, high)
array.push(npochightime, time)
array.push(npoclow, low)
array.push(npoclowtime, time)
if (bar_index == last_bar_index)
//label.new(x=time, y=high, text=str.tostring(array.size(npocfloat)), xloc=xloc.bar_time, color=color.white, style=label.style_none, textcolor=color.green, size=size.normal, textalign=text.align_right)
if (array.size((npocfloat)) > 0)
for y = array.size((npocfloat))-1 to 0
e = line.new(array.get(npoctime, y), array.get(npocfloat, y), time, array.get(npocfloat, y), xloc = xloc.bar_time, color= i_vpocCol, width = line_width, style = line_style)
array.push(npoclines, e)
if (array.size((npochigh)) > 0)
for y = array.size((npochigh))-1 to 0
e = line.new(array.get(npochightime, y), array.get(npochigh, y), time, array.get(npochigh, y), xloc = xloc.bar_time, color= i_vpocCol, width = line_width, style = line_style)
array.push(npochighlines, e)
if (array.size((npoclow)) > 0)
for y = array.size((npoclow))-1 to 0
e = line.new(array.get(npoclowtime, y), array.get(npoclow, y), time, array.get(npoclow, y), xloc = xloc.bar_time, color= i_vpocCol, width = line_width, style = line_style)
array.push(npoclowlines, e)
// if barstate.islast
// label.new(x=time, y=high, text=str.tostring(array.get(npocfloat, 0)), xloc=xloc.bar_time, color=color.white, style=label.style_none, textcolor=color.green, size=size.normal, textalign=text.align_right)
|
Relative Price Volume | https://www.tradingview.com/script/6F2rdwPz-Relative-Price-Volume/ | karimka | https://www.tradingview.com/u/karimka/ | 49 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © karimka
//@version=5
indicator("Relative Price Volume", "RPV", overlay = true)
// The length is the number of periods to calculate the avg.
period = input(10,"Periods", "Number of candles to use for avg")
// shortFactor = input.float(.4, "Short Factor", minval=0, maxval=1, step=.1)
// longFactor = input.float(.6, "Long Factor", minval=0, maxval=1, step=.1)
sizeFactor = input.float(.1, "Size Factor", minval=.1, maxval=.5, step=.05)
candleHeight = math.abs(close-open)
candleSizeAvg = ta.sma(candleHeight, period)
largeFactor = (1+sizeFactor)
smallFactor = (1-sizeFactor)
// Is the candle long or short
longCandle = candleHeight > (candleSizeAvg * largeFactor)
shortCandle = candleHeight < (candleSizeAvg * smallFactor)
// Is Volume average, high, or low
avgVolume = ta.sma(volume, period)
highVol = volume > (avgVolume * largeFactor)
lowVol = volume < (avgVolume * smallFactor)
anomoly = (highVol and shortCandle) or (lowVol and longCandle)
plotshape(title="Signal", series=(anomoly ? candleHeight: na), color=color.yellow, textcolor=color.yellow, style=shape.xcross, location=location.belowbar, size=size.auto)
|
Consecutive Momentum | https://www.tradingview.com/script/MtrW27lX/ | Seungdori_ | https://www.tradingview.com/u/Seungdori_/ | 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/
// © Seungdori_
//@version=5
indicator('Consecutive Momentum')
MAX_Length = input.int(defval = 120, title='MAX Length', minval = 1, step=1, group = 'Length')
EMA_Length = input.int(defval = 120, title='WMA Length', minval = 1, step=1, group = 'Length')
show_dir = input.bool(defval = true, title='Show Direction?')
show_candle = input.string(defval = 'Percent', title='Show Consecutive Candle/Percent/Heikin Ashi Percent?', options =['Candle', 'Percent'])
heikinashi = input.bool(defval = false, title = 'Use Source as HeikinAshi', group = 'Source')
var int cnt_up = 0
var int cnt_down = 0
var float consecutive_plus = 0.0
var float consecutive_minus = 0.0
src_open = open
src_close = close
heikinashi_close = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
heikinashi_open = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
if heikinashi
src_close := heikinashi_close
src_open := heikinashi_open
barup = src_close > src_open
bardown = src_close < src_open
if barup
cnt_up := cnt_up[1] +1
consecutive_plus := consecutive_plus[1] + (src_close[1]-src_open[1])
cnt_down := 0
consecutive_minus := 0
if bardown
cnt_down := cnt_down[1] +1
consecutive_minus := consecutive_minus[1] + (src_open[1] - src_close[1])
cnt_up := 0
consecutive_plus := 0
consecutive_plus_percent = (src_close-src_close[cnt_up])*100/src_close
consecutive_minus_percent = ((src_close[cnt_down])-src_close)*100/src_close[cnt_down]
max_consecutive_up = ta.highest(cnt_up, MAX_Length)
max_consecutive_down = ta.highest(cnt_down, MAX_Length)
ma_max = show_dir ? ta.wma(cnt_up, EMA_Length) : ta.ema((cnt_up+cnt_down)/2, EMA_Length)
ma_min = show_dir ? ta.wma(cnt_down, EMA_Length)*-1 : na
if show_candle == 'Percent'
max_consecutive_up := ta.highest(consecutive_plus_percent, MAX_Length)
max_consecutive_down := ta.highest(consecutive_minus_percent, MAX_Length)
ma_max := show_dir ? ta.wma(max_consecutive_up, EMA_Length) : ta.wma((max_consecutive_up+max_consecutive_down)/2, EMA_Length)
ma_min := show_dir ? ta.wma(max_consecutive_down, EMA_Length)*-1 : na
hline(5, title ='5', color=color.new(color.white,40), linestyle=hline.style_dashed)
hline(show_dir ? -5 : na, title ='-5', color=color.new(color.white,40), linestyle=hline.style_dashed)
plot(show_candle=='Candle' ? cnt_up : consecutive_plus_percent, title='Consecutive Bars Up', color=color.new(color.green, 0), style=plot.style_histogram, linewidth=1)
plot(max_consecutive_up, title = 'Max Consecutive Up Bars', color = color.new(#7ff2a4, 33), style=plot.style_linebr)
plot(show_candle=='Candle' ? (show_dir ? -cnt_down : cnt_down) : (show_dir ? -consecutive_minus_percent : consecutive_minus_percent), title='Consecutive Bars Down', color=color.new(color.red, 0), style=plot.style_histogram, linewidth=1)
plot(show_dir ? -max_consecutive_down : max_consecutive_down, title = 'Max Consecutive Down Bars', color = color.new(#e986af, 20), style=plot.style_linebr)
plot(ma_max, title = 'MA cnt_up', color=color.new(#21b1f3, 0), style=plot.style_line, trackprice = true)
plot(ma_min, title = 'MA cnt_down', color=color.new(#21b1f3, 20), style=plot.style_line, trackprice = true)
|
InsideBar2.0 | https://www.tradingview.com/script/wX8k4Mmh-InsideBar2-0/ | AtulGoswami | https://www.tradingview.com/u/AtulGoswami/ | 297 | 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/
// © AtulGoswami
//@version=5
indicator("InsideBar2.0", overlay = true)
var float h1=na
var float l1 = na
var int mindex=na
var float target1 = na
var float target2 = na
var float target3 = na
var float target4 = na
insidebar()=> (close[1] >open[1] and close<close[1] and close>open[1] and open<close[1] and open>open[1]) or (close[1]<open[1] and close>close[1] and close<open[1] and open>close[1] and open<open[1])
//high<high[1] and low >low[1]
ins=insidebar()
if insidebar()
// if high < high[1] and low >low[1]
h1 := high[1]
l1 := low[1]
mindex:=bar_index[1]
target1:= h1+(h1-l1)
target2:=h1+2*(h1-l1)
target3:=l1-(h1-l1)
target4:=l1-(2*(h1-l1))
//if high <= high[1] and low >= low[1]
barcolor(ins? color.yellow: close>open? color.green:color.red)
hiline=line.new(mindex, h1, bar_index, h1, color=color.green, extend=extend.right, width = 2)
line.delete(hiline[1])
loline=line.new(mindex, l1, bar_index, l1, color=color.red, extend=extend.right, width = 2)
line.delete(loline[1])
linefill.new(hiline, loline, color=color.new(color.purple, 90))
targetline=close>h1?line.new(mindex, target1, bar_index, target1, color=color.aqua, extend=extend.right, width = 2, style=line.style_dotted):line.new(mindex, target3, bar_index, target3, color=color.aqua, extend=extend.right, width = 2, style=line.style_dotted)
lable1=close>h1?label.new(mindex, target1, text="Target1", color=color.blue, textcolor = color.white, style=label.style_none):label.new(mindex, target3, text="Target1", color=color.blue, textcolor = color.white, style=label.style_none)
label.delete(lable1[1])
line.delete(targetline[1])
targetline2=close>h1?line.new(mindex, target2, bar_index, target2, color=color.fuchsia, extend=extend.right, width = 2, style=line.style_dotted):line.new(mindex, target4, bar_index, target4, color=color.fuchsia, extend=extend.right, width = 2, style=line.style_dotted)
line.delete(targetline2[1])
lable2=close>h1?label.new(mindex, target2, text="Target2", color=color.blue, textcolor = color.white, style=label.style_none):label.new(mindex, target4, text="Target2", color=color.blue, textcolor = color.white, style=label.style_none)
label.delete(lable2[1]) |
RISK MANAGEMENT | https://www.tradingview.com/script/7haD48rW-RISK-MANAGEMENT/ | shakibsharifian | https://www.tradingview.com/u/shakibsharifian/ | 20 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © shakibsharifian
//@version=5
indicator("RISK MANAGEMENT",overlay=true)
roundDec(val,dec)=>
ret=math.pow(10,-dec)*(int(val*math.pow(10,dec)))
vlinePrc(BarIndex, Color, LineStyle, LineWidth,prc1,prc2) => // Verticle Line, 54 lines maximum allowable per indicator
barindx=bar_index+BarIndex
_return = line.new(barindx, prc1, barindx, prc2, xloc.bar_index, extend.none, Color, LineStyle, LineWidth)
//
deci=input.int(5,title='ROUND to DECIMAL:',group='⌘ GENERAL',inline='a')
feebuyPer=input.float(0.07,title='Buying Fee (%):',group='⌘ GENERAL',inline='a')
feesellPer=input.float(0.07,title='Selling Fee (%):',group='⌘ GENERAL',inline='a')
Colblnc1=input.color(color.new(color.maroon,0),title='0% Line ',group='😐 0% LINE',inline='a')
Colblnc2=input.color(color.new(color.white,0),title='0% Line ',group='😐 0% LINE',inline='a')
bnft=input.float(2,title='BENEFIT (%):',group='💲💲💲 GOAL',inline='a')
Colbnft1=input.color(color.new(color.lime,0),title='GOAL Line' ,group='💲💲💲 GOAL',inline='b')
Colbnft2=input.color(color.new(color.yellow,0),title='GOAL Line',group='💲💲💲 GOAL',inline='b')
en1=input.bool(false,group='BUY ORDERS',inline='a')
en2=input.bool(false,group='BUY ORDERS',inline='b')
en3=input.bool(false,group='BUY ORDERS',inline='c')
en4=input.bool(false,group='BUY ORDERS',inline='d')
en5=input.bool(false,group='BUY ORDERS',inline='e')
en6=input.bool(false,group='BUY ORDERS',inline='f')
en7=input.bool(false,group='BUY ORDERS',inline='g')
en8=input.bool(false,group='BUY ORDERS',inline='h')
en9=input.bool(false,group='BUY ORDERS',inline='i')
en10=input.bool(false,group='BUY ORDERS',inline='j')
en11=input.bool(false,group='BUY ORDERS',inline='k')
en12=input.bool(false,group='BUY ORDERS',inline='l')
order1=input.float(0,title='Order 1:',group='BUY ORDERS',inline='a')
order2=input.float(0,title='Order 2:',group='BUY ORDERS',inline='b')
order3=input.float(0,title='Order 3:',group='BUY ORDERS',inline='c')
order4=input.float(0,title='Order 4:',group='BUY ORDERS',inline='d')
order5=input.float(0,title='Order 5:',group='BUY ORDERS',inline='e')
order6=input.float(0,title='Order 6:',group='BUY ORDERS',inline='f')
order7=input.float(0,title='Order 7:',group='BUY ORDERS',inline='g')
order8=input.float(0,title='Order 8:',group='BUY ORDERS',inline='h')
order9=input.float(0,title='Order 9:',group='BUY ORDERS',inline='i')
order10=input.float(0,title='Order 10:',group='BUY ORDERS',inline='j')
order11=input.float(0,title='Order 11:',group='BUY ORDERS',inline='k')
order12=input.float(0,title='Order 12:',group='BUY ORDERS',inline='l')
vol1=input.float(0,minval=0,title='VOLUME 1:',group='BUY ORDERS',inline='a')
vol2=input.float(0,minval=0,title='VOLUME 2:',group='BUY ORDERS',inline='b')
vol3=input.float(0,minval=0,title='VOLUME 3:',group='BUY ORDERS',inline='c')
vol4=input.float(0,minval=0,title='VOLUME 4:',group='BUY ORDERS',inline='d')
vol5=input.float(0,minval=0,title='VOLUME 5:',group='BUY ORDERS',inline='e')
vol6=input.float(0,minval=0,title='VOLUME 6:',group='BUY ORDERS',inline='f')
vol7=input.float(0,minval=0,title='VOLUME 7:',group='BUY ORDERS',inline='g')
vol8=input.float(0,minval=0,title='VOLUME 8:',group='BUY ORDERS',inline='h')
vol9=input.float(0,minval=0,title='VOLUME 9:',group='BUY ORDERS',inline='i')
vol10=input.float(0,minval=0,title='VOLUME 10:',group='BUY ORDERS',inline='j')
vol11=input.float(0,minval=0,title='VOLUME 11:',group='BUY ORDERS',inline='k')
vol12=input.float(0,minval=0,title='VOLUME 12:',group='BUY ORDERS',inline='l')
float ttlVol=0
ttlVol:=(en1 and order1>0?ttlVol+vol1:ttlVol)
ttlVol:=(en2 and order2>0?ttlVol+vol2:ttlVol)
ttlVol:=(en3 and order3>0?ttlVol+vol3:ttlVol)
ttlVol:=(en4 and order4>0?ttlVol+vol4:ttlVol)
ttlVol:=(en5 and order5>0?ttlVol+vol5:ttlVol)
ttlVol:=(en6 and order6>0?ttlVol+vol6:ttlVol)
ttlVol:=(en7 and order7>0?ttlVol+vol7:ttlVol)
ttlVol:=(en8 and order8>0?ttlVol+vol8:ttlVol)
ttlVol:=(en9 and order9>0?ttlVol+vol9:ttlVol)
ttlVol:=(en10 and order10>0?ttlVol+vol10:ttlVol)
ttlVol:=(en11 and order11>0?ttlVol+vol11:ttlVol)
ttlVol:=(en12 and order12>0?ttlVol+vol12:ttlVol)
plot(en1 and order1>0? order1 :na, color=bar_index%2==0 ? color.new(color.yellow,0):color.new(color.yellow,70),linewidth=1,title='ORDER 1')
plot(en2 and order2>0? order2 :na, color=bar_index%3==0 ? color.new(color.yellow,0):color.new(color.yellow,70),linewidth=1,title='ORDER 2')
plot(en3 and order3>0? order3 :na, color=bar_index%5==0 ? color.new(color.yellow,0):color.new(color.yellow,70),linewidth=1,title='ORDER 3')
plot(en4 and order4>0? order4 :na, color=bar_index%7==0 ? color.new(color.yellow,0):color.new(color.yellow,70),linewidth=1,title='ORDER 4')
plot(en5 and order5>0? order5 :na, color=bar_index%11==0 ?color.new(color.yellow,0):color.new(color.yellow,70),linewidth=1,title='ORDER 5')
plot(en6 and order6>0? order6 :na, color=bar_index%13==0 ?color.new(color.yellow,0):color.new(color.yellow,70),linewidth=1,title='ORDER 6')
plot(en7 and order7>0? order7 :na, color=bar_index%17==0 ?color.new(color.yellow,0):color.new(color.yellow,70),linewidth=1,title='ORDER 7')
plot(en8 and order8>0? order8 :na, color=bar_index%19==0 ?color.new(color.yellow,0):color.new(color.yellow,70),linewidth=1,title='ORDER 8')
plot(en9 and order9>0? order9 :na, color=bar_index%23==0 ?color.new(color.yellow,0):color.new(color.yellow,70),linewidth=1,title='ORDER 9')
plot(en10 and order10>0?order10:na,color=bar_index%29==0 ?color.new(color.yellow,0):color.new(color.yellow,70),linewidth=1,title='ORDER 10')
plot(en11 and order11>0?order11:na,color=bar_index%31==0 ?color.new(color.yellow,0):color.new(color.yellow,70),linewidth=1,title='ORDER 11')
plot(en12 and order12>0?order12:na,color=bar_index%33==0 ?color.new(color.yellow,0):color.new(color.yellow,70),linewidth=1,title='ORDER 12')
buyPort=(1+(feebuyPer/100))
sellPort=(1+(feesellPer/100))
meanOrder=((vol1*buyPort*order1)+(vol2*buyPort*order2)+(vol3*buyPort*order3)+(vol4*buyPort*order4)+(vol5*buyPort*order5)+(vol6*buyPort*order6)+(vol7*buyPort*order7)+(vol8*buyPort*order8)+(vol9*buyPort*order9)+(vol10*buyPort*order10)+(vol11*buyPort*order11)+(vol12*buyPort*order12))/ttlVol
meanOrder:=meanOrder*(sellPort)
GoalOrder=meanOrder*(1+(bnft/100))
l1=plot(meanOrder,color=bar_index%2==1?Colblnc1:Colblnc2,linewidth=4,title='0% Line')
l2=plot(close,color=color.new(color.olive,100),linewidth=4,title='close Line')
l3=plot(GoalOrder,color=bar_index%2==0?Colbnft1:Colbnft2,linewidth=4,title='Goal Line')
fill(l1,l2,meanOrder<close?color.new(color.lime,90):color.new(color.maroon,90))
label0 = label.new(bar_index,meanOrder , text='😐 '+str.tostring(roundDec(meanOrder,deci)) ,size=size.normal,style=label.style_label_left,color=color.new(color.white,0))
label.delete(label0[1])
labelW = label.new(bar_index,GoalOrder , text='💲💲💲 '+str.tostring(roundDec(GoalOrder,deci)),size=size.normal,style=label.style_label_left,color=color.new(color.white,0))
label.delete(labelW[1])
diffPrc=vlinePrc(1, color.new(color.yellow,50) , line.style_dotted, 2,close,meanOrder)
line.delete(diffPrc[1])
labelS = label.new(bar_index+2,close+((meanOrder-close)/2) , text=(meanOrder<close?'🔺':'🔻')+str.tostring(roundDec(100*((-meanOrder+close)/meanOrder),1))+'%',size=size.normal,style=label.style_label_center,color=color.new(color.white,0))
label.delete(labelS[1]) |
Three Bar Gap (Simple Price Action - with 1 line plot) | https://www.tradingview.com/script/96ZstKf8-Three-Bar-Gap-Simple-Price-Action-with-1-line-plot/ | DojiEmoji | https://www.tradingview.com/u/DojiEmoji/ | 389 | 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/
// © DojiEmoji
// This script is tailored towards experienced traders who prefer to view raw price charts during live execution.
// It searches for a three-bar pattern of what is colloquially called "fair value gap", or "imbalance" and uses
// a single line to plot the results. The goal is to display price in a way that is as simple as possible so that
// chart readers who don't prefer to add indicators on their screen will still find this indicator as an
// acceptable option to consider for.
//@version=5
indicator("3 Bar Gap [DojiEmoji]", overlay=true)
//---------------------
// Settings - Adjustable:
var int atr_filter_len = input.int(20, minval=2, inline="ln1", title="Threshold: ATR")
var float atr_filter_multi = input.float(0.5, minval=0.1, maxval=1, step=0.1, inline="ln1", title="x",
tooltip="The minimum distance that candles [over 3 bars] must 'gap' by in order for move to be"+
"considered significant.\n\n-Higher Multi. => Less lines \n-Lower Multi. => More lines (might be noisy)"
)
var color col_up = input.color(color.new(color.blue,0), title="Colors for Up move / Down move:", inline="ln2", group="Plots")
var color col_dn = input.color(color.new(color.red,0), title="/", inline="ln2", group="Plots")
var int linewidth = input.int(2, minval=1, maxval=9,title="Width of the line", group="Plots")
//---------------------
// Data structure for gaps. Will remember their characteristics. Will also store them according to order of occurrence.
// {
type gap // Attributes to describe gap
float pivot_upper = na
float pivot_lower = na
float pivot_mid = na
color linecolor = na
int barindex = na
var gap[] _history = array.new<gap>() // Array of gaps, to keep track of them.
if barstate.isfirst
array.push(_history, gap.new()) // to prevent none type errors at the beginning when size==0
// @function insert_gap(price[2], price[0]) returns void
insert_gap(gap g, float price_t_minustwo, float price_t_zero) =>
g.pivot_upper := math.max(price_t_minustwo, price_t_zero)
g.pivot_lower := math.min(price_t_minustwo, price_t_zero)
g.pivot_mid := (g.pivot_upper+g.pivot_lower)/2
g.linecolor := price_t_minustwo < price_t_zero ? col_up : price_t_minustwo > price_t_zero ? col_dn : na
g.barindex := bar_index
array.unshift(_history, g)
// @function get_recent_gap() returns an instance of gap obj.
get_recent_gap() =>
if array.size(_history) == 0
runtime.error(message="")
array.get(_history,0)
//}
//---------------------
// Tests for FVGs:
// Requirement 1: Displacement test; upward FVG must > 0, and downward FVG must < 0
// Requirement 2: Threshold test; distance of FVG must > ATR200 x 0.5
float displacement_up = low[0] - high[2] // Test for FVG-up
float displacement_dn = high[0] - low[2] // Test for FVG-down
// FVG is valid iff both requirements (1 & 2) are met:
float _threshold = ta.atr(atr_filter_len) * atr_filter_multi
if math.abs(displacement_up) > _threshold and displacement_up > 0
insert_gap(gap.new(), high[2], low[0])
if math.abs(displacement_dn) > _threshold and displacement_dn < 0
insert_gap(gap.new(), low[2], high[0])
//---------------------
// Plotting:
var float main_pivot = na
main_pivot := get_recent_gap().pivot_mid[0] == get_recent_gap().pivot_mid[1] ? get_recent_gap().pivot_mid[0] : na
plot(main_pivot, color=get_recent_gap().linecolor, linewidth=linewidth, title="Pivot", offset=-1, editable=false, style=plot.style_linebr)
|
Fib Retracement | https://www.tradingview.com/script/UodJ5x9D-Fib-Retracement/ | syntaxgeek | https://www.tradingview.com/u/syntaxgeek/ | 127 | 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/
// © syntaxgeek
// _____ _____ _____ _____ _____ _____ _____ _____ _____
// /\ \ |\ \ /\ \ /\ \ /\ \ ______ /\ \ /\ \ /\ \ /\ \
// /::\ \ |:\____\ /::\____\ /::\ \ /::\ \ |::| | /::\ \ /::\ \ /::\ \ /::\____\
// /::::\ \ |::| | /::::| | \:::\ \ /::::\ \ |::| | /::::\ \ /::::\ \ /::::\ \ /:::/ /
// /::::::\ \ |::| | /:::::| | \:::\ \ /::::::\ \ |::| | /::::::\ \ /::::::\ \ /::::::\ \ /:::/ /
// /:::/\:::\ \ |::| | /::::::| | \:::\ \ /:::/\:::\ \ |::| | /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/ /
// /:::/__\:::\ \ |::| | /:::/|::| | \:::\ \ /:::/__\:::\ \ |::| | /:::/ \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ /:::/____/
// \:::\ \:::\ \ |::| | /:::/ |::| | /::::\ \ /::::\ \:::\ \ |::| | /:::/ \:::\ \ /::::\ \:::\ \ /::::\ \:::\ \ /::::\ \
// ___\:::\ \:::\ \ |::|___|______ /:::/ |::| | _____ /::::::\ \ /::::::\ \:::\ \ |::| | /:::/ / \:::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \ /::::::\____\________
// /\ \:::\ \:::\ \ /::::::::\ \ /:::/ |::| |/\ \ /:::/\:::\ \ /:::/\:::\ \:::\ \ ______|::|___|___ ____ /:::/ / \:::\ ___\ /:::/\:::\ \:::\ \ /:::/\:::\ \:::\ \ /:::/\:::::::::::\ \
// /::\ \:::\ \:::\____\/::::::::::\____/:: / |::| /::\____\/:::/ \:::\____/:::/ \:::\ \:::\____|:::::::::::::::::| /:::/____/ ___\:::| /:::/__\:::\ \:::\____/:::/__\:::\ \:::\____/:::/ |:::::::::::\____\
// \:::\ \:::\ \::/ /:::/~~~~/~~ \::/ /|::| /:::/ /:::/ \::/ \::/ \:::\ /:::/ |:::::::::::::::::|____\:::\ \ /\ /:::|____\:::\ \:::\ \::/ \:::\ \:::\ \::/ \::/ |::|~~~|~~~~~
// \:::\ \:::\ \/____/:::/ / \/____/ |::| /:::/ /:::/ / \/____/ \/____/ \:::\/:::/ / ~~~~~~|::|~~~|~~~ \:::\ /::\ \::/ / \:::\ \:::\ \/____/ \:::\ \:::\ \/____/ \/____|::| |
// \:::\ \:::\ \ /:::/ / |::|/:::/ /:::/ / \::::::/ / |::| | \:::\ \:::\ \/____/ \:::\ \:::\ \ \:::\ \:::\ \ |::| |
// \:::\ \:::\____\/:::/ / |::::::/ /:::/ / \::::/ / |::| | \:::\ \:::\____\ \:::\ \:::\____\ \:::\ \:::\____\ |::| |
// \:::\ /:::/ /\::/ / |:::::/ /\::/ / /:::/ / |::| | \:::\ /:::/ / \:::\ \::/ / \:::\ \::/ / |::| |
// \:::\/:::/ / \/____/ |::::/ / \/____/ /:::/ / |::| | \:::\/:::/ / \:::\ \/____/ \:::\ \/____/ |::| |
// \::::::/ / /:::/ / /:::/ / |::| | \::::::/ / \:::\ \ \:::\ \ |::| |
// \::::/ / /:::/ / /:::/ / |::| | \::::/ / \:::\____\ \:::\____\ \::| |
// \::/ / \::/ / \::/ / |::|___| \::/____/ \::/ / \::/ / \:| |
// \/____/ \/____/ \/____/ ~~ \/____/ \/____/ \|___|
//@version=5
indicator("Fib Retracement", overlay=true, precision=4)
//{ consts
var c_trendLineStyle = line.style_dashed
var c_levelsLineStyle = line.style_solid
var c_levelsLineThickness = 1
//}
//{ inputs
i_price1 = input.price(0, '#1 (price, bar)', group='Range', inline='price1', confirm=true)
i_time1 = input.time(0, '', group='Range', inline='price1', confirm=true)
i_price2 = input.price(0, '#2 (price, bar)', group='Range', inline='price2', confirm=true)
i_time2 = input.time(0, '', group='Range', inline='price2', confirm=true)
i_trendLineEnabled = input.bool(true, 'Trend line', inline='trendLine')
i_trendLineThickness = input.int(1, '', minval=1, maxval=5, step=1, inline='trendLine')
i_trendLineColor = input.color(color.new(color.gray, 50), '', inline='trendLine')
i_trendLineStyle = input.string('Dashed line', '', options=['Line', 'Dashed line', 'Dotted line'], inline='trendLine')
i_levelsLineThickness = input.int(1, 'Levels line', minval=1, maxval=5, step=1, inline='levelsLine')
i_levelsLineStyle = input.string('Line', '', options=['Line', 'Dashed line', 'Dotted line'], inline='levelsLine')
i_fib1Enabled = input.bool(true, '', group='Levels', inline='fib1')
i_fib1Multiplier = input.float(0, '', group='Levels', inline='fib1')
i_fib1Color = input.color(color.gray, '', group='Levels', inline='fib1')
i_fib3Enabled = input.bool(true, '', group='Levels', inline='fib2')
i_fib3Multiplier = input.float(0.382, '', group='Levels', inline='fib2')
i_fib3Color = input.color(color.orange, '', group='Levels', inline='fib2')
i_fib5Enabled = input.bool(true, '', group='Levels', inline='fib3')
i_fib5Multiplier = input.float(0.618, '', group='Levels', inline='fib3')
i_fib5Color = input.color(color.teal, '', group='Levels', inline='fib3')
i_fib7Enabled = input.bool(true, '', group='Levels', inline='fib4')
i_fib7Multiplier = input.float(1, '', group='Levels', inline='fib4')
i_fib7Color = input.color(color.gray, '', group='Levels', inline='fib4')
i_fib9Enabled = input.bool(true, '', group='Levels', inline='fib5')
i_fib9Multiplier = input.float(2.618, '', group='Levels', inline='fib5')
i_fib9Color = input.color(color.red, '', group='Levels', inline='fib5')
i_fib11Enabled = input.bool(false, '', group='Levels', inline='fib6')
i_fib11Multiplier = input.float(4.236, '', group='Levels', inline='fib6')
i_fib11Color = input.color(color.rgb(251, 64, 164), '', group='Levels', inline='fib6')
i_fib13Enabled = input.bool(false, '', group='Levels', inline='fib7')
i_fib13Multiplier = input.float(0, '', group='Levels', inline='fib7')
i_fib13Color = input.color(color.red, '', group='Levels', inline='fib7')
i_fib15Enabled = input.bool(false, '', group='Levels', inline='fib8')
i_fib15Multiplier = input.float(0, '', group='Levels', inline='fib8')
i_fib15Color = input.color(color.red, '', group='Levels', inline='fib8')
i_fib17Enabled = input.bool(false, '', group='Levels', inline='fib9')
i_fib17Multiplier = input.float(0, '', group='Levels', inline='fib9')
i_fib17Color = input.color(color.red, '', group='Levels', inline='fib9')
i_fib19Enabled = input.bool(false, '', group='Levels', inline='fib10')
i_fib19Multiplier = input.float(0, '', group='Levels', inline='fib10')
i_fib19Color = input.color(color.red, '', group='Levels', inline='fib10')
i_fib21Enabled = input.bool(false, '', group='Levels', inline='fib11')
i_fib21Multiplier = input.float(0, '', group='Levels', inline='fib11')
i_fib21Color = input.color(color.red, '', group='Levels', inline='fib11')
i_fib23Enabled = input.bool(false, '', group='Levels', inline='fib12')
i_fib23Multiplier = input.float(0, '', group='Levels', inline='fib12')
i_fib23Color = input.color(color.red, '', group='Levels', inline='fib12')
i_fib2Enabled = input.bool(true, '', group='Levels', inline='fib1')
i_fib2Multiplier = input.float(0.236, '', group='Levels', inline='fib1')
i_fib2Color = input.color(color.red, '', group='Levels', inline='fib1')
i_fib4Enabled = input.bool(true, '', group='Levels', inline='fib2')
i_fib4Multiplier = input.float(0.5, '', group='Levels', inline='fib2')
i_fib4Color = input.color(color.green, '', group='Levels', inline='fib2')
i_fib6Enabled = input.bool(true, '', group='Levels', inline='fib3')
i_fib6Multiplier = input.float(0.786, '', group='Levels', inline='fib3')
i_fib6Color = input.color(color.rgb(95, 209, 250), '', group='Levels', inline='fib3')
i_fib8Enabled = input.bool(true, '', group='Levels', inline='fib4')
i_fib8Multiplier = input.float(1.618, '', group='Levels', inline='fib4')
i_fib8Color = input.color(color.blue, '', group='Levels', inline='fib4')
i_fib10Enabled = input.bool(false, '', group='Levels', inline='fib5')
i_fib10Multiplier = input.float(3.618, '', group='Levels', inline='fib5')
i_fib10Color = input.color(color.purple, '', group='Levels', inline='fib5')
i_fib12Enabled = input.bool(false, '', group='Levels', inline='fib6')
i_fib12Multiplier = input.float(0, '', group='Levels', inline='fib6')
i_fib12Color = input.color(color.red, '', group='Levels', inline='fib6')
i_fib14Enabled = input.bool(false, '', group='Levels', inline='fib7')
i_fib14Multiplier = input.float(0, '', group='Levels', inline='fib7')
i_fib14Color = input.color(color.red, '', group='Levels', inline='fib7')
i_fib16Enabled = input.bool(false, '', group='Levels', inline='fib8')
i_fib16Multiplier = input.float(0, '', group='Levels', inline='fib8')
i_fib16Color = input.color(color.red, '', group='Levels', inline='fib8')
i_fib18Enabled = input.bool(false, '', group='Levels', inline='fib9')
i_fib18Multiplier = input.float(0, '', group='Levels', inline='fib9')
i_fib18Color = input.color(color.red, '', group='Levels', inline='fib9')
i_fib20Enabled = input.bool(false, '', group='Levels', inline='fib10')
i_fib20Multiplier = input.float(0, '', group='Levels', inline='fib10')
i_fib20Color = input.color(color.red, '', group='Levels', inline='fib10')
i_fib22Enabled = input.bool(false, '', group='Levels', inline='fib11')
i_fib22Multiplier = input.float(0, '', group='Levels', inline='fib11')
i_fib22Color = input.color(color.red, '', group='Levels', inline='fib11')
i_fib24Enabled = input.bool(false, '', group='Levels', inline='fib12')
i_fib24Multiplier = input.float(0, '', group='Levels', inline='fib12')
i_fib24Color = input.color(color.red, '', group='Levels', inline='fib12')
i_labelHasValue = input.bool(true, 'Show Price?', group='Labels')
i_labelHasPercent = input.bool(true, 'Show Percentage?', group='Labels')
i_labelLocation = input.string('Right', 'Location', group='Labels', options=['Left', 'Center', 'Right'])
i_reverseEnabled = input.bool(false, 'Reverse', group='Labels')
i_fib1Note = input.string('', 'Note 1', group='Labels', inline='fibL1')
i_fib3Note = input.string('', 'Note 3', group='Labels', inline='fibL2')
i_fib5Note = input.string('', 'Note 5', group='Labels', inline='fibL3')
i_fib7Note = input.string('', 'Note 7', group='Labels', inline='fibL4')
i_fib9Note = input.string('', 'Note 9', group='Labels', inline='fibL5')
i_fib11Note = input.string('', 'Note 11', group='Labels', inline='fibL6')
i_fib13Note = input.string('', 'Note 13', group='Labels', inline='fibL7')
i_fib15Note = input.string('', 'Note 15', group='Labels', inline='fibL8')
i_fib17Note = input.string('', 'Note 17', group='Labels', inline='fibL9')
i_fib19Note = input.string('', 'Note 19', group='Labels', inline='fibL10')
i_fib21Note = input.string('', 'Note 21', group='Labels', inline='fibL11')
i_fib23Note = input.string('', 'Note 23', group='Labels', inline='fibL12')
i_fib2Note = input.string('', 'Note 2', group='Labels', inline='fibL1')
i_fib4Note = input.string('', 'Note 4', group='Labels', inline='fibL2')
i_fib6Note = input.string('', 'Note 6', group='Labels', inline='fibL3')
i_fib8Note = input.string('', 'Note 8', group='Labels', inline='fibL4')
i_fib10Note = input.string('', 'Note 10', group='Labels', inline='fibL5')
i_fib12Note = input.string('', 'Note 12', group='Labels', inline='fibL6')
i_fib14Note = input.string('', 'Note 14', group='Labels', inline='fibL7')
i_fib16Note = input.string('', 'Note 16', group='Labels', inline='fibL8')
i_fib18Note = input.string('', 'Note 18', group='Labels', inline='fibL9')
i_fib20Note = input.string('', 'Note 20', group='Labels', inline='fibL10')
i_fib22Note = input.string('', 'Note 22', group='Labels', inline='fibL11')
i_fib24Note = input.string('', 'Note 24', group='Labels', inline='fibL12')
//}
//{ funcs
f_lineStyle(_styleSetting) =>
switch _styleSetting
'Line' => line.style_solid
'Dashed line' => line.style_dashed
'Dotted line' => line.style_dotted
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)
f_fib(n) => i_reverseEnabled ? (i_price2) - ((i_price2 - i_price1) * -n) + (i_price1 - i_price2) : i_price2 - ((i_price2 - i_price1) * n)
f_fibLine(value, color) =>
var line1 = line.new(0, value, bar_index, value, color=color, style=c_levelsLineStyle, width=c_levelsLineThickness)
line.set_x2(line1, 0)
line.set_xloc(line1, i_time2, i_time1, xloc.bar_time)
line1
f_fibLabelText(note, value, multiplier) =>
var fibText = ''
if note != ''
fibText := note
if i_labelHasValue
fibText := fibText + (fibText != '' ? " " : "") + str.tostring(value, format.mintick)
if i_labelHasPercent
fibText := fibText + (fibText != '' ? " (" : "") + str.tostring(multiplier * 100) + "%" + (fibText != '' ? ")" : "")
fibText
f_fibLabel(value, txt, color, textColor) =>
v_time = i_time1 > i_time2 ? i_time1 : i_time2
v_labelStyle = label.style_label_left
if i_labelLocation == 'Left'
v_time := i_time1 > i_time2 ? i_time2 : i_time1
v_labelStyle := label.style_label_right
if i_labelLocation == 'Center'
v_time := i_time1 + ((i_time2 - i_time1) / 2)
v_labelStyle := label.style_label_center
label.new(v_time, value, txt, textcolor=textColor, color=color, style=v_labelStyle, yloc=yloc.price, xloc=xloc.bar_time)
//}
//{ vars
c_trendLineStyle := f_lineStyle(i_trendLineStyle)
c_levelsLineStyle := f_lineStyle(i_levelsLineStyle)
c_levelsLineThickness := i_levelsLineThickness
var v_highPrice = f_highest(i_price1, i_price2)
var v_priceRange = f_range(i_price1, i_price2)
var v_fib1Value = f_fib(i_fib1Multiplier)
var v_fib2Value = f_fib(i_fib2Multiplier)
var v_fib3Value = f_fib(i_fib3Multiplier)
var v_fib4Value = f_fib(i_fib4Multiplier)
var v_fib5Value = f_fib(i_fib5Multiplier)
var v_fib6Value = f_fib(i_fib6Multiplier)
var v_fib7Value = f_fib(i_fib7Multiplier)
var v_fib8Value = f_fib(i_fib8Multiplier)
var v_fib9Value = f_fib(i_fib9Multiplier)
var v_fib10Value = f_fib(i_fib10Multiplier)
var v_fib11Value = f_fib(i_fib11Multiplier)
var v_fib12Value = f_fib(i_fib12Multiplier)
var v_fib13Value = f_fib(i_fib13Multiplier)
var v_fib14Value = f_fib(i_fib14Multiplier)
var v_fib15Value = f_fib(i_fib15Multiplier)
var v_fib16Value = f_fib(i_fib16Multiplier)
var v_fib17Value = f_fib(i_fib17Multiplier)
var v_fib18Value = f_fib(i_fib18Multiplier)
var v_fib19Value = f_fib(i_fib19Multiplier)
var v_fib20Value = f_fib(i_fib20Multiplier)
var v_fib21Value = f_fib(i_fib21Multiplier)
var v_fib22Value = f_fib(i_fib22Multiplier)
var v_fib23Value = f_fib(i_fib23Multiplier)
var v_fib24Value = f_fib(i_fib24Multiplier)
//}
//{ plots
if i_trendLineEnabled
var trendLine = line.new(0, i_price1, bar_index, i_price2, color=i_trendLineColor, style=c_trendLineStyle, width=i_trendLineThickness)
line.set_x2(trendLine, 0)
line.set_xloc(trendLine, i_time1, i_time2, xloc.bar_time)
var v_fib1Line = i_fib1Enabled ? f_fibLine(v_fib1Value, i_fib1Color) : na
var v_fib2Line = i_fib2Enabled ? f_fibLine(v_fib2Value, i_fib2Color) : na
var v_fib3Line = i_fib3Enabled ? f_fibLine(v_fib3Value, i_fib3Color) : na
var v_fib4Line = i_fib4Enabled ? f_fibLine(v_fib4Value, i_fib4Color) : na
var v_fib5Line = i_fib5Enabled ? f_fibLine(v_fib5Value, i_fib5Color) : na
var v_fib6Line = i_fib6Enabled ? f_fibLine(v_fib6Value, i_fib6Color) : na
var v_fib7Line = i_fib7Enabled ? f_fibLine(v_fib7Value, i_fib7Color) : na
var v_fib8Line = i_fib8Enabled ? f_fibLine(v_fib8Value, i_fib8Color) : na
var v_fib9Line = i_fib9Enabled ? f_fibLine(v_fib9Value, i_fib9Color) : na
var v_fib10Line = i_fib10Enabled ? f_fibLine(v_fib10Value, i_fib10Color) : na
var v_fib11Line = i_fib11Enabled ? f_fibLine(v_fib11Value, i_fib11Color) : na
var v_fib12Line = i_fib12Enabled ? f_fibLine(v_fib12Value, i_fib12Color) : na
var v_fib13Line = i_fib13Enabled ? f_fibLine(v_fib13Value, i_fib13Color) : na
var v_fib14Line = i_fib14Enabled ? f_fibLine(v_fib14Value, i_fib14Color) : na
var v_fib15Line = i_fib15Enabled ? f_fibLine(v_fib15Value, i_fib15Color) : na
var v_fib16Line = i_fib16Enabled ? f_fibLine(v_fib16Value, i_fib16Color) : na
var v_fib17Line = i_fib17Enabled ? f_fibLine(v_fib17Value, i_fib17Color) : na
var v_fib18Line = i_fib18Enabled ? f_fibLine(v_fib18Value, i_fib18Color) : na
var v_fib19Line = i_fib19Enabled ? f_fibLine(v_fib19Value, i_fib19Color) : na
var v_fib20Line = i_fib20Enabled ? f_fibLine(v_fib20Value, i_fib20Color) : na
var v_fib21Line = i_fib21Enabled ? f_fibLine(v_fib21Value, i_fib21Color) : na
var v_fib22Line = i_fib22Enabled ? f_fibLine(v_fib22Value, i_fib22Color) : na
var v_fib23Line = i_fib23Enabled ? f_fibLine(v_fib23Value, i_fib23Color) : na
var v_fib24Line = i_fib24Enabled ? f_fibLine(v_fib24Value, i_fib24Color) : na
var v_fib1Text = f_fibLabelText(i_fib1Note, v_fib1Value, i_fib1Multiplier)
var v_fib2Text = f_fibLabelText(i_fib2Note, v_fib2Value, i_fib2Multiplier)
var v_fib3Text = f_fibLabelText(i_fib3Note, v_fib3Value, i_fib3Multiplier)
var v_fib4Text = f_fibLabelText(i_fib4Note, v_fib4Value, i_fib4Multiplier)
var v_fib5Text = f_fibLabelText(i_fib5Note, v_fib5Value, i_fib5Multiplier)
var v_fib6Text = f_fibLabelText(i_fib6Note, v_fib6Value, i_fib6Multiplier)
var v_fib7Text = f_fibLabelText(i_fib7Note, v_fib7Value, i_fib7Multiplier)
var v_fib8Text = f_fibLabelText(i_fib8Note, v_fib8Value, i_fib8Multiplier)
var v_fib9Text = f_fibLabelText(i_fib9Note, v_fib9Value, i_fib9Multiplier)
var v_fib10Text = f_fibLabelText(i_fib10Note, v_fib10Value, i_fib10Multiplier)
var v_fib11Text = f_fibLabelText(i_fib11Note, v_fib11Value, i_fib11Multiplier)
var v_fib12Text = f_fibLabelText(i_fib12Note, v_fib12Value, i_fib12Multiplier)
var v_fib13Text = f_fibLabelText(i_fib13Note, v_fib13Value, i_fib13Multiplier)
var v_fib14Text = f_fibLabelText(i_fib14Note, v_fib14Value, i_fib14Multiplier)
var v_fib15Text = f_fibLabelText(i_fib15Note, v_fib15Value, i_fib15Multiplier)
var v_fib16Text = f_fibLabelText(i_fib16Note, v_fib16Value, i_fib16Multiplier)
var v_fib17Text = f_fibLabelText(i_fib17Note, v_fib17Value, i_fib17Multiplier)
var v_fib18Text = f_fibLabelText(i_fib18Note, v_fib18Value, i_fib18Multiplier)
var v_fib19Text = f_fibLabelText(i_fib19Note, v_fib19Value, i_fib19Multiplier)
var v_fib20Text = f_fibLabelText(i_fib20Note, v_fib20Value, i_fib20Multiplier)
var v_fib21Text = f_fibLabelText(i_fib21Note, v_fib21Value, i_fib21Multiplier)
var v_fib22Text = f_fibLabelText(i_fib22Note, v_fib22Value, i_fib22Multiplier)
var v_fib23Text = f_fibLabelText(i_fib23Note, v_fib23Value, i_fib23Multiplier)
var v_fib24Text = f_fibLabelText(i_fib24Note, v_fib24Value, i_fib24Multiplier)
var v_fib1Label = i_fib1Enabled ? f_fibLabel(v_fib1Value, v_fib1Text, color.new(color.red, 100), i_fib1Color) : na
var v_fib2Label = i_fib2Enabled ? f_fibLabel(v_fib2Value, v_fib2Text, color.new(color.red, 100), i_fib2Color) : na
var v_fib3Label = i_fib3Enabled ? f_fibLabel(v_fib3Value, v_fib3Text, color.new(color.red, 100), i_fib3Color) : na
var v_fib4Label = i_fib4Enabled ? f_fibLabel(v_fib4Value, v_fib4Text, color.new(color.red, 100), i_fib4Color) : na
var v_fib5Label = i_fib5Enabled ? f_fibLabel(v_fib5Value, v_fib5Text, color.new(color.red, 100), i_fib5Color) : na
var v_fib6Label = i_fib6Enabled ? f_fibLabel(v_fib6Value, v_fib6Text, color.new(color.red, 100), i_fib6Color) : na
var v_fib7Label = i_fib7Enabled ? f_fibLabel(v_fib7Value, v_fib7Text, color.new(color.red, 100), i_fib7Color) : na
var v_fib8Label = i_fib8Enabled ? f_fibLabel(v_fib8Value, v_fib8Text, color.new(color.red, 100), i_fib8Color) : na
var v_fib9Label = i_fib9Enabled ? f_fibLabel(v_fib9Value, v_fib9Text, color.new(color.red, 100), i_fib9Color) : na
var v_fib10Label = i_fib10Enabled ? f_fibLabel(v_fib10Value, v_fib10Text, color.new(color.red, 100), i_fib10Color) : na
var v_fib11Label = i_fib11Enabled ? f_fibLabel(v_fib11Value, v_fib11Text, color.new(color.red, 100), i_fib11Color) : na
var v_fib12Label = i_fib12Enabled ? f_fibLabel(v_fib12Value, v_fib12Text, color.new(color.red, 100), i_fib12Color) : na
var v_fib13Label = i_fib13Enabled ? f_fibLabel(v_fib13Value, v_fib13Text, color.new(color.red, 100), i_fib13Color) : na
var v_fib14Label = i_fib14Enabled ? f_fibLabel(v_fib14Value, v_fib14Text, color.new(color.red, 100), i_fib14Color) : na
var v_fib15Label = i_fib15Enabled ? f_fibLabel(v_fib15Value, v_fib15Text, color.new(color.red, 100), i_fib15Color) : na
var v_fib16Label = i_fib16Enabled ? f_fibLabel(v_fib16Value, v_fib16Text, color.new(color.red, 100), i_fib16Color) : na
var v_fib17Label = i_fib17Enabled ? f_fibLabel(v_fib17Value, v_fib17Text, color.new(color.red, 100), i_fib17Color) : na
var v_fib18Label = i_fib18Enabled ? f_fibLabel(v_fib18Value, v_fib18Text, color.new(color.red, 100), i_fib18Color) : na
var v_fib19Label = i_fib19Enabled ? f_fibLabel(v_fib19Value, v_fib19Text, color.new(color.red, 100), i_fib19Color) : na
var v_fib20Label = i_fib20Enabled ? f_fibLabel(v_fib20Value, v_fib20Text, color.new(color.red, 100), i_fib20Color) : na
var v_fib21Label = i_fib21Enabled ? f_fibLabel(v_fib21Value, v_fib21Text, color.new(color.red, 100), i_fib21Color) : na
var v_fib22Label = i_fib22Enabled ? f_fibLabel(v_fib22Value, v_fib22Text, color.new(color.red, 100), i_fib22Color) : na
var v_fib23Label = i_fib23Enabled ? f_fibLabel(v_fib23Value, v_fib23Text, color.new(color.red, 100), i_fib23Color) : na
var v_fib24Label = i_fib24Enabled ? f_fibLabel(v_fib24Value, v_fib24Text, color.new(color.red, 100), i_fib24Color) : na
//} |
VWOP: Volume Weighted & Oscillated Price | https://www.tradingview.com/script/GsMz7gSF-VWOP-Volume-Weighted-Oscillated-Price/ | EsIstTurnt | https://www.tradingview.com/u/EsIstTurnt/ | 45 | 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/
// © EsIstTurnt
//@version=5
indicator("Volume Weighted & Oscillated Price",shorttitle = "VWOP",overlay=true)
vwosc(src,len1=16,len2=24,len3=32,len4=40,osclen=16,string osctype="RSI",matype="LRC",curve="<>")=>
float osc = switch osctype // \
"RSI" => ta.rsi(src, osclen)// \
"CCI" => ta.cci(src, osclen)// \
"COG" => ta.cog(src, osclen)// \
"MFI" => ta.mfi(src, osclen)// -Select oscillator type to use for calculation below
"CMO" => ta.cmo(src, osclen)// /
"TSI" => ta.tsi(src, osclen,math.round(osclen*1.5))// /
"COPPOCK" => ta.wma(ta.roc(src,math.round(1.1*osclen))+ta.roc(src,math.round(1.4*osclen)),osclen) //
=>ta.rsi(src,osclen)// /
max=ta.max(osc)// \
min=ta.min(osc)// -Get min and max values for selected oscillator, along with the difference between them
dif=max-min // /
int lev = switch curve // -Calculate Variable Length, len1 should be lowest and len4 should
// be highest if custom lengths are chosen for the below to apply
"<>" => osc-min < 0.25*dif or max-osc < 0.25*dif?len1:// \
osc-min < 0.35*dif or max-osc < 0.35*dif?len2:// \
osc-min < 0.45*dif or max-osc < 0.45*dif?len3:// / -Length with higher values as oscillator value approaches midpoint
len4// /
"><" => osc-min < 0.25*dif or max-osc < 0.25*dif?len4:// \
osc-min < 0.35*dif or max-osc < 0.35*dif?len3:// \
osc-min < 0.45*dif or max-osc < 0.45*dif?len2:// / -Length with lower values as oscillator approaches midpoint
len1// /
"<" => osc-min < 0.25*dif ?len1:// \
osc-min < 0.35*dif ?math.round(math.avg(len1,len2)):// \
osc-min < 0.45*dif ?len2:// \
osc-min < 0.55*dif ?math.round(math.avg(len2,len3)):// -Length with higher values as oscillator value increases
osc-min < 0.65*dif ?len3:// /
osc-min < 0.75*dif ?math.round(math.avg(len3,len4)):// /
len4// /
">" => max-osc < 0.25*dif?len1:// \
max-osc < 0.35*dif?math.round(math.avg(len1,len2)):// \
max-osc < 0.45*dif?len2:// \
max-osc < 0.55*dif?math.round(math.avg(len2,len3)):// -Length with lower values as oscillator value increases
max-osc < 0.65*dif?len3:// /
max-osc < 0.75*dif?math.round(math.avg(len3,len4)):// /
len4// /
float ma=switch matype // \
"VWAP"=> ta.vwap (math.sum(ta.vwap (src) * (volume),lev) / math.sum(volume,lev) ) // \
"SWMA"=> ta.swma (math.sum(ta.swma (src) * (volume),lev) / math.sum(volume,lev) ) // \
"VWMA"=> ta.vwma (math.sum(ta.vwma (src,len1) * (volume),lev) / math.sum(volume,lev), len2) // \
"SMA" => ta.sma (math.sum(ta.sma (src,len1) * (volume),lev) / math.sum(volume,lev), len2) // -VWAP Calculation, typical price is replaced by selected moving average "matype" and then multiplied by the volume,
"EMA" => ta.ema (math.sum(ta.ema (src,len1) * (volume),lev) / math.sum(volume,lev), len2) // / then math.sum is used with the oscillating length created above to get a total value which is then divided by
"RMA" => ta.rma (math.sum(ta.rma (src,len1) * (volume),lev) / math.sum(volume,lev), len2) // / the sum of the volume using the same oscillating length value. Result is then passed through the selected
"WMA" => ta.wma (math.sum(ta.wma (src,len1) * (volume),lev) / math.sum(volume,lev), len2) // / "matype" once more to give the final result.
"LRC" => ta.linreg(math.sum(ta.linreg(src,len1,0) * (volume),lev) / math.sum(volume,lev), len2,0)// /
ma//
line=(vwosc(close,osctype="COPPOCK",curve="<") )
plot(line,color=color.new(#eca400,0)) |
Currency Strength [LuxAlgo] | https://www.tradingview.com/script/I1mIzpqC-Currency-Strength-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,410 | 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("Currency Strength [LuxAlgo]")
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
display = input.string('Trailing Relative Strength', options = ['Trailing Relative Strength', 'Relative Strength Scatter Graph'])
freq = input.timeframe('D', 'Timeframe')
currencyA = input('USD', '', inline = 'A')
ACss = input(#ff1100, '', inline = 'A')
currencyB = input('EUR', '', inline = 'B')
BCss = input(#2157f3, '', inline = 'B')
currencyC = input('GBP', '', inline = 'C')
CCss = input(#4caf50, '', inline = 'C')
currencyD = input('JPY', '', inline = 'D')
DCss = input(#e91e63, '', inline = 'D')
currencyE = input('AUD', '', inline = 'E')
ECss = input(#ff9800, '', inline = 'E')
//Meter
showDash = input(true, 'Show Strength Meter' , group = 'Meter')
resolution = input(20, 'Strength Meter Resolution' , group = 'Meter')
dashLoc = input.string('Top Right', 'Location', options = ['Top Right', 'Bottom Right', 'Bottom Left'], group = 'Meter')
textSize = input.string('Small', 'Size' , options = ['Tiny', 'Small', 'Normal'] , group = 'Meter')
//Scatter Graph
scatterRes = input.int(20, 'Scatter Graph Resolution', maxval = 500 , group = 'Scatter Graph')
scatterStrong = input(color.new(color.green, 80), 'Strong' , group = 'Scatter Graph')
scatterImprove = input(color.new(color.aqua, 80), 'Improving' , group = 'Scatter Graph')
scatterWeakening = input(color.new(color.yellow, 80), 'Weakening' , group = 'Scatter Graph')
scatterWeak = input(color.new(color.red, 80), 'Weak' , group = 'Scatter Graph')
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
n = bar_index
set_meter(tb, col, strength, min, max, bg_css)=>
scale = (strength - min) / (max - min) * (resolution-1)
table.clear(tb, col, 2 , col, resolution+1)
for i = 0 to scale
css = color.from_gradient(i, 0, scale, color.new(bg_css, 100), bg_css)
table.cell(tb, col, resolution+1 - i, bgcolor = css, text_size = size.tiny, height = 0.1)
table.cell(tb, col, 1, str.format('{0}{1}', strength > 0 ? '+' : '', strength)
, bgcolor = bg_css
, text_size = size.tiny
, text_color = color.white
, width = 2)
set_point(strength, prev_strength, min, max, css)=>
var label lbl = label.new(na, na, '•'
, color = #00000000
, style = label.style_label_center
, textcolor = css
, size = size.large)
if barstate.islast
scale_prev = (strength - prev_strength - min) / (max - min)
label.set_x(lbl, n + int(scale_prev * scatterRes))
label.set_y(lbl, strength)
//-----------------------------------------------------------------------------}
//Get relative currency strength
//-----------------------------------------------------------------------------{
dt = timeframe.change(freq)
AB = request.security(str.format('{0}{1}', currencyA, currencyB), timeframe.period, (close - open) / open * 100)
AC = request.security(str.format('{0}{1}', currencyA, currencyC), timeframe.period, (close - open) / open * 100)
AD = request.security(str.format('{0}{1}', currencyA, currencyD), timeframe.period, (close - open) / open * 100)
AE = request.security(str.format('{0}{1}', currencyA, currencyE), timeframe.period, (close - open) / open * 100)
BA = -AB
BC = request.security(str.format('{0}{1}', currencyB, currencyC), timeframe.period, (close - open) / open * 100)
BD = request.security(str.format('{0}{1}', currencyB, currencyD), timeframe.period, (close - open) / open * 100)
BE = request.security(str.format('{0}{1}', currencyB, currencyE), timeframe.period, (close - open) / open * 100)
CA = -AC
CB = -BC
CD = request.security(str.format('{0}{1}', currencyC, currencyD), timeframe.period, (close - open) / open * 100)
CE = request.security(str.format('{0}{1}', currencyC, currencyE), timeframe.period, (close - open) / open * 100)
DA = -AD
DB = -BD
DC = -CD
DE = request.security(str.format('{0}{1}', currencyD, currencyE), timeframe.period, (close - open) / open * 100)
EA = -AE
EB = -BE
EC = -CE
ED = -DE
//-----------------------------------------------------------------------------}
//Get trailing relative strength
//-----------------------------------------------------------------------------{
var sumA = 0., var prev_A = 0.
var sumB = 0., var prev_B = 0.
var sumC = 0., var prev_C = 0.
var sumD = 0., var prev_D = 0.
var sumE = 0., var prev_E = 0.
if dt
prev_A := sumA
prev_B := sumB
prev_C := sumC
prev_D := sumD
prev_E := sumE
sumA := math.avg(AB, AC, AD, AE)
sumB := math.avg(BA, BC, BD, BE)
sumC := math.avg(CA, CB, CD, CE)
sumD := math.avg(DA, DB, DC, DE)
sumE := math.avg(EA, EB, EC, ED)
else
sumA += math.avg(AB, AC, AD, AE)
sumB += math.avg(BA, BC, BD, BE)
sumC += math.avg(CA, CB, CD, CE)
sumD += math.avg(DA, DB, DC, DE)
sumE += math.avg(EA, EB, EC, ED)
//-----------------------------------------------------------------------------}
//Meter
//-----------------------------------------------------------------------------{
var table_position = dashLoc == 'Bottom Left' ? position.bottom_left
: dashLoc == 'Top Right' ? position.top_right
: position.bottom_right
var table_size = textSize == 'Tiny' ? size.tiny
: textSize == 'Small' ? size.small
: size.normal
var tb = table.new(table_position, 11, resolution+3
, bgcolor = #1e222d
, border_width = 1
, frame_color = #373a46
, frame_width = 1)
if barstate.isfirst and showDash
table.cell(tb, 0, 0, str.format('Currency Relative Strength ({0})', freq)
, text_size = table_size
, text_color = color.white)
table.merge_cells(tb, 0, 0, 10, 0)
for i = 0 to 10 by 2
table.cell(tb, i, 1, bgcolor = #1e222d, width = 0.1)
table.merge_cells(tb, i, 1, i, resolution+2)
table.cell(tb, 1, resolution+2, currencyA, text_color = color.white, text_size = table_size, bgcolor = ACss)
table.cell(tb, 3, resolution+2, currencyB, text_color = color.white, text_size = table_size, bgcolor = BCss)
table.cell(tb, 5, resolution+2, currencyC, text_color = color.white, text_size = table_size, bgcolor = CCss)
table.cell(tb, 7, resolution+2, currencyD, text_color = color.white, text_size = table_size, bgcolor = DCss)
table.cell(tb, 9, resolution+2, currencyE, text_color = color.white, text_size = table_size, bgcolor = ECss)
if barstate.islast and showDash
min = math.min(sumA, sumB, sumC, sumD, sumE)
max = math.max(sumA, sumB, sumC, sumD, sumE)
set_meter(tb, 1, sumA, min, max, ACss)
set_meter(tb, 3, sumB, min, max, BCss)
set_meter(tb, 5, sumC, min, max, CCss)
set_meter(tb, 7, sumD, min, max, DCss)
set_meter(tb, 9, sumE, min, max, ECss)
//-----------------------------------------------------------------------------}
//Scatter Plot
//-----------------------------------------------------------------------------{
var bx_strong = box.new(na, na, na, na, na
, bgcolor = scatterStrong)
var bx_improve = box.new(na, na, na, na, na
, bgcolor = scatterImprove)
var bx_weakening = box.new(na, na, na, na, na
, bgcolor = scatterWeakening)
var bx_weak = box.new(na, na, na, na, na
, bgcolor = scatterWeak)
var label x_label = label.new(na, na, 'Previous Currency Strength'
, style = label.style_label_up
, color = #00000000
, textcolor = chart.fg_color)
var label y_label = label.new(na, 0, 'Currency\nStrength'
, style = label.style_label_right
, color = #00000000
, textcolor = chart.fg_color)
//Display Graph
if display == 'Relative Strength Scatter Graph'
min = math.min(sumA, sumB, sumC, sumD, sumE)
max = math.max(sumA, sumB, sumC, sumD, sumE)
prev_min = math.min(sumA - prev_A, sumB - prev_B, sumC - prev_C, sumD - prev_D, sumE - prev_E)
prev_max = math.max(sumA - prev_A, sumB - prev_B, sumC - prev_C, sumD - prev_D, sumE - prev_E)
if barstate.islast
//Set areas
box.set_lefttop(bx_strong, n + int(scatterRes / 2), max)
box.set_rightbottom(bx_strong, n + scatterRes, 0)
box.set_lefttop(bx_improve, n, max)
box.set_rightbottom(bx_improve, n + int(scatterRes / 2), 0)
box.set_lefttop(bx_weakening, n + int(scatterRes / 2), 0)
box.set_rightbottom(bx_weakening, n + scatterRes, min)
box.set_lefttop(bx_weak, n, 0)
box.set_rightbottom(bx_weak, n + int(scatterRes / 2), min)
//Set axis labels
label.set_xy(x_label, n + int(scatterRes / 2), min)
label.set_x(y_label, n)
//Set points
set_point(sumA, prev_A, prev_min, prev_max, ACss)
set_point(sumB, prev_B, prev_min, prev_max, BCss)
set_point(sumC, prev_C, prev_min, prev_max, CCss)
set_point(sumD, prev_D, prev_min, prev_max, DCss)
set_point(sumE, prev_E, prev_min, prev_max, ECss)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot(display == 'Trailing Relative Strength' ? sumA : na
, color = dt ? na : ACss)
plot(display == 'Trailing Relative Strength' ? sumB : na
, color = dt ? na : BCss)
plot(display == 'Trailing Relative Strength' ? sumC : na
, color = dt ? na : CCss)
plot(display == 'Trailing Relative Strength' ? sumD : na
, color = dt ? na : DCss)
plot(display == 'Trailing Relative Strength' ? sumE : na
, color = dt ? na : ECss)
//Delimit
bgcolor(display == 'Trailing Relative Strength' and dt
? color.new(color.gray, 50) : na)
//-----------------------------------------------------------------------------} |
Volume Weighted Average Price (VWAP) with Extras [starlord_xrp] | https://www.tradingview.com/script/7c3FRY5s-Volume-Weighted-Average-Price-VWAP-with-Extras-starlord-xrp/ | starlord_xrp | https://www.tradingview.com/u/starlord_xrp/ | 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/
// © starlord_xrp
//@version=5
indicator("Volume Weighted Average Price with Extras", "VWAP+", overlay = true)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//% Price Change by [OrganicPunch]
//
// To visually evaluate the % change in price between two candles
pc_ema_lenght = input.int(7, title="Price Change EMA", minval=1)
pc_display_toggle = input.bool(false, "Two-side display")
pc_price_increase = (close - close[1]) / close[1] * 100
pc_price_decrease = (close[1] - close) / close * 100
pc_price_up = close > close[1]
pc_price_change = pc_price_up ? pc_price_increase : pc_price_decrease
pc_price_change2 = pc_price_up ? pc_price_increase : -pc_price_decrease
pc_price_toggle = pc_display_toggle ? pc_price_change2 : pc_price_change
pc_color = pc_price_up ? color(color.green) : color(color.red)
pc_ema = ta.ema(pc_price_toggle, pc_ema_lenght)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Volume Weighted Average Price
hideonDWM = input(false, title="Hide VWAP on 1D or Above", group="VWAP Settings")
var anchor = input.string(defval = "Percent Change", title="Anchor Period", options=["Percent Change", "Extreme", "Low", "High", "Session", "Week", "Month", "Quarter", "Year", "Decade", "Century", "Earnings", "Dividends", "Splits"], group="VWAP Settings")
src = input(title = "Source", defval = hlc3, group="VWAP Settings")
offset = input(0, title="Offset", group="VWAP Settings")
lookback = input(100, "Lookback length for High and Low", group = "Extra Settings")
check_percent = input(1.00, "Threshhold for price Percent Change", group = "Extra Settings")
showBand_1 = input(true, title="", group="Standard Deviation Bands Settings", inline="band_1")
stdevMult_1 = input(1.0, title="Bands Multiplier #1", group="Standard Deviation Bands Settings", inline="band_1")
showBand_2 = input(false, title="", group="Standard Deviation Bands Settings", inline="band_2")
stdevMult_2 = input(2.0, title="Bands Multiplier #2", group="Standard Deviation Bands Settings", inline="band_2")
showBand_3 = input(false, title="", group="Standard Deviation Bands Settings", inline="band_3")
stdevMult_3 = input(3.0, title="Bands Multiplier #3", group="Standard Deviation Bands Settings", inline="band_3")
if barstate.islast and ta.cum(volume) == 0
runtime.error("No volume is provided by the data vendor.")
new_earnings = request.earnings(syminfo.tickerid, earnings.actual, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true)
new_dividends = request.dividends(syminfo.tickerid, dividends.gross, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true)
new_split = request.splits(syminfo.tickerid, splits.denominator, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true)
var float lowest_number = high
var float highest_number = low
if ta.change(dayofmonth) and dayofweek == dayofweek.saturday
lowest_number := high
highest_number:= low
high_check = ta.highest(high, lookback)
low_check = ta.lowest(low, lookback)
if low_check < lowest_number
lowest_number := low_check
if high_check > highest_number
highest_number := high_check
bool new_low = na
bool new_high = na
bool new_extreme = na
bool new_percent = na
if (ta.change(lowest_number))
new_low := true
if (ta.change(highest_number))
new_high := true
if (new_high or new_low)
new_extreme := true
if (pc_price_toggle > 1.00)
new_percent := true
isNewPeriod = switch anchor
"Percent Change" => not na(new_percent)
"Extreme" => not na(new_extreme)
"Low" => not na(new_low)
"High" => not na(new_high)
"Earnings" => not na(new_earnings)
"Dividends" => not na(new_dividends)
"Splits" => not na(new_split)
"Session" => timeframe.change("D")
"Week" => timeframe.change("W")
"Month" => timeframe.change("M")
"Quarter" => timeframe.change("3M")
"Year" => timeframe.change("12M")
"Decade" => timeframe.change("12M") and year % 10 == 0
"Century" => timeframe.change("12M") and year % 100 == 0
=> false
isEsdAnchor = anchor == "Earnings" or anchor == "Dividends" or anchor == "Splits"
if na(src[1]) and not isEsdAnchor
isNewPeriod := true
float vwapValue = na
float upperBandValue1 = na
float lowerBandValue1 = na
float upperBandValue2 = na
float lowerBandValue2 = na
float upperBandValue3 = na
float lowerBandValue3 = na
if not (hideonDWM and timeframe.isdwm)
[_vwap, _stdevUpper, _] = ta.vwap(src, isNewPeriod, 1)
vwapValue := _vwap
stdevAbs = _stdevUpper - _vwap
upperBandValue1 := _vwap + stdevAbs * stdevMult_1
lowerBandValue1 := _vwap - stdevAbs * stdevMult_1
upperBandValue2 := _vwap + stdevAbs * stdevMult_2
lowerBandValue2 := _vwap - stdevAbs * stdevMult_2
upperBandValue3 := _vwap + stdevAbs * stdevMult_3
lowerBandValue3 := _vwap - stdevAbs * stdevMult_3
plot(vwapValue, title="VWAP", color=#2962FF, offset=offset)
upperBand_1 = plot(upperBandValue1, title="Upper Band #1", color=color.green, offset=offset, display = showBand_1 ? display.all : display.none)
lowerBand_1 = plot(lowerBandValue1, title="Lower Band #1", color=color.green, offset=offset, display = showBand_1 ? display.all : display.none)
fill(upperBand_1, lowerBand_1, title="Bands Fill #1", color= color.new(color.green, 95) , display = showBand_1 ? display.all : display.none)
upperBand_2 = plot(upperBandValue2, title="Upper Band #2", color=color.olive, offset=offset, display = showBand_2 ? display.all : display.none)
lowerBand_2 = plot(lowerBandValue2, title="Lower Band #2", color=color.olive, offset=offset, display = showBand_2 ? display.all : display.none)
fill(upperBand_2, lowerBand_2, title="Bands Fill #2", color= color.new(color.olive, 95) , display = showBand_2 ? display.all : display.none)
upperBand_3 = plot(upperBandValue3, title="Upper Band #3", color=color.teal, offset=offset, display = showBand_3 ? display.all : display.none)
lowerBand_3 = plot(lowerBandValue3, title="Lower Band #3", color=color.teal, offset=offset, display = showBand_3 ? display.all : display.none)
fill(upperBand_3, lowerBand_3, title="Bands Fill #3", color= color.new(color.teal, 95) , display = showBand_3 ? display.all : display.none) |
change in rsi | https://www.tradingview.com/script/vj31BTyi-change-in-rsi/ | bala357 | https://www.tradingview.com/u/bala357/ | 12 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © bala357
//@version=5
indicator("change in rsi","",false)
//inputs
period= input(20,"period")
//calculation
a = ta.rsi(close,period)
b = ta.change(a,1)
c = b*100/a
//plotting
plot(c)
//plotting of horizontal lines
hline(0, color=color.rgb(231, 255, 20),linestyle = hline.style_solid,linewidth=1)
hline(2, color=color.rgb(74, 187, 79),linestyle = hline.style_dotted,linewidth=1)
hline(4, color=color.rgb(74, 187, 79),linestyle = hline.style_dotted,linewidth=1)
hline(6, color=color.rgb(74, 187, 79),linestyle = hline.style_dotted,linewidth=1)
hline(-2, color=color.rgb(182, 58, 21),linestyle = hline.style_dotted,linewidth=1)
hline(-4, color=color.rgb(182, 58, 21),linestyle = hline.style_dotted,linewidth=1)
hline(-6, color=color.rgb(182, 58, 21),linestyle = hline.style_dotted,linewidth=1) |
Average True Range Percent | https://www.tradingview.com/script/FePZrm5b-Average-True-Range-Percent/ | rex_wolfe | https://www.tradingview.com/u/rex_wolfe/ | 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/
// © rex_wolfe
// Average True Range Percent - Arthur
// Version 1.0
//@version=5
indicator("Average True Range Percent - Arthur", shorttitle = "ATRP Arthur")
// Get user input
length = input.int(title = "Length", defval = 168, step = 1, minval = 1, tooltip = "Number of periods to apply smoothing.")
smoothing = input.string(title = "Smoothing", defval = "SMA", options=["SMA", "EMA", "WMA"], tooltip = "SMA - simple moving average, EMA - exponential moving average, WMA - weighted moving average.")
// Declare variables
var trp = float(0)
var atrp = float(0)
// Calculate true range percent
trp := ta.tr / hl2 * 100
// Calculate smoothed percentage range
if smoothing == "SMA"
atrp := ta.sma(trp, length)
else if smoothing == "EMA"
atrp := ta.ema(trp, length)
else if smoothing == "WMA"
atrp := ta.wma(trp, length)
// Plot indicator
plot (trp, title = 'True range percent', color = color.new(color.silver, 60), style = plot.style_histogram)
plot(atrp, title = 'Smoothed average true range percent', color = color.new(color.blue, 0), style = plot.style_line)
// Roger, Candy, Elwood, Blacky, Bill. Not yet, Captain Chaos, not yet. |
Hurst Spectral Analysis Oscillator | https://www.tradingview.com/script/iBrqYMSe-Hurst-Spectral-Analysis-Oscillator/ | BarefootJoey | https://www.tradingview.com/u/BarefootJoey/ | 678 | 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/
// © BarefootJoey
// ██████████████████████████████████████████████████████████████████████
// █▄─▄─▀██▀▄─██▄─▄▄▀█▄─▄▄─█▄─▄▄─█─▄▄─█─▄▄─█─▄─▄─███▄─▄█─▄▄─█▄─▄▄─█▄─█─▄█
// ██─▄─▀██─▀─███─▄─▄██─▄█▀██─▄███─██─█─██─███─███─▄█─██─██─██─▄█▀██▄─▄██
// █▄▄▄▄██▄▄█▄▄█▄▄█▄▄█▄▄▄▄▄█▄▄▄███▄▄▄▄█▄▄▄▄██▄▄▄██▄▄▄███▄▄▄▄█▄▄▄▄▄██▄▄▄██
//@version=5
indicator('Hurst Spectral Analysis Oscillator', overlay=false, format=format.price, precision=3)
//-------------------------------Inputs-------------------------------//
source = input(hl2, 'Source', group="Bandpass Settings")
bandWidth = input.float(0.025, 'Bandwidth', minval=0.0, maxval=1.0, group="Bandpass Settings")
periodBandpassh = input.float(4.3, '5 Day ', minval=2, inline="1", group="Cycle Settings")
periodBandpassf = input.float(8.5, '10 Day ', minval=2, inline="2", group="Cycle Settings")
periodBandpass2 = input.float(17, '20 Day ', minval=2, inline="3", group="Cycle Settings")
periodBandpass4 = input.float(34.1, '40 Day ', minval=2, inline="4", group="Cycle Settings")
periodBandpass8 = input.float(68.2, '80 Day ', minval=2, inline="5", group="Cycle Settings")
periodBandpass16 = input.float(136.4, '20 Week ', minval=2, inline="6", group="Cycle Settings")
periodBandpass32 = input.float(272.8, '40 Week ', minval=2, inline="7", group="Cycle Settings")
periodBandpass64 = input.float(545.6, '18 Month', minval=2, inline="8", group="Cycle Settings")
periodBandpass128 = input.float(1636.8, '54 Month', minval=2, inline="9", group="Cycle Settings")
periodBandpass256 = input.float(3273.6, '9 Year ', minval=2, inline="10", group="Cycle Settings")
periodBandpass512 = input.float(6547.2, '18 Year ', minval=2, inline="11", group="Cycle Settings")
// Color Selection
colh = input.color(color.purple, " ", inline="1", group="Cycle Settings")
colf = input.color(color.blue, " ", inline="2", group="Cycle Settings")
col2 = input.color(color.aqua, " ", inline="3", group="Cycle Settings")
col4 = input.color(color.green, " ", inline="4", group="Cycle Settings")
col8 = input.color(color.yellow, " ", inline="5", group="Cycle Settings")
col16 = input.color(color.orange, " ", inline="6", group="Cycle Settings")
col32 = input.color(color.red, " ", inline="7", group="Cycle Settings")
col64 = input.color(#856c44, " ", inline="8", group="Cycle Settings")
col128 = input.color(color.black, " ", inline="9", group="Cycle Settings")
col256 = input.color(color.gray, " ", inline="10", group="Cycle Settings")
col512 = input.color(color.white, " ", inline="11", group="Cycle Settings")
colcompu = input.color(color.new(#00ff0a, 70), "Composite Model Candle Colors", inline="12", group="Cycle Settings")
colcompd = input.color(color.new(#ff0000, 70), " ", inline="12", group="Cycle Settings")
// Composite Selection
comph = input.bool(true, "Composite", inline="1", group="Cycle Settings")
compf = input.bool(true, "Composite", inline="2", group="Cycle Settings")
comp2 = input.bool(true, "Composite", inline="3", group="Cycle Settings")
comp4 = input.bool(true, "Composite", inline="4", group="Cycle Settings")
comp8 = input.bool(true, "Composite", inline="5", group="Cycle Settings")
comp16 = input.bool(true, "Composite", inline="6", group="Cycle Settings")
comp32 = input.bool(true, "Composite", inline="7", group="Cycle Settings")
comp64 = input.bool(true, "Composite", inline="8", group="Cycle Settings")
comp128 = input.bool(true, "Composite", inline="9", group="Cycle Settings")
comp256 = input.bool(true, "Composite", inline="10", group="Cycle Settings")
comp512 = input.bool(true, "Composite", inline="11", group="Cycle Settings")
// Analysis Inputs
sig_in = input.string("None", "Bandpass for Analysis", options=["5 Day", "10 Day", "20 Day", "40 Day", "80 Day", "20 Week", "40 Week", "18 Month", "54 Month", "9 Year", "18 Year", "None"], group="Analysis Settings")
decimals = input.int(2, 'Price Decimals', minval=0, maxval=10, group="Analysis Settings")
position = input.string(position.bottom_right, "Analysis Position", [position.top_center, position.top_right, position.middle_right, position.bottom_right, position.bottom_center, position.bottom_left, position.middle_left, position.top_left], group="Analysis Settings")
size = input.string(size.small, "Text Size", [size.tiny, size.small, size.normal, size.large, size.huge], group="Analysis Settings")
//-------------------------------Functions & Calculations-------------------------------//
// @TMPascoe found & offered this bandpass by @HPotter found here https://www.tradingview.com/script/A1jhw5fG-Bandpass-Filter/
// @BarefootJoey turned the code into a function and made it accept float Period
bpf(Series, float Period, Delta) =>
float tmpbpf = na
var beta = math.cos(3.14 * (360 / Period) / 180)
var gamma = 1 / math.cos(3.14 * (720 * Delta / Period) / 180)
var alpha = gamma - math.sqrt(gamma * gamma - 1)
tmpbpf := 0.5 * (1 - alpha) * (Series - Series[2]) + beta * (1 + alpha) * nz(tmpbpf[1]) - alpha * nz(tmpbpf[2])
// Individual Bandpass Filters
BPFh = bpf(source, periodBandpassh, bandWidth)
BPFf = bpf(source, periodBandpassf, bandWidth)
BPF2 = bpf(source, periodBandpass2, bandWidth)
BPF4 = bpf(source, periodBandpass4, bandWidth)
BPF8 = bpf(source, periodBandpass8, bandWidth)
BPF16 = bpf(source, periodBandpass16, bandWidth)
BPF32 = bpf(source, periodBandpass32, bandWidth)
BPF64 = bpf(source, periodBandpass64, bandWidth)
BPF128 = bpf(source, periodBandpass128, bandWidth)
BPF256 = bpf(source, periodBandpass256, bandWidth)
BPF512 = bpf(source, periodBandpass512, bandWidth)
// Composite
compBPF = (comph?BPFh:0) + (compf?BPFf:0) + (comp2?BPF2:0) + (comp4?BPF4:0) + (comp8?BPF8:0) + (comp16?BPF16:0) + (comp32?BPF32:0) + (comp64?BPF64:0) + (comp128?BPF128:0) + (comp256?BPF256:0) + (comp512?BPF512:0)
col = ta.change(compBPF) > 0 ? colcompu : colcompd
// Cycle Analysis
// Truncate Decimals
truncate(number, pricedecimals) =>
factor = math.pow(10, pricedecimals)
int(number * factor) / factor
// Switch output/plot for analytics
sig_out = sig_in == "5 Day" ? BPFh : sig_in == "10 Day" ? BPFf : sig_in == "20 Day" ? BPF2 : sig_in == "40 Day" ? BPF4 : sig_in == "80 Day" ? BPF8 : sig_in == "20 Week" ? BPF16 : sig_in == "40 Week" ? BPF32 : sig_in == "18 Month" ? BPF64 : sig_in == "54 Month" ? BPF128 : sig_in == "9 Year" ? BPF256 : sig_in == "18 Year" ? BPF512 : na
period_out = sig_in == "5 Day" ? periodBandpassh : sig_in == "10 Day" ? periodBandpassf : sig_in == "20 Day" ? periodBandpass2 : sig_in == "40 Day" ? periodBandpass4 : sig_in == "80 Day" ? periodBandpass8 : sig_in == "20 Week" ? periodBandpass16 : sig_in == "40 Week" ? periodBandpass32 : sig_in == "18 Month" ? periodBandpass64 : sig_in == "54 Month" ? periodBandpass128 : sig_in == "9 Year" ? periodBandpass256 : sig_in == "18 Year" ? periodBandpass512 : 1 // :na
col_out = sig_in == "5 Day" ? colh : sig_in == "10 Day" ? colf : sig_in == "20 Day" ? col2 : sig_in == "40 Day" ? col4 : sig_in == "80 Day" ? col8 : sig_in == "20 Week" ? col16 : sig_in == "40 Week" ? col32 : sig_in == "18 Month" ? col64 : sig_in == "54 Month" ? col128 : sig_in == "9 Year" ? col256 : sig_in == "18 Year" ? col512 : color.gray
// Highs/Lows
hi = sig_out[2]<sig_out[1] and sig_out[1]>sig_out
lo = sig_out[2]>sig_out[1] and sig_out[1]<sig_out
// Define Crosses
midcross = ta.cross(sig_out, 0)
midcrossbars = ta.barssince(midcross)
midcrossbars2 = ta.barssince(midcross)[1]
last_wavelength = ta.barssince(midcross) - ta.barssince(midcross)
// Bars Since Last Amp Hi & Lo
xhi = ta.barssince(hi)
xlo = ta.barssince(lo)
// Wavelength
wavelength = math.round(math.abs(xhi-xlo)*2)
// Last Amp Hi & Lo
bpfphi = ta.highest(sig_out,math.round(period_out))
bpfamphi = ta.valuewhen(bpfphi, sig_out, 0)
bpfplo = ta.lowest(sig_out,math.round(period_out))
bpfamplo = ta.valuewhen(bpfplo, sig_out, 0)
tot_amp = bpfphi - bpfplo
// Estimates/Forecasts
next_peak = -math.abs(xhi-wavelength)
next_trough = -math.abs(xlo-wavelength)
next_node = math.abs(xhi-xlo)-midcrossbars
// Highlight background of next peak/node/trough
next_peak_col = color.new(color.red,hi?75:100)
next_node_col = color.new(color.gray, midcross?75:100)
next_trough_col = color.new(color.green, lo?75:100)
// Sentiment
amp_sent = bpfphi>math.abs(bpfplo)?"🟢":bpfphi<math.abs(bpfplo)?"🔴":"⚪"
bbwavelen = wavelength>period_out?"🟢":wavelength<period_out?"🔴":"⚪"
bbpt = -next_peak<-next_trough?"Bullish🟢":-next_peak>-next_trough?"Bearish🔴":"Neutral⚪"
// Analytics Tooltip 📏🧮⏳🎰🤖🎭🔮📈📉🔁🌊🔴🟢⚪
labeltt= "🔄 Cycle: " + str.tostring(sig_in) + "/" + str.tostring(period_out) + " bars" +
"\n📏 Period (⊺): ~" + str.tostring(math.abs(xhi-xlo)) + " bars" +
"\n🌊 Wavelength (λ): ~" + str.tostring(wavelength) + " bars " + bbwavelen +
"\n⚖ Delta (∆) Amplitude (ª): " + str.tostring(truncate(tot_amp, decimals)) + " " + amp_sent +
"\n📈 Peak (ª): " + str.tostring(truncate(bpfphi, decimals)) + ", " + str.tostring(xhi) + " bars ago" +
"\n🔀 Node: " + str.tostring(midcrossbars) + " bars ago" +
"\n📉 Trough (ª): " + str.tostring(truncate(bpfplo, decimals)) + ", " + str.tostring(xlo) + " bars ago" +
"\n\n🔮 Estimates: " + bbpt +
"\n📈 Next Peak: " + str.tostring(-next_peak) + "ish bars " +
"\n🔀 Next Node: " + str.tostring(next_node) + "ish bars" +
"\n📉 Next Trough: " + str.tostring(-next_trough) + "ish bars "
// ------------------------------- Plots, Displays, Outputs -------------------------------//
plot(0, "Midline", color.new(color.gray,30), style=plot.style_histogram)
plot(BPFh, '5 Day', color=color.new(colh, 0), linewidth=sig_in == "5 Day" ? 3 : 1)
plot(BPFf, '10 Day', color=color.new(colf, 0), linewidth=sig_in == "10 Day" ? 3 : 1)
plot(BPF2, '20 Day', color=color.new(col2, 0), linewidth=sig_in == "20 Day" ? 3 : 1)
plot(BPF4, '40 Day', color=color.new(col4, 0), linewidth=sig_in == "40 Day" ? 3 : 1)
plot(BPF8, '80 Day', color=color.new(col8, 0), linewidth=sig_in == "80 Day" ? 3 : 1)
plot(BPF16, '20 Week', color=color.new(col16, 0), linewidth=sig_in == "20 Week" ? 3 : 1)
plot(BPF32, '40 Week', color=color.new(col32, 0), linewidth=sig_in == "40 Week" ? 3 : 1)
plot(BPF64, '18 Month', color=color.new(col64, 0), linewidth=sig_in == "18 Month" ? 3 : 1)
plot(BPF128, '54 Month', color=color.new(col128, 0), linewidth=sig_in == "54 Month" ? 3 : 1, display=display.none)
plot(BPF256, '9 Year', color=color.new(col256, 0), linewidth=sig_in == "9 Year" ? 3 : 1, display=display.none)
plot(BPF512, '18 Year', color=color.new(col512, 0), linewidth=sig_in == "18 Year" ? 3 : 1, display=display.none)
plotcandle(compBPF[1], ta.lowest(compBPF,1), math.min(compBPF,compBPF[1]), compBPF, color=col, wickcolor=color.new(col,100), bordercolor=col, title='Composite Candles', display=display.none)
bgcolor(color=next_peak_col, title="Peak Estimate", offset=wavelength)
bgcolor(color=next_node_col, title="Node Estimate", offset=wavelength)
bgcolor(color=next_trough_col, title="Trough Estimate", offset=wavelength)
plotshape(hi, "Actual Peak", shape.triangledown, location.top, color.rgb(255, 0, 0, 33), size=size.tiny)
plotshape(lo, "Actual Trough", shape.triangleup, location.bottom, color.rgb(0, 255, 8, 33), size=size.tiny)
var table Ticker = na
table.delete(Ticker)
Ticker := table.new(position, 1, 1)
if barstate.islast
table.cell(Ticker, 0, 0,
text = "🔄 Cycle Analysis",
text_size = size,
text_color = color.new(col_out,0),
tooltip = sig_in!="None"?labeltt:"No Bandpass selected. Double click to open & change Settings.")
// EoS made w/ ❤ by @BarefootJoey ✌💗📈 |
Glan Nilly candle Trend | https://www.tradingview.com/script/maYiGef8-Glan-Nilly-candle-Trend/ | utsaeed21 | https://www.tradingview.com/u/utsaeed21/ | 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/
// © fauxlife
//@version=5
indicator(title="Glan Nilly candle Trend", shorttitle="GNCT", overlay=true)
tUc = input(color.blue, "Up Trend Color")
tDc = input(color.red, "Down Trend Color")
gc = color.rgb(197, 198, 202)
//-------------Heiken Ashi Calculation-----------------//
//Open = (open of previous bar + close of previous bar)/2.
//Close = (open + high + low + close)/4.
abi(chap, rast) => high[chap] < high[rast] and low[chap] < low[rast]
ghermez(chap, rast) => high[chap] > high[rast] and low[chap] > low[rast]
outerbarabi(chap, rast) => high[chap] < high[rast] and low[chap] > low[rast] and close[rast] > close[chap]
outerbarghermez(chap, rast) => high[chap] < high[rast] and low[chap] > low[rast] and close[rast] < close[chap]
innerbar(chap, rast) => high[chap] > high[rast] and low[chap] < low[rast]
oneouterabi = innerbar(2, 1) and abi(2, 0)
oneouterghermez = innerbar(2, 1) and ghermez(2, 0)
oneouteroutabi = innerbar(2, 1) and outerbarabi(2, 0)
oneouteroutghermez = innerbar(2, 1) and outerbarghermez(2, 0)
twoouterabi = innerbar(3, 2) and innerbar(3, 1) and abi(3, 0)
twoouterghermez = innerbar(3, 2) and innerbar(3, 1) and ghermez(3, 0)
twoouteroutabi = innerbar(3, 2) and innerbar(3, 1) and outerbarabi(3, 0)
twoouteroutghermez = innerbar(3, 2) and innerbar(3, 1) and outerbarghermez(3, 0)
threeouterabi = innerbar(4, 3) and innerbar(4, 2) and innerbar(4, 1) and abi(4, 0)
threeouterghermez = innerbar(4, 3) and innerbar(4, 2) and innerbar(4, 1) and ghermez(4, 0)
threeouteroutabi = innerbar(4, 3) and innerbar(4, 2) and innerbar(4, 1) and outerbarabi(4, 0)
threeouteroutghermez = innerbar(4, 3) and innerbar(4, 2) and innerbar(4, 1) and outerbarghermez(4, 0)
fourouterabi = innerbar(5, 4) and innerbar(5, 3) and innerbar(5, 2) and innerbar(5, 1) and abi(5, 0)
fourouterghermez = innerbar(5, 4) and innerbar(5, 3) and innerbar(5, 2) and innerbar(5, 1) and ghermez(5, 0)
fourouteroutabi = innerbar(5, 4) and innerbar(5, 3) and innerbar(5, 2) and innerbar(5, 1) and outerbarabi(5, 0)
fourouteroutghermez = innerbar(5, 4) and innerbar(5, 3) and innerbar(5, 2) and innerbar(5, 1) and outerbarghermez(5, 0)
fiveouterabi = innerbar(6, 5) and innerbar(6, 4) and innerbar(6, 3) and innerbar(6, 2) and innerbar(6, 1) and abi(6, 0)
fiveouterghermez = innerbar(6, 5) and innerbar(6, 4) and innerbar(6, 3) and innerbar(6, 2) and innerbar(6, 1) and ghermez(4, 0)
fiveouteroutabi = innerbar(6, 5) and innerbar(6, 4) and innerbar(6, 3) and innerbar(6, 2) and innerbar(6, 1) and outerbarabi(4, 0)
fiveouteroutghermez =innerbar(6, 5) and innerbar(6, 4) and innerbar(6, 3) and innerbar(6, 2) and innerbar(6, 1) and outerbarghermez(4, 0)
inner2 = innerbar(2, 1) and innerbar(2, 0)
inner3 = innerbar(3, 2) and innerbar(3, 1) and innerbar(3, 0)
inner4 = innerbar(4, 3) and innerbar(4, 2) and innerbar(4, 1) and innerbar(4, 0)
inner5 = innerbar(5, 4) and innerbar(5, 3) and innerbar(5, 2) and innerbar(5, 1) and innerbar(5, 0)
col = inner2 ? gc : inner3 ? gc : inner4 ? gc : inner5 ? gc : fiveouterabi ? tUc : fiveouterghermez ? tDc : fiveouteroutabi ? tUc : fiveouteroutghermez ?
tDc : fourouterabi ? tUc : fourouterghermez ? tDc : fourouteroutabi ? tUc : fourouteroutghermez ? tDc : threeouterabi ? tUc : threeouterghermez ? tDc :
threeouteroutabi ? tUc : threeouteroutghermez ? tDc : twoouterabi ? tUc : twoouterghermez ? tDc : twoouteroutabi ? tUc : twoouteroutghermez ? tDc :
oneouterabi ? tUc : oneouterghermez ? tDc : oneouteroutabi ? tUc : oneouteroutghermez ? tDc : abi(1, 0) ? tUc : ghermez(1, 0) ? tDc : outerbarabi(1, 0) ?
tUc : outerbarghermez(1, 0) ? tDc : gc
barcolor(col, title="Bar Color") |
Range ( Adjustable ) HLLS | https://www.tradingview.com/script/EJvFW4Au-Range-Adjustable-HLLS/ | Cryptoir | https://www.tradingview.com/u/Cryptoir/ | 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/
// © Cryptoir
// Adjustable Range of Previos candles
//@version=5
indicator("Range ( Adjustable )" , overlay=true)
NumberOfBars = input.int(400, title=" last Candles For Range ")
Heightscale = input.int(10 , title = "Adjust Totall Height ")
offset = input.int(0 , title= "Offset")
BarRange = high - low
emaAvg = ta.ema(close , 200)
avgRange = ta.ema(BarRange , NumberOfBars)
AvgUnder = avgRange * Heightscale + emaAvg
AvgAbove = emaAvg - avgRange * Heightscale
// Lines
plot(AvgAbove, color=color.rgb(255, 59, 59), offset = offset , title="bars")
plot(AvgUnder, color=color.rgb(0, 212, 53), offset = offset , title="bars")
|
DANIEL AGA INDICATOR BB | https://www.tradingview.com/script/skoYbFzt-DANIEL-AGA-INDICATOR-BB/ | agadaniel88 | https://www.tradingview.com/u/agadaniel88/ | 57 | 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/
// © agadaniel88
//@version=4
study("IDEAL BB with MA (With Alerts) by DANIEL AGA", overlay=true)
length1 = input(title="1st Length", type=input.integer, minval=1, defval=120)
length2 = input(title="2nd Length", type=input.integer, minval=1, defval=12)
maInput = input(title="MA Type", defval="EMA", options=["EMA", "SMA", "VWMA", "WMA"])
src = input(title="Source", type=input.source, defval=hl2)
getMA(src, length) =>
ma = 0.0
if maInput == "EMA"
ma := ema(src, length)
if maInput == "SMA"
ma := sma(src, length)
if maInput == "VWMA"
ma := vwma(src, length)
if maInput == "WMA"
ma := wma(src, length)
ma
getNMA(src, length1, length2) =>
lambda = length1 / length2
alpha = lambda * (length1 - 1) / (length1 - lambda)
ma1 = getMA(src, length1)
ma2 = getMA(ma1, length2)
nma = (1 + alpha) * ma1 - alpha * ma2
nma = getNMA(src, length1, length2)
//emaLength = input(90, minval=1, title="EMA Length")
//emaSource = input(close, title="EMA Source")
//ema = ema(emaSource, emaLength)
plot(nma, title="NMA Black Line", linewidth=2, style=plot.style_stepline, color=color.black, transp=0)
//plot(ema, title="EMA", linewidth=1, color=color.red, transp=0)
//VWAP BANDS
lenvwap = input(1, minval=1, title="VWAP Length")
src1a = input(close, title="VWAP Source")
offsetvwap = input(title="VWAP Offset", type=input.integer, defval=0, minval=-500, maxval=500)
srcvwap = hlc3
vvwap = vwap(srcvwap)
line1 = sma(src1a, lenvwap)
plot(vvwap, color=#e91e63, linewidth=2, style=plot.style_line, title="VWAP MIDDLE")
// Boll Bands
emaSource = close
emaPeriod = 20
devMultiple = 2
baseline = sma(emaSource, emaPeriod)
plot(baseline, title = "BB Red Line", color = color.red)
stdDeviation = devMultiple * (stdev(emaSource, emaPeriod))
upperBand = (baseline + stdDeviation)
lowerBand = (baseline - stdDeviation)
p1 = plot(upperBand, title = "BB Top", color = color.blue)
p2 = plot(lowerBand, title = "BB Bottom", color = #311b92)
fill(p1, p2, color = color.blue)
//HULL TREND WITH KAHLMAN
srchull = input(hl2, "Price Data")
lengthhull = input(24, "Lookback")
showcross = input(true, "Show cross over/under")
gain = input(10000, "Gain")
k = input(true, "Use Kahlman")
hma(_srchull, _lengthhull) =>
wma((2 * wma(_srchull, _lengthhull / 2)) - wma(_srchull, _lengthhull), round(sqrt(_lengthhull)))
hma3(_srchull, _lengthhull) =>
p = lengthhull/2
wma(wma(close,p/3)*3 - wma(close,p/2) - wma(close,p),p)
kahlman(x, g) =>
kf = 0.0
dk = x - nz(kf[1], x)
smooth = nz(kf[1],x)+dk*sqrt((g/10000)*2)
velo = 0.0
velo := nz(velo[1],0) + ((g/10000)*dk)
kf := smooth+velo
a = k ? kahlman(hma(srchull, lengthhull), gain) : hma(srchull, lengthhull)
b = k ? kahlman(hma3(srchull, lengthhull), gain) : hma3(srchull, lengthhull)
c = b > a ? color.lime : color.red
crossdn = a > b and a[1] < b[1]
crossup = b > a and b[1] < a[1]
p1hma = plot(a,color=c,linewidth=1,transp=75, title="Long Plot")
p2hma = plot(b,color=c,linewidth=1,transp=75, title="Short Plot")
fill(p1hma,p2hma,color=c,transp=55,title="Fill")
plotshape(showcross and crossdn ? a : na, location=location.abovebar, style=shape.labeldown, color=color.red, size=size.tiny, text="Sell", textcolor=color.white, transp=0, offset=-1)
plotshape(showcross and crossup ? a : na, location=location.belowbar, style=shape.labelup, color=color.green, size=size.tiny, text="Buy", textcolor=color.white, transp=0, offset=-1)
//ALERTS
alertcondition(crossup, title='Buy', message='Go Long')
alertcondition(crossdn, title='Sell', message='Go Short')
|
Financials - Comparing Companies | https://www.tradingview.com/script/yRFF3z4J-Financials-Comparing-Companies/ | LonesomeTheBlue | https://www.tradingview.com/u/LonesomeTheBlue/ | 886 | 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/
// © LonesomeTheBlue
type financials
float MarketCap
float Close
float EPS
float PriceEarningsRatio
float PriceSalesRatio
float PriceBookRatio
float ProfitMargin
float DebttoEquity
float CurrentRatio
float SMA50
float SMA200
float SMA50_1
float SMA200_1
float Volume
float AvgVolume
float Lastday
string Currency
Tooltips = array.from(
"Closing Price",
"The market value of a company’s equity. It is calculated by multiplying a company’s shares outstanding by its price per share",
"Earnings Per Share (EP) is company's net profit divided by the number of common shares it has outstanding. if EPS is higher than 0 then the company",
"the Price-to-Earnings ratio (P/E) is a metric measuring the price of a stock relative to its earnings per share (EPS). A high P/E ratio could mean that a stock's price is high relative to earnings and possibly overvalued",
"Price-to-Sales (P/S) ratio is a valuation ratio that compares a company’s stock price to its revenues. A low ratio may indicate the stock is undervalued, while a ratio that is significantly above the average may suggest overvaluation",
"Price-to-Book (P/B) ratio, by dividing a company's stock price by its book value per share. A lower P/B ratio could indicate that a stock is undervalued",
"Profit Margin is a ratio of a company's profit (sales minus all expenses) divided by its revenue. The profit margin ratio compares profit to sales and tells you how well the company is handling its finances overall",
"Debt-to-Equity ratio measures the company’s total debt relative to the amount originally invested by the owners and the earnings that have been retained over time. Although it varies from industry to industry, a debt-to-equity ratio of around 2 or 2.5 is generally considered good",
"Current Ratio is a liquidity ratio that measures the capability of a business to meet its short-term obligations that are due within a year. A ratio under 1.00 indicates that the company’s debts due in a year or less are greater than its assets",
"Simple Moving Average with the length 50",
"Simple Moving Average with the length 200",
"Current Volume",
"Average Volume")
//@version=5
indicator("Financials", overlay = true)
symbol1 = input.symbol(defval = 'NASDAQ:MSFT')
symbol2 = input.symbol(defval = 'NASDAQ:GOOGL')
symbol3 = input.symbol(defval = 'NASDAQ:META')
symbol4 = input.symbol(defval = 'NASDAQ:NFLX')
symbol5 = input.symbol(defval = 'NASDAQ:ADP')
tableposy = input.string(defval='bottom', title='Chart Location', options=['bottom', 'middle', 'top'], inline='chartpos')
tableposx = input.string(defval='left', title='', options=['left', 'center', 'right'], inline='chartpos')
txtsize = input.string(defval = size.normal, title = "Text Size", options = [size.tiny, size.small, size.normal, size.large])
avgvollen = input.int(defval = 20, title = 'Period for Average Volume', minval = 3, maxval = 100)
movt1 = input.string(defval = "SMA", title = "Moving Average Type 1", options = ["SMA", "EMA"], inline ='MA1')
movlen1 = input.int(defval = 50, title = '', minval = 2, inline ='MA1')
movt2 = input.string(defval = "SMA", title = "Moving Average Type 2", options = ["SMA", "EMA"], inline ='MA2')
movlen2 = input.int(defval = 200, title = '', minval = 2, inline ='MA2')
if timeframe.in_seconds(timeframe.period) < 86400
runtime.error("Please set the time frame 1Day or higher")
var MA1 = movt1 + str.tostring(movlen1)
var MA2 = movt2 + str.tostring(movlen2)
get_sma(source, length)=>
sum = 0.0
for i = 0 to length - 1
sum := sum + source[i] / length
sum
get_ema(source, length)=>
alpha = 2 / (length + 1)
sum = 0.0
sum := na(sum[1]) ? source : alpha * source + (1 - alpha) * nz(sum[1])
get_ma(source, length, type)=>
switch type
"SMA" => get_sma(source, length)
"EMA" => get_ema(source, length)
get_tech_indis()=>
[close, close[1], get_ma(close, movlen1, movt1), get_ma(close, movlen2, movt2), volume, get_sma(volume, avgvollen), " " + syminfo.currency]
get_financials(financials [] AllFinancials, symbol)=>
// get closing price and SMAs
[Price, Lastday, ma1, ma2, Volume, AvgVolume, Currency] = request.security(symbol, timeframe.period, get_tech_indis())
// Price to Earnings Ratio
float EPS = request.financial(symbol, "EARNINGS_PER_SHARE", "TTM")
float PriceEarningsRatio = Price / EPS
// Price/Earnings-to-Growth (PEG) Ratio
// PEG = request.financial(symbol, "PEG_RATIO", "FQ")
// Price Sales Ratio
float TSO = request.financial(symbol, "TOTAL_SHARES_OUTSTANDING", "FQ")
float TR = request.financial(symbol, "TOTAL_REVENUE", "TTM")
float MarketCap = TSO * Price
float PriceSalesRatio = MarketCap / TR
// Price to Book ratio
float BVPS = request.financial(symbol, "BOOK_VALUE_PER_SHARE", "FQ")
float PriceBookRatio = Price / BVPS
// Net Profit Margin (TTM)
float NetIncome = request.financial(symbol, "NET_INCOME", "TTM")
//TR := request.financial(symbol, "TOTAL_REVENUE", "FQ")
float ProfitMargin = 100 * NetIncome / TR
// DEBT TO EQUITY
float DebttoEquity = request.financial(symbol, "DEBT_TO_EQUITY", "FQ")
// CURRENT RATIO
float CurrentRatio = request.financial(symbol, "CURRENT_RATIO", "FQ")
array.push(AllFinancials, financials.new(MarketCap, Price, EPS, PriceEarningsRatio, PriceSalesRatio, PriceBookRatio, ProfitMargin, DebttoEquity, CurrentRatio, ma1, ma2, ma1[1], ma2[1], Volume, AvgVolume, Lastday, Currency))
get_element(financials element, string object)=>
switch object
"EPS" => element.EPS
"PriceEarningsRatio" => element.PriceEarningsRatio
"PriceSalesRatio" => element.PriceSalesRatio
"PriceBookRatio" => element.PriceBookRatio
"ProfitMargin" => element.ProfitMargin
"DebttoEquity" => element.DebttoEquity
"CurrentRatio" => element.CurrentRatio
"Volume" => element.Volume
"AvgVolume" => element.AvgVolume
"Lastday" => element.Lastday
MA1 => element.SMA50
MA2 => element.SMA200
getTheValues(financials [] AllFinancials, float [] order, string object, int objnum, int [] sorting)=>
tmp = array.new_float(0)
for x = 0 to 4
array.push(tmp, get_element(array.get(AllFinancials, x), object) * array.get(sorting, objnum))
for x = array.size(tmp) - 1 to 0
index = array.indexof(tmp, array.max(tmp))
array.set(order, index, array.get(order, index) + x)
array.set(tmp, index, -10e14)
get_ordered(financials [] AllFinancials, string [] objects, int [] sorting)=>
order = array.new_float(5, 0)
for x = 0 to array.size(objects) - 1
getTheValues(AllFinancials, order, array.get(objects, x), x, sorting)
order
getthecolor(financials element, string object)=>
color ret = color.green
if object == "EPS"
ret := element.EPS > 0 ?color.lime : color.red
else if object == "PriceSalesRatio"
ret := element.PriceSalesRatio < 1 ? color.lime : color.red
else if object == "PriceBookRatio"
ret := element.PriceBookRatio < 0 ? color.rgb(113, 115, 119) : element.PriceBookRatio < 1 ? color.lime : color.red
else if object == "debttoEquity"
ret := element.DebttoEquity < 1 ? color.lime : element.DebttoEquity <= 2.5 ? color.green : color.red
else if object == "CurrentRatio"
ret := element.CurrentRatio >= 1 ? color.lime : color.red
else if object == "Lastday"
ret := element.Lastday < element.Close ? color.green : color.red
else if str.contains(object, "Volume")
ret := color.rgb(180, 185, 230)
else
if object == MA1
ret := element.SMA50 > element.SMA50_1 ? color.green : element.SMA50 < element.SMA50_1 ? color.red : color.gray
else if object == MA2
ret := element.SMA200 > element.SMA200_1 ? color.green : element.SMA200 < element.SMA200_1 ? color.red : color.gray
else
ret := color.rgb(183, 189, 211)
ret
// Thanks to Tradingview for the following function
// details: https://www.tradingview.com/script/Lbxl9OqZ-Financials-on-Chart/
formatValue(series float value) =>
float digits = math.log10(math.abs(value))
string result = switch
digits > 12 => str.tostring(value / 1e12, '#.#' + " T")
digits > 9 => str.tostring(value / 1e9, '#.#' + " B")
digits > 6 => str.tostring(value / 1e6, '#.#' + " M")
digits > 3 => str.tostring(value / 1e3, '#.#' + " K")
=> str.tostring(value, "#" + '#')
AllFinancials = array.new<financials>(0)
get_financials(AllFinancials, symbol1)
get_financials(AllFinancials, symbol2)
get_financials(AllFinancials, symbol3)
get_financials(AllFinancials, symbol4)
get_financials(AllFinancials, symbol5)
if barstate.islast
var financetable = table.new(position = tableposy + '_' + tableposx, columns = 20, rows= 10, frame_width = 1, frame_color = color.gray, border_width = 1, border_color = color.gray)
var stocks = array.from(symbol1, symbol2, symbol3, symbol4, symbol5)
var objects = array.from("EPS", "PriceEarningsRatio", "PriceSalesRatio", "PriceBookRatio", "ProfitMargin", "DebttoEquity", "CurrentRatio")
var headers = array.from("EPS", "Price/Earning\nRatio", "Price/Sales\nRatio", "Price/Book\nRatio", "Profit\nMargin", "Debt\nto Equity", "Current\nRatio", movt1 + str.tostring(movlen1), movt2 + str.tostring(movlen2), "Volume", "AvgVolume")
var sorting = array.from(1, -1, -1, -1, 1, -1, 1)
order = get_ordered(AllFinancials, objects, sorting)
table.cell(financetable, 0, 0, text = "#", text_color = color.white, bgcolor = color.rgb(84, 57, 204), text_size = txtsize)
table.cell(financetable, 1, 0, text = "Stocks", text_color = color.white, bgcolor = color.rgb(84, 57, 204), text_size = txtsize)
table.cell(financetable, 2, 0, text = "Price/Change", text_color = color.white, bgcolor = color.navy, tooltip = array.get(Tooltips, 0), text_size = txtsize)
table.cell(financetable, 3, 0, text = "Market\nCap", text_color = color.white, bgcolor = color.navy, tooltip = array.get(Tooltips, 1), text_size = txtsize)
for x = 0 to array.size(headers) - 1
table.cell(financetable, 4 + x, 0, text = array.get(headers, x), text_color = color.white, bgcolor = color.navy, tooltip = array.get(Tooltips, x + 2), text_size = txtsize)
minimum = array.min(order)
for x = 0 to 4
index = array.indexof(order, array.max(order))
element = array.get(AllFinancials, index)
array.set(order, index, minimum - 1)
table.cell(financetable, 0, x + 1, text = str.tostring(x + 1), text_color = color.black, bgcolor = color.rgb(0, 255 - x * 15, 255 - x * 15), text_size = txtsize)
table.cell(financetable, 1, x + 1, text = array.get(stocks, index), text_color = color.black, bgcolor = color.rgb(0, 255 - x * 15, 255 - x * 15), text_size = txtsize)
table.cell(financetable, 2, x + 1, text = str.tostring(element.Close) + element.Currency + " (" + str.format("{0, number, #.##}", 100 * (element.Close - element.Lastday) / element.Lastday) + "%)",
text_color = color.white,
bgcolor = getthecolor(element, "Lastday"), text_size = txtsize)
table.cell(financetable, 3, x + 1, text = formatValue(element.MarketCap) + element.Currency, text_color = color.black, bgcolor = color.rgb(226, 225, 208), text_size = txtsize)
for y = 0 to array.size(headers) - 1
arrayp = y < array.size(objects) ? objects : headers
value = get_element(element, array.get(arrayp, y))
bgcol = getthecolor(element, array.get(arrayp, y))
table.cell(financetable, y + 4, x + 1, text = str.contains(array.get(arrayp, y), "Volume") ? formatValue(value) : str.tostring(value, '#.##'), text_color = color.black, bgcolor = bgcol, text_size = txtsize)
table.merge_cells(financetable, 0, 6, 3, 6)
table.merge_cells(financetable, 11, 6, 14, 6)
table.cell(financetable, 0, 6, text = '', text_color = color.black, bgcolor = color.gray, text_size = txtsize)
table.cell(financetable, 11, 6, text = '', text_color = color.black, bgcolor = color.gray, text_size = txtsize)
table.cell(financetable, 4, 6, text = 'Higher is better' + '\n' + '>0 : Profitable', text_color = color.black, bgcolor = color.rgb(201, 205, 218), text_halign =text.align_left, text_size = txtsize)
table.cell(financetable, 5, 6, text = 'Lower is better', text_color = color.black, bgcolor = color.rgb(179, 183, 196), text_halign =text.align_left, text_size = txtsize)
table.cell(financetable, 6, 6, text = '<1 : Undervalued' + '\n' + '>1 : Overvalued', text_color = color.black, bgcolor = color.rgb(201, 205, 218), text_halign =text.align_left, text_size = txtsize)
table.cell(financetable, 7, 6, text = '<1 : Undervalued' + '\n' + '>1 : Overvalued' + '\n' + '<0 : No meaning', text_color = color.black, bgcolor = color.rgb(179, 183, 196), text_halign =text.align_left, text_size = txtsize)
table.cell(financetable, 8, 6, text = 'Higher is better', text_color = color.black, bgcolor = color.rgb(201, 205, 218), text_halign =text.align_left, text_size = txtsize)
table.cell(financetable, 9, 6, text = 'Lower is better' + '\n' + '<1 : Good' + '\n' + '<2.5 : Okey' + '\n' + '>2.5 : Not good', text_color = color.black, bgcolor = color.rgb(179, 183, 196), text_halign =text.align_left, text_size = txtsize)
table.cell(financetable,10, 6, text = 'Higher is better' + '\n' + '<1 : Not good', text_color = color.black, bgcolor = color.rgb(201, 205, 218), text_halign =text.align_left, text_size = txtsize)
|
Kitti-Playbook request.earnings R0.0 | https://www.tradingview.com/script/PxV5Vbve-Kitti-Playbook-request-earnings-R0-0/ | Kittimasak_S | https://www.tradingview.com/u/Kittimasak_S/ | 12 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kittimasak_S
// Date: Feb 5 2023
//Objective :
// Display Earning per share
//Calculation :
// Get Earning value by use Function "request.earnings "
// Display :
// Plot Earning Data
// Earning History Tab
//@version=5
indicator("Kitti-Playbook request.earnings R0.0")
GetEPS=request.earnings(ticker=syminfo.tickerid, field= earnings.actual, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true, currency= syminfo.currency )
GetEPSColor= GetEPS>0 ? color.new(#4c5eaf, 90) : GetEPS<=0? color.new(#864caf, 70) :color.new(#864caf, 70)
GetEPSColorbm= GetEPS>0 ? color.new(#4c5eaf, 80) : GetEPS<=0? color.new(#864caf, 70) :color.new(#864caf, 70)
plot(GetEPS,"'Eraning per share",color=GetEPSColor,style=plot.style_area)
GetEPSbm = request.earnings(ticker=syminfo.tickerid, field=earnings.actual, gaps=barmerge.gaps_on, lookahead=barmerge.lookahead_on , ignore_invalid_symbol=true, currency= syminfo.currency)
plot(GetEPSbm,"'Eraning per share",color=GetEPSColorbm,style=plot.style_area)
plot(GetEPSbm)
// Eaening when last claculate
s3 = GetEPS == GetEPSbm ? 1: 0
plot(s3*GetEPS," cal date ", color=color.new(color.yellow,80))
E0=ta.valuewhen(s3>0,GetEPS,0) // earning / share T0
E1=ta.valuewhen(s3>0,GetEPS,1) // earning / share T0
E2=ta.valuewhen(s3>0,GetEPS,2) // earning / share T0
E3=ta.valuewhen(s3>0,GetEPS,3) // earning / share T0
Eacc1 = E0+E1
Eacc2 = E0+E1 +E2
Eacc3 = E0+E1 +E2 +E3
// check Last Bar
s4 = 1000
s4 := ta.barssince(s3>0)
// Value when last calcuation
s5=ta.valuewhen(s3>0,close,0)
// Eraning %
s6=E0/s5 *100
Eacc1p = Eacc1/s5 *100
Eacc2p = Eacc2/s5 * 100
Eacc3p = Eacc3/s5 * 100
// Display Label
ShowInfoTab = input.bool(title='Show Infomation Bar ', defval=true, group='Display Setting', inline="line1") // Show Tab
table_position2 = input.string(position.bottom_right, 'Information Bar position', options=
[position.middle_left,
position.middle_center,
position.middle_right,
position.bottom_left,
position.bottom_center,
position.bottom_right,
position.top_center,
position.top_right],
group='Display Setting', inline="line2")
Tab_Width2 = input.int(30, "Size", minval=5, maxval=40, step=1, group='Display Setting', inline="line2")
var table Signal_table2 = table.new(position=table_position2, columns=1, rows=4, border_width=0)
tColor1 = s4 > 0 ? color.new(#888888, 0) : color.new(#ff9900, 90)
bColor0 = s4 > 300? color.new(#d1e43d, 80) : E0 > 0? color.new(color.gray,90) :E0 < 0?color.new(#e43dc0, 80) : color.new(#ff9900, 90)
bColor1 = s4 > 300? color.new(#d1e43d, 80) : E1 > 0? color.new(color.gray,90) :E1 < 0?color.new(#e43dc0, 80) : color.new(#ff9900, 90)
bColor2 = s4 > 300? color.new(#d1e43d, 80) : E2 > 0? color.new(color.gray,90) :E2 < 0?color.new(#e43dc0, 80) : color.new(#ff9900, 90)
bColor3 = s4 > 300? color.new(#d1e43d, 80) : E3 > 0? color.new(color.gray,90) :E3 < 0?color.new(#e43dc0, 80) : color.new(#ff9900, 90)
_TEXT_DisplayA20 = " EPS (E0) = " + str.format("{0,number,#.###}",(E0)) + " " +syminfo.currency +" : " + str.format("{0,number,#.###}",(s6)) + "%" +" ( Report@ = - " + str.tostring(s4) + " Bar : Price "
+ str.format("{0,number,#.###}",(s5)) + " " + syminfo.currency + " )"
_TEXT_DisplayA21 = " EPS (E1) = " + str.format("{0,number,#.###}",(E1)) + " " +syminfo.currency +" :(Acc E0->E1 = " + str.format("{0,number,#.###}",(Eacc1)) + " " + syminfo.currency
+ " / " +str.format("{0,number,#.###}",(Eacc1p)) + "%"+ ")"
_TEXT_DisplayA22 = " EPS (E2) = " + str.format("{0,number,#.###}",(E2)) + " " +syminfo.currency +" : (Acc E0->E2 = " + str.format("{0,number,#.###}",(Eacc2)) + " " + syminfo.currency
+ " / " +str.format("{0,number,#.###}",(Eacc2p)) + "%"+ ")"
_TEXT_DisplayA23 = " EPS (E3) = " + str.format("{0,number,#.###}",(E3)) + " " +syminfo.currency +" : (Acc E0->E3 = " + str.format("{0,number,#.###}",(Eacc3)) + " " + syminfo.currency
+ " / " +str.format("{0,number,#.###}",(Eacc3p)) + "%" + ")"
if ShowInfoTab == true
table.cell(Signal_table2, 0, 0, _TEXT_DisplayA20, bgcolor=bColor0, text_color=tColor1,text_halign=text.align_left, width=Tab_Width2)
table.cell(Signal_table2, 0, 1, _TEXT_DisplayA21, bgcolor=bColor1, text_color=tColor1,text_halign=text.align_left, width=Tab_Width2)
table.cell(Signal_table2, 0, 2, _TEXT_DisplayA22, bgcolor=bColor2, text_color=tColor1,text_halign=text.align_left, width=Tab_Width2)
table.cell(Signal_table2, 0, 3, _TEXT_DisplayA23, bgcolor=bColor3, text_color=tColor1,text_halign=text.align_left, width=Tab_Width2)
//======================== END =================================================================================
|
BE - Golden Cross Crude Key | https://www.tradingview.com/script/GvvnXXyU-BE-Golden-Cross-Crude-Key/ | TradeWiseWithEase | https://www.tradingview.com/u/TradeWiseWithEase/ | 99 | 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/
// © TradeWiseWithEase
//@version=5
indicator("BE - Golden Cross Crude Key",shorttitle = "BE-CRUDE-V0.1.1", overlay = true)
import TradeWiseWithEase/BE_CustomFx_Library/93 as BEL
var string GroupText1 = "Trade Scan Settings"
var string GroupText2 = "Trend Tracker Settings"
var string GroupText3 = "Trade Alerts Settings"
var string GroupText4 = "Trade Table Settings"
var string RealtimeTip = "If Enabled Trade 'ENTRIES' & 'EXITS' shall be on the 'REALTIME' upon 'PRICE' hitting the 'ENTRY ZONE' OR 'SL ZONE' even on the 'yet to complete candle' or trade gets 'CLOSED' Upon specific 'PROFIT BOOKING ZONES' on realtime basis.\n\nSince It doesn't wait for the close of the candle to happen, there may be possibility of showing the 'ENTRIES' which would have closed in realtime but it may still be showing as 'RUNNING' upon 'CHART REFRESH'.\n\nIf set to True, Trades will be notified while the candle is forming / Yet to complete. Else Trades will be notified upon CLOSE of the candle."
var string HedgeTTIP = "This Option Allows you to place HEDGE Leg (options) to avail margin benefit for trades placed in FUTURES.\n\nEnsure to Update Correct Options Symbols along with Expiry Date in the fields provided\n\nDefault 10 refers to 10 OTM CE & PE & the option Legs are brought during the first trade and the same shall be squared off when the TRADING SESSION is CLOSED"
var string UseA_NameTTP = "Plz use symbol constructor from NLB webportal\n\n https://nextlevelbot.com/broker_symbol \n\nIMPORTANT: SPECIFY THE TRADING ACCOUNT NAME CORRECTLY AND USE ': WITH A SPACE'\n\nUSE 'FORWARDSLASH /' TO SEPARATE THE SYMBOLS BETWEEN FUTURES AND OPTIONS"
var string SymbolTextA = 'DHANHQ: CRUDEOIL23FEBFUT/CRUDEOIL23FEB' + '\n' + 'TRADINGVIEW: CRUDEOIL23FEBFUT/CRUDEOIL23FEB'
//#region Trade Scan Settings
var string sess = input.session(
defval = '1800-2330',
title = 'Trade Session',
group = GroupText1,
tooltip = "Default Values refers to -->\n\nTrade Entries Shall be Scanned Post 6 PM and any Open Position Shall be Squared Off Post 11:00 PM or Close of the Candle Whichever is LATER.")
var string NoFreshEntryTime = "0000-" + input.string(
defval = '2230',
title = 'No Fresh Entry Post',
group = GroupText1)
var bool ShowPlots = input.bool(
defval = true,
title = "Show SMA Line",
inline = "SMA",
group = GroupText1)
var color SMAClr = input.color(
defval = color.orange,
title = "",
inline = "SMA",
group = GroupText1)
var int SMAWidth = input.int(
defval = 1,
title = "",
inline = "SMA",
group = GroupText1)
var int SMALength = input.int(
defval = 42,
title = "",
inline = "SMA",
minval = 1,
group = GroupText1)
SMAValue = ta.sma(close, SMALength)
plot(
ShowPlots ? SMAValue : na,
title = "SMA Value",
linewidth = SMAWidth,
color = SMAClr,
editable = false)
//#endregion
//#region Trend Tracker Settings
var int Mode = input.int(
defval = 2,
title = "Tracker Mode",
minval = 1,
group = GroupText2)
var int Sensitivity = input.int(
defval = 1,
title = "Sensitivity [0 - 2]",
group = GroupText2,
minval = 0,
maxval = 2,
tooltip = "Low Value looks for More confirmed pattern, High value predicts for Possible Confirmation.")
var bool ShowTrendTracker = input.bool(
defval = true,
title = "Show Trend Tracker",
group = GroupText2)
var color Tr_LongClr = input.color(
defval = #0cd0deed,
title = "Up",
inline = "TT",
group = GroupText2)
var color Tr_ShortClr = input.color(
defval = #cd13db,
title = "Dn",
inline = "TT",
group = GroupText2)
var int Tr_LineWidth = input.int(
defval = 1,
title = "",
inline = "TT",
group = GroupText2)
//#region Trend Tracker Calculation
var int Trend_Direction = 0
var int NxtTrend_Direction = 0
var float MaxLowPrice = nz(low[1], low)
var float MinHighPrice = nz(high[1], high)
var float TrendLevel = 0.0
var float CapUp = 0.0
var float CapDown = 0.0
float ATR2Level = ta.atr(100) / 2
float HighPrice = high[math.abs(ta.highestbars(Mode))]
float LowPrice = low[math.abs(ta.lowestbars(Mode))]
float HighMovAvg = ta.sma(Sensitivity == 0 ? high : Sensitivity == 1 ? hlc3 : hl2, Mode)
float LowMovAvg = ta.sma(Sensitivity == 0 ? low : Sensitivity == 1 ? hlc3 : hl2, Mode)
float SMAofATR = ta.sma(ATR2Level[1], 4)
Bars_SMAH_LT_InfoHighestLow = ta.barssince(not (HighMovAvg < MaxLowPrice))
Bars_SMAL_GT_InfolowestHigh = ta.barssince(not (LowMovAvg > MinHighPrice))
ConvertHT2Long = (((close - TrendLevel) > SMAofATR * 3.25) or Bars_SMAL_GT_InfolowestHigh == 3) and NxtTrend_Direction == 1 and close > TrendLevel and barstate.isconfirmed
ConvertHT2Short = (((TrendLevel - close) > SMAofATR * 3.25) or Bars_SMAH_LT_InfoHighestLow == 3) and NxtTrend_Direction == -1 and close < TrendLevel and barstate.isconfirmed
if barstate.isconfirmed
if NxtTrend_Direction == -1
MaxLowPrice := math.max(LowPrice, MaxLowPrice)
if HighMovAvg < MaxLowPrice and close < nz(low[1], low) and (Sensitivity < 1 or (Sensitivity >= 1 and (MaxLowPrice - close) > SMAofATR * 1.75))
Trend_Direction := -1
NxtTrend_Direction := 1
MinHighPrice := HighPrice
else if ConvertHT2Short and Sensitivity >= 1
Trend_Direction := -1
NxtTrend_Direction := 1
MinHighPrice := HighPrice
else
MinHighPrice := math.min(HighPrice, MinHighPrice)
if LowMovAvg > MinHighPrice and close > nz(high[1], high) and (Sensitivity < 1 or (Sensitivity >= 1 and (close - MinHighPrice) > SMAofATR * 1.75))
Trend_Direction := 1
NxtTrend_Direction := -1
MaxLowPrice := LowPrice
else if ConvertHT2Long and Sensitivity >= 1
Trend_Direction := 1
NxtTrend_Direction := -1
MaxLowPrice := LowPrice
if Trend_Direction == 1
if Trend_Direction[1] == -1 and not na(Trend_Direction[1])
CapUp := na(CapDown[1]) ? CapDown : CapDown[1]
else
CapUp := na(CapUp[1]) ? MaxLowPrice : math.max(MaxLowPrice, CapUp[1])
else
if Trend_Direction[1] == 1 and not na(Trend_Direction[1])
CapDown := na(CapUp[1]) ? CapUp : CapUp[1]
else
CapDown := na(CapDown[1]) ? MinHighPrice : math.min(MinHighPrice, CapDown[1])
TrendLevel := Trend_Direction == 1 ? CapUp : CapDown
TrendColor = Trend_Direction == 1 ? Tr_LongClr : Tr_ShortClr
plot(
ShowTrendTracker ? TrendLevel : na,
title = "Trend Tracker",
linewidth = Tr_LineWidth,
color = TrendColor,
editable = false)
//#endregion
//#endregion
//#region Trade Alerts Settings
var bool IsRealTime = input.bool(
defval = true,
title = "Trade On Realtime ?",
group = GroupText3,
tooltip = RealtimeTip)
var string SymbolText = str.upper(input.text_area(
defval = SymbolTextA,
title = "Symbol Name. Read Tips -->",
group = GroupText3,
tooltip = UseA_NameTTP))
//#region SymbolExtract Procedure
var ListOfTradingAccount = array.new_string(0)
var ListOfFuturePrefix = array.new_string(0)
var ListOfOptionsPrefix = array.new_string(0)
var SplitOfInputList = str.split(SymbolText,"\n")
var CountOfNLB_AccountsProvided = array.size(SplitOfInputList)
if barstate.isfirst and CountOfNLB_AccountsProvided > 0
array.clear(ListOfTradingAccount)
for [index, value] in SplitOfInputList
AccountSplit = str.split(value,": ")
if array.size(AccountSplit) > 0
array.push(ListOfTradingAccount, array.get(AccountSplit, 0))
ScriptSplit = str.split(array.get(AccountSplit, 1),"/")
if array.size(ScriptSplit) > 0
for [index_, value_] in ScriptSplit
if str.endswith(value_,"FUT") or str.endswith(value_,"F")
array.push(ListOfFuturePrefix, array.get(ScriptSplit, index_))
else
array.push(ListOfOptionsPrefix, array.get(ScriptSplit, index_))
else
runtime.error("Couldn't Extract the NLB TradingAccount List")
break
//#endregion
var bool AvoidOnWed = input.bool(
defval = true,
title = "Avoid Trade On Wednesday",
group = GroupText3)
var bool TakeTrendConfirmation = input.bool(
defval = true,
title = "Confirm Trade With Trend Direction",
group = GroupText3)
var int TradeQty = input.int(
defval = 100,
title = "Qty Per Trade",
group = GroupText3,
step = 100,
minval = 1)
var string FutOrOps = input.string(
defval = "FUT",
title = "Trade On Type",
group = GroupText3,
options = ["FUT","OPS"])
var string IAO = input.string(
defval = "ATM",
title = "Option Moneyness. ",
group = GroupText3,
options = ["ITM","OTM","ATM"],
inline = "OD")
var int deepness = input.int(
defval = 1,
title = "",
group = GroupText3,
inline = "OD",
step = 1,
minval = 1)
var bool PlayHedge = input.bool(
defval = true,
title = "Hedge Legs ",
group = GroupText3,
inline = "Hedge",
tooltip = HedgeTTIP)
var int HedgeLegDeepness = input.int(
defval = 10,
title = "",
group = GroupText3,
inline = "Hedge",
minval = 1,
maxval = 20)
var string TGTType = input.string(
defval = "Capital",
title = "Target Type ",
group = GroupText3,
inline = "TGT",
options = ["Capital", "Point Based", "Biased"])
var float TGT_Value = input.float(
defval = 12000,
title = "",
group = GroupText3,
inline = "TGT")
var string SLType = input.string(
defval = "Capital DD",
title = "Stop Loss Type ",
group = GroupText3,
inline = "SLT",
options = ["Capital DD", "Point Based", "Biased", "Point Based Trail"])
var float SL_Value = input.float(
defval = 5000,
title = "",
group = GroupText3,
inline = "SLT")
var bool LookForBiasExit = input.bool(
defval = false,
title = "Exit based On Bias Method if Possible",
group = GroupText3)
var float TrailPCT = input.float(
defval = 50,
title = "On ",
group = GroupText3,
minval = 0,
maxval = 100,
inline = "TSL") / 100
var float LockSLAt = input.float(
defval = 10,
title = "% of Target Lock SL at %",
group = GroupText3,
minval = -99,
maxval = 99,
inline = "TSL") / 100
var int StrikeDiff = input.int(
defval = 50,
title = "Strike Difference",
group = GroupText3,
minval = 1,
maxval = 5000)
//#endregion
//#region Trade Table Settings
var bool ShowTradeLogTable = input.bool(
defval = true,
title = "Show Trade Table",
inline = "TL",
group = GroupText4)
var color TableTextColor = input.color(
defval = color.orange,
title = "",
inline = "TL",
group = GroupText4)
//#endregion
//#region Declared Variables
var TradeInfoTable = table.new(position.top_right,2,4, frame_color = color.aqua, frame_width = 1, border_width = 1, border_color = color.aqua)
if barstate.isfirst and ShowTradeLogTable
for xrow = 0 to 3
for ycol = 0 to 1
table.cell_set_text_font_family(TradeInfoTable, ycol, xrow, font.family_monospace)
table.cell_set_text_size(TradeInfoTable, ycol, xrow, size.small)
table.cell_set_text_color(TradeInfoTable, ycol, xrow, TableTextColor)
table.cell_set_text_halign(TradeInfoTable, ycol, xrow, ycol == 0 ? text.align_left : text.align_center)
table.cell_set_text(TradeInfoTable, 0, 0, "Total Trades")
table.cell_set_text(TradeInfoTable, 0, 1, "Profitable Trades")
table.cell_set_text(TradeInfoTable, 0, 2, "Profitability %")
table.cell_set_text(TradeInfoTable, 0, 3, "Avg Peak Profitiablity")
varip Days_PNL = array.new_float(0)
varip OverAll_PNL = array.new_float(0)
varip MaxTradeROI_Array = array.new_float(0)
varip LogSummary = array.new_string(0)
varip float Last_TradePNL = 0.0
bool BuyShape = false
bool SellShape = false
bool ExitShape = false
type Setup
float ToBreakValue
int CrossCandle
int MaxToTradeCandle
float SLForTheTrade
var LongSetup = Setup.new()
var ShortSetup = Setup.new()
varip Log = BEL.Trade_Info.new()
Log.T_Qty := TradeQty
Log.T_QtyString := str.tostring(TradeQty)
if session.isfirstbar_regular
array.clear(Days_PNL)
Log.T_HasExited := 1
Log.T_HasEntered := 0
var string ScriptName = BEL.ScriptConvertor("Name", syminfo.ticker)
var bool StartAllThingsWhen = false
var bool RestrictFreshEntry = false
TimeStringCalculation = barstate.isrealtime ? timenow : time_close - 1
bool NotToTradeToday = dayofweek(TimeStringCalculation) == 4 and AvoidOnWed
DateTimeString = str.format_time(TimeStringCalculation, "dd-MM-yyyy HH:mm:ss", syminfo.timezone)
StartAllThingsWhen := BEL.Chk_TradingTime(sess)
RestrictFreshEntry := not BEL.Chk_TradingTime(NoFreshEntryTime)
ChangeInTradingSession = ta.change(StartAllThingsWhen)
HasCrossOverHappened = ta.crossover(close, SMAValue) and barstate.isconfirmed and not NotToTradeToday
HasCrossUnderHappened = ta.crossunder(close, SMAValue) and barstate.isconfirmed and not NotToTradeToday
//#endregion
//#region EntrySetups
if HasCrossOverHappened
LongSetup.ToBreakValue := high + 5
LongSetup.CrossCandle := bar_index + 1
LongSetup.MaxToTradeCandle := bar_index + 2
LongSetup.SLForTheTrade := Log.T_HasEntered == 1 and Log.T_Direction == -1 and bar_index > Log.NextTradeAfter ? high : na
Log.ExitCandleCheck := if not na(LongSetup.SLForTheTrade)
bar_index
if HasCrossUnderHappened
ShortSetup.ToBreakValue := low - 5
ShortSetup.CrossCandle := bar_index + 1
ShortSetup.MaxToTradeCandle := bar_index + 2
ShortSetup.SLForTheTrade := Log.T_HasEntered == 1 and Log.T_Direction == 1 and bar_index > Log.NextTradeAfter ? low : na
Log.ExitCandleCheck := if not na(ShortSetup.SLForTheTrade)
bar_index
LongTadeEntry = false
ShortTadeEntry = false
if BEL.OperatorChk(barstate.isrealtime ? close : (TakeTrendConfirmation and Trend_Direction == -1) ? close : high ,"G", LongSetup.ToBreakValue) and BEL.OperatorChk(bar_index,"BE", LongSetup.CrossCandle, LongSetup.MaxToTradeCandle) and StartAllThingsWhen
ExpectedBarstatus = if (TakeTrendConfirmation and Trend_Direction == -1) or not IsRealTime
barstate.isconfirmed
else
true
LongTadeEntry := if ExpectedBarstatus
true
if BEL.OperatorChk(barstate.isrealtime ? close : (TakeTrendConfirmation and Trend_Direction == 1) ? close : low ,"L", ShortSetup.ToBreakValue) and BEL.OperatorChk(bar_index,"BE", ShortSetup.CrossCandle, ShortSetup.MaxToTradeCandle) and StartAllThingsWhen
ExpectedBarstatus = if (TakeTrendConfirmation and Trend_Direction == 1) or not IsRealTime
barstate.isconfirmed
else
true
ShortTadeEntry := if ExpectedBarstatus
true
//#endregion
//#region Trade Entry
varip HedgeLegOptions = array.new_string(0)
varip MainLegSymbols = array.new_string(0)
if StartAllThingsWhen and bar_index > Log.NextTradeAfter and not RestrictFreshEntry
string FinalEntryAlertText = ""
EntryAlertLegsArray = array.new_string(0)
if Log.T_HasEntered == 0
if LongTadeEntry
Log.T_EnPrice := if barstate.isrealtime and IsRealTime
close
else
LongSetup.ToBreakValue
if PlayHedge and Log.IsFirstTradeForTheDay and FutOrOps == "FUT"
Log.IsFirstTradeForTheDay := false
array.clear(HedgeLegOptions)
for [index, value] in ListOfTradingAccount
Otype = value == "TRADINGVIEW" ? "" : "M"
[Symbol_C, AlertString_C] = BEL.LegScriptContructor(true, "OTM", HedgeLegDeepness, StrikeDiff,
true, "C", 0.0, 0.0, "NLB", array.get(ListOfOptionsPrefix, index), 0, "BUY",
Log.T_QtyString, "", "", value, "MCX", Otype)
[Symbol_P, AlertString_P] = BEL.LegScriptContructor(true, "OTM", HedgeLegDeepness, StrikeDiff,
false, "C", 0.0, 0.0, "NLB", array.get(ListOfOptionsPrefix, index), 0, "BUY",
Log.T_QtyString, "", "", value, "MCX", Otype)
array.push(HedgeLegOptions, Symbol_C)
array.push(HedgeLegOptions, Symbol_P)
array.push(EntryAlertLegsArray, AlertString_C)
array.push(EntryAlertLegsArray, AlertString_P)
Log.HedgeCEOTM := Symbol_C
Log.HedgePEOTM := Symbol_P
Log.T_Symbol := ScriptName
array.clear(MainLegSymbols)
for [index, value] in ListOfTradingAccount
Otype = value == "TRADINGVIEW" ? "" : "L"
[Symbol_T, AlertString_T] = BEL.LegScriptContructor(FutOrOps == "OPS" ? true : false, IAO, deepness, StrikeDiff,
true, "C", 0.0, 0.75, "NLB", FutOrOps == "OPS" ? array.get(ListOfOptionsPrefix, index) : array.get(ListOfFuturePrefix, index), 0,
"BUY", Log.T_QtyString, "", "", value, "MCX", Otype, true, "0.1%")
array.push(MainLegSymbols, Symbol_T)
array.push(EntryAlertLegsArray, AlertString_T)
FinalEntryAlertText := BEL.LegConstructor(EntryAlertLegsArray, "NLB")
if str.length(FinalEntryAlertText) > 3
alert(FinalEntryAlertText, alert.freq_once_per_bar)
Log.T_En_Date_Time := DateTimeString
Log.T_EnCandle := bar_index
Log.T_Name := "Long | Cross Over Trade on " + Log.T_Symbol
Log.T_HasEntered := 1
Log.T_Direction := 1
Log.T_HasExited := 0
Log.T_ExCandle := 0
Log.T_ExPrice := 0
Log.T_TGTPrice := TGTType == "Point Based" ? math.round_to_mintick(Log.T_EnPrice + TGT_Value) : TGTType == "Capital" ? math.round_to_mintick(Log.T_EnPrice + (TGT_Value / Log.T_Qty)) : na
Log.T_SLPrice := (SLType == "Point Based" or SLType == "Point Based Trail") ? math.round_to_mintick(Log.T_EnPrice - SL_Value) : SLType == "Capital DD" ? math.round_to_mintick(Log.T_EnPrice - (SL_Value / Log.T_Qty)) : na
Log.NextTradeAfter := Log.T_EnCandle
Log.LongTrades += 1
Log.AllTrades += 1
Log.DaysTrades += 1
LongSetup.ToBreakValue := na
LongSetup.CrossCandle := na
LongSetup.MaxToTradeCandle := na
Log.Price2MoveForTrailing := if SLType == "Point Based Trail" and (TGTType == "Point Based" or TGTType == "Capital")
math.round_to_mintick(Log.T_EnPrice + (math.abs(Log.T_TGTPrice - Log.T_EnPrice) * TrailPCT))
else
na
Log.TrailSL_Val := if not na(Log.Price2MoveForTrailing)
if LockSLAt == 0
Log.T_EnPrice
else if LockSLAt > 0
math.round_to_mintick(Log.T_EnPrice + (math.abs(Log.T_TGTPrice - Log.T_EnPrice) * LockSLAt))
else
math.round_to_mintick(Log.T_SLPrice + (math.abs(Log.T_SLPrice - Log.T_EnPrice) * math.abs(LockSLAt)))
Log.SL_Level := 0
else if ShortTadeEntry
Log.T_EnPrice := if barstate.isrealtime and IsRealTime
close
else
ShortSetup.ToBreakValue
if PlayHedge and Log.IsFirstTradeForTheDay and FutOrOps == "FUT"
Log.IsFirstTradeForTheDay := false
array.clear(HedgeLegOptions)
for [index, value] in ListOfTradingAccount
Otype = value == "TRADINGVIEW" ? "" : "M"
[Symbol_C, AlertString_C] = BEL.LegScriptContructor(true, "OTM", HedgeLegDeepness, StrikeDiff,
true, "C", 0.0, 0.0, "NLB", array.get(ListOfOptionsPrefix, index), 0, "BUY",
Log.T_QtyString, "", "", value, "MCX", Otype)
[Symbol_P, AlertString_P] = BEL.LegScriptContructor(true, "OTM", HedgeLegDeepness, StrikeDiff,
false, "C", 0.0, 0.0, "NLB", array.get(ListOfOptionsPrefix, index), 0, "BUY",
Log.T_QtyString, "", "", value, "MCX", Otype)
array.push(HedgeLegOptions, Symbol_C)
array.push(HedgeLegOptions, Symbol_P)
array.push(EntryAlertLegsArray, AlertString_C)
array.push(EntryAlertLegsArray, AlertString_P)
Log.HedgeCEOTM := Symbol_C
Log.HedgePEOTM := Symbol_P
Log.T_Symbol := ScriptName
array.clear(MainLegSymbols)
for [index, value] in ListOfTradingAccount
Otype = value == "TRADINGVIEW" ? "" : "L"
DirectionOfTrade = FutOrOps == "OPS" ? "BUY" : "SELL"
[Symbol_T, AlertString_T] = BEL.LegScriptContructor(FutOrOps == "OPS" ? true : false, IAO, deepness, StrikeDiff,
true, "C", 0.0, 0.75, "NLB", FutOrOps == "OPS" ? array.get(ListOfOptionsPrefix, index) : array.get(ListOfFuturePrefix, index), 0,
DirectionOfTrade, Log.T_QtyString, "", "", value, "MCX", Otype, true, "0.1%")
array.push(MainLegSymbols, Symbol_T)
array.push(EntryAlertLegsArray, AlertString_T)
FinalEntryAlertText := BEL.LegConstructor(EntryAlertLegsArray, "NLB")
if str.length(FinalEntryAlertText) > 3
alert(FinalEntryAlertText, alert.freq_once_per_bar)
Log.T_En_Date_Time := DateTimeString
Log.T_EnCandle := bar_index
Log.T_Name := "Short | Cross Under Trade on " + Log.T_Symbol
Log.T_HasEntered := 1
Log.T_Direction := -1
Log.T_HasExited := 0
Log.T_ExCandle := 0
Log.T_ExPrice := 0
Log.T_TGTPrice := TGTType == "Point Based" ? math.round_to_mintick(Log.T_EnPrice - TGT_Value) : TGTType == "Capital" ? math.round_to_mintick(Log.T_EnPrice - (TGT_Value / Log.T_Qty)) : na
Log.T_SLPrice := (SLType == "Point Based" or SLType == "Point Based Trail") ? math.round_to_mintick(Log.T_EnPrice + SL_Value) : SLType == "Capital DD" ? math.round_to_mintick(Log.T_EnPrice + (SL_Value / Log.T_Qty)) : na
Log.NextTradeAfter := Log.T_EnCandle
Log.ShortTrades += 1
Log.AllTrades += 1
Log.DaysTrades += 1
ShortSetup.ToBreakValue := na
ShortSetup.CrossCandle := na
ShortSetup.MaxToTradeCandle := na
Log.Price2MoveForTrailing := if SLType == "Point Based Trail" and (TGTType == "Point Based" or TGTType == "Capital")
math.round_to_mintick(Log.T_EnPrice - (math.abs(Log.T_TGTPrice - Log.T_EnPrice) * TrailPCT))
else
na
Log.TrailSL_Val := if not na(Log.Price2MoveForTrailing)
if LockSLAt == 0
Log.T_EnPrice
else if LockSLAt > 0
math.round_to_mintick(Log.T_EnPrice - (math.abs(Log.T_TGTPrice - Log.T_EnPrice) * LockSLAt))
else
math.round_to_mintick(Log.T_SLPrice - (math.abs(Log.T_SLPrice - Log.T_EnPrice) * math.abs(LockSLAt)))
Log.SL_Level := 0
//#endregion
//#region Peforming Regular Exit Check
Log.ExitCandleCheck := not barstate.isrealtime ? Log.T_EnCandle + 1 : Log.T_EnCandle
if Log.T_Direction == 1 and not na(Log.Price2MoveForTrailing) and SLType == "Point Based Trail" and Log.SL_Level == 0
if BEL.OperatorChk(close, "GE", Log.Price2MoveForTrailing)
Log.T_SLPrice := Log.TrailSL_Val
Log.SL_Level := 1
else if Log.T_Direction == -1 and not na(Log.Price2MoveForTrailing) and SLType == "Point Based Trail" and Log.SL_Level == 0
if BEL.OperatorChk(close, "LE", Log.Price2MoveForTrailing)
Log.T_SLPrice := Log.TrailSL_Val
Log.SL_Level := 1
CloseCrossUnderTrend = ta.crossunder(close, TrendLevel) and barstate.isconfirmed
CloseCrossOverTrend = ta.crossover(close, TrendLevel) and barstate.isconfirmed
HasHitTGT = if Log.T_Direction == 1 and not na(Log.T_TGTPrice)
BEL.OperatorChk(barstate.isrealtime and IsRealTime ? close : barstate.isrealtime and not IsRealTime and barstate.isconfirmed ? close : not barstate.isrealtime ? high : close ,"GE", Log.T_TGTPrice)
else if Log.T_Direction == -1 and not na(Log.T_TGTPrice)
BEL.OperatorChk(barstate.isrealtime and IsRealTime ? close : barstate.isrealtime and not IsRealTime and barstate.isconfirmed ? close : not barstate.isrealtime ? low : close,"LE", Log.T_TGTPrice)
else
false
HasHitSL = if Log.T_Direction == 1 and not na(Log.T_SLPrice)
BEL.OperatorChk(barstate.isrealtime and IsRealTime ? close : barstate.isrealtime and not IsRealTime and barstate.isconfirmed ? close : not barstate.isrealtime ? low : close ,"L", Log.T_SLPrice)
else if Log.T_Direction == 1 and not na(ShortSetup.SLForTheTrade) and bar_index > Log.ExitCandleCheck and (SLType == "Biased" or LookForBiasExit)
BEL.OperatorChk(barstate.isrealtime and IsRealTime ? close : barstate.isrealtime and not IsRealTime and barstate.isconfirmed ? close : not barstate.isrealtime ? low : close ,"L", ShortSetup.SLForTheTrade - 1)
else if Log.T_Direction == -1 and not na(Log.T_SLPrice)
BEL.OperatorChk(barstate.isrealtime and IsRealTime ? close : barstate.isrealtime and not IsRealTime and barstate.isconfirmed ? close : not barstate.isrealtime ? high : close,"G", Log.T_SLPrice)
else if Log.T_Direction == -1 and not na(LongSetup.SLForTheTrade) and bar_index > Log.ExitCandleCheck and (SLType == "Biased" or LookForBiasExit)
BEL.OperatorChk(barstate.isrealtime and IsRealTime ? close : barstate.isrealtime and not IsRealTime and barstate.isconfirmed ? close : not barstate.isrealtime ? high : close,"G", LongSetup.SLForTheTrade + 1)
else
false
HasHitBias = if Log.T_Direction == 1 and CloseCrossUnderTrend and bar_index > Log.ExitCandleCheck and (SLType == "Biased" or LookForBiasExit)
true
else if Log.T_Direction == -1 and CloseCrossOverTrend and bar_index > Log.ExitCandleCheck and (SLType == "Biased" or LookForBiasExit)
true
//#endregion
//#region Peforming Regular Exit of Trades
string FinalExitAlertMessage = ""
if StartAllThingsWhen
if (Log.T_HasExited == 0 and Log.T_HasEntered == 1) and bar_index >= Log.ExitCandleCheck and (HasHitSL or HasHitTGT or HasHitBias)
ExitAlertLegsArray = array.new_string(0)
if Log.T_Direction == 1
for [index, value] in ListOfTradingAccount
if FutOrOps == "OPS"
array.push(ExitAlertLegsArray, BEL.CancelClose(true, value, "MCX", array.get(ListOfOptionsPrefix, index)))
else if FutOrOps == "FUT"
array.push(ExitAlertLegsArray, BEL.CancelClose(false, value, "MCX", array.get(ListOfFuturePrefix, index), "A", "S"))
FinalExitAlertMessage := BEL.LegConstructor(ExitAlertLegsArray, "NLB")
if str.length(FinalExitAlertMessage) > 3
alert(FinalExitAlertMessage, alert.freq_once_per_bar)
Log.T_Ex_Date_Time := DateTimeString
Log.T_ExCandle := bar_index
Log.T_ExPrice := if barstate.isrealtime
close
else if not na(ShortSetup.SLForTheTrade) and SLType == "Biased"
ShortSetup.SLForTheTrade
else if low < Log.T_SLPrice and SLType != "Biased"
Log.T_SLPrice
else if HasHitTGT
Log.T_TGTPrice
else
close
Log.NextTradeAfter := Log.T_ExCandle
Log.T_HasExited := 1
Log.T_HasEntered := 0
Log.T_Direction := 0
PNLCalc = (Log.T_ExPrice - Log.T_EnPrice) * TradeQty
array.push(Days_PNL, PNLCalc)
array.push(OverAll_PNL, PNLCalc)
array.push(LogSummary, Log.T_En_Date_Time + " | " + str.tostring(Log.T_EnPrice, format.mintick) + " || " + Log.T_Ex_Date_Time + " | " + str.tostring(Log.T_ExPrice, format.mintick) + " || PNL : " + str.tostring(PNLCalc,format.mintick))
Last_TradePNL := PNLCalc
if PNLCalc > 0
Log.ProfitableTrade += 1
if not na(ShortSetup.SLForTheTrade)
ShortSetup.SLForTheTrade := na
float yHigh = high
for x = 0 to (bar_index - Log.T_EnCandle)
yHigh := math.max(yHigh, high[x])
Log.MaxTradeROI := yHigh - Log.T_EnPrice
array.push(MaxTradeROI_Array, math.round_to_mintick(Log.MaxTradeROI))
else if Log.T_Direction == -1
for [index, value] in ListOfTradingAccount
if FutOrOps == "OPS"
array.push(ExitAlertLegsArray, BEL.CancelClose(true, value, "MCX", array.get(ListOfOptionsPrefix, index)))
else if FutOrOps == "FUT"
array.push(ExitAlertLegsArray, BEL.CancelClose(false, value, "MCX", array.get(ListOfFuturePrefix, index), "A", "S"))
FinalExitAlertMessage := BEL.LegConstructor(ExitAlertLegsArray, "NLB")
if str.length(FinalExitAlertMessage) > 3
alert(FinalExitAlertMessage, alert.freq_once_per_bar)
Log.T_Ex_Date_Time := DateTimeString
Log.T_ExCandle := bar_index
Log.T_ExPrice := if barstate.isrealtime
close
else if not na(LongSetup.SLForTheTrade) and SLType == "Biased"
LongSetup.SLForTheTrade
else if high > Log.T_SLPrice and SLType != "Biased"
Log.T_SLPrice
else if HasHitTGT
Log.T_TGTPrice
else
close
Log.NextTradeAfter := Log.T_ExCandle
Log.T_HasExited := 1
Log.T_HasEntered := 0
Log.T_Direction := 0
PNLCalc = (Log.T_EnPrice - Log.T_ExPrice) * TradeQty
array.push(Days_PNL, PNLCalc)
array.push(OverAll_PNL, PNLCalc)
array.push(LogSummary, Log.T_En_Date_Time + " | " + str.tostring(Log.T_EnPrice, format.mintick) + " || " + Log.T_Ex_Date_Time + " | " + str.tostring(Log.T_ExPrice, format.mintick) + " || PNL : " + str.tostring(PNLCalc,format.mintick))
Last_TradePNL := PNLCalc
if PNLCalc > 0
Log.ProfitableTrade += 1
if not na(LongSetup.SLForTheTrade)
LongSetup.SLForTheTrade := na
float yLow = low
for x = 0 to (bar_index - Log.T_EnCandle)
yLow := math.min(yLow, low[x])
Log.MaxTradeROI := Log.T_EnPrice - yLow
array.push(MaxTradeROI_Array, math.round_to_mintick(Log.MaxTradeROI))
else
ExitAlertString = array.new_string(0)
if Log.T_HasExited == 0 and Log.T_HasEntered == 1 and Log.T_Direction != 0
for [index, value] in ListOfTradingAccount
array.push(ExitAlertString, BEL.CancelClose(true, value, "MCX", array.get(ListOfOptionsPrefix, index)))
array.push(ExitAlertString, BEL.CancelClose(true, value, "MCX", array.get(ListOfFuturePrefix, index)))
AlertMessage = BEL.LegConstructor(ExitAlertString, "NLB")
alert(AlertMessage, alert.freq_once_per_bar)
Log.T_Ex_Date_Time := DateTimeString
Log.T_ExCandle := bar_index
Log.T_ExPrice := barstate.isrealtime ? close : ohlc4
Log.NextTradeAfter := bar_index + 100
PNLCalc = if Log.T_Direction == 1
(Log.T_ExPrice - Log.T_EnPrice) * TradeQty
else if Log.T_Direction == -1
(Log.T_EnPrice - Log.T_ExPrice) * TradeQty
float y = Log.T_Direction == 1 ? high : low
for x = 0 to (bar_index - Log.T_EnCandle)
if Log.T_Direction == -1
y := math.min(y, low[x])
else
y := math.max(y, high[x])
Log.MaxTradeROI := Log.T_Direction == -1 ? Log.T_EnPrice - y : y - Log.T_EnPrice
array.push(MaxTradeROI_Array, math.round_to_mintick(Log.MaxTradeROI))
Log.T_Direction := 0
array.push(Days_PNL, PNLCalc)
array.push(OverAll_PNL, PNLCalc)
array.push(LogSummary, Log.T_En_Date_Time + " | " + str.tostring(Log.T_EnPrice, format.mintick) + " || " + Log.T_Ex_Date_Time + " | " + str.tostring(Log.T_ExPrice, format.mintick) + " || PNL : " + str.tostring(PNLCalc,format.mintick))
Last_TradePNL := PNLCalc
if PNLCalc > 0
Log.ProfitableTrade += 1
LongSetup.SLForTheTrade := na
ShortSetup.SLForTheTrade := na
Log.T_HasExited := 1
Log.T_HasEntered := 0
//#endregion
//#region Trade Entry Exit Plot
if ta.change(Log.T_HasEntered) and Log.T_Direction == -1 and Log.T_HasEntered == 1
SellShape := true
if ta.change(Log.T_HasEntered) and Log.T_Direction == 1 and Log.T_HasEntered == 1
BuyShape := true
if ta.change(Log.T_HasExited) and Log.T_Direction == 0 and Log.T_HasExited == 1
ExitShape := true
//#endregion
plotshape(BuyShape, "Long Trade Entry", shape.triangleup, location.belowbar, color.green, 0, size = size.tiny, display = display.all - display.price_scale - display.status_line, text = "LE", textcolor = color.white)
plotshape(SellShape , "Short Trade Entry", shape.triangledown, location.abovebar, color.red, 0, size = size.tiny, display = display.all - display.price_scale - display.status_line, text = "SE", textcolor = color.white)
plotshape(ExitShape , "Trade Exit", shape.xcross, location.abovebar, color.orange, 0, size = size.tiny, display = display.all - display.price_scale - display.status_line, text = "EX", textcolor = color.white)
if barstate.islast and ShowTradeLogTable
for x = 0 to 3
switch x
0 => table.cell_set_text(TradeInfoTable, 1, x, str.tostring(Log.AllTrades))
1 =>
table.cell_set_text(TradeInfoTable, 1, x, str.tostring(Log.ProfitableTrade))
table.cell_set_bgcolor(TradeInfoTable, 1, x, Log.ProfitableTrade > 0 ? color.rgb(25, 56, 26) : color.rgb(109, 42, 42))
table.cell_set_text_color(TradeInfoTable, 1, x, color.white)
2 =>
table.cell_set_text(TradeInfoTable, 1, x, str.tostring(math.round(Log.ProfitableTrade / Log.AllTrades, 2) * 100) + "%")
table.cell_set_bgcolor(TradeInfoTable, 1, x, Log.ProfitableTrade > 0 ? color.rgb(25, 56, 26) : color.rgb(109, 42, 42))
table.cell_set_text_color(TradeInfoTable, 1, x, color.white)
3 =>
table.cell_set_text(TradeInfoTable, 1, x, str.tostring(math.round(array.avg(MaxTradeROI_Array),2)))
table.cell_set_text_color(TradeInfoTable, 1, x, color.white)
|
Profit Monitor | https://www.tradingview.com/script/6pjhBhzd-Profit-Monitor/ | jisappu77 | https://www.tradingview.com/u/jisappu77/ | 4 | 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/
// © jisappu77
//@version=5
indicator("Profit Monitor","",true)
currentvalue = close
quantity = input(title="Quatity", defval=1.0)
bvalue = input(title="Entry price", defval=1.0)
usdtvalue = request.security("FX_IDC:USDINR", "1", currentvalue)
profitOrLoss = (currentvalue - bvalue)*quantity*usdtvalue
percent = ((currentvalue - bvalue)/bvalue)*100
printTable(txt) => var table t = table.new(position.middle_right, 1, 1), table.cell(t, 0, 0, txt, bgcolor = color.yellow,text_halign=text.align_left)
printTable("Invested: "+str.tostring(bvalue*usdtvalue*quantity)+"\On Sell : "+str.tostring(currentvalue*usdtvalue*quantity)+"\nProfit n Loss\n" + str.tostring(profitOrLoss) + "\n"+str.tostring(percent)+"%")
//plot(close)
|
Kitti-Playbook request.dividends R0.0 | https://www.tradingview.com/script/bBZi5GjT-Kitti-Playbook-request-dividends-R0-0/ | Kittimasak_S | https://www.tradingview.com/u/Kittimasak_S/ | 4 | 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/
// © Kittimasak_S
// Date Feb 5 2023
// Objective : Display Devidends Amount per Share
// Calculation :
// Use function request.dividends(ticker, field, gaps, lookahead, ignore_invalid_symbol, currenc
// Display : The value of Dividends
//@version=5
indicator("Kitti-Playbook request.dividends R0.0")
ReqDiv = request.dividends(ticker=syminfo.tickerid, field=dividends.gross, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off , ignore_invalid_symbol=false, currency=syminfo.currency)
ReqDivBM = request.dividends(syminfo.tickerid, dividends.gross, gaps=barmerge.gaps_on, lookahead=barmerge.lookahead_on, ignore_invalid_symbol=false, currency=syminfo.currency)
ReqDiv2=ReqDivBM>0? ReqDiv:na
ReqDivGross1=ReqDivBM>0? na:ReqDiv
plot(ReqDivGross1,"dividends Area",color= color.new(color.green, 90),style=plot.style_area)
plot(ReqDiv2,"dividends Con",color=color.new(color.green,90),style=plot.style_area)
s3= ReqDiv>0 and ReqDivBM > 0 ? 1 : 0 // When XD
// Count Last XD date
s4=ta.barssince(s3>0)
// XD Percent calculate
s5=ta.valuewhen(s3>0,close,0) // Value when XD
//plot(s5,"Value when XD" , color.fuchsia)
// Devidents amount per share = ReqDiv
// Devidents amount % per share = ReqDiv/s5
s6=ReqDiv/s5 * 100 // % Divident / Share
//plot(s6," s6" , color.green)
// =========
// XD when last claculate
plot(s3*ReqDiv," cal date ", color=color.new(color.blue,50))
// Display Label
ShowInfoTab = input.bool(title='Show Infomation Bar ', defval=true, group='Display Setting') // Show Tab
Tab_Width2 = input.int(16, "Information Bar Size", minval=1, maxval=20, step=1,group='Display Setting')
table_position2 = input.string(position.bottom_right, 'Information Bar position', options=
[position.middle_left,
position.middle_center,
position.middle_right,
position.bottom_left,
position.bottom_center,
position.bottom_right,
position.top_center,
position.top_right],
group='Display Setting')
var table Signal_table2 = table.new(position=table_position2, columns=1, rows=1, border_width=2)
tColor1 = color.new(#888888, 0)
bColor0 = s4 < 300? color.new(color.gray,90) :color.new(#e43dc0, 80)
_TEXT_DisplayA2 = " \Since Last XD = " + str.tostring(s4) + " Bar"
+ " \n Value when XD = " + str.format("{0,number,#.###}",(s5)) + " " +syminfo.currency
+ " \n Div per share = " + str.format("{0,number,#.###}",(ReqDiv)) + " " +syminfo.currency +" : " + str.format("{0,number,#.###}",(s6)) + " %"
if ShowInfoTab == true
table.cell(Signal_table2, 0, 0, _TEXT_DisplayA2, bgcolor=bColor0, text_color=tColor1,text_halign=text.align_left, width=Tab_Width2)
//======================== END =================================================================================
|
Position Sizing Tool [Skiploss] | https://www.tradingview.com/script/7vBjHAU6-Position-Sizing-Tool-Skiploss/ | Skiploss | https://www.tradingview.com/u/Skiploss/ | 221 | 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/
// © Skiploss
//@version=5
indicator("Position Sizing Tool [Skiploss]", shorttitle = "PST v0.77" , overlay = true)
// Input account info
float account_size = input.float(10000, "Account Size", minval = 0, inline = '0', group = 'Basic Info')
string account_currency = input.string("USD", "", options = ["USD", "GBP", "EUR", "CAD", "AUD", "NZD", "CHF", "JPY", "CNY"], inline = '0', group = 'Basic Info')
float risk_value = input.float(10, "Risk ", minval = 0, inline = '1', group = 'Basic Info')
string risk_unit = input.string("%", "", options = ["%", "Currency"], inline = '1', group = 'Basic Info')
float contract_size = input.float(100, "Contract Size", options = [10, 100, 1000, 10000, 100000], tooltip = "You can find details on MetaTrader, Ctrader, or your broker.", group = 'Basic Info')
// Input level
float input_price_entry = input.price(0, "Entry", tooltip = "Please select the entry point.", confirm = true, group = 'Price Levels')
float input_price_takeprofit = input.price(0, "Take Profits", tooltip = "The take profit point must be more than the entry point in the long position. On the other hand, it will be a short position.", confirm = true, group = 'Price Levels')
float input_price_stoploss = input.price(0, "Stop Loss", tooltip = "The stop loss point must be less than the entry point in the long position. On the other hand, it will be a short position.", confirm = true, group = 'Price Levels')
// Style Setting
color_takeprofits = input(#8ebbff, 'Take Profits', group = 'Style Settings')
color_stoploss = input(#ff8e8e, 'Stop Loss', group = 'Style Settings')
color_text = input(#93959f, 'Texts', group = 'Style Settings')
dashboard_location = input.session("Top Right", "Dashboard Location", options = ["Top Right","Bottom Right","Top Left","Bottom Left", "Middle Right","Bottom Center"], group = 'Style Settings')
dashboard_text_size = input.session( 'Normal', "Dashboard Size", options = ["Tiny","Small","Normal","Large"], group = 'Style Settings')
// Plot line Entry
line_price_entry = line.new(bar_index - 5 , input_price_entry, bar_index + 20 , input_price_entry, color = color_text, width = 1)
line.delete(line_price_entry[1])
label_price_entry = label.new(bar_index + 27, input_price_entry, text = "Entry (" + str.tostring(input_price_entry, format.mintick) + ")", style = label.style_none, textcolor = color_text)
label.delete(label_price_entry[1])
// Plot line Take Profit
line_price_takeprofit = line.new(bar_index - 5 , input_price_takeprofit, bar_index + 20 , input_price_takeprofit, color = color_takeprofits, width = 1)
line.delete(line_price_takeprofit[1])
label_price_takeprofit = label.new(bar_index + 27, input_price_takeprofit, text = "TP (" + str.tostring(input_price_takeprofit, format.mintick) + ")", style = label.style_none, textcolor = color_takeprofits)
label.delete(label_price_takeprofit[1])
// Plot line Stop Loss
line_price_stoploss = line.new(bar_index - 5 , input_price_stoploss, bar_index + 20 , input_price_stoploss, color = color_stoploss, width = 1)
line.delete(line_price_stoploss[1])
label_price_stoploss = label.new(bar_index + 27, input_price_stoploss, text = "SL (" + str.tostring(input_price_stoploss, format.mintick) + ")", style = label.style_none, textcolor = color_stoploss)
label.delete(label_price_stoploss[1])
// Round values
float price_entry = math.round_to_mintick(input_price_entry)
float price_takeprofit = math.round_to_mintick(input_price_takeprofit)
float price_stoploss = math.round_to_mintick(input_price_stoploss)
// Calculations
float risk_value_percentage = risk_unit == '%' ? risk_value : (risk_value / account_size) * 100
float risk_value_currency = risk_unit == 'Currency' ? risk_value : account_size * (risk_value / 100)
ratio_ = (price_takeprofit-price_entry)/(price_entry - price_stoploss)
Lots_ = risk_value_currency / ((price_entry - price_stoploss) * contract_size)
gain_ = Lots_ * ((price_entry - price_takeprofit) * contract_size)
// Dashboard Start
var table_position = dashboard_location == 'Top Left' ? position.top_left :
dashboard_location == 'Bottom Left' ? position.bottom_left :
dashboard_location == 'Middle Right' ? position.middle_right :
dashboard_location == 'Bottom Center' ? position.bottom_center :
dashboard_location == 'Top Right' ? position.top_right : position.bottom_right
var table_text_size = dashboard_text_size == 'Tiny' ? size.tiny :
dashboard_text_size == 'Small' ? size.small :
dashboard_text_size == 'Normal' ? size.normal : size.large
var table_one = table.new(table_position, 7, 5, frame_color = color.new(color_takeprofits,80), frame_width = 1)
if barstate.islast
// 1st Row
table.cell(table_one, 0, 0, '', text_color = color_text, text_size=table_text_size, bgcolor = na)
table.cell(table_one, 1, 0, str.replace_all(syminfo.tickerid, syminfo.prefix + ":", '') + " " + str.tostring(close, format.mintick), text_color = color.new(close > close[1] ? color_takeprofits : color_stoploss , 0),text_size=table_text_size, bgcolor = na)
table.cell(table_one, 2, 0, '', text_color = color_text,text_size=table_text_size, bgcolor = na)
// 2nd Row
table.cell(table_one, 0, 1, 'Balance', text_color = color_text, text_size=table_text_size, bgcolor = color.new(color_takeprofits,90))
table.cell(table_one, 1, 1, 'Risk %', text_color = color_text, text_size=table_text_size, bgcolor = color.new(color_takeprofits,90))
table.cell(table_one, 2, 1, 'SL Loss', text_color = color_text, text_size=table_text_size, bgcolor = color.new(color_takeprofits,90))
// 3nd Row
table.cell(table_one, 0, 2, str.tostring(account_size), text_color = color_text, text_size=table_text_size, bgcolor = na)
table.cell(table_one, 1, 2, str.tostring(risk_value_percentage, '#.##'), text_color = color_text, text_size=table_text_size, bgcolor = na)
table.cell(table_one, 2, 2, str.tostring(risk_value_currency, '#.##'), text_color = color_text, text_size=table_text_size, bgcolor = na)
// 4nd Row
table.cell(table_one, 0, 3, 'Lots', text_color = color_text, text_size=table_text_size, bgcolor = color.new(color_takeprofits,90))
table.cell(table_one, 1, 3, 'R:R', text_color = color_text, text_size=table_text_size, bgcolor = color.new(color_takeprofits,90))
table.cell(table_one, 2, 3, 'TP Gain', text_color = color_text, text_size=table_text_size, bgcolor = color.new(color_takeprofits,90))
// 5nd Row
table.cell(table_one, 0, 4, str.tostring(Lots_ < 0 ? Lots_ * (-1) : Lots_ , '#.##'), text_color = color_text,text_size=table_text_size, bgcolor = na)
table.cell(table_one, 1, 4, '1 : ' + str.tostring(ratio_ < 0 ? ratio_ * (-1) : ratio_ , '#.##'), text_color = color_text,text_size=table_text_size, bgcolor = na)
table.cell(table_one, 2, 4, str.tostring( gain_ < 0 ? gain_ * (-1) : gain_ , '#.##'), text_color = color_text,text_size=table_text_size, bgcolor = na)
|
Cryptos Pump Hunter[liwei666] | https://www.tradingview.com/script/XtGCd9Jw-Cryptos-Pump-Hunter-liwei666/ | liwei666 | https://www.tradingview.com/u/liwei666/ | 339 | 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/
// © liwei666
//@version=5
// # ========================================================================= #
// # |Cryptos Pump Hunter Indicator |
// # ========================================================================= #
indicator(
title = "Cryptos Pump Hunter[liwei666]",
shorttitle = "Cryptos Pump Hunter",
overlay = true,
max_lines_count = 500,
max_labels_count = 500,
max_boxes_count = 500,
max_bars_back = 5000
)
// # ========================================================================= #
// # |Cryptos Pump Hunter Indicator |
// # ========================================================================= #
// BINANCE:BTCUSDTPERP,BINANCE:ETHUSDTPERP,BINANCE:LTCUSDTPERP,BINANCE:LUNCBUSD,BINANCE:SOLUSDT,BINANCE:ANCBUSDPERP,BINANCE:KEYBUSD,BINANCE:1000LUNCBUSDPERP,BINANCE:LUNA2BUSDPERP,BINANCE:ATOMUSDTPERP,BINANCE:FLOWUSDTPERP,BINANCE:FIDABUSD,BINANCE:APEBUSD,BINANCE:RVNUSDTPERP,BINANCE:FTTUSDTPERP
// --------------- Inputs ---------------
pump_timeframe = input.timeframe(defval = "", title = "Resolution for Pump")
pump_bars_cnt = input.int(defval = 16)
top_k = input.int(defval = 10)
res = pump_timeframe == '0' ? timeframe.period : pump_timeframe
// Table color
t_loc = input.string(defval="top_right",
options=["top_right", "middle_right", "bottom_right",
"top_center", "middle_center", "bottom_center",
"top_left", "middle_left", "bottom_left"], title = "table position", tooltip = "table_position", inline = "11", group = 'Table')
t_size = input.string(defval="Auto",
options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"],
title = "table size", tooltip = "table size", inline = "11", group = 'Table')
t_header_color = input.color(defval = color.new(#787b86, 10), title = "t_header_color", tooltip = "t_header_color", inline = "12", group = 'Table')
t_cell_bg_color1 = input.color(defval = color.new(color.green, 40) , title = "t_cell_bg_color1", tooltip = "t_cell_bg_color1", inline = "13", group = 'Table')
t_cell_bg_color2 = input.color(defval = color.new(color.red, 40) , title = "t_cell_bg_color2", tooltip = "t_cell_bg_color2", inline = "13", group = 'Table')
t_cell_txt_color = input.color(defval = color.new(color.white, 30) , title = "t_cell_txt_color", tooltip = "t_cell_txt_color", inline = "13", group = 'Table')
// Alert Condition
pump_threhold = input.float(defval = 5.0, title = "pump threhold", tooltip = 'pump threhold', inline = "11", group = 'Alert')
pump_position_threhold = input.float(defval = 0.8, title = "pump position threhold", tooltip = 'pump position threhold', inline = "11", group = 'Alert')
cell_color = input.color(defval = color.new(color.orange, 40) , title = "alert_cell_color", tooltip = "cell_color", inline = "12", group = 'Alert')
// up_up_bars = input.int(defval = 5, title = "up_up_bars", minval = 3, maxval = 10, step = 1, tooltip = "up_up_up bar apart", inline = "13", group = 'Alert')
max_arr_size = 100
show_top1 = input.bool(defval = true, inline = "14", group = "Alert")
show_pump = input.bool(defval = false, inline = "14", group = "Alert")
show_history_label = input.bool(defval = true, inline = "15", group = "Alert")
// symbol_arr = array.from('1000LUNCUSDTPERP','1000SHIBUSDTPERP','AAVEUSDTPERP','ADAUSDTPERP','ALGOUSDTPERP','APEUSDTPERP','APTUSDTPERP','ATOMUSDTPERP','AVAXUSDTPERP','AXSUSDTPERP','BANDUSDTPERP','BCHUSDTPERP','BNBUSDTPERP','BTCUSDTPERP','CELOUSDTPERP','CHZUSDTPERP','COMPUSDTPERP','CRVUSDTPERP','CVXUSDTPERP','DOGEUSDTPERP','DOTUSDTPERP','DYDXUSDTPERP','ENJUSDTPERP','EOSUSDTPERP','ETCUSDTPERP','ETHUSDTPERP','FILUSDTPERP','FLOWUSDTPERP','FTMUSDTPERP','GALAUSDTPERP','GALUSDTPERP','GMTUSDTPERP','GRTUSDTPERP','HNTUSDTPERP','KAVAUSDTPERP','KNCUSDTPERP','LDOUSDTPERP','LINKUSDTPERP','LITUSDTPERP','LRCUSDTPERP','LTCUSDTPERP','LUNA2USDTPERP','MANAUSDTPERP','MASKUSDTPERP','MATICUSDTPERP','NEARUSDTPERP','OCEANUSDTPERP','ONEUSDTPERP','OPUSDTPERP','PEOPLEUSDTPERP','RLCUSDTPERP','SANDUSDTPERP','SOLUSDTPERP','SUSHIUSDTPERP','THETAUSDTPERP','TRXUSDTPERP','UNFIUSDTPERP','UNIUSDTPERP','WAVESUSDTPERP','WOOUSDTPERP','XMRUSDTPERP','XRPUSDTPERP','ZECUSDTPERP','ZILUSDTPERP')
// --------------- Inputs ---------------
// --------------- Functions ---------------
type Symbol
string ticker = na
float price_change = na
float current_pos = na
add_to_zigzag(arr, value) =>
array.unshift(arr, value)
if array.size(arr) > max_arr_size
array.pop(arr)
create_symbol_obj(symbol) =>
res_high = request.security(symbol, pump_timeframe, high)
highest = ta.highest(res_high, length = pump_bars_cnt)
lowest = ta.lowest(res_high, length = pump_bars_cnt)
temp_move = math.round(number = (highest - lowest) / lowest , precision = 3) * 100
temp_per = math.round(number = (res_high - lowest) / (highest - lowest) , precision = 1)
Symbol.new(ticker= symbol, price_change= temp_move, current_pos= temp_per)
// top1 名次变化 top1_change
top1_change(current_name_arr, prev_name_arr_str) =>
curr_top1 = array.get(current_name_arr,0)
prev_name_arr = str.split(prev_name_arr_str, ',')
if array.size(prev_name_arr) > 1
prev_top1 = array.get(prev_name_arr,0)
top1_change = curr_top1 == prev_top1 ? false: true
top1_change
else
false
// change 超过threhold over_threhold
var overthrehold_arr = array.new_int(0)
over_threhold(val_arr, val_threhold, pos_arr, pos_threhold) =>
array.clear(overthrehold_arr)
for i = 0 to array.size(val_arr) - 1
val = array.get(val_arr, i)
pos = array.get(pos_arr, i)
if val > val_threhold and pos > pos_threhold
array.push(overthrehold_arr, i)
overthrehold_arr
// --------------- Functions ---------------
// --------------- vars ---------------
symbol_a = array.new <Symbol> ()
// 1000LUNCUSDTPERP = create_symbol_obj('BINANCE:1000LUNCUSDTPERP'), array.unshift(symbol_a, 1000LUNCUSDTPERP )
// 1000SHIBUSDTPERP = create_symbol_obj('BINANCE:1000SHIBUSDTPERP'), array.unshift(symbol_a, 1000SHIBUSDTPERP )
AAVEUSDTPERP = create_symbol_obj('BINANCE:AAVEUSDTPERP'), array.unshift(symbol_a, AAVEUSDTPERP )
ADAUSDTPERP = create_symbol_obj('BINANCE:ADAUSDTPERP'), array.unshift(symbol_a, ADAUSDTPERP )
ALGOUSDTPERP = create_symbol_obj('BINANCE:ALGOUSDTPERP'), array.unshift(symbol_a, ALGOUSDTPERP )
APEUSDTPERP = create_symbol_obj('BINANCE:APEUSDTPERP'), array.unshift(symbol_a, APEUSDTPERP )
APTUSDTPERP = create_symbol_obj('BINANCE:APTUSDTPERP'), array.unshift(symbol_a, APTUSDTPERP )
ATOMUSDTPERP = create_symbol_obj('BINANCE:ATOMUSDTPERP'), array.unshift(symbol_a, ATOMUSDTPERP )
AVAXUSDTPERP = create_symbol_obj('BINANCE:AVAXUSDTPERP'), array.unshift(symbol_a, AVAXUSDTPERP )
AXSUSDTPERP = create_symbol_obj('BINANCE:AXSUSDTPERP'), array.unshift(symbol_a, AXSUSDTPERP )
BANDUSDTPERP = create_symbol_obj('BINANCE:BANDUSDTPERP'), array.unshift(symbol_a, BANDUSDTPERP )
BCHUSDTPERP = create_symbol_obj('BINANCE:BCHUSDTPERP'), array.unshift(symbol_a, BCHUSDTPERP )
BNBUSDTPERP = create_symbol_obj('BINANCE:BNBUSDTPERP'), array.unshift(symbol_a, BNBUSDTPERP )
BTCUSDTPERP = create_symbol_obj('BINANCE:BTCUSDTPERP'), array.unshift(symbol_a, BTCUSDTPERP )
CELOUSDTPERP = create_symbol_obj('BINANCE:CELOUSDTPERP'), array.unshift(symbol_a, CELOUSDTPERP )
CHZUSDTPERP = create_symbol_obj('BINANCE:CHZUSDTPERP'), array.unshift(symbol_a, CHZUSDTPERP )
COMPUSDTPERP = create_symbol_obj('BINANCE:COMPUSDTPERP'), array.unshift(symbol_a, COMPUSDTPERP )
CRVUSDTPERP = create_symbol_obj('BINANCE:CRVUSDTPERP'), array.unshift(symbol_a, CRVUSDTPERP )
CVXUSDTPERP = create_symbol_obj('BINANCE:CVXUSDTPERP'), array.unshift(symbol_a, CVXUSDTPERP )
DOGEUSDTPERP = create_symbol_obj('BINANCE:DOGEUSDTPERP'), array.unshift(symbol_a, DOGEUSDTPERP )
DOTUSDTPERP = create_symbol_obj('BINANCE:DOTUSDTPERP'), array.unshift(symbol_a, DOTUSDTPERP )
DYDXUSDTPERP = create_symbol_obj('BINANCE:DYDXUSDTPERP'), array.unshift(symbol_a, DYDXUSDTPERP )
ENJUSDTPERP = create_symbol_obj('BINANCE:ENJUSDTPERP'), array.unshift(symbol_a, ENJUSDTPERP )
EOSUSDTPERP = create_symbol_obj('BINANCE:EOSUSDTPERP'), array.unshift(symbol_a, EOSUSDTPERP )
ETCUSDTPERP = create_symbol_obj('BINANCE:ETCUSDTPERP'), array.unshift(symbol_a, ETCUSDTPERP )
ETHUSDTPERP = create_symbol_obj('BINANCE:ETHUSDTPERP'), array.unshift(symbol_a, ETHUSDTPERP )
FILUSDTPERP = create_symbol_obj('BINANCE:FILUSDTPERP'), array.unshift(symbol_a, FILUSDTPERP )
FLOWUSDTPERP = create_symbol_obj('BINANCE:FLOWUSDTPERP'), array.unshift(symbol_a, FLOWUSDTPERP )
FTMUSDTPERP = create_symbol_obj('BINANCE:FTMUSDTPERP'), array.unshift(symbol_a, FTMUSDTPERP )
GALAUSDTPERP = create_symbol_obj('BINANCE:GALAUSDTPERP'), array.unshift(symbol_a, GALAUSDTPERP )
// GALUSDTPERP = create_symbol_obj('BINANCE:GALUSDTPERP'), array.unshift(symbol_a, GALUSDTPERP )
// GMTUSDTPERP = create_symbol_obj('BINANCE:GMTUSDTPERP'), array.unshift(symbol_a, GMTUSDTPERP )
// GRTUSDTPERP = create_symbol_obj('BINANCE:GRTUSDTPERP'), array.unshift(symbol_a, GRTUSDTPERP )
// HNTUSDTPERP = create_symbol_obj('BINANCE:HNTUSDTPERP'), array.unshift(symbol_a, HNTUSDTPERP )
// KAVAUSDTPERP = create_symbol_obj('BINANCE:KAVAUSDTPERP'), array.unshift(symbol_a, KAVAUSDTPERP )
// KNCUSDTPERP = create_symbol_obj('BINANCE:KNCUSDTPERP'), array.unshift(symbol_a, KNCUSDTPERP )
// LDOUSDTPERP = create_symbol_obj('BINANCE:LDOUSDTPERP'), array.unshift(symbol_a, LDOUSDTPERP )
// LINKUSDTPERP = create_symbol_obj('BINANCE:LINKUSDTPERP'), array.unshift(symbol_a, LINKUSDTPERP )
// LITUSDTPERP = create_symbol_obj('BINANCE:LITUSDTPERP'), array.unshift(symbol_a, LITUSDTPERP )
// LRCUSDTPERP = create_symbol_obj('BINANCE:LRCUSDTPERP'), array.unshift(symbol_a, LRCUSDTPERP )
// LTCUSDTPERP = create_symbol_obj('BINANCE:LTCUSDTPERP'), array.unshift(symbol_a, LTCUSDTPERP )
// LUNA2USDTPERP = create_symbol_obj('BINANCE:LUNA2USDTPERP'), array.unshift(symbol_a, LUNA2USDTPERP )
// MANAUSDTPERP = create_symbol_obj('BINANCE:MANAUSDTPERP'), array.unshift(symbol_a, MANAUSDTPERP )
// MASKUSDTPERP = create_symbol_obj('BINANCE:MASKUSDTPERP'), array.unshift(symbol_a, MASKUSDTPERP )
// MATICUSDTPERP = create_symbol_obj('BINANCE:MATICUSDTPERP'), array.unshift(symbol_a, MATICUSDTPERP )
// NEARUSDTPERP = create_symbol_obj('BINANCE:NEARUSDTPERP'), array.unshift(symbol_a, NEARUSDTPERP )
// OCEANUSDTPERP = create_symbol_obj('BINANCE:OCEANUSDTPERP'), array.unshift(symbol_a, OCEANUSDTPERP )
// ONEUSDTPERP = create_symbol_obj('BINANCE:ONEUSDTPERP'), array.unshift(symbol_a, ONEUSDTPERP )
// OPUSDTPERP = create_symbol_obj('BINANCE:OPUSDTPERP'), array.unshift(symbol_a, OPUSDTPERP )
// PEOPLEUSDTPERP = create_symbol_obj('BINANCE:PEOPLEUSDTPERP'), array.unshift(symbol_a, PEOPLEUSDTPERP )
// RLCUSDTPERP = create_symbol_obj('BINANCE:RLCUSDTPERP'), array.unshift(symbol_a, RLCUSDTPERP )
// SANDUSDTPERP = create_symbol_obj('BINANCE:SANDUSDTPERP'), array.unshift(symbol_a, SANDUSDTPERP )
// SOLUSDTPERP = create_symbol_obj('BINANCE:SOLUSDTPERP'), array.unshift(symbol_a, SOLUSDTPERP )
// SUSHIUSDTPERP = create_symbol_obj('BINANCE:SUSHIUSDTPERP'), array.unshift(symbol_a, SUSHIUSDTPERP )
// THETAUSDTPERP = create_symbol_obj('BINANCE:THETAUSDTPERP'), array.unshift(symbol_a, THETAUSDTPERP )
// TRXUSDTPERP = create_symbol_obj('BINANCE:TRXUSDTPERP'), array.unshift(symbol_a, TRXUSDTPERP )
// UNFIUSDTPERP = create_symbol_obj('BINANCE:UNFIUSDTPERP'), array.unshift(symbol_a, UNFIUSDTPERP )
// UNIUSDTPERP = create_symbol_obj('BINANCE:UNIUSDTPERP'), array.unshift(symbol_a, UNIUSDTPERP )
// WAVESUSDTPERP = create_symbol_obj('BINANCE:WAVESUSDTPERP'), array.unshift(symbol_a, WAVESUSDTPERP )
// WOOUSDTPERP = create_symbol_obj('BINANCE:WOOUSDTPERP'), array.unshift(symbol_a, WOOUSDTPERP )
// XMRUSDTPERP = create_symbol_obj('BINANCE:XMRUSDTPERP'), array.unshift(symbol_a, XMRUSDTPERP )
// XRPUSDTPERP = create_symbol_obj('BINANCE:XRPUSDTPERP'), array.unshift(symbol_a, XRPUSDTPERP )
// ZECUSDTPERP = create_symbol_obj('BINANCE:ZECUSDTPERP'), array.unshift(symbol_a, ZECUSDTPERP )
// ZILUSDTPERP = create_symbol_obj('BINANCE:ZILUSDTPERP'), array.unshift(symbol_a, ZILUSDTPERP )
float[] pos_arr = array.new_float(size = array.size(symbol_a), initial_value = 0.0)
float[] move_arr = array.new_float(size = array.size(symbol_a), initial_value = 0.0)
string[] symbol_arr = array.new_string(size = array.size(symbol_a), initial_value = "")
string[] topk_pair_name_arr = array.new_string(size = top_k, initial_value = "")
string[] prev_topk_pair_name_arr = array.new_string(top_k, "")
var string prev_topk_pair_name_str = na
var string prev_topk_val_arr_str = na
var string prev_topk_pos_arr_str = na
// --------------- vars ---------------
// --------------- Calculate TopK Symbols---------------
for i = 0 to array.size(symbol_a) -1
pair = array.get(symbol_a, i)
pair_ticker = pair.ticker
pair_change = pair.price_change
pair_pos = pair.current_pos
array.set(id = symbol_arr, index = i, value = pair_ticker)
array.set(id = move_arr, index = i, value = pair_change)
array.set(id = pos_arr, index = i, value = pair_pos)
sorted_indices_arr = array.sort_indices(move_arr, order = order.descending) // [1, 2, 4, 0, 3]
array.sort(id = move_arr, order = order.descending)
sorted_move_arr = array.copy(move_arr)
// 将symbol 名称重新排序 与sorted_move_arr的值对应上
sorted_symbol_arr = array.new_string(size = array.size(symbol_arr), initial_value = "")
sorted_pos_arr = array.new_float(size = array.size(symbol_arr), initial_value = 0.0)
for i = 0 to array.size(sorted_indices_arr) - 1
j = array.get(sorted_indices_arr, i)
pair2 = array.get(id = symbol_arr, index = j)
array.set(id = sorted_symbol_arr, index=i, value = pair2)
pair3 = array.get(id = pos_arr, index = j)
array.set(id = sorted_pos_arr, index=i, value = pair3)
topk_name_arr = array.slice(id = sorted_symbol_arr, index_from = 0, index_to = top_k)
topk_val_arr = array.slice(id = sorted_move_arr, index_from = 0, index_to = top_k)
topk_pos_arr = array.slice(id = sorted_pos_arr, index_from = 0, index_to = top_k)
// 干掉 BINANCE: 字符串
for i = 0 to array.size(id = topk_name_arr) - 1
symbol_name = array.get(topk_name_arr, i)
s_arr = str.split(symbol_name, ':')
pair_name = array.get(s_arr, 1)
array.set(id = topk_pair_name_arr, index = i, value = pair_name)
// --------------- Calculate TopK Symbols---------------
// --------------- Calculate Alert Condition ---------------
// top_change
top_change_ = top1_change(topk_pair_name_arr, prev_topk_pair_name_str[1])
// over threhold
overthrehold_arr_ = over_threhold(topk_val_arr, pump_threhold, topk_pos_arr, pump_position_threhold)
overthrehold_size = array.size(id = overthrehold_arr_)
// add label in chart
top_change_cond = top_change_ and show_top1
pump_cond = overthrehold_size >= 1 and show_pump
var lbl = label.new(bar_index, na, "", color = color.orange, style = label.style_label_up)
label_text = ''
tooltip_text = ''
if top_change_cond or pump_cond
if top_change_cond
label_text := label_text + 'T: ' + str.tostring(array.get(topk_pair_name_arr, 0))
tooltip_text := tooltip_text + 'top1: '
tooltip_text := tooltip_text + str.tostring(array.get(topk_pair_name_arr, 0))
// tooltip_text := '\n'
if pump_cond
label_text := label_text + 'P: '
tooltip_text := tooltip_text + '\npump: '
for i = 0 to overthrehold_size - 1
pairname = array.get(topk_pair_name_arr, array.get(overthrehold_arr_, i))
tooltip_text := tooltip_text + str.tostring(pairname)
if show_history_label
label.new(bar_index, low, label_text, tooltip = tooltip_text, color = color.orange, style = label.style_label_up)
else
label.set_xy(lbl, bar_index, low)
label.set_text(lbl, label_text)
label.set_tooltip(lbl, tooltip_text)
// add alert when top_change_cond or pump_cond
alertcondition(top_change_cond, title='top1_change', message='{{tooltip_text}} || {{timenow}}')
alertcondition(pump_cond, title='cryptos pump', message='{{tooltip_text}} || {{timenow}}')
// if overthrehold_size >= 1
// labelText = ''
// for i = 0 to overthrehold_size - 1
// labelText := labelText + str.tostring(array.get(overthrehold_arr_, i))
// // labelText = prev_topk_pair_name_str[1]
// // labelText = "High: " + str.tostring(new_up_size, format.mintick)
// tooltipText = "Offest in bars: " + str.tostring(111) + "\nLow: " + str.tostring(low[10], format.mintick)
// // Update the label's position, text and tooltip.
// label.new(bar_index, high, labelText, tooltip = tooltipText, color = color.orange, style = label.style_label_down)
// // label.set_text(lbl, labelText)
// // label.set_tooltip(lbl, tooltipText)
// --------------- Calculate Alert Condition ---------------
// --------------- Save history array value ---------------
prev_topk_pair_name_str := array.join(topk_pair_name_arr, separator = ",")
prev_topk_val_arr_str := array.join(topk_val_arr, separator = ",")
prev_topk_pos_arr_str := array.join(topk_pos_arr, separator = ",")
// --------------- Calculate Alert Condition ---------------
// --------------- plot table cells---------------
// 画table.cell()
table_position = t_loc== "top_right" ? position.top_right:
t_loc== "middle_right" ? position.middle_right:
t_loc== "bottom_right" ? position.bottom_right:
t_loc== "top_center" ? position.top_center:
t_loc== "middle_center"? position.middle_center:
t_loc== "bottom_center"? position.bottom_center:
t_loc== "top_left" ? position.top_left:
t_loc== "middle_left" ? position.middle_left:position.bottom_left
table_size = t_size == "Auto" ? size.auto: t_size == "Huge" ? size.huge: t_size == "Large"? size.large: t_size == "Normal"? size.normal: t_size == "Small"? size.small: size.tiny
table_rows = array.size(id= topk_pair_name_arr)
var tabl = table.new (table_position, columns= 4, rows= table_rows)
table.cell(tabl, 0, 0, "Rank", bgcolor = t_header_color, text_size = table_size)
table.cell(tabl, 1, 0, "Symbol", bgcolor = t_header_color, text_size = table_size)
table.cell(tabl, 2, 0, "Value", bgcolor = t_header_color, text_size = table_size)
table.cell(tabl, 3, 0, "Position", bgcolor = t_header_color, text_size = table_size)
if barstate.isconfirmed
table.clear(tabl, 0,0,3,table_rows - 1)
for i = 0 to table_rows - 2
mod = i % 2 == 0
bg_color = mod ? t_cell_bg_color1 : t_cell_bg_color2
txt_color = mod ? t_cell_txt_color : t_cell_txt_color
row_1_txt = array.get(id = topk_pair_name_arr, index =i)
row_2_txt = array.get(id = topk_val_arr, index =i)
row_3_txt = array.get(id = topk_pos_arr, index =i)
table.cell(table_id= tabl, column= 0, row= i+1, text= str.tostring(i+1), text_font_family=font.family_monospace, text_color= txt_color, bgcolor= bg_color, text_size = table_size)
table.cell(table_id= tabl, column= 1, row= i+1, text= row_1_txt, text_font_family=font.family_monospace, text_color= txt_color, bgcolor= bg_color, text_size = table_size)
table.cell(table_id= tabl, column= 2, row= i+1, text= str.tostring(row_2_txt), text_font_family=font.family_monospace, text_color= txt_color, bgcolor= bg_color, text_size = table_size)
table.cell(table_id= tabl, column= 3, row= i+1, text= str.tostring(row_3_txt), text_font_family=font.family_monospace, text_color= txt_color, bgcolor= bg_color, text_size = table_size) |
ONCHAIN: BTC HOLDERS/RETAIL Assets Ratio | https://www.tradingview.com/script/S6W5JEbB-ONCHAIN-BTC-HOLDERS-RETAIL-Assets-Ratio/ | cryptoonchain | https://www.tradingview.com/u/cryptoonchain/ | 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/
// © cryptoonchain
//@version=5
indicator("ONCHAIN: BTC HOLDERS/RETAIL Assets")
R = input.symbol("BTC_RETAILASSETS", "Symbol")
r = request.security(R, 'W', close)
S = input.symbol("BTC_HODLERSBALANCE", "Symbol")
s = request.security(S, 'W', close)
a=s/r
plot (a, color=color.blue)
|
JSS Table - RSI, DI+, DI-, ADX | https://www.tradingview.com/script/AQa8qiYY-JSS-Table-RSI-DI-DI-ADX/ | jatinder.sodhi | https://www.tradingview.com/u/jatinder.sodhi/ | 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/
// © jatinder.sodhi
//Table to have ADX, RSI, DI values
//@version=5
indicator(title="JSSTable", shorttitle="JSSTable", overlay=true)
//rsi
mrsi = ta.rsi(close,14)
colorRsi = mrsi>55?color.green: mrsi<45?color.red:color.gray
//ADX
len = input.int(14, minval=1, title="DI Length")
lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50)
[diplus, diminus, adx] = ta.dmi(len, lensig)
colorADX = adx>25?color.rgb(33, 208, 243):color.gray
//creating the table
var testTable = table.new(position = position.top_right, columns = 4, rows = 2, border_width = 1, border_color = color.black, frame_width = 1, frame_color = color.black)
//column Headings
table.cell(table_id = testTable, column = 0, row = 0, text = " RSI ", bgcolor=color.aqua, text_color = color.white)
table.cell(table_id = testTable, column = 1, row = 0, text = " DI+ ", bgcolor=color.green, text_color = color.white)
table.cell(table_id = testTable, column = 2, row = 0, text = " DI- ", bgcolor=color.red, text_color = color.white)
table.cell(table_id = testTable, column = 3, row = 0, text = " ADX ", bgcolor=color.aqua, text_color = color.white)
//column values
table.cell(table_id = testTable, column = 0, row = 1, text = str.tostring(math.round(mrsi,0)) , bgcolor= color.aqua, text_color = color.white)
table.cell(table_id = testTable, column = 1, row = 1, text = str.tostring(math.round(diplus,0)) , bgcolor= color.green, text_color = color.white)// "RSI")//, bgcolor=color.red)
table.cell(table_id = testTable, column = 2, row = 1, text = str.tostring(math.round(diminus,0)) , bgcolor= color.red, text_color = color.white)// "DI+")//, bgcolor=color.red)
table.cell(table_id = testTable, column = 3, row = 1, text = str.tostring(math.round(adx,0)) , bgcolor= color.aqua, text_color = color.white)//"DI-")//, bgcolor=color.red) |
Percentage of direction alternation | https://www.tradingview.com/script/2nwBDxsl-Percentage-of-direction-alternation/ | Koalems | https://www.tradingview.com/u/Koalems/ | 11 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Koalems
// @version=5
indicator(
title = "Percentage of direction alternation",
shorttitle = "% of direction alternation",
overlay = false
)
Group0000 = 'Show'
poaShowPoa = input.bool(true, '% of alternation', group=Group0000)
poaShowPoaWeighted = input.bool(true, '% of weighted alternation', group=Group0000)
poaShowInvered = input.bool(false, 'Invert', group=Group0000)
Group0010 = 'Settings'
poaMinBarsForCompare = 2
poaLen = input.int(8, 'Length', group=Group0010, minval=poaMinBarsForCompare)
poaAlternated = 0
poaMaxCompares = poaLen - poaMinBarsForCompare + 1
poaMaxWeight = poaMaxCompares
poaMaxWeightAlt = 0
poaWeightedAlternated = 0
for i = 0 to poaLen - poaMinBarsForCompare
s1 = math.sign(close[i ] - open[i ])
s2 = math.sign(close[i + 1] - open[i + 1])
weight = poaMaxWeight - i
poaMaxWeightAlt += weight
if s1 == 1 and s2 == -1 or s1 == -1 and s2 == 1
poaAlternated += 1
poaWeightedAlternated += weight
poaPoa = 100 * (poaAlternated / poaMaxCompares)
poaWeightedAlternated := 100 * (poaWeightedAlternated / poaMaxWeightAlt)
if poaShowInvered
poaPoa := 100 - poaPoa
poaWeightedAlternated := 100 - poaWeightedAlternated
hline(0, '0%', #f57c00, linestyle=hline.style_dotted, display = display.none)
hline(50, '50%', #f57c00, linestyle=hline.style_dotted)
hline(100, '100%', #f57c00, linestyle=hline.style_dotted)
plot(poaShowPoa ? poaPoa : na, color=color.new(#056656, 0), style=plot.style_area, title="% of alternation")
plot(poaShowPoaWeighted ? poaWeightedAlternated : na, color=color.new(#0c3299, 30), style=plot.style_area, title="% of weighted alternation")
|
Bollinger Bands Signals | https://www.tradingview.com/script/OXY83XcZ-Bollinger-Bands-Signals/ | capissimo | https://www.tradingview.com/u/capissimo/ | 267 | 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("Bollinger Bands Signals", 'BBS', true, timeframe="", timeframe_gaps=true)
// Description:
// This indicator works well in trendy markets on long runs and in mean-reverting markets, at almost any timeframe.
// That said, higher timeframes are much preferred for their intrinsic ability to cut out noise.
// Be mindful, the script shows somewhat erratic jigsaw-like behaviour during consolidation periods when the price
// jupms up and down in indecision which way to go. Fortunately, there are scripts out there that detect such periods.
// You can choose between 4 Moving Averages, Vidya being the default. Period, Deviation and Bands Width parameters
// all all of them affect the signal generation.
// For the Pine Script coder this script is pretty obvious.
// It uses a standard technical analysis indicator - Bollinger Bands - and appends it with a 'width' parameter and
// a signal generation procedure.
// The signal generation procedure is the heart of this script that keeps the script pumping signals.
// The BB width is used as a filter.
// You can use this procedure in your own scripts and it will continue generate signals according to your rules.
//-- Inputs
Data = input.source(close, 'Dataset')
Ma = input.string('Vidya', 'Base Moving Average', ['EMA','SMA','WMA','Vidya'])
Period = input.int (42, 'Period [1..n]', 1)
Mult = input.float (2.0, 'Deviation [0.01..50]', minval=0.01, maxval=50, step=0.01)
Width = input.float (0.019, 'Bands Width [0.0001..0.1]', minval=0.0001, maxval=0.1, step=0.0001)
Offset = input.int (0, 'Offset [-500..+500]', -500, 500)
//-- Constants
var string up = 'Δ'
var string dn = '∇'
type SignalType // enum
int BUY = 1
int SELL =-1
int CLEAR = 0
//-- Variables
var SignalType stype = SignalType.new()
var int signal = stype.CLEAR
//-- Functions
vidya(float x, int p) =>
float mom = ta.change(x)
float upSum = math.sum(math.max(mom, 0), p)
float downSum = math.sum(-math.min(mom, 0), p)
float cmo = math.abs((upSum - downSum) / (upSum + downSum))
float alpha = 2 / (p + 1)
float vidya = 0.0
vidya := x * alpha * cmo + nz(vidya[1]) * (1 - alpha * cmo)
//-- Logic
float basis = switch Ma
'EMA' => ta.ema(Data, Period)
'SMA' => ta.sma(Data, Period)
'WMA' => ta.wma(Data, Period)
=> vidya(Data, Period)
float dev = Mult * ta.stdev(Data, Period)
float upper = basis + dev
float lower = basis - dev
float width = (upper-lower)/basis
// signal generation procedure
bool long = (ta.crossunder(close, lower) or close>basis or close>lower) and width>Width
bool short = (ta.crossover (close, upper) or close<basis or close<upper) and width>Width
// assemble a signal
signal := long ? stype.BUY :
short ? stype.SELL :
nz(signal[1])
int changed = ta.change(signal)
bool long_condition = changed and signal==stype.BUY
bool short_condition = changed and signal==stype.SELL
//-- Visuals
plot(basis, "Basis", color=#FF6D00, offset=Offset)
p1 = plot(upper, "Upper", color=#2962FF, offset=Offset)
p2 = plot(lower, "Lower", color=#2962FF, offset=Offset)
fill(p1, p2, color.rgb(33, 150, 243, 95), "Background")
plotshape(long_condition, '', shape.labelup, location.belowbar, color.green, 0, up, color.white, size=size.tiny)
plotshape(short_condition, '', shape.labeldown, location.abovebar, color.red, 0, dn, color.white, size=size.tiny)
//-- Notification
alertcondition(long_condition, 'Go long', 'Upturn!')
alertcondition(short_condition, 'Go short', 'Downturn!')
alertcondition(long_condition or short_condition, 'Reversal', 'Time to ACT!') |
How To Limit Repeating Signals | https://www.tradingview.com/script/swT4NEBY-How-To-Limit-Repeating-Signals/ | allanster | https://www.tradingview.com/u/allanster/ | 88 | 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/
// © allanster
//@version=5
indicator("How To Limit Repeating Signals")
inputN = input.int(1, 'Allow N', tooltip = ' 0 Disables Signal\n-N Disables Filter')
limitN(_condition, _reset, _N)=> // create a function
var countN = 0 // create a counter
countN := _reset ? 0 : _condition ? countN + 1 : countN // if reset 0, else if condition +1, else previous count
allowN = _N >= 0 ? countN <= _N : true // if filter enabled and within allowed N else true
signal = _condition and allowN // if condition and within allowed N
taRSI = ta.rsi(close, 14) // create an oscillator
level = 50 // create a level
above = taRSI > level // create a condition
below = taRSI < level // create a condition
sigHi = limitN(above, below, inputN) // create a signal using the function
sigLo = limitN(below, above, inputN) // create a signal using the function
if sigHi // if above within N occurrences, reset N on below
alert('signal Hi') // trigger an alert function event
if sigLo // if below within N occurrences, reset N on above
alert('signal Lo') // trigger an alert function event
plotshape(sigHi ? taRSI : na, '', shape.triangleup,
location.absolute, color.lime) // if signal plot shape at Y value of RSI else not available
plotshape(sigLo ? taRSI : na, '', shape.triangledown,
location.absolute, color.red) // if signal plot shape at Y value of RSI else not available
hline(30), hline(50), hline(70) // plot some levels
plot(taRSI, '', color.purple) // plot oscillator |
Renko Ichimoku Cloud | https://www.tradingview.com/script/UY6Q5DBc-Renko-Ichimoku-Cloud/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 77 | 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/
// © PerpetuallyTryingFutures
//@version=5
indicator('Renko Ichimoku Cloud', shorttitle= 'Renko Ichimoku', overlay=true)
mode =input.string(title = 'Input Method', defval ='ATR', options=['Traditional', 'ATR'])
modevalue = input.int(title ='ATR Brick Size', defval = 14, minval = 1)
boxsize = input.float(title ='Traditional Brick Size', defval = 1, step= 0.001, minval = 0.0000001)
//Calculations//
conv_atr(value)=>
a = 0
num = syminfo.mintick
s = value
if na(s)
s := syminfo.mintick
if num < 1
for i = 1 to 20
num := num * 10
if num > 1
break
a := a +1
for x = 1 to a
s := s * 10
s := math.round(s)
for x = 1 to a
s := s / 10
s := s < syminfo.mintick ? syminfo.mintick : s
s
atrboxsize = conv_atr(ta.atr(modevalue))
float box = na
box := na(box[1]) ? mode == 'ATR' ? atrboxsize : boxsize : box[1]
reversal = 2
top = 0.0, bottom = 0.0
trend = 0
trend := barstate.isfirst ? 0 : nz(trend[1])
currentprice = 0.0
currentprice := close
float beginprice = na
beginprice := barstate.isfirst ? math.floor(open / box) * box : nz(beginprice[1])
openprice = 0.0
closeprice = 0.0
if trend == 0 and box * reversal <= math.abs(beginprice - currentprice)
if beginprice > currentprice
numcell = math.floor(math.abs(beginprice - currentprice) / box)
openprice := beginprice
closeprice := beginprice - numcell * box
trend := -1
if beginprice < currentprice
numcell = math.floor(math.abs(beginprice - currentprice) / box)
openprice := beginprice
closeprice := beginprice + numcell * box
trend := 1
if trend == -1
nok = true
if beginprice > currentprice and box <= math.abs(beginprice - currentprice)
numcell = math.floor(math.abs(beginprice - currentprice) / box)
closeprice := beginprice - numcell * box
trend := -1
beginprice := closeprice
nok := false
else
openprice := openprice == 0 ? nz(openprice[1]) : openprice
closeprice := closeprice == 0 ? nz(closeprice[1]) : closeprice
tempcurrentprice = close
if beginprice < tempcurrentprice and box * reversal <= math.abs(beginprice - tempcurrentprice) and nok //new column
numcell = math.floor(math.abs(beginprice - tempcurrentprice) / box)
openprice := beginprice + box
closeprice := beginprice + numcell * box
trend := 1
beginprice := closeprice
else
openprice := openprice == 0 ? nz(openprice[1]) : openprice
closeprice := closeprice == 0 ? nz(closeprice[1]) : closeprice
else
if trend == 1
nok = true
if beginprice < currentprice and box <= math.abs(beginprice - currentprice)
numcell = math.floor(math.abs(beginprice - currentprice) / box)
closeprice := beginprice + numcell * box
trend := 1
beginprice := closeprice
nok := false
else
openprice := openprice == 0 ? nz(openprice[1]) : openprice
closeprice := closeprice == 0 ? nz(closeprice[1]) : closeprice
tempcurrentprice = close
if beginprice > tempcurrentprice and box * reversal <= math.abs(beginprice - tempcurrentprice) and nok //new column
numcell = math.floor(math.abs(beginprice - tempcurrentprice) / box)
openprice := beginprice - box
closeprice := beginprice - numcell * box
trend := -1
beginprice := closeprice
else
openprice := openprice == 0 ? nz(openprice[1]) : openprice
closeprice := closeprice == 0 ? nz(closeprice[1]) : closeprice
box := ta.change(closeprice) ? mode == 'ATR' ? atrboxsize : boxsize : box
//Ichimoku//
TenkenSenL = input.int(9, minval=1, title='Tenken Sen Length')
KijunSenL = input.int(26, minval=1, title='Kijun Sen Length')
SenkouBL = input.int(52, minval=1, title='Senkou B Length')
chikouoffset = input.int(26, minval=1, title='Chikou Span Offset')
donchian(src, len) => math.avg(ta.lowest(src,len), ta.highest(src, len))
TenkenSen = donchian(closeprice, TenkenSenL)
KijunSen= donchian(closeprice,KijunSenL)
SenkouA = math.avg(TenkenSen, KijunSen)
SenkouB = donchian(closeprice, SenkouBL)
//Plots//
plot(TenkenSen, color=color.blue, title='Tenken Sen')
plot(KijunSen, color=#B71C1C, title='Kijun Sen')
plotshape(ta.crossover(TenkenSen,KijunSen), title = 'Tenken/Kijun Crossover', style= shape.cross, color=color.blue, size= size.small, location= location.bottom)
plotshape(ta.crossunder(TenkenSen,KijunSen), title = 'Tenken/Kijun Crossunder', style= shape.cross, color=color.red, size = size.small, location= location.bottom)
plot(closeprice, offset = -chikouoffset + 1, color=color.new(color.gray,50), title='Chikou Span')
p1 = plot(SenkouA, offset = chikouoffset - 1, color=color.lime,
title='Senkou A')
p2 = plot(SenkouB, offset = chikouoffset - 1, color=color.red,
title='Senkou B')
fill(p1, p2, color = SenkouA > SenkouB ? color.new(color.lime,90) : color.new(color.red, 90))
plotshape(ta.crossover(SenkouA,SenkouB), offset= chikouoffset -1, title = 'Bullish Kumo Twist', style= shape.arrowup, color=color.green, size= size.normal, location= location.bottom)
plotshape(ta.crossunder(SenkouA,SenkouB), offset= chikouoffset -1, title = 'Bearish Kumo Twist', style= shape.arrowdown, color=color.red, size = size.normal, location= location.bottom) |
Orders Blocks [TK] | https://www.tradingview.com/script/kZZWmpRV-Orders-Blocks-TK/ | mentalRock19315 | https://www.tradingview.com/u/mentalRock19315/ | 357 | 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/
// © mentalRock19315
//@version=5
//////////////////////////////////
// This indicator draw the orders blocks on your chart
//
// Order blocks are defined by the candle and its wicks.
// If the price goes into the order block, the size of the order block will change accordingly
// If the price cross the order block, the order block will disappear
//
// This way, you will have on your screen only the orders blocks never touched.
//
// Order block olders than 5000 bars are deleted
//
// You can choose to alway show the order block :
// - of the 1D (One day) timeframe
// - of the 1h (One hour) timeframe
// On those order block, you can choose the backgroung and border color
// you can also choose to write the order block name
//
// By default, the number of drawn 1D and 1h Order Block is limited to 1 above and 1 below the range of the chart price
// Modifications
// Way of storing and sorting the matrix more effective
// The script draw all the OB inside the lowest and highest value of the price
// + will draw 1 OB which are outside the price range
MaxDrawn = 0
indicator("Orders Blocks [TK]", overlay= true, max_bars_back = 4999, max_boxes_count = 500)
import mentalRock19315/NumberOfVisibleBars/3
Color_border_order_bloc_bull = input.color(color.new(color.green,50),"Bull Order Block border color")
Color_background_order_bloc_bull = input.color(color.new(color.green,90),"Bull Order Block background color")
Color_border_order_bloc_bear = input.color(color.new(color.red,50),"Bear Order Block border color")
Color_background_order_bloc_bear = input.color(color.new(color.red,90),"Bear Order Block background color")
One_Day_Order_Block = input.bool(true,"Always draw the Order Block from the 1 Day timeframe ?", group="One Day Timeframe")
Color_border_1D_order_bloc_bull = input.color(color.new(color.aqua,50),"1D Bull Order Block border color", group="One Day Timeframe")
Color_background_1D_order_bloc_bull = input.color(color.new(color.aqua,90),"1D Bull Order Block background color", group="One Day Timeframe")
Color_border_1D_order_bloc_bear = input.color(color.new(color.aqua,50),"1D Bear Order Block border color", group="One Day Timeframe")
Color_background_1D_order_bloc_bear = input.color(color.new(color.aqua,90),"1D Bear Order Block background color", group="One Day Timeframe")
Text_1D_Order_Block = input.bool(true,"Write the name of the order block inside it ?", group="One Day Timeframe")
One_Hour_Order_Block = input.bool(true,"Always draw the Order Block from the 1 Hour timeframe ?", group="One Hour Timeframe")
Color_border_1h_order_bloc_bull = input.color(color.new(color.teal,50),"1h Bull Order Block border color", group="One Hour Timeframe")
Color_background_1h_order_bloc_bull = input.color(color.new(color.teal,90),"1h Bull Order Block background color", group="One Hour Timeframe")
Color_border_1h_order_bloc_bear = input.color(color.new(color.teal,50),"1h Bear Order Block border color", group="One Hour Timeframe")
Color_background_1h_order_bloc_bear = input.color(color.new(color.teal,90),"1h Bear Order Block background color", group="One Hour Timeframe")
Text_1h_Order_Block = input.bool(true,"Write the name of the order block inside it ?", group="One Hour Timeframe")
Max_bar_back = 4999
max_bars_back(time, 4999)
// Contains the OB formed by a Bear candle followed by a Bull candle
var Ob_Bull_Matrix = matrix.new<float>(0, 3, na) // Columns : bar_index_start / bottom_ob // top_ob
// Contains the OB formed by a Bull candle followed by a Bear candle
var Ob_Bear_Matrix = matrix.new<float>(0, 3, na) // Columns : bar_index_start / bottom_ob // top_ob
//
var Ob_1D_Bull_Matrix = matrix.new<float>(0, 3, na) // Columns : bar_index_start / bottom_ob // top_ob
var Ob_1D_Bear_Matrix = matrix.new<float>(0, 3, na) // Columns : bar_index_start / bottom_ob // top_ob
DailyLow = request.security(syminfo.tickerid, "1D", low)
DailyHigh = request.security(syminfo.tickerid, "1D", high)
DailyOpen = request.security(syminfo.tickerid, "1D", open)
DailyClose = request.security(syminfo.tickerid, "1D", close)
var DailyBarIndex = 0
var Last_Previous_Bar_Time_Daily_Test = 0
//
var Ob_1h_Bull_Matrix = matrix.new<float>(0, 3, na) // Columns : bar_index_start / bottom_ob // top_ob
var Ob_1h_Bear_Matrix = matrix.new<float>(0, 3, na) // Columns : bar_index_start / bottom_ob // top_ob
HourlyLow = request.security(syminfo.tickerid, "60", low)
HourlyHigh = request.security(syminfo.tickerid, "60", high)
HourlyOpen = request.security(syminfo.tickerid, "60", open)
HourlyClose = request.security(syminfo.tickerid, "60", close)
var HourlyBarIndex = 0
var Last_Previous_Bar_Time_Hourly_Test = 0
if timeframe.in_seconds() < 86400 // The actual timeframe is under 1 Day
if dayofmonth(time, "UTC+1") != dayofmonth(Last_Previous_Bar_Time_Daily_Test, "UTC+1")
// It a new day
DailyBarIndex := bar_index
if timeframe.in_seconds() < 3600 // The actual timeframe is under 1 Hour
if hour(time, "UTC+1") != hour(Last_Previous_Bar_Time_Daily_Test, "UTC+1")
// It a new hour
HourlyBarIndex := bar_index
// chart.left_visible_bar_time
// Functionto calculated the number of visible bar
// Function to draw the box
// Calcul the number of bar in the screen
NbBar = NumberOfVisibleBars.NumberOfVisibleBars()
HighestPrice = ta.highest(high, NbBar)
LowestPrice = ta.lowest(low, NbBar)
var Number_Of_Lines_To_Remove = 0
Draw(Matrix, BgColor, BorderColor, Max_bar_back, Text) =>
// The Matrix should be sorted as the first line is the line the closest to the price (the last line is the farest to the price)
if matrix.rows(Matrix) > 0
Number_Of_OB_Drawn_Outside = 0
for Line = 0 to matrix.rows(Matrix)-1
// Are we in the range of the price drawn on the user screen ?
left_box = int(matrix.get(Matrix, Line, 0))
if left_box < bar_index - Max_bar_back
left_box := bar_index - Max_bar_back
top_box = matrix.get(Matrix, Line, 2)
right_box = bar_index
bottom_box = matrix.get(Matrix, Line, 1)
if top_box < HighestPrice and bottom_box > LowestPrice
box.new(left_box, top_box, right_box, bottom_box, border_color = BorderColor, bgcolor = BgColor, text = Text, text_halign = text.align_right, text_color = color.black, text_size = size.normal)
else // the OB is outside the price range, we only draw MaxDrawn time
if Number_Of_OB_Drawn_Outside <= MaxDrawn
box.new(left_box, top_box, right_box, bottom_box, border_color = BorderColor, bgcolor = BgColor, text = Text, text_halign = text.align_right, text_color = color.black, text_size = size.normal)
else
break
Number_Of_OB_Drawn_Outside := Number_Of_OB_Drawn_Outside + 1
result = true
result = true
if barstate.isconfirmed // On each close of a bar
// Adjustments of the OB in the Bull Matrix
// The OB Bull Matrix are those UNDER the actual price
// Sorted from the top_ob (column index 2) from the highest to the lowest
if matrix.rows(Ob_Bull_Matrix) > 0
Number_Of_Lines_To_Remove := 0
matrix.sort(Ob_Bull_Matrix, 2, order.descending)
for L = 0 to matrix.rows(Ob_Bull_Matrix)-1
// Columns : bar_index_start / bottom_ob // top_ob
// The low of the price is lower than the top_ob
if low < matrix.get(Ob_Bull_Matrix, L, 2)
// The low of the price is higher than the bottom_ob
if low > matrix.get(Ob_Bull_Matrix, L, 1) // The price bites the OB
matrix.set(Ob_Bull_Matrix, L, 2, low) // Adjust the OB
break // End of the loop,
else // The low of the price is lower than the bottom_ob
Number_Of_Lines_To_Remove := Number_Of_Lines_To_Remove + 1
else if low > matrix.get(Ob_Bull_Matrix, L, 2) // The price is now higher than the other OB
break
if Number_Of_Lines_To_Remove > 0
for L = 0 to Number_Of_Lines_To_Remove - 1
matrix.remove_row(Ob_Bull_Matrix, 0)
// Adjustments of the OB in the 1D Bull Matrix
if timeframe.in_seconds() < 86400 and One_Day_Order_Block// The actual timeframe is under 1 Day
if matrix.rows(Ob_1D_Bull_Matrix) > 0
Number_Of_Lines_To_Remove := 0
matrix.sort(Ob_1D_Bull_Matrix, 2, order.descending)
for L = 0 to matrix.rows(Ob_1D_Bull_Matrix)-1
// Columns : bar_index_start / bottom_ob // top_ob
// The low of the price is lower than the top_ob
if low < matrix.get(Ob_1D_Bull_Matrix, L, 2)
// The low of the price is higher than the bottom_ob
if low > matrix.get(Ob_1D_Bull_Matrix, L, 1) // The price bites the OB
matrix.set(Ob_1D_Bull_Matrix, L, 2, low) // Adjust the OB
break // End of the loop,
else // The low of the price is lower than the bottom_ob
Number_Of_Lines_To_Remove := Number_Of_Lines_To_Remove + 1
else if low > matrix.get(Ob_1D_Bull_Matrix, L, 2) // The price is now higher than the other OB
break
if Number_Of_Lines_To_Remove > 0
for L = 0 to Number_Of_Lines_To_Remove - 1
matrix.remove_row(Ob_1D_Bull_Matrix, 0)
// Adjustments of the OB in the 1h Bull Matrix
if timeframe.in_seconds() < 3600 and One_Hour_Order_Block// The actual timeframe is under 1 Hour
if matrix.rows(Ob_1h_Bull_Matrix) > 0
Number_Of_Lines_To_Remove := 0
matrix.sort(Ob_1h_Bull_Matrix, 2, order.descending)
for L = 0 to matrix.rows(Ob_1h_Bull_Matrix)-1
// Columns : bar_index_start / bottom_ob // top_ob
// The low of the price is lower than the top_ob
if low < matrix.get(Ob_1h_Bull_Matrix, L, 2)
// The low of the price is higher than the bottom_ob
if low > matrix.get(Ob_1h_Bull_Matrix, L, 1) // The price bites the OB
matrix.set(Ob_1h_Bull_Matrix, L, 2, low) // Adjust the OB
break // End of the loop,
else // The low of the price is lower than the bottom_ob
Number_Of_Lines_To_Remove := Number_Of_Lines_To_Remove + 1
else if low > matrix.get(Ob_1h_Bull_Matrix, L, 2) // The price is now higher than the other OB
break
if Number_Of_Lines_To_Remove > 0
for L = 0 to Number_Of_Lines_To_Remove - 1
matrix.remove_row(Ob_1h_Bull_Matrix, 0)
// Adjustments of the OB in the Bear Matrix
// Adjustments of the OB in the Bear Matrix
// The OB BuBearll Matrix are those ABOVE the actual price
// Sorted from the bottom_ob (column index 1) from the lowest to the highest
// Columns : bar_index_start / bottom_ob // top_ob
if matrix.rows(Ob_Bear_Matrix) > 0
Number_Of_Lines_To_Remove := 0
matrix.sort(Ob_Bear_Matrix, 1, order.ascending)
for L = 0 to matrix.rows(Ob_Bear_Matrix)-1
// The high of the price is higher than the bottom_ob
if high > matrix.get(Ob_Bear_Matrix, L, 1)
// The high of the price is lower than the top_ob
if high < matrix.get(Ob_Bear_Matrix, L, 2) // The price bites the OB
matrix.set(Ob_Bear_Matrix, L, 1, high) // Adjust the OB
break // End of the loop,
else // The high of the price is higher than the top_ob
Number_Of_Lines_To_Remove := Number_Of_Lines_To_Remove + 1
else if high < matrix.get(Ob_Bear_Matrix, L, 1) // The price is now higher than the other OB
break // End of the loop
if Number_Of_Lines_To_Remove > 0
for L = 0 to Number_Of_Lines_To_Remove - 1
matrix.remove_row(Ob_Bear_Matrix, 0)
// Adjustments of the OB in the 1D Bear Matrix
if timeframe.in_seconds() < 86400 and One_Day_Order_Block// The actual timeframe is under 1 Day
if matrix.rows(Ob_1D_Bear_Matrix) > 0
Number_Of_Lines_To_Remove := 0
matrix.sort(Ob_1D_Bear_Matrix, 1, order.ascending)
for L = 0 to matrix.rows(Ob_1D_Bear_Matrix) - 1
// The high of the price is higher than the bottom_ob
if high > matrix.get(Ob_1D_Bear_Matrix, L, 1)
// The high of the price is lower than the top_ob
if high < matrix.get(Ob_1D_Bear_Matrix, L, 2) // The price bites the OB
matrix.set(Ob_1D_Bear_Matrix, L, 1, high) // Adjust the OB
break // End of the loop,
else // The high of the price is higher than the top_ob
Number_Of_Lines_To_Remove := Number_Of_Lines_To_Remove + 1
else if high < matrix.get(Ob_1D_Bear_Matrix, L, 1) // The price is now higher than the other OB
break // End of the loop
if Number_Of_Lines_To_Remove > 0
for L = 0 to Number_Of_Lines_To_Remove - 1
matrix.remove_row(Ob_1D_Bear_Matrix, 0)
// Adjustments of the OB in the 1h Bear Matrix
if timeframe.in_seconds() < 3600 and One_Hour_Order_Block// The actual timeframe is under 1 Hour
if matrix.rows(Ob_1h_Bear_Matrix) > 0
Number_Of_Lines_To_Remove := 0
matrix.sort(Ob_1h_Bear_Matrix, 1, order.ascending)
for L = 0 to matrix.rows(Ob_1h_Bear_Matrix) - 1
// The high of the price is higher than the bottom_ob
if high > matrix.get(Ob_1h_Bear_Matrix, L, 1)
// The high of the price is lower than the top_ob
if high < matrix.get(Ob_1h_Bear_Matrix, L, 2) // The price bites the OB
matrix.set(Ob_1h_Bear_Matrix, L, 1, high) // Adjust the OB
break // End of the loop,
else // The high of the price is higher than the top_ob
Number_Of_Lines_To_Remove := Number_Of_Lines_To_Remove + 1
else if high < matrix.get(Ob_1h_Bear_Matrix, L, 1) // The price is now higher than the other OB
break // End of the loop
if Number_Of_Lines_To_Remove > 0
for L = 0 to Number_Of_Lines_To_Remove - 1
matrix.remove_row(Ob_1h_Bear_Matrix, 0)
// Add a Bull OB : Bear Candle followed by a Bull Candle
if open[1] > close[1] and open < close and high > high[1]
ArrayToAdd = array.from(bar_index, low[1], high[1])
matrix.add_row(Ob_Bull_Matrix, matrix.rows(Ob_Bull_Matrix), ArrayToAdd)
matrix.sort(Ob_Bull_Matrix, 2, order.descending)
// Add a 1 Day Bull OB : Bear Candle followed by a Bull Candle
if timeframe.in_seconds() < 86400 and One_Day_Order_Block// The actual timeframe is under 1 Day
if DailyOpen[1] > DailyClose[1] and DailyOpen < DailyClose and DailyClose > DailyHigh[1]
ArrayToAdd = array.from(DailyBarIndex, DailyLow[1], DailyHigh[1])
matrix.add_row(Ob_1D_Bull_Matrix, matrix.rows(Ob_1D_Bull_Matrix), ArrayToAdd)
matrix.sort(Ob_1D_Bull_Matrix, 2, order.descending)
// Add a 1 Hour Bull OB : Bear Candle followed by a Bull Candle
if timeframe.in_seconds() < 3600 and One_Hour_Order_Block// The actual timeframe is under 1 Hour
if HourlyOpen[1] > HourlyClose[1] and HourlyOpen < HourlyClose and HourlyClose > HourlyHigh[1]
ArrayToAdd = array.from(HourlyBarIndex, HourlyLow[1], HourlyHigh[1])
matrix.add_row(Ob_1h_Bull_Matrix, matrix.rows(Ob_1h_Bull_Matrix), ArrayToAdd)
// Inverted Sort of the Matrix with the top_ob key (columns index 2) => Line 0 = highest, Line max = lowest
matrix.sort(Ob_1h_Bull_Matrix, 2, order.descending)
// Add a Bear OB : Bull Candle followed by a Bear Candle
if open[1] < close[1] and open > close and low < low[1]
ArrayToAdd = array.from(bar_index, low[1], high[1])
matrix.add_row(Ob_Bear_Matrix, matrix.rows(Ob_Bear_Matrix), ArrayToAdd)
matrix.sort(Ob_Bear_Matrix, 1, order.ascending)
// Add a 1 Day Bear OB : Bull Candle followed by a Bear Candle
if timeframe.in_seconds() < 86400 and One_Day_Order_Block// The actual timeframe is under 1 Day
if DailyOpen[1] < DailyClose[1] and DailyOpen > DailyClose and DailyClose < DailyLow[1]
ArrayToAdd = array.from(DailyBarIndex, DailyLow[1], DailyHigh[1])
matrix.add_row(Ob_1D_Bear_Matrix, matrix.rows(Ob_1D_Bear_Matrix), ArrayToAdd)
matrix.sort(Ob_1D_Bear_Matrix, 1, order.ascending)
// Add a 1 Hour Bear OB : Bull Candle followed by a Bear Candle
if timeframe.in_seconds() < 3600 and One_Hour_Order_Block// The actual timeframe is under 1 Day
if HourlyOpen[1] < HourlyClose[1] and HourlyOpen > HourlyClose and HourlyClose < HourlyLow[1]
ArrayToAdd = array.from(HourlyBarIndex, HourlyLow[1], HourlyHigh[1])
matrix.add_row(Ob_1h_Bear_Matrix, matrix.rows(Ob_1h_Bear_Matrix), ArrayToAdd)
matrix.sort(Ob_1h_Bear_Matrix, 1, order.ascending)
if barstate.islast // On the last bar on the screen
// Drawing
// Delete all the box on screen
a_allBoxes = box.all
if array.size(a_allBoxes) > 0
for i = 0 to array.size(a_allBoxes) - 1
box.delete(array.get(a_allBoxes, i))
// Sort
// Draw all the box of the Ob_Bull_Matrix
Draw(Ob_Bull_Matrix, Color_background_order_bloc_bull, Color_border_order_bloc_bull, Max_bar_back, "")
// Draw all the box of the Ob_Bear_Matrix
Draw(Ob_Bear_Matrix, Color_background_order_bloc_bear, Color_border_order_bloc_bear, Max_bar_back, "")
if timeframe.in_seconds() < 86400 and One_Day_Order_Block
// Draw all the box of the Ob_Bull_Matrix
Draw(Ob_1D_Bull_Matrix, Color_background_1D_order_bloc_bull, Color_border_1D_order_bloc_bull, Max_bar_back, "Order Block [1D]")
// Draw all the box of the Ob_Bear_Matrix
Draw(Ob_1D_Bear_Matrix, Color_background_1D_order_bloc_bear, Color_border_1D_order_bloc_bear, Max_bar_back, "Order Block [1D]")
if timeframe.in_seconds() < 3600 and One_Hour_Order_Block
// Draw all the box of the Ob_Bull_Matrix
Draw(Ob_1h_Bull_Matrix, Color_background_1h_order_bloc_bull, Color_border_1h_order_bloc_bull, Max_bar_back, "Order Block [1h]")
// Draw all the box of the Ob_Bear_Matrix
Draw(Ob_1h_Bear_Matrix, Color_background_1h_order_bloc_bear, Color_border_1h_order_bloc_bear, Max_bar_back, "Order Block [1h]")
|
Price Swing Detection - Smart Money Concept | https://www.tradingview.com/script/GtWKHvJB-Price-Swing-Detection-Smart-Money-Concept/ | MirNader_ | https://www.tradingview.com/u/MirNader_/ | 558 | 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/
// © MirNader_
//@version=5
indicator("Price Swing Detection - Smart Money Concept" , overlay = true)
//Input & Swing Detection
// Define the input "swingLength" for the number of candles to look back for Swing detection
int swingLength = input.int(20, 'Lookback Period' , minval = 5 , tooltip = "Determines the length of bullish and bearish swings in the market")
// Set the line color for bullish trend
color swingcolorBullish = input.color(color.green, 'Bullish Line' , inline = '01' , tooltip = "This line represents the trend direction. Green color indicates a bullish trend and red color indicates a bearish trend")
// Set the line color for bearish trend
color swingcolorBearish = input.color(color.red , 'Bearish Line' , inline = '01' , tooltip = "This line represents the trend direction. Green color indicates a bullish trend and red color indicates a bearish trend")
//End of Input & Swing Detection
//------------------------------\\
//Swing Detection Function
// The "detectSwing" function will calculate the swing highs and lows for the given number of candles
detectSwing(swingPeriod) =>
// Initialize the "currentSwingState" variable, which will be used to determine the swing state (0 for swing high, 1 for swing low)
var currentSwingState = 0
// Calculate the highest high and lowest low for the given number of candles
highestSwing = ta.highest(swingPeriod)
lowestSwing = ta.lowest(swingPeriod)
// Determine the swing state based on the current candle high and low compared to the highest high and lowest low
currentSwingState := high[swingPeriod] > highestSwing ? 0 : low[swingPeriod] < lowestSwing ? 1 : currentSwingState[1]
// If the current candle is a swing high and the previous candle was not a swing high, set "currentSwingTop" to the current candle high
currentSwingTop = currentSwingState == 0 and currentSwingState[1] != 0 ? high[swingPeriod] : 0
// If the current candle is a swing low and the previous candle was not a swing low, set "currentSwingBottom" to the current candle low
currentSwingBottom = currentSwingState == 1 and currentSwingState[1] != 1 ? low[swingPeriod] : 0
// Return the calculated swing high and swing low values
[currentSwingTop, currentSwingBottom]
//End of Swing Detection
//------------------------------\\
//Parameters
// Initialize the "trendDirection" variable, which will keep track of the trend state (0 for downtrend, 1 for uptrend)
var trendDirection = 0
// Initialize variables for storing pivot high values
var swingTopValue = 0., var swingTopTimestamp = 0
// Initialize variables for storing pivot low values
var swingBottomValue = 0., var swingBottomTimestamp = 0
// Initialize variables for keeping track of the trailing maximum
var trailingSwingHigh = high, var trailingSwingLow = low
var trailingSwingHighTimestamp = 0, var trailingSwingLowTimestamp = 0
// Initialize variables for keeping track of pivot crosses
var topCrossCheck = true, var bottomCrossCheck = true
// Call the "detectSwing" function to calculate the swing highs and lows
[currentSwingTop, currentSwingBottom] = detectSwing(swingLength)
//Line Extend
var line extendingTopLine = na // Initialize a line object for extending the recent top
var line extendingBottomLine = na // Initialize a line object for extending the recent bottom
//End of Parameters
//------------------------------\\
//Pivot High Function
//The calculation of pivot high is an important step in detecting bullish structures in the market
if currentSwingTop
// If a new top is found, set "topCrossCheck" to true
topCrossCheck := true
// Delete the previous extendingTopLine line
line.delete(extendingTopLine[1])
// Create a new extendingTopLine line from the recent top to the last bar
extendingTopLine := line.new(bar_index-swingLength, currentSwingTop, bar_index, currentSwingTop, color = swingcolorBullish)
// Store the pivot high values
swingTopValue := currentSwingTop
swingTopTimestamp := bar_index - swingLength
// Update the trailing maximum values
trailingSwingHigh := currentSwingTop
trailingSwingHighTimestamp := bar_index - swingLength
//Update the trailing maximum values
trailingSwingHigh := math.max(high, trailingSwingHigh)
trailingSwingHighTimestamp := trailingSwingHigh == high ? bar_index : trailingSwingHighTimestamp
//Set the top extension line properties
if barstate.islast
line.set_xy1(extendingTopLine, trailingSwingHighTimestamp, trailingSwingHigh)
line.set_xy2(extendingTopLine, bar_index + 20, trailingSwingHigh)
//End of Pivot High Function
//------------------------------\\
//Pivot Low Function
//the Pivot low is used to detect the presence of a bearish structure in the price movement and update the trend accordingly.
if currentSwingBottom
// If a new low is found, set "bottomCrossCheck" to true
bottomCrossCheck := true
//Extend recent bottom to last bar
line.delete(extendingBottomLine[1])
extendingBottomLine := line.new(bar_index - swingLength, currentSwingBottom, bar_index, currentSwingBottom, color = swingcolorBearish)
//Store the pivot low values
swingBottomValue := currentSwingBottom
swingBottomTimestamp := bar_index - swingLength
//Update the trailing minimum values
trailingSwingLow := currentSwingBottom
trailingSwingLowTimestamp := bar_index - swingLength
//Update the trailing minimum values
trailingSwingLow := math.min(low, trailingSwingLow)
trailingSwingLowTimestamp := trailingSwingLow == low ? bar_index : trailingSwingLowTimestamp
//Set the bottom extension line properties
if barstate.islast
line.set_xy1(extendingBottomLine, trailingSwingLowTimestamp, trailingSwingLow)
line.set_xy2(extendingBottomLine, bar_index + 20, trailingSwingLow)
// End of Pivot Low Function
//------------------------------\\
// You can use 'trendDirection' for your strategy to identify the uptrend or downtrend
// This section of code checks if the close price crosses over the trailing maximum value (top_y).
// If it does, the top_cross boolean is set to false and the trend is set to 1, indicating a bullish trend.
//Detect bullish Structure
if ta.crossover(close, swingTopValue) and topCrossCheck
topCrossCheck := false
trendDirection := 1
// This section of code checks if the close price crosses under the trailing minimum value (btm_y).
// If it does, the btm_cross boolean is set to false and the trend is set to -1, indicating a bearish trend.
// Detect bearish Structure
if ta.crossunder(close, swingBottomValue) and bottomCrossCheck
bottomCrossCheck := false
trendDirection := -1
// End |
PinBar Detector [Mr_Zed] | https://www.tradingview.com/script/J8MbCjOY-PinBar-Detector-Mr-Zed/ | Indicator_Wizard | https://www.tradingview.com/u/Indicator_Wizard/ | 119 | 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/
// © MR_zed
// This PineScript indicator is based on the original MQ4 indicator from EarnForex (https://www.earnforex.com/metatrader-indicators/Pinbar-Detector/).
// The indicator has been converted and optimized for use in PineScript for use on trading platforms such as TradingView.
// While the core logic remains the same, some modifications have been made to improve the performance and functionality of the indicator.
// Please note that the original strategy and its code are property of EarnForex and protected
//@version=5
indicator(title="PinBar Detector [Mr_Zed]",overlay = true)
//============================================================================
// Settings
//===========================================================================
UseAlerts = input(true, "UseAlerts (default = true) ",tooltip=" tells the indicator to issue platform alert with sound on Pinbar detection.")
UseCustomSettings = input(false, "UseCustomSettings (default = false) ",tooltip=" tells the indicator to use custom Pinbar detection parameters described below.")
CustomMaxNoseBodySize = input(0.33, "CustomMaxNoseBodySize (default = 0.33) ",tooltip=" maximum allowed body/length ratio for the Nose bar.")
CustomNoseBodyPosition = input(0.4, "CustomNoseBodyPosition (default = 0.4) ",tooltip=" Nose body should be positioned in the top (bottom for bearish pattern) part of the Nose bar.")
CustomLeftEyeOppositeDirection = input(true, "CustomLeftEyeOppositeDirection (default = true) ",tooltip=" tells the indicator that the Left Eye bar should be bearish for bullish Pinbar, and bullish for bearish Pinbar.")
CustomNoseSameDirection = input(false, "CustomNoseSameDirection (default = true) ",tooltip=" tells the indicator that the Nose bar should be of the same direction as the pattern itself.")
CustomNoseBodyInsideLeftEyeBody = input(false, "CustomNoseBodyInsideLeftEyeBody (default = false) ",tooltip=" tells the indicator that the Nose body should be inside the Left Eye body.")
CustomLeftEyeMinBodySize = input(0.1, "CustomLeftEyeMinBodySize (default = 0.1) ",tooltip=" minimum size of the Left Eye body relative to the bar length.")
CustomNoseProtruding = input(0.5, "CustomNoseProtruding (default = 0.5) ",tooltip=" minimum protrusion of the Nose bar relative to the bar length.")
CustomNoseBodyToLeftEyeBody = input(1, "CustomNoseBodyToLeftEyeBody (default = 1) ",tooltip=" maximum size of the Nose body relative to the Left eye body.")
CustomNoseLengthToLeftEyeLength = input(0, "CustomNoseLengthToLeftEyeLength (default = 0) ",tooltip=" minimum Nose length relative to the Left Eye length.")
CustomLeftEyeDepth = input(0.1, "CustomLeftEyeDepth (default = 0.1) ",tooltip=" minimum depth of the Left Eye relative to its length. Depth is difference with Nose's back.")
CustomMinimumNoseLength = input(1, "CustomMinimumNoseLength (default = 1) ",tooltip=" Minimum nose candlestick length in points.")
//============================================================================
// Consts
//===========================================================================
int LastBars = 0
float MaxNoseBodySize = 0.33
float NoseBodyPosition = 0.4
bool LeftEyeOppositeDirection = true
bool NoseSameDirection = false
bool NoseBodyInsideLeftEyeBody = false
float LeftEyeMinBodySize = 0.1
float NoseProtruding = 0.5
float NoseBodyToLeftEyeBody = 1
float NoseLengthToLeftEyeLength = 0
float LeftEyeDepth = 0.1
float MinimumCandlestickLength = 1
BearishPinbar = false
BullishPinbar = false
if UseCustomSettings
MaxNoseBodySize := CustomMaxNoseBodySize
NoseBodyPosition := CustomNoseBodyPosition
LeftEyeOppositeDirection := CustomLeftEyeOppositeDirection
NoseSameDirection := CustomNoseSameDirection
LeftEyeMinBodySize := CustomLeftEyeMinBodySize
NoseProtruding := CustomNoseProtruding
NoseBodyToLeftEyeBody := CustomNoseBodyToLeftEyeBody
NoseLengthToLeftEyeLength := CustomNoseLengthToLeftEyeLength
LeftEyeDepth := CustomLeftEyeDepth
MinimumCandlestickLength := CustomMinimumNoseLength
float NoseLength = 0.0
float NoseBody = 0.0
float LeftEyeBody = 0.0
float LeftEyeLength = 0.0
//============================================================================
// Functions
//===========================================================================
SendAlert(message) =>
if UseAlerts
alert(message,alert.freq_once_per_bar_close)
//============================================================================
// Pin Bar Detection
//===========================================================================
_Point = syminfo.pointvalue
// Left Eye and Nose bars' parameters.
NoseLength := high - low
if (NoseLength == 0)
NoseLength := _Point
LeftEyeLength := high[1] - low[1]
if (LeftEyeLength == 0)
LeftEyeLength := _Point
NoseBody := math.abs(open - close)
if (NoseBody == 0)
NoseBody := _Point
LeftEyeBody := math.abs(open[1] - close[1])
if (LeftEyeBody == 0)
LeftEyeBody := _Point
// Bearish Pinbar
if (high - high[1] >= NoseLength * NoseProtruding) // Nose protrusion
if (NoseBody / NoseLength <= MaxNoseBodySize) // Nose body to candle length ratio
if (1 - (high - math.max(open, close)) / NoseLength < NoseBodyPosition) // Nose body position in bottom part of the bar
if ((not LeftEyeOppositeDirection) or (close[1] > open[1])) // Left Eye bullish if required
if ((not NoseSameDirection) or (close < open)) // Nose bearish if required
if (LeftEyeBody / LeftEyeLength >= LeftEyeMinBodySize) // Left eye body to candle length ratio
if ((math.max(open, close) <= high[1]) and (math.min(open, close) >= low[1])) // Nose body inside Left Eye bar
if (NoseBody / LeftEyeBody <= NoseBodyToLeftEyeBody) // Nose body to Left Eye body ratio
if (NoseLength / LeftEyeLength >= NoseLengthToLeftEyeLength) // Nose length to Left Eye length ratio
if (low - low[1] >= LeftEyeLength * LeftEyeDepth) // Left Eye low is low enough
if ((not NoseBodyInsideLeftEyeBody) or ((math.max(open, close) <= math.max(open[1], close[1])) and (math.min(open, close) >= math.min(open[1], close[1])))) // Nose body inside Left Eye body if required
BearishPinbar := true
SendAlert("Bearish")
// Bullish Pinbar
if (low[1] - low >= NoseLength * NoseProtruding) // Nose protrusion
if (NoseBody / NoseLength <= MaxNoseBodySize) // Nose body to candle length ratio
if (1 - (math.min(open, close) - low) / NoseLength < NoseBodyPosition) // Nose body position in top part of the bar
if ((not LeftEyeOppositeDirection) or (close[1] < open[1])) // Left Eye bearish if required
if ((not NoseSameDirection) or (close > open)) // Nose bullish if required
if (LeftEyeBody / LeftEyeLength >= LeftEyeMinBodySize) // Left eye body to candle length ratio
if ((math.max(open, close) <= high[1]) and (math.min(open, close) >= low[1])) // Nose body inside Left Eye bar
if (NoseBody / LeftEyeBody <= NoseBodyToLeftEyeBody) // Nose body to Left Eye body ratio
if (NoseLength / LeftEyeLength >= NoseLengthToLeftEyeLength) // Nose length to Left Eye length ratio
if (high[1] - high >= LeftEyeLength * LeftEyeDepth) // Left Eye high is high enough
if ((not NoseBodyInsideLeftEyeBody) or ((math.max(open, close) <= math.max(open[1], close[1])) and (math.min(open, close) >= math.min(open[1], close[1])))) // Nose body inside Left Eye body if required
BullishPinbar := true
SendAlert("Bullish")
plotshape(BearishPinbar, location=location.abovebar, style=shape.triangledown, size=size.normal, color=color.rgb(255, 0, 0),display=display.all)
plotshape(BullishPinbar, location=location.belowbar, style=shape.triangleup, size=size.normal, color=color.green,display=display.all)
|
Bursa Malaysia Index Series | https://www.tradingview.com/script/g0euxOMd-Bursa-Malaysia-Index-Series/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 8 | 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
//@version=5
indicator('Bursa Malaysia Index Series')
// 0. Inputs
// 1. Switch
// 2. Variables
// 3. Constructs
//#region ———————————————————— 0. Inputs
stringIndex = input.string( defval = 'Construction',
title = 'Choose Sector',
options = ['Construction', 'Consumer Products', 'Energy', 'Finance', 'Health Care',
'Industrial Products', 'Plantation', 'Property', 'REIT', 'Technology',
'Telecommunications & Media', 'Transportation & Logistics', 'Utilities'])
displayPlot = input.string('close', 'Display Plot', options = ['close', 'ohlc'])
T1 = '1) Tick to show table\n2) Small font size recommended for mobile app or multiple layout'
tblY = input.string( 'bottom', 'Table Position', inline = '1', options = [ 'top', 'middle', 'bottom'])
tblX = input.string( 'right', '', inline = '1', options = ['left', 'center', 'right'])
tblfont = input.string( 'small', 'Font size', inline = '2', options = ['tiny', 'small', 'normal', 'large', 'huge'], tooltip = T1)
//#endregion
//#region ———————————————————— 1. Switch
index = switch stringIndex
'Construction' => 'MYX:CONSTRUCTN'
'Consumer Products' => 'MYX:CONSUMER'
'Energy' => 'MYX:ENERGY'
'Finance' => 'MYX:FINANCE'
'Health Care' => 'MYX:HEALTH'
'Industrial Products' => 'MYX:IND-PROD'
'Plantation' => 'MYX:PLANTATION'
'Property' => 'MYX:PROPERTIES'
'REIT' => 'MYX:REIT'
'Technology' => 'MYX:TECHNOLOGY'
'Telecommunications & Media' => 'MYX:TELECOMMUNICATIONS'
'Transportation & Logistics' => 'MYX:TRANSPORTATION'
'Utilities' => 'MYX:UTILITIES'
//#endregion
//#region ———————————————————— 2. Variables
OHLC(bool enable = true) => [open, high, low, close]
RS = request.security(index, '', close, lookahead = barmerge.lookahead_off)
[O, H, L, C] = request.security(index, '', OHLC(), lookahead = barmerge.lookahead_off)
var TBL = table.new(tblY + '_' + tblX, 1, 1, border_width = 1)
//#endregion
//#region ———————————————————— 3. Constructs
plot(displayPlot == 'close' ? RS : na, 'Index', chart.fg_color)
plotcandle( displayPlot == 'ohlc' ? O : na,
displayPlot == 'ohlc' ? H : na,
displayPlot == 'ohlc' ? L : na,
displayPlot == 'ohlc' ? C : na,
'OHLC',
color = open < close ? color.teal : color.red,
wickcolor = open < close ? color.teal : color.red,
bordercolor = open < close ? color.teal : color.red)
if barstate.islast
table.cell(TBL, 0, 0, str.upper(stringIndex), text_color = chart.bg_color, bgcolor = chart.fg_color)
//#endregion
|
RTH & ETH TWAPs [vnhilton] | https://www.tradingview.com/script/D4ulaPFm-RTH-ETH-TWAPs-vnhilton/ | vnhilton | https://www.tradingview.com/u/vnhilton/ | 12 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vnhilton
//@version=5
indicator("RTH & ETH TWAPs [vnhilton]", "RTHÐ TWAPS", true)
//RTH Timezone
rth = time(timeframe.period, session.regular, syminfo.timezone)
//Parameters
srcrth = input(ohlc4, "Source For RTH TWAP", group="RTH Parameters")
srceth = input(ohlc4, "Source For ETH TWAP", group="ETH Parameters")
//TWAP Calculation - Function By TradingView (modified)
twap(source) =>
var prices = 0.0
var count = 0
if timeframe.change("1D")
prices := 0
count := 0
prices += source
count += 1
prices / count
//Get RTH TWAP
var float twapRTH = na
if rth
twapRTH := twap(srcrth)
//Get ETH TWAP
twapETH = twap(srceth)
//Plots
plotRTH = plot(rth ? twapRTH : na, "RTH TWAP", color.new(#a5ff8d, 0), style=plot.style_linebr)
plotETH = plot(twapETH, "ETH TWAP", color.new(#a5ff8d, 75))
fill(plotRTH, plotETH, color.new(#a5ff8d, 95), "Plot Fill", display=display.none)
|
RSI Screener and Divergence [5ema] | https://www.tradingview.com/script/vfLe2QBa-RSI-Screener-and-Divergence-5ema/ | vn5ema | https://www.tradingview.com/u/vn5ema/ | 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/
// Reused some functions from (I believe made by @kingthies, ©paaax, @QuantNomad)
// ©paaax: The table position function (https://www.tradingview.com/script/Jp37jHwT-PX-MTF-Overview/).
// @kingthies: The RSI divergence function (https://www.tradingview.com/script/CaMohiJM-RSI-Divergence-Pine-v4/).
// @QuantNomad: The function calculated value and array screener for 40+ instruments (https://www.tradingview.com/script/zN8rwPFF-Screener-for-40-instruments/).
// © vn-5ema
//@version=5
indicator("RSI Divergence Multi Timeframe and Alert [5ema]", shorttitle = "RSI [5ema]", overlay = false)
// RSI 1
lenRSI = input.int(defval = 14, title = "Length of RSI ", minval = 1, tooltip = "By defaul, 14")
rsiUpper = input.int(defval = 70, title = "RSI Upper", tooltip = "Use to compare overbought.")
rsiLower = input.int(defval = 30, title = "RSI Lower", tooltip = "Use to compare oversold.")
// Input divergence
righBar = input.int(defval = 5, minval = 2, title = "Number righbar", tooltip = "Recommend 5, use to returns price of the pivot low & high point.")
leftBar = input.int(defval = 5, minval = 2, title = "Number leftbar", tooltip = "Recommend 5, use to returns price of the pivot low & high point.")
rangeUpper = input.int(defval = 60, minval = 2, title = "Number range upper", tooltip = "Recommend 60, use to compare the low & high point.")
rangeLower = input.int(defval = 5, minval = 2, title = "Number range lower", tooltip = "Recommend 5, use to compare the low & high point.")
// Plot RSI
plotsignalBool = input.bool(defval= true, title = "Show signal on RSI chart", group = "set up rsi on chart", tooltip = "The signal base on condition of divergence and the over RSI.")
boolRsiMA = input.bool(defval = true, title = "Show RSI MA ", group = "set up rsi on chart", inline ="ma")
Malenght = input.int(defval = 14, minval = 2, title = "", group = "set up rsi on chart", inline ="ma")
boolplotRSI = input.bool(defval = true, title = "Time frame ", group = "set up rsi on chart", inline ="rsi chart")
opplotRSI = input.timeframe("", title = "", group = "set up rsi on chart", inline ="rsi chart")
/////// This bool symbool refer from @QuantNomad /////
// Bool Symbols
u01 = input.bool(true, title = "Time frame 1 ", group = "Time frame following", inline = "s01")
u02 = input.bool(true, title = "Time frame 2 ", group = "Time frame following", inline = "s02")
u03 = input.bool(true, title = "Time frame 3 ", group = "Time frame following", inline = "s03")
u04 = input.bool(true, title = "Time frame 4 ", group = "Time frame following", inline = "s04")
u05 = input.bool(true, title = "Time frame 5 ", group = "Time frame following", inline = "s05")
u06 = input.bool(true, title = "Time frame 6 ", group = "Time frame following", inline = "s06")
// Input Symbols
s01 = input.timeframe("", title = "", group = "Time frame following", inline = "s01")
s02 = input.timeframe("5", title = "", group = "Time frame following", inline = "s02")
s03 = input.timeframe("15", title = "", group = "Time frame following", inline = "s03")
s04 = input.timeframe("60", title = "", group = "Time frame following", inline = "s04")
s05 = input.timeframe("240", title = "", group = "Time frame following", inline = "s05")
s06 = input.timeframe("D", title = "", group = "Time frame following", inline = "s06")
//////////
// Divergence
plotBull = input.bool(title="Regular Bullish ", defval=true, group = "Show divergence on chart", tooltip = "Show regular Bullish divergence on chart. The table will display >>.")
plotBear = input.bool(title="Regular Bearish", defval=true, group = "Show divergence on chart", tooltip = "Show regular Bearish divergence on chart. The table will display <<.")
plotHiddenBull = input.bool(title="Hidden Bullish ", defval=false, group = "Show divergence on chart", tooltip = "Show hidden Bullish divergence on chart. The table will display >.")
plotHiddenBear = input.bool(title="Hidden Bearish ", defval=false, group = "Show divergence on chart", tooltip = "Show hidden Bearish divergence on chart. The table will display <.")
// Set up table
boolTable = input.bool(defval = true, title = "Show table ", group = "Set up table", inline ="tb")
pTable = input.string("Bottom Right", title="", inline ="tb", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group="Set up table", tooltip = "On table will appear the shapes: divergence (>, <), strong signal ⦿, review signal (〇) with the color green (bull) or bear (red).")
/////// This function reused from ©paaax /////
getPosition(pTable) =>
ret = position.top_left
if pTable == "Top Center"
ret := position.top_center
if pTable == "Top Right"
ret := position.top_right
if pTable == "Middle Left"
ret := position.middle_left
if pTable == "Middle Center"
ret := position.middle_center
if pTable == "Middle Right"
ret := position.middle_right
if pTable == "Bottom Left"
ret := position.bottom_left
if pTable == "Bottom Center"
ret := position.bottom_center
if pTable == "Bottom Right"
ret := position.bottom_right
ret
//////////
// Set up color of table
table_boder = input(color.new(color.white, 100), group = "Set up table", title = "Border Color ")
table_frame = input(#151715, group = "Set up table", title ="Frame Color ")
table_bg = input(color.black, group = "Set up table", title ="Back Color ")
table_text = input(color.white, group = "Set up table", title ="Text Color ")
// Alert
onlyStrongAlert = input.bool(title="Only strong Signal", defval=false, group = "Set up Alert", tooltip = "Select this if want to alert only strong signal.")
onlyRegularDivergenceAlert = input.bool(title="Only regular divergence Signal", defval=false, group = "Set up Alert", tooltip = "Select this if want to alert only regular divergence Signal.")
/////// This divergence function refer from @kingthies/////
// Calculate RSi
RSI()=>
rsi = ta.rsi(close, lenRSI)
Orsi()=>
Orsi = RSI()
plFind()=>
plFind = na(ta.pivotlow(Orsi(), leftBar, righBar)) ? false : true
phFind()=>
phFind = na(ta.pivothigh(Orsi(), leftBar, righBar)) ? false : true
// RSI divergence
inRange(Cdt) =>
bars = ta.barssince(Cdt == true)
rangeLower <= bars and bars <= rangeUpper
// Regular bullish rsi
OrsiHL() =>
OrsiHL = Orsi()[righBar] > ta.valuewhen(plFind(), Orsi()[righBar], 1) and inRange(plFind()[1])
// Hidden bullish rsi
OrsiLL() =>
OrsiLL = Orsi()[righBar] < ta.valuewhen(plFind(), Orsi()[righBar], 1) and inRange(plFind()[1])
//Hidden bearish
OrsiHH () =>
OrsiHH = Orsi()[righBar] > ta.valuewhen(phFind(), Orsi()[righBar], 1) and inRange(phFind()[1])
// Regular bearish rsi
OrsiLH() =>
OrsiLH = Orsi()[righBar] < ta.valuewhen(phFind(), RSI()[righBar], 1) and inRange(phFind()[1])
// Regular bullish price
priceLL() =>
priceLL = low[righBar] < ta.valuewhen(plFind(), low[righBar], 1)
// Hidden bullish price
priceHL() =>
priceHL = low[righBar] > ta.valuewhen(plFind(), low[righBar], 1)
//Regular bearish price
priceHH() =>
priceHH = high[righBar] > ta.valuewhen(phFind(), high[righBar], 1)
//Hidden bearish price
priceLH() =>
priceLH = high[righBar] < ta.valuewhen(phFind(), high[righBar], 1)
//////////
// Screener function
scr_RSI() =>
RSI = RSI()
Orsi = RSI()
plFind = plFind()
phFind = phFind()
OrsiHL = OrsiHL()
OrsiLL = OrsiLL()
OrsiHH = OrsiHH()
OrsiLH = OrsiLH()
priceLL = priceLL()
priceHH = priceHH()
priceLH = priceLH()
priceHL = priceHL()
BullCdt = plotBull and priceLL and OrsiHL
hiddenBullCdt = plotHiddenBull and priceHL and OrsiLL
BearCdt = plotBear and priceHH and OrsiLH
hiddenBearCdt = plotHiddenBear and priceLH and OrsiHH
[RSI, Orsi, plFind, phFind, OrsiHL, OrsiLL, OrsiHH, OrsiLH, priceLL, priceHH, priceLH, priceHL, BullCdt, hiddenBullCdt, BearCdt, hiddenBearCdt]
/////// This function refer from @QuantNomad /////
// Security call
[RSI, Orsi, plFind, phFind, OrsiHL, OrsiLL, OrsiHH, OrsiLH, priceLL, priceHH, priceLH, priceHL, BullCdt, hiddenBullCdt, BearCdt, hiddenBearCdt] = request.security(timeframe = opplotRSI, symbol = syminfo.tickerid, expression = scr_RSI())
[RSI01, Orsi01, plFind01, phFind01, OrsiHL01, OrsiLL01, OrsiHH01, OrsiLH01, priceLL01, priceHH01, priceLH01, priceHL01, BullCdt01, hiddenBullCdt01, BearCdt01, hiddenBearCdt01] = request.security(timeframe = s01, symbol = syminfo.tickerid, expression = scr_RSI())
[RSI02, Orsi02, plFind02, phFind02, OrsiHL02, OrsiLL02, OrsiHH02, OrsiLH02, priceLL02, priceHH02, priceLH02, priceHL02, BullCdt02, hiddenBullCdt02, BearCdt02, hiddenBearCdt02] = request.security(timeframe = s02, symbol = syminfo.tickerid, expression = scr_RSI())
[RSI03, Orsi03, plFind03, phFind03, OrsiHL03, OrsiLL03, OrsiHH03, OrsiLH03, priceLL03, priceHH03, priceLH03, priceHL03, BullCdt03, hiddenBullCdt03, BearCdt03, hiddenBearCdt03] = request.security(timeframe = s03, symbol = syminfo.tickerid, expression = scr_RSI())
[RSI04, Orsi04, plFind04, phFind04, OrsiHL04, OrsiLL04, OrsiHH04, OrsiLH04, priceLL04, priceHH04, priceLH04, priceHL04, BullCdt04, hiddenBullCdt04, BearCdt04, hiddenBearCdt04] = request.security(timeframe = s04, symbol = syminfo.tickerid, expression = scr_RSI())
[RSI05, Orsi05, plFind05, phFind05, OrsiHL05, OrsiLL05, OrsiHH05, OrsiLH05, priceLL05, priceHH05, priceLH05, priceHL05, BullCdt05, hiddenBullCdt05, BearCdt05, hiddenBearCdt05] = request.security(timeframe = s05, symbol = syminfo.tickerid, expression = scr_RSI())
[RSI06, Orsi06, plFind06, phFind06, OrsiHL06, OrsiLL06, OrsiHH06, OrsiLH06, priceLL06, priceHH06, priceLH06, priceHL06, BullCdt06, hiddenBullCdt06, BearCdt06, hiddenBearCdt06] = request.security(timeframe = s06, symbol = syminfo.tickerid, expression = scr_RSI())
// Arrays //
s_arr = array.new_string(0)
u_arr = array.new_bool(0)
rsi_arr = array.new_float(0)
Orsi_arr = array.new_float(0)
plFind_arr = array.new_bool(0)
phFind_arr = array.new_bool(0)
OrsiHL_arr = array.new_bool(0)
OrsiLL_arr = array.new_bool(0)
OrsiHH_arr = array.new_bool(0)
OrsiLH_arr = array.new_bool(0)
priceLL_arr = array.new_bool(0)
priceHH_arr = array.new_bool(0)
priceLH_arr = array.new_bool(0)
priceHL_arr = array.new_bool(0)
BullCdt_arr = array.new_bool(0)
hiddenBullCdt_arr = array.new_bool(0)
BearCdt_arr = array.new_bool(0)
hiddenBearCdt_arr = array.new_bool(0)
// Add Symbols
array.push(s_arr, s01)
array.push(s_arr, s02)
array.push(s_arr, s03)
array.push(s_arr, s04)
array.push(s_arr, s05)
array.push(s_arr, s06)
// Flags //
array.push(u_arr, u01)
array.push(u_arr, u02)
array.push(u_arr, u03)
array.push(u_arr, u04)
array.push(u_arr, u05)
array.push(u_arr, u06)
array.push(rsi_arr, RSI01)
array.push(rsi_arr, RSI02)
array.push(rsi_arr, RSI03)
array.push(rsi_arr, RSI04)
array.push(rsi_arr, RSI05)
array.push(rsi_arr, RSI06)
array.push(Orsi_arr, Orsi01)
array.push(Orsi_arr, Orsi02)
array.push(Orsi_arr, Orsi03)
array.push(Orsi_arr, Orsi04)
array.push(Orsi_arr, Orsi05)
array.push(Orsi_arr, Orsi06)
array.push(plFind_arr, plFind01)
array.push(plFind_arr, plFind02)
array.push(plFind_arr, plFind03)
array.push(plFind_arr, plFind04)
array.push(plFind_arr, plFind05)
array.push(plFind_arr, plFind06)
array.push(phFind_arr, phFind01)
array.push(phFind_arr, phFind02)
array.push(phFind_arr, phFind03)
array.push(phFind_arr, phFind04)
array.push(phFind_arr, phFind05)
array.push(phFind_arr, phFind06)
array.push(hiddenBearCdt_arr, hiddenBearCdt01)
array.push(hiddenBearCdt_arr, hiddenBearCdt02)
array.push(hiddenBearCdt_arr, hiddenBearCdt03)
array.push(hiddenBearCdt_arr, hiddenBearCdt04)
array.push(hiddenBearCdt_arr, hiddenBearCdt05)
array.push(hiddenBearCdt_arr, hiddenBearCdt06)
array.push(BearCdt_arr, BearCdt01)
array.push(BearCdt_arr, BearCdt02)
array.push(BearCdt_arr, BearCdt03)
array.push(BearCdt_arr, BearCdt04)
array.push(BearCdt_arr, BearCdt05)
array.push(BearCdt_arr, BearCdt06)
array.push(hiddenBullCdt_arr, hiddenBullCdt01)
array.push(hiddenBullCdt_arr, hiddenBullCdt02)
array.push(hiddenBullCdt_arr, hiddenBullCdt03)
array.push(hiddenBullCdt_arr, hiddenBullCdt04)
array.push(hiddenBullCdt_arr, hiddenBullCdt05)
array.push(hiddenBullCdt_arr, hiddenBullCdt06)
array.push(BullCdt_arr, BullCdt01)
array.push(BullCdt_arr, BullCdt02)
array.push(BullCdt_arr, BullCdt03)
array.push(BullCdt_arr, BullCdt04)
array.push(BullCdt_arr, BullCdt05)
array.push(BullCdt_arr, BullCdt06)
array.push(priceHL_arr, priceHL01)
array.push(priceHL_arr, priceHL02)
array.push(priceHL_arr, priceHL03)
array.push(priceHL_arr, priceHL04)
array.push(priceHL_arr, priceHL05)
array.push(priceHL_arr, priceHL06)
array.push(priceLH_arr, priceLH01)
array.push(priceLH_arr, priceLH02)
array.push(priceLH_arr, priceLH03)
array.push(priceLH_arr, priceLH04)
array.push(priceLH_arr, priceLH05)
array.push(priceLH_arr, priceLH06)
array.push(priceHH_arr, priceHH01)
array.push(priceHH_arr, priceHH02)
array.push(priceHH_arr, priceHH03)
array.push(priceHH_arr, priceHH04)
array.push(priceHH_arr, priceHH05)
array.push(priceHH_arr, priceHH06)
array.push(priceLL_arr, priceLL01)
array.push(priceLL_arr, priceLL02)
array.push(priceLL_arr, priceLL03)
array.push(priceLL_arr, priceLL04)
array.push(priceLL_arr, priceLL05)
array.push(priceLL_arr, priceLL06)
array.push(OrsiLH_arr, OrsiLH01)
array.push(OrsiLH_arr, OrsiLH02)
array.push(OrsiLH_arr, OrsiLH03)
array.push(OrsiLH_arr, OrsiLH04)
array.push(OrsiLH_arr, OrsiLH05)
array.push(OrsiLH_arr, OrsiLH06)
array.push(OrsiHH_arr, OrsiHH01)
array.push(OrsiHH_arr, OrsiHH02)
array.push(OrsiHH_arr, OrsiHH03)
array.push(OrsiHH_arr, OrsiHH04)
array.push(OrsiHH_arr, OrsiHH05)
array.push(OrsiHH_arr, OrsiHH06)
array.push(OrsiLL_arr, OrsiLL01)
array.push(OrsiLL_arr, OrsiLL02)
array.push(OrsiLL_arr, OrsiLL03)
array.push(OrsiLL_arr, OrsiLL04)
array.push(OrsiLL_arr, OrsiLL05)
array.push(OrsiLL_arr, OrsiLL06)
array.push(OrsiHL_arr, OrsiHL01)
array.push(OrsiHL_arr, OrsiHL02)
array.push(OrsiHL_arr, OrsiHL03)
array.push(OrsiHL_arr, OrsiHL04)
array.push(OrsiHL_arr, OrsiHL05)
array.push(OrsiHL_arr, OrsiHL06)
/////// /////
//plot
var tbl = table.new(getPosition(pTable), 4, 7, frame_color=table_frame, frame_width=1, border_width=1, border_color= table_boder)
if barstate.islast and boolTable
table.cell(tbl, 0, 0, "Tfr.", text_halign = text.align_center, bgcolor = table_bg, text_color = table_text, text_size = size.small)
table.cell(tbl, 1, 0, "RSI", text_halign = text.align_center, bgcolor = table_bg, text_color = table_text, text_size = size.small)
table.cell(tbl, 2, 0, "Div.", text_halign = text.align_center, bgcolor = table_bg, text_color = table_text, text_size = size.small)
table.cell(tbl, 3, 0, "Signal", text_halign = text.align_center, bgcolor = table_bg, text_color = table_text, text_size = size.small)
for i = 0 to 5
if array.get(u_arr, i)
checkOverbought = array.get(rsi_arr, i) > rsiUpper
checkOversold = array.get(rsi_arr, i) < rsiLower
checkOverbought_2 = array.get(rsi_arr[righBar], i) > rsiUpper
checkOversold_2 = array.get(rsi_arr[righBar], i) < rsiLower
checkBull = array.get(plFind_arr, i) and array.get(BullCdt_arr,i)
checkhdBull = array.get(plFind_arr, i) and array.get(hiddenBullCdt_arr, i)
checkBear = array.get(phFind_arr, i) and array.get(BearCdt_arr, i)
checkhdBear = array.get(phFind_arr, i) and array.get(hiddenBearCdt_arr, i)
plBull_sha = checkBull ? ">>" : na
plhdBull_sha = checkhdBull ? ">" : na
phBear_sha = checkBear ? "<<" : na
phhdBear_sha = checkhdBear ? "<" : na
sgStrongBuy = checkBull and (checkOversold or checkOversold_2)
sgStrongSell = checkBear and (checkOverbought or checkOverbought_2)
sgBuy_1 = checkhdBull and (not checkOverbought or not checkOverbought_2)
sgBuy_2 = checkBull and (not checkOverbought or not checkOverbought_2)
sgBuy = checkOversold or sgBuy_1 or sgBuy_2
sgSell_1 = checkhdBear and (not checkOversold or not checkOversold_2)
sgSell_2 = checkBear and (not checkOversold or not checkOversold_2)
sgSell = checkOverbought or sgSell_1 or sgSell_2
table.cell(tbl, 0, i + 1, array.get(s_arr, i), text_halign = text.align_center, bgcolor = table_bg, text_color = table_text, text_size = size.small)
table.cell(tbl, 1, i + 1, str.tostring(array.get(rsi_arr, i), "#.#"), text_halign = text.align_center, bgcolor = table_bg, text_color = checkOverbought ? color.new(color.red, 0) : checkOversold ? color.new(color.green, 0) : table_text, text_size = size.small)
table.cell(tbl, 2, i + 1, checkBull ? plBull_sha : checkBear ? phBear_sha : checkhdBull ? plhdBull_sha : checkhdBear ? phhdBear_sha : "", text_halign = text.align_center, bgcolor = table_bg, text_color = checkBull or checkhdBull ? color.new(color.green, 0) : checkBear or checkhdBear ? color.new(color.red, 0) : table_text , text_size = size.small)
table.cell(tbl, 3, i + 1, sgStrongBuy or sgStrongSell ? "⦿" : sgBuy or sgSell ? "〇" : "", text_color = sgBuy or sgStrongBuy ? color.new(color.green, 0) : sgSell or sgStrongSell ? color.new(color.red, 0) : table_text , text_halign = text.align_center, bgcolor = table_bg, text_size = size.small)
// Plot RSI
rsiPlot = plot(boolplotRSI? RSI : na, title="RSI line", linewidth=1, color = RSI > rsiUpper ? color.new (color.red, 50) : RSI < rsiLower ? color.new (color.green, 50) : color.new(#808080, 0))
plot(boolRsiMA? ta.sma(RSI, Malenght) : na, title="RSI MA", linewidth=1, color=color.new(#ff9800, 50))
rsiUpperBand = hline(boolplotRSI ? rsiUpper : na, "RSI Upper Band", color=color.new(#787B86, 50), linestyle = hline.style_dotted)
hline(boolplotRSI ? 50 : na, "RSI Middle Band", color=color.new(#787B86, 50), linestyle = hline.style_dotted)
rsiLowerBand = hline(boolplotRSI ? rsiLower : na, "RSI Lower Band", color=color.new(#787B86, 50), linestyle = hline.style_dotted)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
plot(boolplotRSI and plFind ? Orsi[righBar] : na, offset=-righBar, title="Buy signal on table", linewidth=1, color=BullCdt ? color.new(color.green, 0) : color.new(color.white, 100))
plot(boolplotRSI and plFind ? Orsi[righBar] : na, offset=-righBar, title="Review Buy on table", linewidth=1, color=hiddenBullCdt ? color.new(color.green, 0) : color.new(color.white, 100) )
plot(boolplotRSI and phFind ? Orsi[righBar] : na, offset=-righBar, title="Sell signal on table", linewidth=1, color=BearCdt ? color.new(color.red, 0) : color.new(color.white, 100))
plot(boolplotRSI and phFind ? Orsi[righBar] : na, offset=-righBar, title="Review Sell on table", linewidth=1, color=hiddenBearCdt ? color.new(color.red, 0) : color.new(color.white, 100))
midLine = plot(50, color = na, editable = false, display = display.none)
fill(rsiPlot, midLine, 100, rsiUpper, top_color = color.new(color.red, 0), bottom_color = color.new(color.red, 100), title = "Overbought Fill")
fill(rsiPlot, midLine, rsiLower, 0, top_color = color.new(color.green, 100), bottom_color = color.new(color.green, 0), title = "Oversold Fill")
// For current RSI chart
checkOverbought_cr = RSI > rsiUpper
checkOversold_cr = RSI < rsiLower
checkOverbought_cr_2 = RSI[righBar] > rsiUpper
checkOversold_cr_2 = RSI[righBar] < rsiLower
checkBull_cr = plFind and BullCdt
checkhdBull_cr = plFind and hiddenBullCdt
checkBear_cr = phFind and BearCdt
checkhdBear_cr = phFind and hiddenBearCdt
sgStrongBuy_cr_1 = checkBull_cr and checkOversold_cr
sgStrongBuy_cr_2 = checkBull_cr and checkOversold_cr_2
sgStrongSell_cr_1 = checkBear_cr and checkOverbought_cr
sgStrongSell_cr_2 = checkBear_cr and checkOverbought_cr_2
sgStrongBuy_cr = sgStrongBuy_cr_1 or sgStrongBuy_cr_2
sgStrongSell_cr = sgStrongSell_cr_1 or sgStrongSell_cr_2
sgBuy_1_cr = checkBull_cr and not checkOversold_cr
sgBuy_2_cr = checkhdBull_cr and not checkOversold_cr
sgSell_1_cr = checkBear_cr and not checkOverbought_cr_2
sgSell_2_cr = checkhdBear_cr and not checkOverbought_cr
// Plot Signal
plotshape((plotsignalBool) and plotBull ? sgStrongBuy_cr ? Orsi[righBar] : na : na, text = "⦿", textcolor = color.new(color.green, 0), title = "Regular Buy signal on charrt", size = size.tiny, style=shape.labelup, color = table_bg, location=location.absolute, offset = - righBar)
plotshape((plotsignalBool) and plotBear ? sgStrongSell_cr ? Orsi[righBar] : na : na, text = "⦿", textcolor = color.new(color.red, 0), title = "Regular Sell signal on charrt", size = size.tiny,style=shape.labeldown, color = table_bg, location=location.absolute, offset = - righBar )
plotshape((plotsignalBool) and plotBull ? sgBuy_1_cr ? Orsi[righBar] : na : na, text = "〇", textcolor = color.new(color.green, 0), title = "Regular review Buy on chart", size = size.tiny, style=shape.labelup, color = table_bg, location=location.absolute, offset = - righBar)
plotshape((plotsignalBool) and plotBear ? sgSell_1_cr ? Orsi[righBar] : na : na, text = "〇", textcolor = color.new(color.red, 0), title = "Regular review Sell on chart", size = size.tiny,style=shape.labeldown, color = table_bg, location=location.absolute, offset = - righBar)
plotshape((plotsignalBool) and plotHiddenBull ? sgBuy_2_cr ? Orsi[righBar] : na : na, text = "〇", textcolor = color.new(color.green, 0), title = "Hidden review Buy on chart", size = size.tiny, style=shape.labelup, color = table_bg, location=location.absolute, offset = - righBar)
plotshape((plotsignalBool) and plotHiddenBear ? sgSell_2_cr ? Orsi[righBar] : na : na, text = "〇", textcolor = color.new(color.red, 0), title = "Hidden review Sell on chart", size = size.tiny,style=shape.labeldown, color = table_bg, location=location.absolute, offset = - righBar)
// For Alert
crh_alert = ""
//Signal Review BUY
crh_alert := (u01 != false and (plFind01 and (BullCdt01 or hiddenBullCdt01)) or RSI01 < rsiLower) ? crh_alert + syminfo.ticker + "\n" + "Time frame: " + s01 + "\n" + "Signal: BUY" + "\n" : crh_alert
crh_alert := (u02 != false and (plFind02 and (BullCdt02 or hiddenBullCdt02)) or RSI02 < rsiLower) ? crh_alert + syminfo.ticker + "\n" + "Time frame: " + s02 + "\n" + "Signal: BUY" + "\n" : crh_alert
crh_alert := (u03 != false and (plFind03 and (BullCdt03 or hiddenBullCdt03)) or RSI03 < rsiLower) ? crh_alert + syminfo.ticker + "\n" + "Time frame: " + s03 + "\n" + "Signal: BUY" + "\n" : crh_alert
crh_alert := (u04 != false and (plFind04 and (BullCdt04 or hiddenBullCdt04)) or RSI04 < rsiLower) ? crh_alert + syminfo.ticker + "\n" + "Time frame: " + s04 + "\n" + "Signal: BUY" + "\n" : crh_alert
crh_alert := (u05 != false and (plFind05 and (BullCdt05 or hiddenBullCdt05)) or RSI05 < rsiLower) ? crh_alert + syminfo.ticker + "\n" + "Time frame: " + s05 + "\n" + "Signal: BUY" + "\n" : crh_alert
crh_alert := (u06 != false and (plFind06 and (BullCdt06 or hiddenBullCdt06)) or RSI06 < rsiLower) ? crh_alert + syminfo.ticker + "\n" + "Time frame: " + s06 + "\n" + "Signal: BUY" + "\n" : crh_alert
//Signal Review SELL
crh_alert := (u01 != false and (phFind01 and (BearCdt01 or hiddenBearCdt01)) or RSI01 > rsiUpper) ? crh_alert + syminfo.ticker + "\n" + "Time frame: " + s01 + "\n" + "Signal: SELL" + "\n" : crh_alert
crh_alert := (u02 != false and (phFind02 and (BearCdt02 or hiddenBearCdt02)) or RSI02 > rsiUpper) ? crh_alert + syminfo.ticker + "\n" + "Time frame: " + s02 + "\n" + "Signal: SELL" + "\n" : crh_alert
crh_alert := (u03 != false and (phFind03 and (BearCdt03 or hiddenBearCdt03)) or RSI03 > rsiUpper) ? crh_alert + syminfo.ticker + "\n" + "Time frame: " + s03 + "\n" + "Signal: SELL" + "\n" : crh_alert
crh_alert := (u04 != false and (phFind04 and (BearCdt04 or hiddenBearCdt04)) or RSI04 > rsiUpper) ? crh_alert + syminfo.ticker + "\n" + "Time frame: " + s04 + "\n" + "Signal: SELL" + "\n" : crh_alert
crh_alert := (u05 != false and (phFind05 and (BearCdt05 or hiddenBearCdt05)) or RSI05 > rsiUpper) ? crh_alert + syminfo.ticker + "\n" + "Time frame: " + s05 + "\n" + "Signal: SELL" + "\n" : crh_alert
crh_alert := (u06 != false and (phFind06 and (BearCdt06 or hiddenBearCdt06)) or RSI06 > rsiUpper) ? crh_alert + syminfo.ticker + "\n" + "Time frame: " + s06 + "\n" + "Signal: SELL" + "\n" : crh_alert
// Send alert only if screener is not empty
if (crh_alert != "") and not onlyStrongAlert and not onlyRegularDivergenceAlert
alert(crh_alert + "\n(RSI - 5ema.vn)", freq = alert.freq_once_per_bar_close)
crh_alert_sg = ""
//Signal strong BUY
crh_alert_sg := (u01 != false and (plFind01 and BullCdt01 and RSI01 < rsiLower)) ? crh_alert_sg + syminfo.ticker + "\n" + "Time frame: " + s01 + "\n" + "Signal: BUY" + "\n" : crh_alert_sg
crh_alert_sg := (u02 != false and (plFind02 and BullCdt02 and RSI02 < rsiLower)) ? crh_alert_sg + syminfo.ticker + "\n" + "Time frame: " + s02 + "\n" + "Signal: BUY" + "\n" : crh_alert_sg
crh_alert_sg := (u03 != false and (plFind03 and BullCdt03 and RSI03 < rsiLower)) ? crh_alert_sg + syminfo.ticker + "\n" + "Time frame: " + s03 + "\n" + "Signal: BUY" + "\n" : crh_alert_sg
crh_alert_sg := (u04 != false and (plFind04 and BullCdt04 and RSI04 < rsiLower)) ? crh_alert_sg + syminfo.ticker + "\n" + "Time frame: " + s04 + "\n" + "Signal: BUY" + "\n" : crh_alert_sg
crh_alert_sg := (u05 != false and (plFind05 and BullCdt05 and RSI05 < rsiLower)) ? crh_alert_sg + syminfo.ticker + "\n" + "Time frame: " + s05 + "\n" + "Signal: BUY" + "\n" : crh_alert_sg
crh_alert_sg := (u06 != false and (plFind06 and BullCdt06 and RSI06 < rsiLower)) ? crh_alert_sg + syminfo.ticker + "\n" + "Time frame: " + s06 + "\n" + "Signal: BUY" + "\n" : crh_alert_sg
//Signal strong SELL
crh_alert_sg := (u01 != false and (phFind01 and BearCdt01 and RSI01 > rsiUpper)) ? crh_alert_sg + syminfo.ticker + "\n" + "Time frame: " + s01 + "\n" + "Signal: SELL" + "\n" : crh_alert_sg
crh_alert_sg := (u02 != false and (phFind02 and BearCdt02 and RSI02 > rsiUpper)) ? crh_alert_sg + syminfo.ticker + "\n" + "Time frame: " + s02 + "\n" + "Signal: SELL" + "\n" : crh_alert_sg
crh_alert_sg := (u03 != false and (phFind03 and BearCdt03 and RSI03 > rsiUpper)) ? crh_alert_sg + syminfo.ticker + "\n" + "Time frame: " + s03 + "\n" + "Signal: SELL" + "\n" : crh_alert_sg
crh_alert_sg := (u04 != false and (phFind04 and BearCdt04 and RSI04 > rsiUpper)) ? crh_alert_sg + syminfo.ticker + "\n" + "Time frame: " + s04 + "\n" + "Signal: SELL" + "\n" : crh_alert_sg
crh_alert_sg := (u05 != false and (phFind05 and BearCdt05 and RSI05 > rsiUpper)) ? crh_alert_sg + syminfo.ticker + "\n" + "Time frame: " + s05 + "\n" + "Signal: SELL" + "\n" : crh_alert_sg
crh_alert_sg := (u06 != false and (phFind06 and BearCdt06 and RSI06 > rsiUpper)) ? crh_alert_sg + syminfo.ticker + "\n" + "Time frame: " + s06 + "\n" + "Signal: SELL" + "\n" : crh_alert_sg
// Send alert only if screener is not empty
if (crh_alert_sg != "") and onlyStrongAlert
alert(crh_alert_sg + "\n(RSI - 5ema.vn)", freq = alert.freq_once_per_bar_close)
crh_alert_rd = ""
//Signal Regular divergence BUY
crh_alert_rd := (u01 != false and (plFind01 and BullCdt01)) ? crh_alert_rd + syminfo.ticker + "\n" + "Time frame: " + s01 + "\n" + "Signal: Review BUY" + "\n" : crh_alert_rd
crh_alert_rd := (u02 != false and (plFind02 and BullCdt02)) ? crh_alert_rd + syminfo.ticker + "\n" + "Time frame: " + s02 + "\n" + "Signal: Review BUY" + "\n" : crh_alert_rd
crh_alert_rd := (u03 != false and (plFind03 and BullCdt03)) ? crh_alert_rd + syminfo.ticker + "\n" + "Time frame: " + s03 + "\n" + "Signal: Review BUY" + "\n" : crh_alert_rd
crh_alert_rd := (u04 != false and (plFind04 and BullCdt04)) ? crh_alert_rd + syminfo.ticker + "\n" + "Time frame: " + s04 + "\n" + "Signal: Review BUY" + "\n" : crh_alert_rd
crh_alert_rd := (u05 != false and (plFind05 and BullCdt05)) ? crh_alert_rd + syminfo.ticker + "\n" + "Time frame: " + s05 + "\n" + "Signal: Review BUY" + "\n" : crh_alert_rd
crh_alert_rd := (u06 != false and (plFind06 and BullCdt06)) ? crh_alert_rd + syminfo.ticker + "\n" + "Time frame: " + s06 + "\n" + "Signal: Review BUY" + "\n" : crh_alert_rd
//Signal Regular divergence SELL
crh_alert_rd := (u01 != false and (phFind01 and BearCdt01)) ? crh_alert_rd + syminfo.ticker + "\n" + "Time frame: " + s01 + "\n" + "Signal: Review SELL" + "\n" : crh_alert_rd
crh_alert_rd := (u02 != false and (phFind02 and BearCdt02)) ? crh_alert_rd + syminfo.ticker + "\n" + "Time frame: " + s02 + "\n" + "Signal: Review SELL" + "\n" : crh_alert_rd
crh_alert_rd := (u03 != false and (phFind03 and BearCdt03)) ? crh_alert_rd + syminfo.ticker + "\n" + "Time frame: " + s03 + "\n" + "Signal: Review SELL" + "\n" : crh_alert_rd
crh_alert_rd := (u04 != false and (phFind04 and BearCdt04)) ? crh_alert_rd + syminfo.ticker + "\n" + "Time frame: " + s04 + "\n" + "Signal: Review SELL" + "\n" : crh_alert_rd
crh_alert_rd := (u05 != false and (phFind05 and BearCdt05)) ? crh_alert_rd + syminfo.ticker + "\n" + "Time frame: " + s05 + "\n" + "Signal: Review SELL" + "\n" : crh_alert_rd
crh_alert_rd := (u06 != false and (phFind06 and BearCdt06)) ? crh_alert_rd + syminfo.ticker + "\n" + "Time frame: " + s06 + "\n" + "Signal: Review SELL" + "\n" : crh_alert_rd
// Send alert only if screener is not empty
if (crh_alert_rd != "") and onlyRegularDivergenceAlert
alert(crh_alert_rd + "\n(RSI - 5ema.vn)", freq = alert.freq_once_per_bar_close)
|
Swing Boxes | https://www.tradingview.com/script/Rd33PlMt-swing-boxes/ | tarasenko_ | https://www.tradingview.com/u/tarasenko_/ | 481 | 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("Swing Boxes", overlay = 1)
// Inputs
// Main Settings
p = input.int(200, "Black Box Period", 0, group = "Main Settings")
atr_p = input.int(14, "ATR Period", 1, group = "Main Settings")
atr_f = input.float(1.0, "ATR Factor", 0.1, step = 0.1, group = "Main Settings")
// Extra
show_box = input.bool(false, "Show Boxes?", group = "Extra")
show_midline = input.bool(false, "Show Baseline?", group = "Extra")
// Calculations
h = high
l = low
highest_low = p != 0 ? ta.highest(p) : open
lowest_high = p != 0 ? ta.lowest(p) : open
atr = ta.atr(atr_p)
// e means epsilon from calculus, so it is used
// for making top and bottom for "boxes", which are
// based on ATR
e = atr * atr_f
src = close[1]
// If previous close is higher than variable, which contains previous HIGHEST value,
// then update the this variable by taking up-to-date highest value and add
// epsilon(e) to it
//
// Analogically for price being lower than variable, which contains previous LOWEST value
if src > nz(h[1], h)
h := highest_low + e
else if src < nz(l[1], l)
l := lowest_high - e
else
h := nz(h[1], h)
l := nz(l[1], l)
// Baseline. Formed as a midline between box's top and bottom
bl = (h + l) / 2
// Colours
col = bl > bl[1] ? #00ff00 : #ff0000
col := bl == bl[1] ? col[1] : col
// Signal logic
buy = bl > bl[1] and col != col[1]
sell = bl < bl[1] and col != col[1]
// Visuals
plot(show_midline ? bl : na, "bl", col, 2)
plot(show_box ? h : na, "Box Top" , color.gray, 1, plot.style_stepline)
plot(show_box ? l : na, "Box Bottom", color.gray, 1, plot.style_stepline)
plotshape(buy , "Buy" , shape.triangleup , location.belowbar, col, 0, "" , col, size = size.tiny)
plotshape(sell, "sell", shape.triangledown, location.abovebar, col, 0, "", col, size = size.tiny)
barcolor(col)
|
LNL Smart TICK | https://www.tradingview.com/script/xXfZifQm-LNL-Smart-TICK/ | lnlcapital | https://www.tradingview.com/u/lnlcapital/ | 86 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//
// @version=5
//
// LNL Smart $TICK
//
// This study is mostly beneficial for intraday traders. It is basically a user-friendly "colorful" representation of the $TICK chart with highlighted the $TICK extremes.
// Smart TICK also includes simple EMA gauge as well as cumulative $TICK values & cumulative $TICK cloud which can serve as an additional confirmation for intraday bias.
//
// Credit for the main part of the cumulative tick code to PineCoders-LucF & Investorito
//
// Created by L&L Capital
//
indicator("LNL Smart TICK",shorttitle = "Smart TICK")
// Inputs
emalength = input(20,title = "EMA Length")
Hi1 = input(500,title = "HighLine 1")
Hi2 = input(1000,title = "HighLine 2")
Hi3 = input(1300,title = "HighLine 3")
Lo1 = input(-500,title = "LowLine 1")
Lo2 = input(-1000,title = "LowLine 2")
Lo3 = input(-1300,title = "LowLine 3")
// $TICK Calculations & Plot
tickO = request.security("USI:TICK", timeframe.period, open)
tickH = request.security("USI:TICK", timeframe.period, high)
tickL = request.security("USI:TICK", timeframe.period, low)
tickC = request.security("USI:TICK", timeframe.period, close)
tickHL2 = (tickH + tickL)/2
plotcandle(tickO,tickH,tickL,tickC, title='TICK', color = tickO < tickC ? #009900 : #cc0000, wickcolor = tickO < tickC ? #009900 : #cc0000)
// Cumulative $TICK Calculations & Plot
cumtickdata = (request.security("USI:TICK", timeframe.period, hl2))
timeset = not na(time(timeframe.period, "0930-1555"))
start = timeset and not timeset[1]
var cumtick = 0.
cumtick := start ? 0. : cumtick + cumtickdata
cloudcolor = cumtick > ta.ema(cumtick,5) ? color.rgb(76,175,80,70) : color.rgb(255,82,82,70)
devidor = timeframe.period == "1" ? 80 : timeframe.period == "5" ? 20 : 5
plot(cumtick/devidor, title = "Cumulative Tick Cloud", color = cloudcolor, linewidth = 1, style =plot.style_area)
// $TICK Extreme Lines Calculations & Plot
hline(0, title = "ZeroLine", linestyle = hline.style_solid, linewidth = 1, color = #787b86)
hline(Hi1, title = "HighLine 1", linestyle = hline.style_solid, linewidth = 1, color = #1b5e20)
hline(Hi2, title = "HighLine 2", linestyle = hline.style_solid, linewidth = 2, color = #27c22e)
hline(Hi3, title = "HighLine 3", linestyle = hline.style_dashed, linewidth = 1, color = #1b5e20)
hline(Lo1, title = "LowLine 1", linestyle = hline.style_solid, linewidth = 1, color = #801922)
hline(Lo2, title = "LowLine 2", linestyle = hline.style_solid, linewidth = 2, color = #ff0000)
hline(Lo3, title = "LowLine 3", linestyle = hline.style_dashed, linewidth = 1, color = #801922)
// EMA Trend Gauge Plot
ema = ta.sma(tickC,emalength)
plot(ema,title = "ema", color = ema > 0 ? #27c22e : #ff0000, linewidth = 3)
// Extreme Readings Calculations & Plot
extremeup = tickH > Hi2
plotshape(extremeup, title='Extreme Up',style=shape.triangleup,location=location.top,color=#27c22e,size=size.tiny)
extremedn = tickL < Lo2
plotshape(extremedn, title='Extreme Down',style=shape.triangledown,location=location.bottom,color=#ff0000,size=size.tiny)
// Breadth Ratios
uvol = request.security("USI:UVOL", timeframe.period, close)
dvol = request.security("USI:DVOL", timeframe.period, close)
uvolq = request.security("USI:UVOLQ", timeframe.period, close)
dvolq = request.security("USI:DVOLQ", timeframe.period, close)
nyseratio = (uvol >= dvol) ? (uvol / dvol) : -(dvol / uvol)
nasdratio = (uvolq >= dvolq) ? (uvolq / dvolq) : -(dvolq / uvolq)
// $TICK Tables Calculations & Plot
Text1 = string ("$TICK:")
Color1 = color.gray
if tickC > 0
Color1 := #27c22e
else
Color1 := #ff0000
Text2 = string ("Cumulative $TICK:")
Color2 = color.gray
if cumtick > 0
Color2 := #27c22e
else
Color2 := #ff0000
Text3 = string ("NYSE:")
Color3 = color.gray
if nyseratio >= 0
Color3 := #27c22e
else
Color3 := #ff0000
Text4 = string ("NASD:")
Color4 = color.gray
if nasdratio >= 0
Color4 := #27c22e
else
Color4 := #ff0000
Table = table.new(position = position.top_left, columns=10, rows=1, bgcolor=color.gray)
if barstate.islast
table.cell(table_id=Table, column=1, row=0, text=Text1, height=0, text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_size = size.auto, text_valign= text.align_center, bgcolor=Color1)
table.cell(table_id=Table, column=2, row=0, text=str.tostring(tickC), height=0, text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_size = size.auto, text_valign= text.align_center, bgcolor=Color1)
table.cell(table_id=Table, column=3, row=0, text=Text2, height=0,text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_valign=text.align_center, bgcolor=Color2)
table.cell(table_id=Table, column=4, row=0, text=str.tostring(cumtick), height=0,text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_valign=text.align_center, bgcolor=Color2)
table.cell(table_id=Table, column=5, row=0, text=Text3, height=0,text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_valign=text.align_center, bgcolor=Color3)
table.cell(table_id=Table, column=6, row=0, text=str.tostring(math.round(nyseratio,2)), height=0,text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_valign=text.align_center, bgcolor=Color3)
table.cell(table_id=Table, column=7, row=0, text=Text4, height=0,text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_valign=text.align_center, bgcolor=Color4)
table.cell(table_id=Table, column=8, row=0, text=str.tostring(math.round(nasdratio,2)), height=0,text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_valign=text.align_center, bgcolor=Color4) |
HTF Bar Close Countdown | https://www.tradingview.com/script/MKj0V6Pi-HTF-Bar-Close-Countdown/ | SamRecio | https://www.tradingview.com/u/SamRecio/ | 134 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SamRecio
//This indicator utilizes some
//@version=5
indicator("HTF Bar Close Countdown", shorttitle = "⏳", overlay = true)
//Requesting and plotting (but hiding the display of) Crypto values to force a more consistent ticking.
//By using data from constantly moving sources I can force the indicator to update more often.
//If I did not do this the indicator would only update every time the price changed on your current chart,
//for really slow moving tickers it basically just freezes the count for a couple seconds every couple seconds... which is not the point of a countdown.
plot(request.security("COINBASE:BTCUSD","",close), display = display.none, title = "BTCUSD", editable = false)
plot(request.security("COINBASE:ETHUSD","",close), display = display.none, title = "ETHUSD", editable = false)
//Timeframe Settings
tf1tog = input.bool(true, title = "", group ="HTF Bar Close Countdown", inline = "1")
tf1 = input.timeframe("15", title = "", group ="HTF Bar Close Countdown", inline = "1")
col1 = input.color(color.white, title = "Text", group ="HTF Bar Close Countdown", inline = "1")
bg1 = input.color(color.rgb(0,0,0,100), title = "Background", group ="HTF Bar Close Countdown", inline = "1")
tf2tog = input.bool(true, title = "", group ="HTF Bar Close Countdown", inline = "2")
tf2 = input.timeframe("60", title = "", group ="HTF Bar Close Countdown", inline = "2")
col2 = input.color(color.white, title = "Text", group ="HTF Bar Close Countdown", inline = "2")
bg2 = input.color(color.rgb(0,0,0,100), title = "Background", group ="HTF Bar Close Countdown", inline = "2")
tf3tog = input.bool(true, title = "", group ="HTF Bar Close Countdown", inline = "3")
tf3 = input.timeframe("240", title = "", group ="HTF Bar Close Countdown", inline = "3")
col3 = input.color(color.white, title = "Text", group ="HTF Bar Close Countdown", inline = "3")
bg3 = input.color(color.rgb(0,0,0,100), title = "Background", group ="HTF Bar Close Countdown", inline = "3")
tf4tog = input.bool(true, title = "", group ="HTF Bar Close Countdown", inline = "4")
tf4 = input.timeframe("D", title = "", group ="HTF Bar Close Countdown", inline = "4")
col4 = input.color(color.white, title = "Text", group ="HTF Bar Close Countdown", inline = "4")
bg4 = input.color(color.rgb(0,0,0,100), title = "Background", group ="HTF Bar Close Countdown", inline = "4")
tf5tog = input.bool(true, title = "", group ="HTF Bar Close Countdown", inline = "5")
tf5 = input.timeframe("W", title = "", group ="HTF Bar Close Countdown", inline = "5")
col5 = input.color(color.white, title = "Text", group ="HTF Bar Close Countdown", inline = "5")
bg5 = input.color(color.rgb(0,0,0,100), title = "Background", group ="HTF Bar Close Countdown", inline = "5")
//Table Settings
tsize = input.string("normal", title = "Table Size", options = ["auto","tiny","small", "normal", "large","huge"], group = "Countdown Table Settings", inline = "1")
flat = input.bool(false, title = "Flat Display?", group = "Countdown Table Settings", inline = "1")
typos = input.string("middle", title = "Position", options = ["top", "middle", "bottom"], group = "Countdown Table Settings", inline = "2")
txpos = input.string("right", title = "", options=["left", "center", "right"], group = "Countdown Table Settings", inline = "2")
tframe = input.color(color.white, title = "Frame Color:", group = "Countdown Table Settings", inline = "3")
tframes = input.int(0, minval = 0, title = "Width:", group = "Countdown Table Settings", inline = "3")
tborder = input.color(color.new(color.white,30), title ="Border Color:", group = "Countdown Table Settings", inline = "4")
tborders = input.int(1, minval = 0, title = "Width:", group = "Countdown Table Settings", inline = "4")
//Table Setup
var display = table.new(typos+"_"+txpos,10,5, border_color = tborder, border_width = tborders, frame_color = tframe, frame_width = tframes)
//Countdown Function
//This countdown method takes advantage of the "time_close()" function to determine where the input timeframe's candle close.
//By knowing at what time it closes, we can subtract where we are now from it to get how far we are from the input timeframe's close.
//This function converts all the data into strings so that I may easily input it as text into the table.
countdown(tf) =>
til_next = ((time_close(tf)/1000) - math.floor(timenow/1000))
next_day = math.floor(((til_next/60)/60)/24)
next_hour = math.floor((til_next/60)/60) - (next_day*24)
next_min = math.floor(til_next/60) - math.floor((til_next/60)/60)*60
next_sec = til_next - (math.floor(til_next/60)*60)
place0 = next_day == 0?"":str.tostring(next_day,"00") + ":"
place1 = next_hour == 0?"": str.tostring(next_hour,"00") + ":"
place2 = str.tostring(next_min,"00") + ":"
place3 = str.tostring(next_sec,"00")
place0 + place1 + place2 + place3
//Send to table function,
//This function allows me to add the stuff to the table based on the individual toggles.
//By creating a function to add them to the table, you can see later that executing this function is a lot simpler and easier to follow than otherwise, since it is just doing the same thing 5 times.
//Theoretically this can be easily expaned to how ever many countdowns you want. I decided 5 was a good number, and if you want less, you can toggle them off!
to_table(_tog,_flat,_pos,_tf,_col,_bg) =>
if (_flat == false) and _tog
//Timeframe Title
table.cell(display,0,_pos-1,text = _tf, text_halign = text.align_left, text_color = _col, bgcolor = _bg, text_size = tsize)
//Countdown Values
table.cell(display,1,_pos-1,text = session.islastbar?"Closed":countdown(_tf), text_halign = text.align_right, text_color = _col, bgcolor = _bg, text_size = tsize)
if _flat and _tog
//Timeframe Title
table.cell(display,(_pos*2)-2,0,text = _tf, text_halign = text.align_right, text_color = _col, bgcolor = _bg, text_size = tsize)
//Countdown Values
table.cell(display,(_pos*2)-1,0,text = session.islastbar?"Closed":countdown(_tf), text_halign = text.align_left, text_color = _col, bgcolor = _bg, text_size = tsize)
//Function Execution
if barstate.islast
to_table(tf1tog,flat,1,tf1,col1,bg1)
to_table(tf2tog,flat,2,tf2,col2,bg2)
to_table(tf3tog,flat,3,tf3,col3,bg3)
to_table(tf4tog,flat,4,tf4,col4,bg4)
to_table(tf5tog,flat,5,tf5,col5,bg5)
|
Grid Indicator - The Quant Science | https://www.tradingview.com/script/h3CJ9GDY-Grid-Indicator-The-Quant-Science/ | thequantscience | https://www.tradingview.com/u/thequantscience/ | 204 | 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/
// © thequantscience
//@version=5
indicator("Grid Indicator - The Quant Science", overlay = true)
price = input.price(defval = 0, title = "Price:", confirm = true)
price_range = input.float(defval = 0.50, title = "Price range: ", confirm = true)
grid1up = price + ((price_range/2) * price / 100)
grid1down = price - ((price_range/2) * price / 100)
grid2up = grid1up + ((price_range) * price / 100)
grid2down = grid1down - ((price_range) * price / 100)
grid3up = grid2up + ((price_range) * price / 100)
grid3down = grid2down - ((price_range) * price / 100)
grid4up = grid3up + ((price_range) * price / 100)
grid4down = grid3down - ((price_range) * price / 100)
grid5up = grid4up + ((price_range) * price / 100)
grid5down = grid4down - ((price_range) * price / 100)
plot(grid1up, color = color.rgb(119, 255, 0))
plot(grid1down, color = color.rgb(255, 0, 0))
plot(grid2up, color = color.rgb(119, 255, 0))
plot(grid2down, color = color.rgb(255, 0, 0))
plot(grid3up, color = color.rgb(119, 255, 0))
plot(grid3down, color = color.rgb(255, 0, 0))
plot(grid4up, color = color.rgb(119, 255, 0))
plot(grid4down, color = color.rgb(255, 0, 0))
plot(grid5up, color = color.rgb(119, 255, 0))
plot(grid5down, color = color.rgb(255, 0, 0)) |
Сoncentrated Market Maker Strategy by oxowl | https://www.tradingview.com/script/8XAwN3v7-%D0%A1oncentrated-Market-Maker-Strategy-by-oxowl/ | deperp | https://www.tradingview.com/u/deperp/ | 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/
// © deperp
//@version=5
indicator('Сoncentrated Market Maker Strategy by oxowl', shorttitle='СMM by oxowl', overlay=true)
// Set input parameters
liquidityPercentage = input(5, title='Liquidity Range %')
rebalanceFrequency = input(60, title='Rebalance Frequency (minutes)')
minTradeSize = input(0.01, title='Minimum Trade Size (Asset)')
// Calculate the range for liquidity provision
rangeMultiplier = 1 + liquidityPercentage / 100
upperBound = close * rangeMultiplier
lowerBound = close / rangeMultiplier
// Define the rebalancing logic
var float lastRebalanceTime = na
var float lastRebalancePrice = na
rebalanceCondition = (na(lastRebalanceTime) or time - lastRebalanceTime >= rebalanceFrequency * 60 * 1000 * 1000) and close >= lowerBound and close <= upperBound
if rebalanceCondition
lastRebalanceTime := time
lastRebalancePrice := close
lastRebalancePrice
// Plot the range and trades on the chart
upperBoundLine = plot(upperBound, color=color.new(color.red, 0), linewidth=1, title='Upper Bound')
lowerBoundLine = plot(lowerBound, color=color.new(color.green, 0), linewidth=1, title='Lower Bound')
// Display price labels for upper and lower bounds
label.new(x=bar_index, y=upperBound, text=str.tostring(upperBound, '#.##'), style=label.style_none, color=color.red, textcolor=color.red, size=size.large, yloc=yloc.price)
label.new(x=bar_index, y=lowerBound, text=str.tostring(lowerBound, '#.##'), style=label.style_none, color=color.green, textcolor=color.green, size=size.large, yloc=yloc.price)
// Define alert conditions
alertConditionUpper = ta.crossover(close, upperBound)
alertConditionLower = ta.crossunder(close, lowerBound)
// Create alert conditions
alertcondition(alertConditionUpper, title='Price crossed Upper Bound', message='Price crossed the Upper Bound')
alertcondition(alertConditionLower, title='Price crossed Lower Bound', message='Price crossed the Lower Bound')
|
Trail Blaze - (Multi Function Trailing Stop Loss) - [mutantdog] | https://www.tradingview.com/script/YBPV8OiX-Trail-Blaze-Multi-Function-Trailing-Stop-Loss-mutantdog/ | mutantdog | https://www.tradingview.com/u/mutantdog/ | 616 | 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/
// © mutantdog
//@version=5
indicator ('Trail Blaze', 'Trail Blaze', true, explicit_plot_zorder=true)
// v1.1
//
string S01 = 'open'
string S02 = 'high'
string S03 = 'low'
string S04 = 'close'
string S11 = 'hl2'
string S12 = 'hlc3'
string S13 = 'ohlc4'
string S14 = 'hlcc4'
string S51 = 'oc2'
string S52 = 'hlc2-o2'
string S53 = 'hl-oc2'
string S54 = 'cc-ohlc4'
string S91 = '*AUX 1'
string S92 = '*AUX 2'
string S93 = '*TRIGGER'
string M00 = 'none'
string M01 = 'SMA'
string M02 = 'EMA'
string M03 = 'WMA'
string M04 = 'RMA'
string M11 = 'VWMA'
string M12 = 'VWEMA'
string M13 = 'HMA'
string M41 = 'Median'
string M42 = 'Mid Range'
// INPUTS
auxSource_1 = input.source (close, 'Aux 1 ', inline='01')
auxSource_2 = input.source (close, 'Aux 2 ', inline='01')
triggerSource = input.string ('close', 'Source', [S01, S02, S03, S04, S11, S12, S13, S14, S51, S52, S53, S54, S91, S92], inline='11', group='Trigger')
triggerFilter = input.string ('RMA', 'Filter ', [M00, M01, M02, M03, M04, M11, M12, M13, M41, M42], inline='12', group='Trigger')
triggerLength = input.int (2, 'Length', minval=1, inline='12', group='Trigger')
centreSource = input.string ('hl2', 'Source', [S01, S02, S03, S04, S11, S12, S13, S14, S51, S52, S53, S54, S91, S92, S93], inline='21', group='Centre')
centreFilter = input.string ('EMA', 'Filter ', [M00, M01, M02, M03, M04, M11, M12, M13, M41, M42], inline='22', group='Centre')
centreLength = input.int (8, 'Length', minval=1, inline='22', group='Centre')
tslActive = input.bool (true, 'Trailing ', inline='41', group='Dynamics')
tslPercent = input.float (0, '%', step=0.1, inline='41', group='Dynamics')
atrActive = input.bool (true, 'ATR', inline='42', group='Dynamics')
atrLength = input.int (8, 'Length', minval=1, inline='42', group='Dynamics')
atrMult = input.float (1, 'Mult', step=0.1, inline='42', group='Dynamics')
iqrActive = input.bool (true, 'IQR', inline='43', group='Dynamics')
iqrLength = input.int (12, 'Length', minval=1, inline='43', group='Dynamics')
iqrMult = input.float (0, 'Mult', step=0.1, inline='43', group='Dynamics')
filterSum = input.bool (false, 'Filter Sum', inline='47', group='Dynamics')
loMult = input.float (1, 'Side Mult: Lo', minval=0, step=0.05, inline='49', group='Dynamics')
hiMult = input.float (1, 'Hi ', minval=0, step=0.05, inline='49', group='Dynamics')
showLostop = input.bool (true, 'LoStop', inline='71', group='Visual')
showHistop = input.bool (true, 'HiStop', inline='71', group='Visual')
showCentre = input.bool (false, 'Centre', inline='71', group='Visual')
showTrigger = input.bool (false, 'Trigger', inline='71', group='Visual')
showBands = input.bool (false, 'Bands', inline='71', group='Visual')
bullCol = input.color (#5a6e30, '', inline='88', group='Visual')
bearCol = input.color (#a11030, '', inline='88', group='Visual')
centreCol = input.color (#58aeb1, '', inline='88', group='Visual')
triggerCol = input.color (#ccc26d, '', inline='88', group='Visual')
bandCol = input.color (#6d6969, '', inline='88', group='Visual')
stopsOpac = input.int (100, 'Opacity: Stops', minval=0, maxval=100, step=5, inline='89', group='Visual')
otherOpac = input.int (40, 'Other', minval=0, maxval=100, step=5, inline='89', group='Visual')
// FUNCTIONS
source_switch (src, aux1, aux2) =>
source = switch src
'open' => open
'high' => high
'low' => low
'close' => close
'hl2' => hl2
'hlc3' => hlc3
'ohlc4' => ohlc4
'hlcc4' => hlcc4
'oc2' => (open + close) / 2
'hlc2-o2' => (high + low + close - open) / 2
'hl-oc2' => high + low - (open + close) / 2
'cc-ohlc4' => 2 * close - ohlc4
'*AUX 1' => aux1
'*AUX 2' => aux2
//
filter_switch (src, len, mode) =>
filter = switch mode
'none' => src
'SMA' => ta.sma (src, len)
'EMA' => ta.ema (src, len)
'WMA' => ta.wma (src, len)
'RMA' => ta.rma (src, len)
'VWMA' => ta.vwma (src, len)
'Median' => ta.median (src, len)
'Mid Range' => ta.lowest (src, len) + ta.range (src, len) / 2
'VWEMA' => ta.ema (src * volume, len) / ta.ema (volume, len)
'HMA' => len >= 2 ? ta.hma (src, len) : src
//
iqr_array (len) =>
float[] hiArray = array.new_float (0)
float[] loArray = array.new_float (0)
float[] cmArray = array.new_float (0)
for i = 0 to len - 1
array.push (hiArray, high[i])
array.push (loArray, low[i])
array.push (cmArray, hlcc4[i])
hlArray = array.concat (hiArray, loArray)
hlcmArray = array.concat (hlArray, cmArray)
q1 = array.percentile_linear_interpolation (hlcmArray, 25)
q3 = array.percentile_linear_interpolation (hlcmArray, 75)
iqr = (q3 - q1) / 2
//
trail_blaze (srct, srcc, lofac, hifac) =>
lostop = 0.0
histop = 0.0
trend = 0
trend := srct > histop[1] ? 1 : srct < lostop[1] ? -1 : nz (trend[1], 1)
lostop00 = trend == 1 and trend[1] == -1
histop00 = trend == -1 and trend[1] == 1
lostop := lostop00 ? srcc - lofac : srct[1] > lostop[1] ? math.max (srcc - lofac, lostop[1]) : srcc - lofac
histop := histop00 ? srcc + hifac : srct[1] < histop[1] ? math.min (srcc + hifac, histop[1]) : srcc + hifac
[lostop, histop, trend]
//
// PROCESS
triggerSwitch = source_switch (triggerSource, auxSource_1, auxSource_2)
trigger = filter_switch (triggerSwitch, triggerLength, triggerFilter)
centreSwitch = centreSource == '*TRIGGER' ? trigger : source_switch (centreSource, auxSource_1, auxSource_2)
centre = filter_switch (centreSwitch, centreLength, centreFilter)
tslFactor = tslActive ? centre * tslPercent / 100 : 0
atrFactor = atrActive ? atrMult * ta.atr (atrLength) : 0
iqrFactor = iqrActive ? iqrMult * iqr_array (iqrLength) : 0
sumFactor = filterSum ? ta.swma (nz (tslFactor) + nz (atrFactor) + nz (iqrFactor)) : nz (atrFactor) + nz (iqrFactor) + nz (tslFactor)
loFactor = math.max (sumFactor, 0) * loMult
hiFactor = math.max (sumFactor, 0) * hiMult
[lostop, histop, trend] = trail_blaze (trigger, centre, loFactor, hiFactor)
// VISUALS AND ALERTS
lostopColour = color.new (bullCol, 100 - stopsOpac)
histopColour = color.new (bearCol, 100 - stopsOpac)
centreColour = color.new (centreCol, 100 - otherOpac)
triggerColour = color.new (triggerCol, 100 - otherOpac)
bandColour = color.new (bandCol, 100 - otherOpac)
plotCentre = plot (showCentre ? centre : na, 'Centre', centreColour, 2)
plotTrigger = plot (showTrigger ? trigger : na, 'Trigger', triggerColour, 2)
plotLoband = plot (showBands ? centre - loFactor : na, 'Lo Band', bandColour, 2)
plotHiband = plot (showBands ? centre + hiFactor : na, 'Hi Band', bandColour, 2)
plotLostop = plot (showLostop ? trend == 1 ? lostop : na : na, 'Lo Stop', lostopColour, 2, plot.style_linebr)
plotHistop = plot (showHistop ? trend == 1 ? na : histop : na, 'Hi Stop', histopColour, 2, plot.style_linebr)
isNewTrend = trend != trend[1]
isNewUp = trend == 1 and trend[1] == -1
isNewDown = trend == -1 and trend[1] == 1
plotshape (isNewUp ? lostop : na, 'Long Start', shape.circle, location.absolute, lostopColour, size=size.tiny)
plotshape (isNewDown ? histop : na, 'Short Start', shape.circle, location.absolute, histopColour, size=size.tiny)
alertcondition (isNewTrend, '00: Trail Blaze - Direction Change', 'Trail Blaze has changed direction!')
alertcondition (isNewDown, '01: Trail Blaze - Sell', 'SELL SIGNAL: Trail Blaze Down!')
alertcondition (isNewUp, '02: Trail Blaze - Buy', 'BUY SIGNAL: Trail Blaze Up!')
|
Weekly Opening Gap (cryptonnnite) | https://www.tradingview.com/script/f0yubFhD-Weekly-Opening-Gap-cryptonnnite/ | cryptonnnite | https://www.tradingview.com/u/cryptonnnite/ | 2,235 | 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/
// © cryptonnnite
//@version=5
indicator("NWOG/NDOG (cryptonnnite)", overlay = true, max_boxes_count = 500, max_labels_count = 500)
import cryptonnnite/helpers/1 as helpers
type gap
float high
float low
int start
int end
var string nwogGroup = "New Week Opening Gap"
var string ndogGroup = "New Day Opening Gap"
var string generalSettings = "General Settings"
var string openLineSettings = "Week & Day Open"
bool showNWOG = input.bool(true, "", inline = "1", group = nwogGroup)
string nwogLabel = input.string("NWOG", "", inline = "1", group = nwogGroup)
color nwogBg = input.color(color.rgb(164, 249, 73, 85), "", inline = "1", group = nwogGroup)
bool showNwogCE = input.bool(false, "NWOG C.E.", tooltip = "C.E. - Consequent Encroachment or 'middle point' of any Gap or Inefficiency.", group = nwogGroup, inline = "2")
string nwogCEStyle = input.string("dotted", "", options = ["dotted", "dashed", "solid"], group = nwogGroup, inline = "2")
color nwogCEColor = input.color(color.blue, "", group = nwogGroup, inline = "2")
string nwogLabelXPosition = input.string('right', title = "Label", options = ["left", "center", "right"], inline = "5", group = nwogGroup)
string nwogLabelYPosition = input.string('top', title = "", options = ["top", "center", "bottom"], inline = "5", group = nwogGroup)
string nwogLabelSize = input.string('small', title = "", options = ["tiny", "small", "normal", "large", "huge"], inline = "5", group = nwogGroup)
color nwogLabelColor = input.color(color.black, "", inline = "5", group = nwogGroup)
int nwogsAmount = input.int(4, "Previous NWOGs", minval = 1, maxval = 100, inline = "3", group = nwogGroup)
color previousNwogBg = input.color(color.rgb(0, 0, 0, 90), "", inline = "3", group = nwogGroup)
bool extendAllNwogs = input.bool(false, "Extend Previous NWOGs", group = nwogGroup)
bool extendToCurrentDayCloseTime = input.bool(true, "Extend to Current Day", tooltip = "Otherwise it will be extended to the end of the week", group = nwogGroup)
bool showNDOG = input.bool(true, "", inline = "2", group = ndogGroup)
string ndogLabel = input.string("NDOG", "", inline = "2", group = ndogGroup)
color ndogBg = input.color(color.rgb(255, 235, 59, 85), "", inline = "2", group = ndogGroup)
bool showNdogCE = input.bool(false, "NDOG C.E.", tooltip = "C.E. - Consequent Encroachment or 'middle point' of any Gap or Inefficiency.", group = ndogGroup, inline = "3")
string ndogCEStyle = input.string("dotted", "", options = ["dotted", "dashed", "solid"], group = ndogGroup, inline = "3")
color ndogCEColor = input.color(color.blue, "", group = ndogGroup, inline = "3")
string ndogLabelXPosition = input.string('right', title = "Label", options = ["left", "center", "right"], inline = "5", group = ndogGroup)
string ndogLabelYPosition = input.string('top', title = "", options = ["top", "center", "bottom"], inline = "5", group = ndogGroup)
string ndogLabelSize = input.string('small', title = "", options = ["tiny", "small", "normal", "large", "huge"], inline = "5", group = ndogGroup)
color ndogLabelColor = input.color(color.black, "", inline = "5", group = ndogGroup)
int ndogsAmount = input.int(4, "Previous NDOG", minval = 1, maxval = 100, inline = "4", group = ndogGroup)
color previousNdogBg = input.color(color.rgb(0, 0, 0, 90), "", inline = "4", group = ndogGroup)
bool extendAllNdogs = input.bool(false, "Extend Previous NDOGs", group = ndogGroup)
bool eventHorizon = input.bool(false, "Event Horizon", inline = "2", group = generalSettings)
string eventHorizonLineStyle = input.string("dashed", "", options = ["dotted", "dashed", "solid"], group = generalSettings, inline = "2")
color eventHorizonLineColor = input.color(color.red, "", inline = "2", group = generalSettings)
bool fiveToSixGap = input.bool(true, "5pm to 6pm GAP", tooltip = "This option will show only 5pm to 6pm gaps. If you will see at the daily timeframe there is a big difference between previous day close and current day open GAP and 5pm to 6pm GAP. This option allows you to choose which GAP to use.", group = generalSettings)
bool showPriceLabels = input.bool(false, "Price Labels", inline = "1", group = generalSettings)
string priceLabelSize = input.string('small', title = "", options = ["tiny", "small", "normal", "large", "huge"], inline = "1", group = generalSettings)
color priceLabelColor = input.color(color.black, "", inline = "1", group = generalSettings)
bool showDateLabel = input.bool(true, "Show date label", group = generalSettings)
string dateFormat = input.string("dd.MM", title = "Date Format", options = ["dd.MM", "MM.dd", "dd.MM.yy", "MM.dd.yy"], group = generalSettings)
getGapData() =>
gap.new(math.max(close[1], open), math.min(close[1], open), time, time_close)
getDayOfWeekLabel(_dayofweek) =>
switch _dayofweek
dayofweek.sunday => "Sun"
dayofweek.monday => "Mon"
dayofweek.tuesday => "Tue"
dayofweek.wednesday => "Wed"
dayofweek.thursday => "Thu"
dayofweek.friday => "Fri"
dayofweek.saturday => "Sat"
gap weekOpeningGap = request.security(syminfo.tickerid, "1W", getGapData(), lookahead = barmerge.lookahead_on)
[dayOpeningGap, currentDayTimeClose] = request.security(syminfo.tickerid, "1D", [getGapData(), time_close], lookahead = barmerge.lookahead_on)
[isNewWeek, hourPreviousBarClose, hourCurrentBarOpen] = request.security(syminfo.tickerid, "240", [helpers.isNewbar("W"), close[1], open], lookahead = barmerge.lookahead_on)
if timeframe.isintraday and helpers.isNewbar("D") and fiveToSixGap
dayOpeningGap.high := math.max(close[1], open)
dayOpeningGap.low := math.min(close[1], open)
if timeframe.multiplier < 60
if isNewWeek and fiveToSixGap
weekOpeningGap.high := math.max(hourPreviousBarClose, hourCurrentBarOpen)
weekOpeningGap.low := math.min(hourPreviousBarClose, hourCurrentBarOpen)
else if (timeframe.isdaily or timeframe.isintraday) and helpers.isNewbar("W") and fiveToSixGap
weekOpeningGap.high := math.max(close[1], open)
weekOpeningGap.low := math.min(close[1], open)
var array<box> nwogArray = array.new<box>(0)
var array<line> nwogCEArray = array.new<line>(0)
var array<label> nwogHighLabel = array.new<label>(0)
var array<label> nwogCELabel = array.new<label>(0)
var array<label> nwogLowLabel = array.new<label>(0)
var array<box> ndogArray = array.new<box>(0)
var array<line> ndogCEArray = array.new<line>(0)
var array<label> ndogHighLabel = array.new<label>(0)
var array<label> ndogCELabel = array.new<label>(0)
var array<label> ndogLowLabel = array.new<label>(0)
var line eventHorizonLine = na
if showNWOG and (timeframe.isdaily or timeframe.isintraday)
if helpers.isNewbar("W") // if (hour(time, "America/New_York") == 9 and minute(time, America/New_York) == 30 and nineThirtyGap) or (not nineThirtyGap and helpers.isNewbar("W"))
string weekLabel = showDateLabel ? str.format_time(weekOpeningGap.start, dateFormat, syminfo.timezone) + " - " + str.format_time(weekOpeningGap.end, dateFormat, syminfo.timezone) + " | " + nwogLabel : nwogLabel
float nwogCePrice = (weekOpeningGap.high + weekOpeningGap.low) / 2
array.push(nwogArray, box.new(weekOpeningGap.start, weekOpeningGap.high, weekOpeningGap.end, weekOpeningGap.low, xloc = xloc.bar_time, bgcolor = nwogBg, border_width = 0, text = weekLabel, text_size = helpers.getTextSize(nwogLabelSize), text_halign = helpers.getBoxTextPosition(nwogLabelXPosition), text_valign = helpers.getBoxTextPosition(nwogLabelYPosition), text_color = nwogLabelColor))
if showNwogCE
array.push(nwogCEArray, line.new(weekOpeningGap.start, nwogCePrice, weekOpeningGap.end, nwogCePrice, xloc = xloc.bar_time, style = helpers.getLineStyle(nwogCEStyle), color = nwogCEColor))
if showPriceLabels
array.push(nwogHighLabel, label.new(weekOpeningGap.end, weekOpeningGap.high, str.tostring(weekOpeningGap.high, format.mintick), style = label.style_label_lower_left, xloc = xloc.bar_time, color = color.rgb(0, 0, 0, 100), textcolor = priceLabelColor, size = helpers.getTextSize(priceLabelSize)))
array.push(nwogCELabel, label.new(weekOpeningGap.end, nwogCePrice, str.tostring(nwogCePrice, format.mintick), style = label.style_label_left, xloc = xloc.bar_time, color = color.rgb(0, 0, 0, 100), textcolor = priceLabelColor, size = helpers.getTextSize(priceLabelSize)))
array.push(nwogLowLabel, label.new(weekOpeningGap.end, weekOpeningGap.low, str.tostring(weekOpeningGap.low, format.mintick), style = label.style_label_upper_left, xloc = xloc.bar_time, color = color.rgb(0, 0, 0, 100), textcolor = priceLabelColor, size = helpers.getTextSize(priceLabelSize)))
if array.size(nwogArray) > nwogsAmount
box.delete(array.shift(nwogArray))
if showNwogCE
line.delete(array.shift(nwogCEArray))
if showPriceLabels
label.delete(array.shift(nwogHighLabel))
label.delete(array.shift(nwogCELabel))
label.delete(array.shift(nwogLowLabel))
if eventHorizon and array.size(nwogArray) > 1
box currentNwog = array.last(nwogArray)
box previousNwog = array.get(nwogArray, array.size(nwogArray) - 2)
float currentNwog_high = box.get_top(currentNwog)
float currentNwog_low = box.get_bottom(currentNwog)
float previousNwog_high = box.get_top(previousNwog)
float previousNwog_low = box.get_bottom(previousNwog)
float eventHorizonLevel = 0.0
if currentNwog_high > previousNwog_high and currentNwog_low > previousNwog_high
eventHorizonLevel := (currentNwog_low + previousNwog_high) / 2
else if previousNwog_high > currentNwog_high and previousNwog_low > currentNwog_high
eventHorizonLevel := (previousNwog_low + currentNwog_high) / 2
eventHorizonLine := line.new(weekOpeningGap.start, eventHorizonLevel, weekOpeningGap.end, eventHorizonLevel, xloc = xloc.bar_time, style = helpers.getLineStyle(eventHorizonLineStyle), color = eventHorizonLineColor)
line.delete(eventHorizonLine[1])
if helpers.isNewbar("D")
if extendAllNwogs and array.size(nwogArray) > 0
for i = array.size(nwogArray) - 1 to 0
extendTo = extendToCurrentDayCloseTime ? currentDayTimeClose : weekOpeningGap.end
box.set_right(array.get(nwogArray, i), extendTo)
if i != array.size(nwogArray) - 1
box.set_bgcolor(array.get(nwogArray, i), previousNwogBg)
if showNwogCE
line.set_x2(array.get(nwogCEArray, i), extendTo)
if showPriceLabels
label.set_x(array.get(nwogHighLabel, i), extendTo)
label.set_x(array.get(nwogCELabel, i), extendTo)
label.set_x(array.get(nwogLowLabel, i), extendTo)
if extendToCurrentDayCloseTime and array.size(nwogArray) > 0
box.set_right(array.last(nwogArray), currentDayTimeClose)
if showNwogCE
line.set_x2(array.last(nwogCEArray), currentDayTimeClose)
if showPriceLabels
label.set_x(array.last(nwogHighLabel), currentDayTimeClose)
label.set_x(array.last(nwogCELabel), currentDayTimeClose)
label.set_x(array.last(nwogLowLabel), currentDayTimeClose)
if eventHorizon
line.set_x2(eventHorizonLine, currentDayTimeClose)
if showNDOG and timeframe.isintraday
if helpers.isNewbar("D")// and dayOpeningGap.high != dayOpeningGap.low
if (dayofweek != dayofweek.sunday and showNWOG) or not showNWOG
string dayLabel = showDateLabel ? str.format_time(dayOpeningGap.start, dateFormat, syminfo.timezone) + " | " + ndogLabel : ndogLabel //showDayLabels ? getDayOfWeekLabel(dayofweek) + " | " + ndogLabel : ndogLabel
float ndogCePrice = (dayOpeningGap.high + dayOpeningGap.low) / 2
array.push(ndogArray, box.new(dayOpeningGap.start, dayOpeningGap.high, dayOpeningGap.end, dayOpeningGap.low, xloc = xloc.bar_time, bgcolor = ndogBg, border_width = 0, text = dayLabel, text_size = helpers.getTextSize(ndogLabelSize), text_halign = helpers.getBoxTextPosition(ndogLabelXPosition), text_valign = helpers.getBoxTextPosition(ndogLabelYPosition), text_color = ndogLabelColor))
if showNdogCE
array.push(ndogCEArray, line.new(dayOpeningGap.start, ndogCePrice, dayOpeningGap.end, ndogCePrice, xloc = xloc.bar_time, style = helpers.getLineStyle(ndogCEStyle), color = ndogCEColor))
if showPriceLabels
array.push(ndogHighLabel, label.new(dayOpeningGap.end, dayOpeningGap.high, str.tostring(dayOpeningGap.high, format.mintick), style = label.style_label_lower_left, xloc = xloc.bar_time, color = color.rgb(0, 0, 0, 100), textcolor = priceLabelColor, size = helpers.getTextSize(priceLabelSize)))
array.push(ndogCELabel, label.new(dayOpeningGap.end, ndogCePrice, str.tostring(ndogCePrice, format.mintick), style = label.style_label_left, xloc = xloc.bar_time, color = color.rgb(0, 0, 0, 100), textcolor = priceLabelColor, size = helpers.getTextSize(priceLabelSize)))
array.push(ndogLowLabel, label.new(dayOpeningGap.end, dayOpeningGap.low, str.tostring(dayOpeningGap.low, format.mintick), style = label.style_label_upper_left, xloc = xloc.bar_time, color = color.rgb(0, 0, 0, 100), textcolor = priceLabelColor, size = helpers.getTextSize(priceLabelSize)))
if array.size(ndogArray) > ndogsAmount
box.delete(array.shift(ndogArray))
if showNdogCE
line.delete(array.shift(ndogCEArray))
if showPriceLabels
label.delete(array.shift(ndogHighLabel))
label.delete(array.shift(ndogCELabel))
label.delete(array.shift(ndogLowLabel))
if extendAllNdogs and array.size(ndogArray) > 0
for i = 0 to array.size(ndogArray) - 1
box.set_right(array.get(ndogArray, i), dayOpeningGap.end)
if (showNWOG and dayofweek == dayofweek.sunday and i <= array.size(ndogArray) - 1) or i < array.size(ndogArray) - 1
box.set_bgcolor(array.get(ndogArray, i), previousNdogBg)
if showNdogCE
line.set_x2(array.get(ndogCEArray, i), dayOpeningGap.end)
if showPriceLabels
label.set_x(array.get(ndogHighLabel, i), dayOpeningGap.end)
label.set_x(array.get(ndogCELabel, i), dayOpeningGap.end)
label.set_x(array.get(ndogLowLabel, i), dayOpeningGap.end)
|
OHLC [TFO] | https://www.tradingview.com/script/DbmEwLl4-OHLC-TFO/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 1,187 | 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/
// © tradeforopp
//@version=5
indicator("OHLC [TFO]", "OHLC [TFO]", true)
var g1 = "Settings"
tf = input.timeframe("D", "Timeframe", group = g1)
bar_offset = input.int(20, "OHLC Bar Offset", minval = 0, maxval = 100, group = g1)
bar_width = input.int(30, "OHLC Bar Width", minval = 0, maxval = 100, group = g1)
var g2 = "Style"
up_color = input.color(color.green, "Up Color", group = g2)
down_color = input.color(color.red, "Down Color", group = g2)
wick_color = input.color(color.gray, "Wick Color", group = g2)
border_color = input.color(color.gray, "Border Color", group = g2)
body_width = input.int(10, "Body Border Width", group = g2)
wick_width = input.int(5, "Wick Border Width", group = g2)
[d_o, d_h, d_l, d_c] = request.security(syminfo.tickerid, tf, [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
up_candle = d_c > d_o
wick_start = bar_offset + math.floor(bar_width / 2 - 1)
wick_end = bar_offset + math.ceil(bar_width / 2 + 1)
var box candle_wick = box.new(na, na, na, na, border_color = wick_color, bgcolor = wick_color, border_width = wick_width)
var box candle_body = box.new(na, na, na, na, border_color = border_color, bgcolor = wick_color, border_width = body_width)
box.set_lefttop(candle_wick, bar_index + wick_start, d_h)
box.set_rightbottom(candle_wick, bar_index + wick_end, d_l)
box.set_lefttop(candle_body, bar_index + bar_offset, up_candle ? d_c : d_o)
box.set_rightbottom(candle_body, bar_index + bar_offset + bar_width, up_candle ? d_o : d_c)
if up_candle
box.set_bgcolor(candle_body, up_color)
else
box.set_bgcolor(candle_body, down_color) |
Kitti-Playbook Request.Volume X Price R0.00 | https://www.tradingview.com/script/IkCE0WYs-Kitti-Playbook-Request-Volume-X-Price-R0-00/ | Kittimasak_S | https://www.tradingview.com/u/Kittimasak_S/ | 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/
// © Kittimasak_S
//@version=5
indicator("Kitti-Playbook Request.Volume X Price R0.01")
//=================================================================================================
// Date July 30 2023. R 0.01
// Add Setting functions
// setting Chart for Column / Area
// setting Chart color
// setting Label for Short / Full Type
// setting Front size of TEXT label
// add cutoff line ON OFF
// Date Jan 31 2023
// OVERVIEW : Kitti-Playbook Request.Volume X Price R0.00
// Objective : Visualize Volume X Last Price
//
// ==============================================================================================
// ====== Setting Menu. ============================================================================
i_MKCapCutoffInt = input.float( 5," CUTOFF level" ,0.1,1000,step=0.1 ,
tooltip=" It is recommended to use more than 100 times of the investment." ,group="Market Trade Value ( Currency) ",inline="L1" )
i_MKCapCutoffUnit = input.session("Million", " : ", options=["Thousand", "10Thousand","Million", "10Million","Billion","10Billion","Non" ],
tooltip=" It is recommended to use more than 100 times of the investment." ,group="Market Trade Value ( Currency) ",inline="L1" )
i_Cutoff_Dis = input.bool(false,"Show CUTOFF Line " ,group="Market Trade Value ( Currency) ",inline="L2")
i_Cutoff_lin__col= input.color(color.new(color.orange,70),": Line Color",group="Market Trade Value ( Currency) ",inline="L2")
i_TopRange0 = input.float( 8.6," Zoom level (0 - 10) " ,0,10,step=0.2 ,
tooltip=" 0 = Zoom turn Off " ,group="Market Trade Value ( Currency) ",inline="L3" )
i_BarStstue = input.string("Current", "Current Bar / Previoue Bar",["Current","Previous"],
tooltip=" In case the market is openning , the previous bar also needs to be considered." ,group="Market Trade Value ( Currency) ",inline="L4")
// ==== PLot cut off line ====
DisplaySW3 = i_Cutoff_Dis ? display.all : display.none
plot(i_MKCapCutoffInt," Cutoff Line ",color=i_Cutoff_lin__col,style = plot.style_circles, display=DisplaySW3 )
//-------------------------------
// Unit Converter
DivUnit = switch i_MKCapCutoffUnit
"Thousand" => 1e3
"10Thousand" => 1e3 *10
"Million" => 1e6
"10Million" => 1e6 *10
"Billion" => 1e9
"10Billion" => 1e9 *10
"Non" => 1
i_MKCapCutoff = i_MKCapCutoffInt*DivUnit / DivUnit
//
TopRange= (10.5-i_TopRange0) *i_MKCapCutoff
// Data Collection
VOL=i_BarStstue== "Current" ? volume : i_BarStstue== "Previous" ? volume[1] : na
Sour= i_BarStstue== "Current" ? close : i_BarStstue== "Previous" ? close[1] : na
offset_Plot= i_BarStstue== "Current" ? 0 : i_BarStstue== "Previous" ? -1 : na
// Requesr Market cap
TSO = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ") // TTM , FQ , FY // SET Use FQ
MarketCap = TSO * close /DivUnit
// Market Cap Calculation
Value = (VOL * Sour) / DivUnit
Valuex=Value/MarketCap *100
// Market Cap Limit Calculation
ValueP = i_TopRange0==0? Value :Value >=TopRange ? TopRange : Value
// Display Graph
i_Dis_Type = input.string("Column", 'Plot Chart Type', options=
["Column",
"Area"],
group='Display Setting',
inline="L0")
i_Dis_Chart_col= input.color(color.new(color.blue,70)," Color",group='Display Setting', inline="L0",tooltip="The graph is below the CUTOFF value, showing red.")
plot(ValueP,color=i_Dis_Chart_col, linewidth=2, style=plot.style_area, offset=offset_Plot, trackprice=true)
ColorFill=color.from_gradient(ValueP,0,i_MKCapCutoff,color.rgb(214, 10, 10), i_Dis_Chart_col )
Dis_Area=i_Dis_Type == "Area" ? true : false
Dis_Colums=i_Dis_Type == "Column" ? true : false
DisplaySW1 = Dis_Area ? display.all : display.none
DisplaySW2 = Dis_Colums ? display.all : display.none
plot(ValueP,"Market Trade value ",color=color.new(ColorFill, 50), linewidth=2, style=plot.style_area, offset=offset_Plot, trackprice=true, display=DisplaySW1)
plot(ValueP,"Market Trade value ",color=color.new(ColorFill, 50), linewidth=2, style=plot.style_columns, offset=offset_Plot, trackprice=true, display=DisplaySW2)
// ====================== Display Switch Full / Short / Off =============================================================
i_LabelDisplayType= input.string("Short", 'Label Display format', options=
["Short",
"Full",
" OFF"],
group='Display Setting',
inline="L1")
// ==================== Full Label ===================================================================
ShowInfoTab0 = i_LabelDisplayType== "Full" ? true : false
i_Tab_Width0 = input.int(20, "Label Size ", minval=1, maxval=40, step=1,group='Display Setting',inline="L2")
i_table_position0 = input.string(position.top_right, 'Label Location : Full', options=
[position.middle_left,
position.middle_center,
position.middle_right,
position.bottom_left,
position.bottom_center,
position.bottom_right,
position.top_center,
position.top_right],
group='Display Setting',
inline="L3")
var table Signal_table0 = table.new(position=i_table_position0, columns=1, rows=1, border_width=2)
i_Front0=input.string(size.large,"Text Size",options=
[
size.tiny,
size.small,
size.normal,
size.large,
size.huge],
group='Display Setting',
display=display.none,
inline="L2")
tColor1 = color.new(#888888, 0)
bColor0 = Value<i_MKCapCutoff*0.5 ? color.new(color.red,80) :Value<i_MKCapCutoff? color.new(color.yellow,80) : color.new(color.gray,90)
_TEXT_DisplayA0 =" " + i_BarStstue + " Bar : Listed Shares = " + str.format("{0,number,#.###}",(TSO/DivUnit)) +" " +i_MKCapCutoffUnit //" M Unit "
+ " \n Last Price = " + str.format("{0,number,#.##} ", Sour) + syminfo.currency + ": Market Cap.=" + str.format("{0,number,#.##} ",MarketCap ) + i_MKCapCutoffUnit+" "+syminfo.currency
+ " \n Volume(Share) = " + str.format("{0,number,#.###}",(VOL/DivUnit)) +" " + i_MKCapCutoffUnit +" : "+ str.format("{0,number,#.###}",((VOL/TSO)*100)) +" % of Listed Shares"
+ " \n Value (Currency) = " + str.format("{0,number,#.###}",(Value)) +" " + i_MKCapCutoffUnit +" "+ syminfo.currency+ " : " + str.format("{0,number,#.###}",(Valuex)) + "% of Market Cap. "
+ " \n Cutoff Trade Value = " + str.format("{0,number,#.###}",(i_MKCapCutoff)) +" " +i_MKCapCutoffUnit +" "+ syminfo.currency
+ " \n Value of Trade VS Cutoff = " + str.format("{0,number,#.###}",(Value/i_MKCapCutoff)) +" Times "
if ShowInfoTab0 == true
table.cell(Signal_table0, 0, 0, _TEXT_DisplayA0, bgcolor=bColor0, text_color=tColor1,text_halign=text.align_left, width=i_Tab_Width0 , text_size = i_Front0)
//======================== Short Label =================================================================================
ShowInfoTab3 = i_LabelDisplayType== "Short" ? true : false
table_position3 = input.string(position.middle_right, 'Shot', options=
[position.middle_left,
position.middle_center,
position.middle_right,
position.bottom_left,
position.bottom_center,
position.bottom_right,
position.top_center,
position.top_right],
group='Display Setting',
inline="L3")
var table Signal_table3 = table.new(position=table_position3, columns=1, rows=1, border_width=2)
tColor3 = color.new(#888888, 0)
bColor3 = Value<i_MKCapCutoff*0.5 ? color.new(color.red,80) :Value<i_MKCapCutoff? color.new(color.yellow,80) : color.new(color.gray,90)
_TEXT_DisplayA3 = " Value (Currency) = " + str.format("{0,number,#.###}",(Value)) +" " + i_MKCapCutoffUnit +" "+ syminfo.currency
+ "/"+ str.format("{0,number,#.###}",(Valuex)) +" %"
+ " \n Cutoff Trade Value = " + str.format("{0,number,#.###}",(i_MKCapCutoff)) +" " +i_MKCapCutoffUnit +" "+ syminfo.currency
if ShowInfoTab3 == true
table.cell(Signal_table3, 0, 0, _TEXT_DisplayA3, bgcolor=bColor0, text_color=tColor1,text_halign=text.align_left, width=i_Tab_Width0 , text_size = i_Front0)
//=============. END ================================================================================== |
Balance of Force Day of the Week (BOFDW) | https://www.tradingview.com/script/WjruW8u3-Balance-of-Force-Day-of-the-Week-BOFDW/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("BOFDW", overlay = true)
style = input.string("Bottom Right", "Position",
["Bottom Left","Bottom Middle","Bottom Right","Middle Left","Middle Center","Middle Right",
"Top Left","Top Middle","Top Right"])
txt_col = input.color(color.new(#c8d7ff, 0), "Title Color", inline = "bull", group = "Settings")
box_col = input.color(color.new(#202236, 10), "", inline = "bull", group = "Settings")
box_hi = input.color(color.new(#602236, 10), "", inline = "bull", group = "Settings")
box_min = input.color(color.new(#202276, 10), "", inline = "bull", group = "Settings")
location() =>
switch style
"Bottom Left" => position.bottom_left
"Bottom Middle" => position.bottom_center
"Bottom Right" => position.bottom_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Top Left" => position.top_left
"Top Middle" => position.top_center
"Top Right" => position.top_right
simple_moving_average(source)=>
var float sum = na
var int count = na
if close == close
count := nz(count[1]) + 1
sum := nz(sum[1]) + source
sum/count
bes(float source = close, float length = 9)=>
alpha = 2 / (length + 1)
var float smoothed = na
smoothed := alpha * (source) + (1 - alpha) * nz(smoothed[1])
pof(input_day)=>
var int count = na
var float deviation = na
var int count_bearish = na
var int count_bullish = na
var float bearish = na
var float bullish = na
if open > close and input_day
bearish := nz(bearish[1]) + math.abs(open - close)
count_bearish := nz(count_bearish[1]) + 1
if close > open and input_day
bullish := nz(bullish[1]) + math.abs(close - open)
count_bullish := nz(count_bullish[1]) + 1
bearish_true_range = (bearish)/(count_bearish)
bullish_true_range = (bullish)/(count_bullish)
bof = math.log(bullish_true_range/bearish_true_range)
if 1 == 1 and input_day
count := nz(count[1]) + 1
deviation := nz(deviation[1]) + math.pow(bof - math.log(1), 2)
square_diff = math.sqrt(deviation/(count-1))
[bof, square_diff]
monday = dayofweek == dayofweek.monday
tuesday = dayofweek == dayofweek.tuesday
wednesday = dayofweek == dayofweek.wednesday
thursday = dayofweek == dayofweek.thursday
friday = dayofweek == dayofweek.friday
saturday = dayofweek == dayofweek.saturday
sunday = dayofweek == dayofweek.sunday
[monday_pof, monday_square_diff] = pof(monday)
[tuesday_pof, tuesday_square_diff] = pof(tuesday)
[wednesday_pof, wednesday_square_diff] = pof(wednesday)
[thursday_pof, thursday_square_diff] = pof(thursday)
[friday_pof, friday_square_diff] = pof(friday)
[saturday_pof, saturday_square_diff] = pof(saturday)
[sunday_pof, sunday_square_diff] = pof(sunday)
monday_pof_average = simple_moving_average(monday_pof)
tuesday_pof_average = simple_moving_average(tuesday_pof)
wednesday_pof_average = simple_moving_average(wednesday_pof)
thursday_pof_average = simple_moving_average(thursday_pof)
friday_pof_average = simple_moving_average(friday_pof)
saturday_pof_average = simple_moving_average(saturday_pof)
sunday_pof_average = simple_moving_average(sunday_pof)
max_pof(input_day)=>
largest = math.max(na(monday_pof) ? -10 : monday_pof, na(tuesday_pof) ? -10 : tuesday_pof, na(wednesday_pof) ? -10 : wednesday_pof, na(thursday_pof) ? -10 : thursday_pof, na(friday_pof) ? -10 : friday_pof, na(saturday_pof) ? -10 : saturday_pof, na(sunday_pof) ? -10 : sunday_pof)
out = input_day == largest ? true : false
max_pof_average(input_day)=>
largest = math.max(na(monday_pof_average) ? -10 : monday_pof_average, na(tuesday_pof_average) ? -10 : tuesday_pof_average, na(wednesday_pof_average) ? -10 : wednesday_pof_average, na(thursday_pof_average) ? -10 : thursday_pof_average, na(friday_pof_average) ? -10 : friday_pof_average, na(saturday_pof_average) ? -10 : saturday_pof_average, na(sunday_pof_average) ? -10 : sunday_pof_average)
out = input_day == largest ? true : false
min_pof(input_day)=>
lowest = math.min(na(monday_pof) ? 10 : monday_pof, na(tuesday_pof) ? 10 : tuesday_pof, na(wednesday_pof) ? 10 : wednesday_pof, na(thursday_pof) ? 10 : thursday_pof, na(friday_pof) ? 10 : friday_pof, na(saturday_pof) ? 10 : saturday_pof, na(sunday_pof) ? 10 : sunday_pof)
out = input_day == lowest ? true : false
min_pof_average(input_day)=>
lowest = math.min(na(monday_pof_average) ? 10 : monday_pof_average, na(tuesday_pof_average) ? 10 : tuesday_pof_average, na(wednesday_pof_average) ? 10 : wednesday_pof_average, na(thursday_pof_average) ? 10 : thursday_pof_average, na(friday_pof_average) ? 10 : friday_pof_average, na(saturday_pof_average) ? 10 : saturday_pof_average, na(sunday_pof_average) ? 10 : sunday_pof_average)
out = input_day == lowest ? true : false
monday_pof_average_colour = max_pof_average(monday_pof_average) ? box_hi : min_pof_average(monday_pof_average) ? box_min : box_col
monday_pof_colour = max_pof(monday_pof) ? box_hi : min_pof(monday_pof) ? box_min : box_col
tuesday_pof_average_colour = max_pof_average(tuesday_pof_average) ? box_hi : min_pof_average(tuesday_pof_average) ? box_min : box_col
tuesday_pof_colour = max_pof(tuesday_pof) ? box_hi : min_pof(tuesday_pof) ? box_min : box_col
wednesday_pof_average_colour = max_pof_average(wednesday_pof_average) ? box_hi : min_pof_average(wednesday_pof_average) ? box_min : box_col
wednesday_pof_colour = max_pof(wednesday_pof) ? box_hi : min_pof(wednesday_pof) ? box_min : box_col
thursday_pof_average_colour = max_pof_average(thursday_pof_average) ? box_hi : min_pof_average(thursday_pof_average) ? box_min : box_col
thursday_pof_colour = max_pof(thursday_pof) ? box_hi : min_pof(thursday_pof) ? box_min : box_col
friday_pof_average_colour = max_pof_average(friday_pof_average) ? box_hi : min_pof_average(friday_pof_average) ? box_min : box_col
friday_pof_colour = max_pof(friday_pof) ? box_hi : min_pof(friday_pof) ? box_min : box_col
saturday_pof_average_colour = max_pof_average(saturday_pof_average) ? box_hi : min_pof_average(saturday_pof_average) ? box_min : box_col
saturday_pof_colour = max_pof(saturday_pof) ? box_hi : min_pof(saturday_pof) ? box_min : box_col
sunday_pof_average_colour = max_pof_average(sunday_pof_average) ? box_hi : min_pof_average(sunday_pof_average) ? box_min : box_col
sunday_pof_colour = max_pof(sunday_pof) ? box_hi : min_pof(sunday_pof) ? box_min : box_col
var tbl = table.new(location(), 2, 14)
if barstate.islast
table.cell(tbl, 0, 0, "Monday POF Average", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 1, "Monday POF", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 2, "Tuesday POF Average", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 3, "Tuesday POF", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 4, "Wednesday POF Average", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 5, "Wednesday POF", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 6, "Thursday POF Average", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 7, "Thursday POF", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 8, "Friday POF Average", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 9, "Friday POF", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 10, "Saturday POF Average", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 11, "Saturday POF", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 12, "Sunday POF Average", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 0, 13, "Sunday POF", text_color = txt_col, bgcolor = box_col)
table.cell(tbl, 1, 0, str.tostring(math.round(monday_pof_average, 4)), text_color = txt_col, bgcolor = monday_pof_average_colour)
table.cell(tbl, 1, 1, str.tostring(math.round(monday_pof, 4)), text_color = txt_col, bgcolor = monday_pof_colour)
table.cell(tbl, 1, 2, str.tostring(math.round(tuesday_pof_average, 4)), text_color = txt_col, bgcolor = tuesday_pof_average_colour)
table.cell(tbl, 1, 3, str.tostring(math.round(tuesday_pof, 4)), text_color = txt_col, bgcolor = tuesday_pof_colour)
table.cell(tbl, 1, 4, str.tostring(math.round(wednesday_pof_average, 4)), text_color = txt_col, bgcolor = wednesday_pof_average_colour)
table.cell(tbl, 1, 5, str.tostring(math.round(wednesday_pof, 4)), text_color = txt_col, bgcolor = wednesday_pof_colour)
table.cell(tbl, 1, 6, str.tostring(math.round(thursday_pof_average, 4)), text_color = txt_col, bgcolor = thursday_pof_average_colour)
table.cell(tbl, 1, 7, str.tostring(math.round(thursday_pof, 4)), text_color = txt_col, bgcolor = thursday_pof_colour)
table.cell(tbl, 1, 8, str.tostring(math.round(friday_pof_average, 4)), text_color = txt_col, bgcolor = friday_pof_average_colour)
table.cell(tbl, 1, 9, str.tostring(math.round(friday_pof, 4)), text_color = txt_col, bgcolor = friday_pof_colour)
table.cell(tbl, 1, 10,str.tostring(math.round(saturday_pof_average, 4)) , text_color = txt_col, bgcolor = saturday_pof_average_colour)
table.cell(tbl, 1, 11,str.tostring(math.round(saturday_pof, 4)) , text_color = txt_col, bgcolor = saturday_pof_colour)
table.cell(tbl, 1, 12,str.tostring(math.round(sunday_pof_average, 4)) , text_color = txt_col, bgcolor = sunday_pof_average_colour)
table.cell(tbl, 1, 13,str.tostring(math.round(sunday_pof, 4)) , text_color = txt_col, bgcolor = sunday_pof_colour)
|
Prior day and pre-market high low | https://www.tradingview.com/script/Iev9qjV6-Prior-day-and-pre-market-high-low/ | nkwdesmond | https://www.tradingview.com/u/nkwdesmond/ | 453 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © nkwdesmond
//@version=5
indicator('Price levels: Prior day, pre-market, after-hour high low; prior day open close; daily open', 'Price levels', overlay=true)
levelSettingOption = input.string('Individual level for each day', title='Display', options=['Individual level for each day', 'Most recent level on most recent day', 'Most recent level across the chart'], group='Price level')
levelSetting = levelSettingOption == 'Most recent level on most recent day' ? 'b' : levelSettingOption == 'Most recent level across the chart' ? 'c' : 'a'
pmHighLevel = input.bool(true, title='Pre-market high', group='Price level', inline='pmHigh')
pmLowLevel = input.bool(true, title='Pre-market low', group='Price level', inline='pmLow')
priorHighLevel = input.bool(true, title='Prior day high', group='Price level', inline='priorHigh')
priorLowLevel = input.bool(true, title='Prior day low', group='Price level', inline='priorLow')
priorOpenLevel = input.bool(false, title='Prior day open', group='Price level', inline='priorOpen')
priorCloseLevel = input.bool(false, title='Prior day close', group='Price level', inline='priorClose')
currentOpenLevel = input.bool(false, title='Current day open', group='Price level', inline='currentOpen')
afterHighLevel = input.bool(false, title='After-hour high', group='Price level', inline='afterHigh')
afterLowLevel = input.bool(false, title='After-hour Low', group='Price level', inline='afterLow')
pmHighPrice = input.bool(true, title='Pre-market high', group='Price axis')
pmLowPrice = input.bool(true, title='Pre-market low', group='Price axis')
priorHighPrice = input.bool(true, title='Prior day high', group='Price axis')
priorLowPrice = input.bool(true, title='Prior day low', group='Price axis')
priorOpenPrice = input.bool(false, title='Prior day open', group='Price axis')
priorClosePrice = input.bool(false, title='Prior day close', group='Price axis')
currentOpenPrice = input.bool(false, title='Current day open', group='Price axis')
afterHighPrice = input.bool(false, title='After-hour high', group='Price axis')
afterLowPrice = input.bool(false, title='After-hour Low', group='Price axis')
pmHighLabelBool = input.bool(true, title='Pre-market high', group='Label', inline='pmHigh')
pmLowLabelBool = input.bool(true, title='Pre-market low', group='Label', inline='pmLow')
priorHighLabelBool = input.bool(true, title='Prior day high', group='Label', inline='priorHigh')
priorLowLabelBool = input.bool(true, title='Prior day low', group='Label', inline='priorLow')
priorOpenLabelBool = input.bool(false, title='Prior day open', group='Label', inline='priorOpen')
priorCloseLabelBool = input.bool(false, title='Prior day close', group='Label', inline='priorClose')
currentOpenLabelBool = input.bool(false, title='Current open', group='Label', inline='currentOpen')
afterHighLabelBool = input.bool(false, title='After-hour high', group='Label', inline='afterHigh')
afterLowLabelBool = input.bool(false, title='After-hour Low', group='Label', inline='afterLow')
off = input.int(1, title='Label offset from last bar', group='Label')
pmHighLabelAlignOption = input.string('align left', title='', options=['align left', 'align center', 'align right'], group='Label', inline='pmHigh')
pmLowLabelAlignOption = input.string('align left', title='', options=['align left', 'align center', 'align right'], group='Label', inline='pmLow')
priorHighLabelAlignOption = input.string('align left', title='', options=['align left', 'align center', 'align right'], group='Label', inline='priorHigh')
priorLowLabelAlignOption = input.string('align left', title='', options=['align left', 'align center', 'align right'], group='Label', inline='priorLow')
priorOpenLabelAlignOption = input.string('align left', title='', options=['align left', 'align center', 'align right'], group='Label', inline='priorOpen')
priorCloseLabelAlignOption = input.string('align left', title='', options=['align left', 'align center', 'align right'], group='Label', inline='priorClose')
currentOpenLabelAlignOption = input.string('align left', title='', options=['align left', 'align center', 'align right'], group='Label', inline='currentOpen')
afterHighLabelAlignOption = input.string('align left', title='', options=['align left', 'align center', 'align right'], group='Label', inline='afterHigh')
afterLowLabelAlignOption = input.string('align left', title='', options=['align left', 'align center', 'align right'], group='Label', inline='afterLow')
pmHighLabelAlign = pmHighLabelAlignOption == 'align left' ? text.align_left : pmHighLabelAlignOption == 'align center' ? text.align_center : text.align_right
pmLowLabelAlign = pmLowLabelAlignOption == 'align left' ? text.align_left : pmLowLabelAlignOption == 'align center' ? text.align_center : text.align_right
priorHighLabelAlign = priorHighLabelAlignOption == 'align left' ? text.align_left : priorHighLabelAlignOption == 'align center' ? text.align_center : text.align_right
priorLowLabelAlign = priorLowLabelAlignOption == 'align left' ? text.align_left : priorLowLabelAlignOption == 'align center' ? text.align_center : text.align_right
priorOpenLabelAlign = priorOpenLabelAlignOption == 'align left' ? text.align_left : priorOpenLabelAlignOption == 'align center' ? text.align_center : text.align_right
priorCloseLabelAlign = priorCloseLabelAlignOption == 'align left' ? text.align_left : priorCloseLabelAlignOption == 'align center' ? text.align_center : text.align_right
currentOpenLabelAlign = currentOpenLabelAlignOption == 'align left' ? text.align_left : currentOpenLabelAlignOption == 'align center' ? text.align_center : text.align_right
afterHighLabelAlign = afterHighLabelAlignOption == 'align left' ? text.align_left : afterHighLabelAlignOption == 'align center' ? text.align_center : text.align_right
afterLowLabelAlign = afterLowLabelAlignOption == 'align left' ? text.align_left : afterLowLabelAlignOption == 'align center' ? text.align_center : text.align_right
pmHighLabelText = input.string('PM high', title='Text', group='Label', inline='pmHigh')
pmLowLabelText = input.string('PM low', title='Text', group='Label', inline='pmLow')
priorHighLabelText = input.string('Prior day high', title='Text', group='Label', inline='priorHigh')
priorLowLabelText = input.string('Prior day low', title='Text', group='Label', inline='priorLow')
priorOpenLabelText = input.string('Prior day open', title='Text', group='Label', inline='priorOpen')
priorCloseLabelText = input.string('Prior day close', title='Text', group='Label', inline='priorClose')
currentOpenLabelText = input.string('Open', title='Text', group='Label', inline='currentOpen')
afterHighLabelText = input.string('AM high', title='Text', group='Label', inline='afterHigh')
afterLowLabelText = input.string('AM low', title='Text', group='Label', inline='afterLow')
pmHighLabelTextColour = input(title='', defval=#000000, group='Label', inline='pmHigh')
pmLowLabelTextColour = input(title='', defval=#000000, group='Label', inline='pmLow')
priorHighLabelTextColour = input(title='', defval=#000000, group='Label', inline='priorHigh')
priorLowLabelTextColour = input(title='', defval=#000000, group='Label', inline='priorLow')
priorOpenLabelTextColour = input(title='', defval=#000000, group='Label', inline='priorOpen')
priorCloseLabelTextColour = input(title='', defval=#000000, group='Label', inline='priorClose')
currentOpenLabelTextColour = input(title='', defval=#000000, group='Label', inline='currentOpen')
afterHighLabelTextColour = input(title='', defval=#000000, group='Label', inline='afterHigh')
afterLowLabelTextColour = input(title='', defval=#ffffff, group='Label', inline='afterLow')
secondBool = input.bool(true, title='Seconds', group='Price axis visibility', inline='second')
minuteBool = input.bool(true, title='Minutes', group='Price axis visibility', inline='minute')
hourBool = input.bool(false, title='Hours', group='Price axis visibility', inline='hour')
dayBool = input.bool(false, title='Days', group='Price axis visibility', inline='day')
weekBool = input.bool(false, title='Weeks', group='Price axis visibility', inline='week')
monthBool = input.bool(false, title='Months', group='Price axis visibility', inline='month')
noPeriodBool = input.bool(false, title='No alert period', group='No alert period', inline='period', tooltip='Time period where alerts will not be triggered')
noPeriod = input.session('0930-0935', title='', group='No alert period', inline='period')
t = time(timeframe.period, noPeriod)
alertbool = not (noPeriodBool and t)
secondMin = input.int(1, '', 1, 59, group='Price axis visibility', inline='second')
secondMax = input.int(59, '-', 1, 59, group='Price axis visibility', inline='second')
minuteMin = input.int(1, '', 1, 59, group='Price axis visibility', inline='minute')
minuteMax = input.int(5, '-', 1, 59, group='Price axis visibility', inline='minute')
hourMin = input.int(1, '', 1, 24, group='Price axis visibility', inline='hour')
hourMax = input.int(24, '-', 1, 24, group='Price axis visibility', inline='hour')
dayMin = input.int(1, '', 1, 366, group='Price axis visibility', inline='day')
dayMax = input.int(366, '-', 1, 366, group='Price axis visibility', inline='day')
weekMin = input.int(1, '', 1, 52, group='Price axis visibility', inline='week')
weekMax = input.int(52, '-', 1, 52, group='Price axis visibility', inline='week')
monthMin = input.int(1, '', 1, 12, group='Price axis visibility', inline='month')
monthMax = input.int(12, '-', 1, 12, group='Price axis visibility', inline='month')
timeframeNumberstr = str.match(timeframe.period, '[0-9]*')
timeframeNumber = str.tonumber(timeframeNumberstr)
timeframeLetter = str.match(timeframe.period, '[A-Z]')
bool timeframePlot = false
if secondBool and timeframeLetter=='S' and secondMin<=timeframeNumber and secondMax>=timeframeNumber
timeframePlot := true
if minuteBool and timeframeLetter=='' and minuteMin<=timeframeNumber and minuteMax>=timeframeNumber
timeframePlot := true
if hourBool and timeframeLetter=='' and hourMin*60<=timeframeNumber and hourMax*60>=timeframeNumber
timeframePlot := true
if dayBool and timeframeLetter=='D' and dayMin<=timeframeNumber and dayMax>=timeframeNumber
timeframePlot := true
if weekBool and timeframeLetter=='W' and weekMin<=timeframeNumber and weekMax>=timeframeNumber
timeframePlot := true
if monthBool and timeframeLetter=='M' and monthMin<=timeframeNumber and monthMax>=timeframeNumber
timeframePlot := true
pmHighColour = input(title='', defval=#81c583, group='Price level', inline='pmHigh')
pmLowColour = input(title='', defval=#ee9899, group='Price level', inline='pmLow')
priorHighColour = input(title='', defval=#00ff00, group='Price level', inline='priorHigh')
priorLowColour = input(title='', defval=#ff80ff, group='Price level', inline='priorLow')
priorOpenColour = input(title='', defval=#ffb54e, group='Price level', inline='priorOpen')
priorCloseColour = input(title='', defval=#00ffff, group='Price level', inline='priorClose')
currentOpenColour = input(title='', defval=#ffff00, group='Price level', inline='currentOpen')
afterHighColour = input(title='', defval=#80ffbb, group='Price level', inline='afterHigh')
afterLowColour = input(title='', defval=#8080ff, group='Price level', inline='afterLow')
pmHighLineWidth = input(1, 'Thickness', group='Price level', inline='pmHigh')
pmLowLineWidth = input(1, 'Thickness', group='Price level', inline='pmLow')
priorHighLineWidth = input(1, 'Thickness', group='Price level', inline='priorHigh')
priorLowLineWidth = input(1, 'Thickness', group='Price level', inline='priorLow')
priorOpenLineWidth = input(1, 'Thickness', group='Price level', inline='priorOpen')
priorCloseLineWidth = input(1, 'Thickness', group='Price level', inline='priorClose')
currentOpenLineWidth = input(1, 'Thickness', group='Price level', inline='currentOpen')
afterHighLineWidth = input(1, 'Thickness', group='Price level', inline='afterHigh')
afterLowLineWidth = input(1, 'Thickness', group='Price level', inline='afterLow')
pmHighStyleOption = input.string('solid (─)', title='', options=['solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)'], group='Price level', inline='pmHigh')
pmLowStyleOption = input.string('solid (─)', title='', options=['solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)'], group='Price level', inline='pmLow')
priorHighStyleOption = input.string('solid (─)', title='', options=['solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)'], group='Price level', inline='priorHigh')
priorLowStyleOption = input.string('solid (─)', title='', options=['solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)'], group='Price level', inline='priorLow')
priorOpenStyleOption = input.string('solid (─)', title='', options=['solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)'], group='Price level', inline='priorOpen')
priorCloseStyleOption = input.string('solid (─)', title='', options=['solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)'], group='Price level', inline='priorClose')
currentOpenStyleOption = input.string('solid (─)', title='', options=['solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)'], group='Price level', inline='currentOpen')
afterHighStyleOption = input.string('solid (─)', title='', options=['solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)'], group='Price level', inline='afterHigh')
afterLowStyleOption = input.string('solid (─)', title='', options=['solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)'], group='Price level', inline='afterLow')
pmHighLineStyle = pmHighStyleOption == 'dotted (┈)' ? line.style_dotted : pmHighStyleOption == 'dashed (╌)' ? line.style_dashed : pmHighStyleOption == 'arrow left (←)' ? line.style_arrow_left :
pmHighStyleOption == 'arrow right (→)' ? line.style_arrow_right : pmHighStyleOption == 'arrows both (↔)' ? line.style_arrow_both : line.style_solid
pmLowLineStyle = pmLowStyleOption == 'dotted (┈)' ? line.style_dotted : pmLowStyleOption == 'dashed (╌)' ? line.style_dashed : pmLowStyleOption == 'arrow left (←)' ? line.style_arrow_left :
pmLowStyleOption == 'arrow right (→)' ? line.style_arrow_right : pmLowStyleOption == 'arrows both (↔)' ? line.style_arrow_both : line.style_solid
priorHighLineStyle = priorHighStyleOption == 'dotted (┈)' ? line.style_dotted : priorHighStyleOption == 'dashed (╌)' ? line.style_dashed : priorHighStyleOption == 'arrow left (←)' ? line.style_arrow_left :
priorHighStyleOption == 'arrow right (→)' ? line.style_arrow_right : priorHighStyleOption == 'arrows both (↔)' ? line.style_arrow_both : line.style_solid
priorLowLineStyle = priorLowStyleOption == 'dotted (┈)' ? line.style_dotted : priorLowStyleOption == 'dashed (╌)' ? line.style_dashed : priorLowStyleOption == 'arrow left (←)' ? line.style_arrow_left :
priorLowStyleOption == 'arrow right (→)' ? line.style_arrow_right : priorLowStyleOption == 'arrows both (↔)' ? line.style_arrow_both : line.style_solid
priorOpenLineStyle = priorOpenStyleOption == 'dotted (┈)' ? line.style_dotted : priorOpenStyleOption == 'dashed (╌)' ? line.style_dashed : priorOpenStyleOption == 'arrow left (←)' ? line.style_arrow_left :
priorOpenStyleOption == 'arrow right (→)' ? line.style_arrow_right : priorOpenStyleOption == 'arrows both (↔)' ? line.style_arrow_both : line.style_solid
priorCloseLineStyle = priorCloseStyleOption == 'dotted (┈)' ? line.style_dotted : priorCloseStyleOption == 'dashed (╌)' ? line.style_dashed : priorCloseStyleOption == 'arrow left (←)' ? line.style_arrow_left :
priorCloseStyleOption == 'arrow right (→)' ? line.style_arrow_right : priorCloseStyleOption == 'arrows both (↔)' ? line.style_arrow_both : line.style_solid
currentOpenLineStyle = currentOpenStyleOption == 'dotted (┈)' ? line.style_dotted : currentOpenStyleOption == 'dashed (╌)' ? line.style_dashed : currentOpenStyleOption == 'arrow left (←)' ? line.style_arrow_left :
currentOpenStyleOption == 'arrow right (→)' ? line.style_arrow_right : currentOpenStyleOption == 'arrows both (↔)' ? line.style_arrow_both : line.style_solid
afterHighLineStyle = afterHighStyleOption == 'dotted (┈)' ? line.style_dotted : afterHighStyleOption == 'dashed (╌)' ? line.style_dashed : afterHighStyleOption == 'arrow left (←)' ? line.style_arrow_left :
afterHighStyleOption == 'arrow right (→)' ? line.style_arrow_right : afterHighStyleOption == 'arrows both (↔)' ? line.style_arrow_both : line.style_solid
afterLowLineStyle = afterLowStyleOption == 'dotted (┈)' ? line.style_dotted : afterLowStyleOption == 'dashed (╌)' ? line.style_dashed : afterLowStyleOption == 'arrow left (←)' ? line.style_arrow_left :
afterLowStyleOption == 'arrow right (→)' ? line.style_arrow_right : afterLowStyleOption == 'arrows both (↔)' ? line.style_arrow_both : line.style_solid
var line pmHighLine = na
var line pmLowLine = na
var line priorHighLine = na
var line priorLowLine = na
var line priorOpenLine = na
var line priorCloseLine = na
var line currentOpenLine = na
var line afterHighLine = na
var line afterLowLine = na
var float pmHigh = na
var float pmLow = na
var float priorHigh = na
var float priorLow = na
var float priorOpen = na
var float priorClose = na
var float currentHigh = na
var float currentLow = na
var float currentOpen = na
var float currentClose = na
var float afterHigh = na
var float afterLow = na
var label pmHighLabel = na
var label pmLowLabel = na
var label priorHighLabel = na
var label priorLowLabel = na
var label priorOpenLabel = na
var label priorCloseLabel = na
var label currentOpenLabel = na
var label afterHighLabel = na
var label afterLowLabel = na
if session.isfirstbar and session.ispremarket // initialize pmHigh and pmLow for new day
pmHigh := high
pmLow := low
// var float temp = na
// array <float> test = request.security_lower_tf(syminfo.tickerid,'1',high)
// if array.size(test)>0 and time('1','0400-0859','UTC-4') // time condition does not work because request.security_lower_tf will take all prices in the completed candle
// temp := array.max(test)
if high > pmHigh and session.ispremarket
pmHigh := high
line.set_y1(pmHighLine, pmHigh) // shift pmHigh in real-time
line.set_y2(pmHighLine, pmHigh)
label.set_y(pmHighLabel, pmHigh)
if low < pmLow and session.ispremarket
pmLow := low
line.set_y1(pmLowLine, pmLow) // shift pmLow in real-time
line.set_y2(pmLowLine, pmLow)
label.set_y(pmLowLabel, pmLow)
currentOpen := request.security(syminfo.tickerid,'D',open,lookahead=barmerge.lookahead_on)
if not session.isfirstbar_regular
currentOpen := currentOpen[1]
if session.isfirstbar_regular
// currentHigh := high
// currentLow := low
// currentOpen := open
line.set_extend(currentOpenLine, extend.none) // currentOpen line should only be drawn starting from first regular bar
if levelSetting!='a'
line.delete(currentOpenLine)
label.delete(currentOpenLabel)
if timeframe.isintraday
if currentOpenLevel
currentOpenLine := line.new(bar_index, currentOpen, bar_index, currentOpen, color=currentOpenColour, style=currentOpenLineStyle, width=currentOpenLineWidth, extend=levelSetting=='c' ? extend.both : extend.right)
if currentOpenLabelBool
currentOpenLabel := label.new(bar_index + off, currentOpen, text=currentOpenLabelText, color=currentOpenColour, style=label.style_label_left, textcolor=currentOpenLabelTextColour, size=size.normal, textalign=currentOpenLabelAlign)
if high > currentHigh and session.ismarket
currentHigh := high // update currentHigh
if low < currentLow and session.ismarket
currentLow := low // update currentLow
if session.ismarket
currentClose := close // update currentClose
if session.ispostmarket and session.ispostmarket[1] == false // initialize after-hour prices for the day
afterHigh := high
afterLow := low
if session.ispostmarket and high > afterHigh
afterHigh := high
line.set_y1(afterHighLine, afterHigh) // shift afterHigh in real-time
line.set_y2(afterHighLine, afterHigh)
label.set_y(afterHighLabel, afterLow)
if session.ispostmarket and low < afterLow
afterLow := low
line.set_y1(afterLowLine, afterLow) // shift afterHigh in real-time
line.set_y2(afterLowLine, afterLow)
label.set_y(afterLowLabel, afterLow)
if session.ispostmarket and session.ispostmarket[1] == false
line.set_extend(afterHighLine, extend.none) // afterhourlines should only be drawn starting from first after-hour bar
line.set_extend(afterLowLine, extend.none)
if levelSetting!='a'
line.delete(afterHighLine)
line.delete(afterLowLine)
label.delete(afterLowLabel)
label.delete(afterHighLabel)
if timeframe.isintraday
if afterHighLevel
afterHighLine := line.new(bar_index, afterHigh, bar_index, afterHigh, color=afterHighColour, style=afterHighLineStyle, width=afterHighLineWidth, extend=levelSetting=='c' ? extend.both : extend.right)
if afterHighLabelBool
afterHighLabel := label.new(bar_index + off, afterHigh, text=afterHighLabelText, color=afterHighColour, style=label.style_label_left, textcolor=afterHighLabelTextColour, size=size.normal, textalign=afterHighLabelAlign)
if afterLowLevel
afterLowLine := line.new(bar_index, afterLow, bar_index, afterLow, color=afterLowColour, style=afterLowLineStyle, width=afterLowLineWidth, extend=levelSetting=='c' ? extend.both : extend.right)
if afterLowLabelBool
afterLowLabel := label.new(bar_index + off, afterLow, text=afterLowLabelText, color=afterLowColour, style=label.style_label_left, textcolor=afterLowLabelTextColour, size=size.normal, textalign=afterLowLabelAlign)
// priorHigh := request.security(syminfo.tickerid,'D',session.isfirstbar?(syminfo.session==session.extended?high:high[1]):priorHigh,lookahead=barmerge.lookahead_on)
priorHigh := request.security(syminfo.tickerid,'D',(syminfo.session==session.extended?high:high[1]),lookahead=barmerge.lookahead_on) // session.isfirstbar does not work here
priorLow := request.security(syminfo.tickerid,'D',(syminfo.session==session.extended?low:low[1]),lookahead=barmerge.lookahead_on)
priorOpen := request.security(syminfo.tickerid,'D',(syminfo.session==session.extended?open:open[1]),lookahead=barmerge.lookahead_on)
priorClose := request.security(syminfo.tickerid,'D',(syminfo.session==session.extended?close:close[1]),lookahead=barmerge.lookahead_on)
if not session.isfirstbar
priorHigh := priorHigh[1]
priorLow := priorLow[1]
priorOpen := priorOpen[1]
priorClose := priorClose[1]
if session.isfirstbar
line.set_extend(pmHighLine, extend.none) // so that lines from prior days will not extend right to price axis
line.set_extend(pmLowLine, extend.none)
line.set_extend(priorHighLine, extend.none)
line.set_extend(priorLowLine, extend.none)
line.set_extend(priorOpenLine, extend.none)
line.set_extend(priorCloseLine, extend.none)
// priorHigh := currentHigh[1] // since this is first bar, the previous value will be that of prior day
// priorLow := currentLow[1]
// priorOpen := currentOpen[1]
// priorClose := currentClose[1]
if levelSetting!='a' // delete the old lines if option 'a' is not selected
line.delete(pmHighLine)
line.delete(pmLowLine)
line.delete(priorHighLine)
line.delete(priorLowLine)
line.delete(priorOpenLine)
line.delete(priorCloseLine)
label.delete(pmHighLabel)
label.delete(pmLowLabel)
label.delete(priorHighLabel)
label.delete(priorLowLabel)
label.delete(priorOpenLabel)
label.delete(priorCloseLabel)
if timeframe.isintraday
if pmHighLevel
pmHighLine := line.new(bar_index, pmHigh, bar_index, pmHigh, color=pmHighColour, style=pmHighLineStyle, width=pmHighLineWidth, extend=levelSetting=='c' ? extend.both : extend.right)
if pmHighLabelBool
pmHighLabel := label.new(bar_index + off, pmHigh, text=pmHighLabelText, color=pmHighColour, style=label.style_label_left, textcolor=pmHighLabelTextColour, size=size.normal, textalign=pmHighLabelAlign)
if pmLowLevel
pmLowLine := line.new(bar_index, pmLow, bar_index, pmLow, color=pmLowColour, style=pmLowLineStyle, width=pmLowLineWidth, extend=levelSetting=='c' ? extend.both : extend.right)
if pmLowLabelBool
pmLowLabel := label.new(bar_index + off, pmLow, text=pmLowLabelText, color=pmLowColour, style=label.style_label_left, textcolor=pmLowLabelTextColour, size=size.normal, textalign=pmLowLabelAlign)
if priorHighLevel
priorHighLine := line.new(bar_index, priorHigh, bar_index, priorHigh, color=priorHighColour, style=priorHighLineStyle, width=priorHighLineWidth, extend=levelSetting=='c' ? extend.both : extend.right)
if priorHighLabelBool
priorHighLabel := label.new(bar_index + off, priorHigh, text=priorHighLabelText, color=priorHighColour, style=label.style_label_left, textcolor=priorHighLabelTextColour, size=size.normal, textalign=priorHighLabelAlign)
if priorLowLevel
priorLowLine := line.new(bar_index, priorLow, bar_index, priorLow, color=priorLowColour, style=priorLowLineStyle, width=priorLowLineWidth, extend=levelSetting=='c' ? extend.both : extend.right)
if priorLowLabelBool
priorLowLabel := label.new(bar_index + off, priorLow, text=priorLowLabelText, color=priorLowColour, style=label.style_label_left, textcolor=priorLowLabelTextColour, size=size.normal, textalign=priorLowLabelAlign)
if priorOpenLevel
priorOpenLine := line.new(bar_index, priorOpen, bar_index, priorOpen, color=priorOpenColour, style=priorOpenLineStyle, width=priorOpenLineWidth, extend=levelSetting=='c' ? extend.both : extend.right)
if priorOpenLabelBool
priorOpenLabel := label.new(bar_index + off, priorOpen, text=priorOpenLabelText, color=priorOpenColour, style=label.style_label_left, textcolor=priorOpenLabelTextColour, size=size.normal, textalign=priorOpenLabelAlign)
if priorCloseLevel
priorCloseLine := line.new(bar_index, priorClose, bar_index, priorClose, color=priorCloseColour, style=priorCloseLineStyle, width=priorCloseLineWidth, extend=levelSetting=='c' ? extend.both : extend.right)
if priorCloseLabelBool
priorCloseLabel := label.new(bar_index + off, priorClose, text=priorCloseLabelText, color=priorCloseColour, style=label.style_label_left, textcolor=priorCloseLabelTextColour, size=size.normal, textalign=priorCloseLabelAlign)
line.set_x2(pmHighLine, bar_index)
line.set_x2(pmLowLine, bar_index)
line.set_x2(priorHighLine, bar_index)
line.set_x2(priorLowLine, bar_index)
line.set_x2(priorOpenLine, bar_index)
line.set_x2(priorCloseLine, bar_index)
if not session.ispremarket
line.set_x2(currentOpenLine, bar_index) // currentOpen should not be drawn during premarket
line.set_x2(afterHighLine, bar_index)
line.set_x2(afterLowLine, bar_index)
label.set_x(pmHighLabel, bar_index + off)
label.set_x(pmLowLabel, bar_index + off)
label.set_x(priorHighLabel, bar_index + off)
label.set_x(priorLowLabel, bar_index + off)
label.set_x(priorOpenLabel, bar_index + off)
label.set_x(priorCloseLabel, bar_index + off)
label.set_x(currentOpenLabel, bar_index + off)
label.set_x(afterHighLabel, bar_index + off)
label.set_x(afterLowLabel, bar_index + off)
plot(timeframe.isintraday and pmHighPrice and timeframePlot ? pmHigh : na, color=pmHighColour, editable=false, display=display.price_scale) // plot the value on price axis without the line
plot(timeframe.isintraday and pmLowPrice and timeframePlot? pmLow : na, color=pmLowColour, editable=false, display=display.price_scale)
plot(timeframe.isintraday and priorHighPrice and timeframePlot ? priorHigh : na, color=priorHighColour, editable=false, display=display.price_scale)
plot(timeframe.isintraday and priorLowPrice and timeframePlot ? priorLow : na, color=priorLowColour, editable=false, display=display.price_scale)
plot(timeframe.isintraday and priorOpenPrice and timeframePlot ? priorOpen : na, color=priorOpenColour, editable=false, display=display.price_scale)
plot(timeframe.isintraday and priorClosePrice and timeframePlot ? priorClose : na, color=priorCloseColour, editable=false, display=display.price_scale)
plot(timeframe.isintraday and currentOpenPrice and timeframePlot ? currentOpen : na, color=currentOpenColour, editable=false, display=display.price_scale)
plot(timeframe.isintraday and afterHighPrice and timeframePlot ? afterHigh : na, color=afterHighColour, editable=false, display=display.price_scale)
plot(timeframe.isintraday and afterLowPrice and timeframePlot ? afterLow : na, color=afterLowColour, editable=false, display=display.price_scale)
// plotshape(timeframe.isintraday and afterLowLabelBool and timeframePlot ? afterLow : na, style=shape.labeldown, location=location.absolute, color=afterLowColour, offset=6, text="afterLow", textcolor=#ffffff, editable=false, show_last=1, display=display.pane)
alertcondition(alertbool and session.ismarket and close>=pmHigh and close[1]<pmHigh, title='Cross abv pm high (do not use Once Per Bar Close)', message='Price crossed above pre-market high!')
alertcondition(alertbool and session.ismarket and close<=pmLow and close[1]>pmLow, title='Cross blw pm low (do not use Once Per Bar Close)', message='Price crossed below pre-market low!')
alertcondition(alertbool and session.ismarket and close>=pmHigh and open<pmHigh, title='Close abv pm high (use Once Per Bar Close)', message='Price closed above pre-market high!')
alertcondition(alertbool and session.ismarket and close<=pmLow and open>pmLow, title='Close blw pm low (use Once Per Bar Close)', message='Price closed below pre-market low!')
// label.new(bar_index, pmHigh, text=str.tostring(pmHigh))
// plot(pmHigh, style=plot.style_linebr, color=#81c583, linewidth=1)
// plot(pmLow, style=plot.style_linebr, color=#ee9899, linewidth=1)
// plot(high, style=plot.style_linebr, color=#ffff00, linewidth=1)
// plot(priorLow, style=plot.style_linebr, color=#ff0000, linewidth=1) |
[@btc_charlie] Trader XO Macro Trend Scanner | https://www.tradingview.com/script/Q95qqFgC-btc-charlie-Trader-XO-Macro-Trend-Scanner/ | btc_charlie | https://www.tradingview.com/u/btc_charlie/ | 3,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/
// © btc_charlie / @TheParagonGrp
//@version=5
indicator('[@btc_charlie] Trader XO Macro Trend Scanner', overlay=true)
// Variables
var ok = 0
var countBuy = 0
var countSell = 0
src = input(close, title='OHLC Type')
i_fastEMA = input(12, title='Fast EMA')
i_slowEMA = input(25, title='Slow EMA')
i_defEMA = input(25, title='Consolidated EMA')
// Allow the option to show single or double EMA
i_bothEMAs = input(title='Show Both EMAs', defval=true)
// Define EMAs
v_fastEMA = ta.ema(src, i_fastEMA)
v_slowEMA = ta.ema(src, i_slowEMA)
v_biasEMA = ta.ema(src, i_defEMA)
// Color the EMAs
emaColor = v_fastEMA > v_slowEMA ? color.green : v_fastEMA < v_slowEMA ? color.red : #FF530D
// Plot EMAs
plot(i_bothEMAs ? na : v_biasEMA, color=emaColor, linewidth=3, title='Consolidated EMA')
plot(i_bothEMAs ? v_fastEMA : na, title='Fast EMA', color=emaColor)
plot(i_bothEMAs ? v_slowEMA : na, title='Slow EMA', color=emaColor)
// Colour the bars
buy = v_fastEMA > v_slowEMA
sell = v_fastEMA < v_slowEMA
if buy
countBuy += 1
countBuy
if buy
countSell := 0
countSell
if sell
countSell += 1
countSell
if sell
countBuy := 0
countBuy
buysignal = countBuy < 2 and countBuy > 0 and countSell < 1 and buy and not buy[1]
sellsignal = countSell > 0 and countSell < 2 and countBuy < 1 and sell and not sell[1]
barcolor(buysignal ? color.green : na)
barcolor(sellsignal ? color.red : na)
// Plot Bull/Bear
plotshape(buysignal, title='Bull', text='Bull', style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), textcolor=color.new(color.black, 0), size=size.tiny)
plotshape(sellsignal, title='Bear', text='Bear', style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.black, 0), size=size.tiny)
bull = countBuy > 1
bear = countSell > 1
barcolor(bull ? color.green : na)
barcolor(bear ? color.red : na)
// Set Alerts
alertcondition(ta.crossover(v_fastEMA, v_slowEMA), title='Bullish EMA Cross', message='Bullish EMA crossover')
alertcondition(ta.crossunder(v_fastEMA, v_slowEMA), title='Bearish EMA Cross', message='Bearish EMA Crossover')
// Stoch RSI code
smoothK = input.int(3, 'K', minval=1)
smoothD = input.int(3, 'D', minval=1)
lengthRSI = input.int(14, 'RSI Length', minval=1)
lengthStoch = input.int(14, 'Stochastic Length', minval=1)
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
bandno0 = input.int(80, minval=1, title='Upper Band', group='Bands (change this instead of length in Style for Stoch RSI colour to work properly)')
bandno2 = input.int(50, minval=1, title='Middle Band', group='Bands (change this instead of length in Style for Stoch RSI colour to work properly)')
bandno1 = input.int(20, minval=1, title='Lower Band', group='Bands (change this instead of length in Style for Stoch RSI colour to work properly)')
// Alerts
crossoverAlertBgColourMidOnOff = input.bool(title='Crossover Alert Background Colour (Middle Level) [ON/OFF]', group='Crossover Alerts', defval=false)
crossoverAlertBgColourOBOSOnOff = input.bool(title='Crossover Alert Background Colour (OB/OS Level) [ON/OFF]', group='Crossover Alerts', defval=false)
crossoverAlertBgColourGreaterThanOnOff = input.bool(title='Crossover Alert >input [ON/OFF]', group='Crossover Alerts', defval=false)
crossoverAlertBgColourLessThanOnOff = input.bool(title='Crossover Alert <input [ON/OFF]', group='Crossover Alerts', defval=false)
maTypeChoice = input.string('EMA', title='MA Type', group='Moving Average', options=['EMA', 'WMA', 'SMA', 'None'])
maSrc = input.source(close, title='MA Source', group='Moving Average')
maLen = input.int(200, minval=1, title='MA Length', group='Moving Average')
maValue = if maTypeChoice == 'EMA'
ta.ema(maSrc, maLen)
else if maTypeChoice == 'WMA'
ta.wma(maSrc, maLen)
else if maTypeChoice == 'SMA'
ta.sma(maSrc, maLen)
else
0
crossupCHECK = maTypeChoice == 'None' or open > maValue and maTypeChoice != 'None'
crossdownCHECK = maTypeChoice == 'None' or open < maValue and maTypeChoice != 'None'
crossupalert = crossupCHECK and ta.crossover(k, d) and (k < bandno2 or d < bandno2)
crossdownalert = crossdownCHECK and ta.crossunder(k, d) and (k > bandno2 or d > bandno2)
crossupOSalert = crossupCHECK and ta.crossover(k, d) and (k < bandno1 or d < bandno1)
crossdownOBalert = crossdownCHECK and ta.crossunder(k, d) and (k > bandno0 or d > bandno0)
aboveBandalert = ta.crossunder(k, bandno0)
belowBandalert = ta.crossover(k, bandno1)
bgcolor(color=crossupalert and crossoverAlertBgColourMidOnOff ? #4CAF50 : crossdownalert and crossoverAlertBgColourMidOnOff ? #FF0000 : na, title='Crossover Alert Background Colour (Middle Level)', transp=70)
bgcolor(color=crossupOSalert and crossoverAlertBgColourOBOSOnOff ? #fbc02d : crossdownOBalert and crossoverAlertBgColourOBOSOnOff ? #000000 : na, title='Crossover Alert Background Colour (OB/OS Level)', transp=70)
bgcolor(color=aboveBandalert and crossoverAlertBgColourGreaterThanOnOff ? #ff0014 : crossdownalert and crossoverAlertBgColourMidOnOff ? #FF0000 : na, title='Crossover Alert - K > Upper level', transp=70)
bgcolor(color=belowBandalert and crossoverAlertBgColourLessThanOnOff ? #4CAF50 : crossdownalert and crossoverAlertBgColourMidOnOff ? #FF0000 : na, title='Crossover Alert - K < Lower level', transp=70)
alertcondition(crossupalert or crossdownalert, title='Stoch RSI Crossover', message='STOCH RSI CROSSOVER')
|
DEVIATION OF THE STOCHASTIC INDICATOR | https://www.tradingview.com/script/yu523z5h/ | ceshead | https://www.tradingview.com/u/ceshead/ | 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/
// © ceshead
//@version=5
//The Stochastic Oscillator is a technical indicator created by George Lane in the
//1950s. It is used to identify potential overbought or oversold conditions in an
//asset's price by comparing its closing price to its price range over a set number of
//periods. The resulting value is displayed as a percentage between 0 and 100.
//This new technical indicator uses the stochastic oscillator as its base and calculates
//the deviation of its moving average, generating an alternative view of market volatility.
//31/01/23
indicator(title="DEVIATION OF THE STOCHASTIC INDICATOR", shorttitle="DSI", timeframe = "")
// Getting inputs
periodK = input.int(14, title="%K Length", minval=1, group="Stochastic")
smoothK = input.int(4, title="%K Smoothing", minval=1, group="Stochastic")
periodD = input.int(3, title="%D Smoothing", minval=1, group="Stochastic")
len = input(20, title="Length", group="Deviation")
smooth = input(6, title="Smooth ema", group="Deviation")
dev = input(2, title="Deviation", group="Deviation")
// Logic
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)
src = d
emaR = ta.ema(src, len)
out=(src-emaR)
fastOut=ta.ema(out,smooth)
slowOut=ta.ema(out,smooth*4)
sumaDevs=math.pow(out-slowOut,2)
smaSums=ta.sma(sumaDevs,5)
devs=dev*math.sqrt(smaSums/5)
bandUp2=slowOut+devs
bandDn2=slowOut-devs
sumaDevf=math.pow(out-fastOut,2)
smaSumf=ta.sma(sumaDevf,5)
devf=dev*math.sqrt(smaSumf/5)
bandUp=fastOut+devf
bandDn=fastOut-devf
bandDn2:=fastOut>0? 0:bandDn2
bandUp2:=fastOut<0? 0:bandUp2
bandUp:= bandUp<0? 0:bandUp
bandDn:= bandDn>0? 0:bandDn
// Colors
col_grow_above = input.color(#26A69A, group="Histogram", inline="grow_above")
col_fall_above = input.color(#B2DFDB, group="Histogram", inline="fall_above")
col_grow_below = input.color(#FFCDD2, group="Histogram", inline="grow_below")
col_fall_below = input.color(#FF5252, group="Histogram", inline="fall_below")
// Plots
plot(out, title="Histogram", style=plot.style_columns, color=(out>=0 ? (out[1] < out ? col_grow_above : col_fall_above) : (out[1] < out ? col_grow_below : col_fall_below)))
plot(bandUp, color=color.white , style=plot.style_line)
plot(bandUp2, color=color.blue)
plot(bandDn2, color=color.yellow)
plot(bandDn, color=color.white)
|
Market Sessions - By Leviathan | https://www.tradingview.com/script/hNpilzEG-Market-Sessions-By-Leviathan/ | LeviathanCapital | https://www.tradingview.com/u/LeviathanCapital/ | 3,327 | 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/
// © LeviathanCapital
//@version=5
indicator("Market Sessions - By Leviathan", overlay = true, max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500)
// Box generation code inspired by Jos(TradingCode), session box visuals inspired by @boitoki
// Session 1 - user inputs
showTokyo = input.bool(true, '', inline='Tokyo', group='Sessions')
stringTokyo = input.string('Tokyo', '', inline='Tokyo', group='Sessions')
TokyoTimeX = input.session(defval="0000-0900", title=' ', inline='Tokyo2', group='Sessions', tooltip = 'If you want to change the start/end time of the session, just make sure they are in UTC. There is no need to change the timezone of your Tradingview chart or to change the Timezone input below, because the sessions will be plotted correctly as long as the start/end time is set in UTC.')
TokyoCol = input.color(color.rgb(255, 153, 0, 90), '' , inline='Tokyo', group='Sessions')
// Session 2 - user inputs
showLondon = input.bool(true, '', inline='London', group='Sessions')
stringLondon = input.string('London', '', inline='London', group='Sessions')
LondonTimeX = input.session(defval="0700-1600", title=' ', inline='London2', group='Sessions', tooltip = 'If you want to change the start/end time of the session, just make sure they are in UTC. There is no need to change the timezone of your Tradingview chart or to change the Timezone input below, because the sessions will be plotted correctly as long as the start/end time is set in UTC.')
LondonCol = input.color(color.rgb(76, 175, 79, 90), '' , inline='London', group='Sessions')
// Session 3 - user inputs
showNewYork = input.bool(true, title='', inline='New York', group='Sessions')
stringNewYork = input.string('New York', '', inline='New York', group='Sessions')
NewYorkTimeX = input.session(defval="1300-2200", title=' ', inline='New York2', group='Sessions', tooltip = 'If you want to change the start/end time of the session, just make sure they are in UTC. There is no need to change the timezone of your Tradingview chart or to change the Timezone input below, because the sessions will be plotted correctly as long as the start/end time is set in UTC.')
NewYorkCol = input.color(color.rgb(33, 149, 243, 90), '', inline='New York', group='Sessions')
// Session 4 - user inputs
showSydney = input.bool(false, title='', inline='Sydney', group='Sessions')
stringSydney = input.string('Sydney', '', inline='Sydney', group='Sessions')
SydneyTimeX = input.session(defval="2100-0600", title=' ', inline='Sydney2', group='Sessions', tooltip = 'If you want to change the start/end time of the session, just make sure they are in UTC. There is no need to change the timezone of your Tradingview chart or to change the Timezone input below, because the sessions will be plotted correctly as long as the start/end time is set in UTC.')
SydneyCol = input.color(color.rgb(164, 97, 187, 90), '', inline='Sydney', group='Sessions')
// Additional tools and settings - user inputs
pipChange = input.bool(false, 'Change (Pips) ', inline='0', group = 'Additional Tools and Settings')
percentChange = input.bool(false, 'Change (%)', inline='0', group = 'Additional Tools and Settings')
merge = input.bool(false, 'Merge Overlaps', inline='2', group = 'Additional Tools and Settings')
hideWeekends = input.bool(true, 'Hide Weekends', inline='2', group = 'Additional Tools and Settings')
sessionOC = input.bool(true, 'Open/Close Line', inline='3', group = 'Additional Tools and Settings')
halfline = input.bool(false, 'Session 0.5 Level', inline='3', group = 'Additional Tools and Settings')
colorcandles = input.bool(false, 'Color Candles ', inline='4', group = 'Additional Tools and Settings')
showScreener = input.bool(false, 'Screener (Soon)', inline='4', group = 'Additional Tools and Settings')
displayType = input.string('Boxes', 'Display Type', options = ['Boxes', 'Zones','Timeline', 'Candles'], group='Additional Tools and Settings', tooltip='Choose whether the scripts should plot session in the for of boxes or colored background zones.')
daysBack = input.float(150, 'Lookback (Days)', group='Additional Tools and Settings', tooltip= 'This inputs defines the lookback period for plotting sessions. Eg. If it is set to 1, only the sessions of the past day will appear')
changeType = input.string('Session High/Low','Change (%/Pips) Source', options = ['Session High/Low', 'Session Open/Close'], group='Additional Tools and Settings', tooltip='Choose whether the Change (%) and Change (Pips) should measure the distance between Session High and Session Low or the distance between Session Open and Session Close.')
SessionZone = input.string("UTC", title="Input Timezone", group='Additional Tools and Settings', tooltip = 'This input is defining the timezone for the session times selected above. It has nothing to do with the timezone of your chart, because the sessions will be plotted correctly even if your chart is not set to UTC.')
// Appearance - user inputs
borderWidth = input.int(1, 'Box Border', inline='border', group='Appearance')
borderStyle = input.string('Dashed', '', ['Solid', 'Dashed', 'Dotted'] , inline='border', group='Appearance', tooltip='Select the width and style of session box borders')
levelsStyle = input.string('Dashed', 'Line Style', ['Solid', 'Dashed', 'Dotted'], group='Appearance', tooltip='Select the style of 0.5 and Open/Close lines.')
labelSize = input.string('Normal', 'Label Size', options = ['Auto', 'Tiny', 'Small', 'Normal'], group='Appearance', tooltip='Select the size of text labels.')
showLabels = input.bool(true, 'Session Labels ', inline='00', group = 'Appearance')
colorBoxes = input.bool(true, 'Box Background', inline='00', group = 'Appearance')
// Excluding or Including Weekends
var TokyoTime = hideWeekends ? TokyoTimeX+":123456" : TokyoTimeX+":1234567"
var LondonTime = hideWeekends ? LondonTimeX+":123456" : LondonTimeX+":1234567"
var NewYorkTime = hideWeekends ? NewYorkTimeX+":123456" : NewYorkTimeX+":1234567"
var SydneyTime = hideWeekends ? SydneyTimeX+":123456" : SydneyTimeX+":1234567"
// Defining Line Style and Label Size Variables
lineStyle(x) =>
switch x
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
labelStyle(x) =>
switch x
'Auto' => size.auto
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
// Calculating inRange, used for lookback
MSPD = 24 * 60 * 60 * 1000
lastBarDate = timestamp(year(timenow), month(timenow), dayofmonth(timenow), hour(timenow), minute(timenow), second(timenow))
thisBarDate = timestamp(year, month, dayofmonth, hour, minute, second)
daysLeft = math.abs(math.floor((lastBarDate - thisBarDate) / MSPD))
inRange = daysLeft < daysBack
// Session Time
InTokyo(TokyoTime, TokyoTimeZone=syminfo.timezone) =>
not na(time(timeframe.period, TokyoTime, SessionZone))
InLondon(LondonTime, LondonTimeZone=syminfo.timezone) =>
not na(time(timeframe.period, LondonTime, SessionZone))
InNewYork(NewYorkTime, NewYorkTimeZone=syminfo.timezone) =>
not na(time(timeframe.period, NewYorkTime, SessionZone))
InSydney(SydneyTime, SydneyTimeZone=syminfo.timezone) =>
not na(time(timeframe.period, SydneyTime, SessionZone))
// Creating variables Session High, Low, Open and Session Boxes, Lines and Texts
var TokyoHighPrice = 0.0, var TokyoLowPrice = 0.0, var TokyoOpenPrice = 0.0, var box TokyoBox = na, var line TokyoLine = na, var label TokyoLabel = na, var line TokyoOC = na, var string TokyoText = str.tostring(stringTokyo)
var LondonHighPrice = 0.0, var LondonLowPrice = 0.0, var LondonOpenPrice = 0.0, var box LondonBox = na, var line LondonLine = na, var label LondonLabel = na, var line LondonOC = na, var string LondonText = str.tostring(stringLondon)
var NewYorkHighPrice = 0.0, var NewYorkLowPrice = 0.0, var NewYorkOpenPrice = 0.0, var box NewYorkBox = na, var line NewYorkLine = na, var label NewYorkLabel = na, var line NewYorkOC = na, var string NewYorkText = str.tostring(stringNewYork)
var SydneyHighPrice = 0.0, var SydneyLowPrice = 0.0, var SydneyOpenPrice = 0.0, var box SydneyBox = na, var line SydneyLine = na, var label SydneyLabel = na, var line SydneyOC = na, var string SydneyText = str.tostring(stringSydney)
// Checking if session is active/has started
inTokyo = InTokyo(TokyoTime, SessionZone) and timeframe.isintraday
TokyoStart = inTokyo and not inTokyo[1]
inLondon = InLondon(LondonTime, SessionZone) and timeframe.isintraday
LondonStart = inLondon and not inLondon[1]
inNewYork = InNewYork(NewYorkTime, SessionZone) and timeframe.isintraday
NewYorkStart = inNewYork and not inNewYork[1]
inSydney = InSydney(SydneyTime, SessionZone) and timeframe.isintraday
SydneyStart = inSydney and not inSydney[1]
// Settings high, low, open at the beggining of the session
if TokyoStart
TokyoHighPrice := high
TokyoLowPrice := low
TokyoOpenPrice := open
if LondonStart
LondonHighPrice := high
LondonLowPrice := low
LondonOpenPrice := open
if NewYorkStart
NewYorkHighPrice := high
NewYorkLowPrice := low
NewYorkOpenPrice := open
if SydneyStart
SydneyHighPrice := high
SydneyLowPrice := low
SydneyOpenPrice := open
// Track session's max high and max low during the session
else if inTokyo
TokyoHighPrice := math.max(TokyoHighPrice, high)
TokyoLowPrice := math.min(TokyoLowPrice, low)
else if inLondon
LondonHighPrice := math.max(LondonHighPrice, high)
LondonLowPrice := math.min(LondonLowPrice, low)
else if inNewYork
NewYorkHighPrice := math.max(NewYorkHighPrice, high)
NewYorkLowPrice := math.min(NewYorkLowPrice, low)
else if inSydney
SydneyHighPrice := math.max(SydneyHighPrice, high)
SydneyLowPrice := math.min(SydneyLowPrice, low)
// Plotting session boxes at the beginning of each session
if TokyoStart and showTokyo and inRange
TokyoBox := displayType=='Boxes' ? box.new(left=bar_index, top=na, right=na, bottom=na, border_width=borderWidth, bgcolor = colorBoxes ? TokyoCol : na, border_style = lineStyle(borderStyle), border_color=color.new(TokyoCol, 40)) : na
TokyoLine := halfline ? line.new(x1=bar_index, y1=na, x2=na, y2=na, style=lineStyle(levelsStyle), color = color.new(TokyoCol, 40)) : na
TokyoLabel := showLabels ? label.new(x=na, y=na, text=TokyoText, textcolor=color.new(TokyoCol, 40), color=color.rgb(0,0,0,100), size=labelStyle(labelSize)) : na
TokyoOC := sessionOC ? line.new(x1=bar_index, y1=TokyoOpenPrice, x2=na, y2=na, style=lineStyle(levelsStyle), color = color.new(TokyoCol, 40)) : na
if LondonStart and showLondon and inRange
LondonBox := displayType=='Boxes' ? box.new(left=bar_index, top=na, right=na, bottom=na, border_width=borderWidth, bgcolor = colorBoxes ? LondonCol : na, border_style = lineStyle(borderStyle), border_color=color.new(LondonCol, 40)) : na
LondonLine := halfline ? line.new(x1=bar_index, y1=na, x2=na, y2=na, style=lineStyle(levelsStyle), color = color.new(LondonCol, 40)) : na
LondonLabel := showLabels ? label.new(x=na, y=na, text=LondonText, textcolor=color.new(LondonCol, 40), color=color.rgb(0,0,0,100), size=labelStyle(labelSize)) : na
LondonOC := sessionOC ? line.new(x1=bar_index, y1=LondonOpenPrice, x2=na, y2=na, style=lineStyle(levelsStyle), color = color.new(LondonCol, 40)) : na
if NewYorkStart and showNewYork and inRange
NewYorkBox := displayType=='Boxes' ? box.new(left=bar_index, top=na, right=na, bottom=na, border_width=borderWidth, bgcolor = colorBoxes ? NewYorkCol : na, border_style = lineStyle(borderStyle), border_color=color.new(NewYorkCol, 40)) : na
NewYorkLine := halfline ? line.new(x1=bar_index, y1=na, x2=na, y2=na, style=lineStyle(levelsStyle), color = color.new(NewYorkCol, 40)) : na
NewYorkLabel := showLabels ? label.new(x=na, y=na, text=NewYorkText, textcolor=color.new(NewYorkCol, 40), color=color.rgb(0,0,0,100), size=labelStyle(labelSize)) : na
NewYorkOC := sessionOC ? line.new(x1=bar_index, y1=NewYorkOpenPrice, x2=na, y2=na, style=lineStyle(levelsStyle), color = color.new(NewYorkCol, 40)) : na
if SydneyStart and showSydney and inRange
SydneyBox := displayType=='Boxes' ? box.new(left=bar_index, top=na, right=na, bottom=na, border_width=borderWidth, bgcolor = colorBoxes ? SydneyCol : na, border_style = lineStyle(borderStyle), border_color=color.new(SydneyCol, 40)) : na
SydneyLine := halfline ? line.new(x1=bar_index, y1=na, x2=na, y2=na, style=lineStyle(levelsStyle), color = color.new(SydneyCol, 40)) : na
SydneyLabel := showLabels ? label.new(x=na, y=na, text=SydneyText, textcolor=color.new(SydneyCol, 40), color=color.rgb(0,0,0,100), size=labelStyle(labelSize)) : na
SydneyOC := sessionOC ? line.new(x1=bar_index, y1=SydneyOpenPrice, x2=na, y2=na, style=lineStyle(levelsStyle), color = color.new(SydneyCol, 40)) : na
// Creating variables for alternative Sessions Box top and bottom (used for merging sessions)
var float TokyoHighM = 0, var float TokyoLowM = 0, var float LondonHighM = 0, var float LondonLowM = 0, var float NewYorkHighM = 0, var float NewYorkLowM = 0, var float SydneyHighM = 0, var float SydneyLowM = 0
// Updating session boxes during sessions
if inTokyo and inRange
TokyoHighPrice := math.max(TokyoHighPrice, high)
TokyoLowPrice := math.min(TokyoLowPrice, low)
box.set_top(TokyoBox, TokyoHighPrice)
box.set_bottom(TokyoBox, TokyoLowPrice)
box.set_right(TokyoBox, bar_index + 1)
label.set_x(TokyoLabel, (box.get_left(TokyoBox)+box.get_right(TokyoBox))/2)
label.set_y(TokyoLabel, TokyoHighPrice)
if sessionOC
line.set_x2(TokyoOC, bar_index)
line.set_y2(TokyoOC, close)
if halfline
line.set_y1(TokyoLine, (TokyoHighPrice+TokyoLowPrice)/2)
line.set_y2(TokyoLine, (TokyoHighPrice+TokyoLowPrice)/2)
line.set_x2(TokyoLine, bar_index+1)
if merge and not inLondon and showLondon
TokyoHighM := TokyoHighPrice
TokyoLowM := TokyoLowPrice
if merge and inLondon and showLondon
box.set_top(TokyoBox, TokyoHighM)
box.set_bottom(TokyoBox, TokyoLowM)
label.set_y(TokyoLabel, TokyoHighM)
box.set_right(TokyoBox, (box.get_left(LondonBox)))
line.set_x2(TokyoLine, (box.get_left(LondonBox)))
label.set_x(TokyoLabel, (box.get_left(TokyoBox)+box.get_right(TokyoBox))/2)
line.set_x2(TokyoOC, (box.get_left(LondonBox)))
line.set_y2(TokyoOC, LondonOpenPrice)
line.set_y1(TokyoLine, (TokyoHighM+TokyoLowM)/2)
line.set_y2(TokyoLine, (TokyoHighM+TokyoLowM)/2)
var float pips = 0
var float chg = 0
pips := changeType=='Session High/Low' ? ((TokyoHighPrice - TokyoLowPrice) / syminfo.mintick / 10) : ((close - TokyoOpenPrice) / syminfo.mintick / 10)
chg := changeType=='Session Open/Close' ? (100 * (close - TokyoOpenPrice) / TokyoOpenPrice) : ((TokyoHighPrice - TokyoLowPrice) / TokyoLowPrice * 100)
if percentChange and not pipChange
label.set_text(TokyoLabel, str.tostring(TokyoText) + ' (' + str.tostring(chg, format.percent) + ')')
if pipChange and not percentChange
label.set_text(TokyoLabel, str.tostring(TokyoText) + ' (' + str.tostring(pips) + ')')
if percentChange and pipChange
label.set_text(TokyoLabel, str.tostring(TokyoText) + ' ('+ str.tostring(chg, format.percent)+ ' • ' + str.tostring(pips) + ')')
if inLondon and inRange
LondonHighPrice := math.max(LondonHighPrice, high)
LondonLowPrice := math.min(LondonLowPrice, low)
box.set_top(LondonBox, LondonHighPrice)
box.set_bottom(LondonBox, LondonLowPrice)
box.set_right(LondonBox, bar_index+1)
label.set_x(LondonLabel, (box.get_left(LondonBox)+box.get_right(LondonBox))/2)
label.set_y(LondonLabel, LondonHighPrice)
if sessionOC
line.set_x2(LondonOC, bar_index)
line.set_y2(LondonOC, close)
if halfline
line.set_y1(LondonLine, (LondonHighPrice+LondonLowPrice)/2)
line.set_y2(LondonLine, (LondonHighPrice+LondonLowPrice)/2)
line.set_x2(LondonLine, bar_index+1)
if merge and not inNewYork and showNewYork
LondonHighM := LondonHighPrice
LondonLowM := LondonLowPrice
if merge and inNewYork and showNewYork
box.set_top(LondonBox, LondonHighM)
box.set_bottom(LondonBox, LondonLowM)
label.set_y(LondonLabel, LondonHighM)
box.set_right(LondonBox, (box.get_left(NewYorkBox)))
line.set_x2(LondonLine, (box.get_left(NewYorkBox)))
label.set_x(LondonLabel, (box.get_left(LondonBox)+box.get_right(LondonBox))/2)
line.set_x2(LondonOC, (box.get_left(NewYorkBox)))
line.set_y2(LondonOC, NewYorkOpenPrice)
line.set_y1(LondonLine, (LondonHighM+LondonLowM)/2)
line.set_y2(LondonLine, (LondonHighM+LondonLowM)/2)
var float pips = 0
var float chg = 0
pips := changeType=='Session High/Low' ? ((LondonHighPrice - LondonLowPrice) / syminfo.mintick / 10) : ((close - LondonOpenPrice) / syminfo.mintick / 10)
chg := changeType=='Session Open/Close' ? (100 * (close - LondonOpenPrice) / LondonOpenPrice) : ((LondonHighPrice - LondonLowPrice) / LondonLowPrice * 100)
if percentChange and not pipChange
label.set_text(LondonLabel, str.tostring(LondonText) + ' (' + str.tostring(chg, format.percent) + ')')
if pipChange and not percentChange
label.set_text(LondonLabel, str.tostring(LondonText) + ' (' + str.tostring(pips) + ')')
if percentChange and pipChange
label.set_text(LondonLabel, str.tostring(LondonText) + ' ('+ str.tostring(chg, format.percent)+ ' • ' + str.tostring(pips) + ')')
if inNewYork and inRange
NewYorkHighPrice := math.max(NewYorkHighPrice, high)
NewYorkLowPrice := math.min(NewYorkLowPrice, low)
box.set_top(NewYorkBox, NewYorkHighPrice)
box.set_bottom(NewYorkBox, NewYorkLowPrice)
box.set_right(NewYorkBox, bar_index + 1)
label.set_x(NewYorkLabel, (box.get_left(NewYorkBox)+box.get_right(NewYorkBox))/2)
label.set_y(NewYorkLabel, NewYorkHighPrice)
if sessionOC
line.set_x2(NewYorkOC, bar_index)
line.set_y2(NewYorkOC, close)
if halfline
line.set_y1(NewYorkLine, (NewYorkHighPrice+NewYorkLowPrice)/2)
line.set_y2(NewYorkLine, (NewYorkHighPrice+NewYorkLowPrice)/2)
line.set_x2(NewYorkLine, bar_index+1)
if merge and not inSydney and showSydney
NewYorkHighM := NewYorkHighPrice
NewYorkLowM := NewYorkLowPrice
if merge and inSydney and showSydney
box.set_top(NewYorkBox, NewYorkHighM)
box.set_bottom(NewYorkBox, NewYorkLowM)
label.set_y(NewYorkLabel, NewYorkHighM)
box.set_right(NewYorkBox, (box.get_left(SydneyBox)))
line.set_x2(NewYorkLine, (box.get_left(SydneyBox)))
label.set_x(NewYorkLabel, (box.get_left(NewYorkBox)+box.get_right(NewYorkBox))/2)
line.set_x2(NewYorkOC, (box.get_left(SydneyBox)))
line.set_y2(NewYorkOC, SydneyOpenPrice)
line.set_y1(NewYorkLine, (NewYorkHighM+NewYorkLowM)/2)
line.set_y2(NewYorkLine, (NewYorkHighM+NewYorkLowM)/2)
var float pips = 0
var float chg = 0
pips := changeType=='Session High/Low' ? ((NewYorkHighPrice - NewYorkLowPrice) / syminfo.mintick / 10) : ((close - NewYorkOpenPrice) / syminfo.mintick / 10)
chg := changeType=='Session Open/Close' ? (100 * (close - NewYorkOpenPrice) / NewYorkOpenPrice) : ((NewYorkHighPrice - NewYorkLowPrice) / NewYorkLowPrice * 100)
if percentChange and not pipChange
label.set_text(NewYorkLabel, str.tostring(NewYorkText) + ' (' + str.tostring(chg, format.percent) + ')')
if pipChange and not percentChange
label.set_text(NewYorkLabel, str.tostring(NewYorkText) + ' (' + str.tostring(pips) + ')')
if percentChange and pipChange
label.set_text(NewYorkLabel, str.tostring(NewYorkText) + ' ('+ str.tostring(chg, format.percent)+ ' • ' + str.tostring(pips) + ')')
if inSydney and inRange
SydneyHighPrice := math.max(SydneyHighPrice, high)
SydneyLowPrice := math.min(SydneyLowPrice, low)
box.set_top(SydneyBox, SydneyHighPrice)
box.set_bottom(SydneyBox, SydneyLowPrice)
box.set_right(SydneyBox, bar_index + 1)
label.set_x(SydneyLabel, (box.get_left(SydneyBox)+box.get_right(SydneyBox))/2)
label.set_y(SydneyLabel, SydneyHighPrice)
if sessionOC
line.set_x2(SydneyOC, bar_index)
line.set_y2(SydneyOC, close)
if halfline
line.set_y1(SydneyLine, (SydneyHighPrice+SydneyLowPrice)/2)
line.set_y2(SydneyLine, (SydneyHighPrice+SydneyLowPrice)/2)
line.set_x2(SydneyLine, bar_index+1)
if merge and not inTokyo and showTokyo
SydneyHighM := SydneyHighPrice
SydneyLowM := SydneyLowPrice
if merge and inTokyo and showTokyo
box.set_top(SydneyBox, SydneyHighM)
box.set_bottom(SydneyBox, SydneyLowM)
label.set_y(SydneyLabel, SydneyHighM)
box.set_right(SydneyBox, (box.get_left(TokyoBox)))
line.set_x2(SydneyLine, (box.get_left(TokyoBox)))
label.set_x(SydneyLabel, (box.get_left(SydneyBox)+box.get_right(SydneyBox))/2)
line.set_x2(SydneyOC, (box.get_left(TokyoBox)))
line.set_y2(SydneyOC, TokyoOpenPrice)
line.set_y1(SydneyLine, (SydneyHighM+SydneyLowM)/2)
line.set_y2(SydneyLine, (SydneyHighM+SydneyLowM)/2)
var float pips = 0
var float chg = 0
pips := changeType=='Session High/Low' ? ((SydneyHighPrice - SydneyLowPrice) / syminfo.mintick / 10) : ((close - SydneyOpenPrice) / syminfo.mintick / 10)
chg := changeType=='Session Open/Close' ? (100 * (close - SydneyOpenPrice) / SydneyOpenPrice) : ((SydneyHighPrice - SydneyLowPrice) / SydneyLowPrice * 100)
if percentChange and not pipChange
label.set_text(SydneyLabel, str.tostring(SydneyText) + ' (' + str.tostring(chg, format.percent) + ')')
if pipChange and not percentChange
label.set_text(SydneyLabel, str.tostring(SydneyText) + ' (' + str.tostring(pips) + ')')
if percentChange and pipChange
label.set_text(SydneyLabel, str.tostring(SydneyText) + ' ('+ str.tostring(chg, format.percent)+ ' • ' + str.tostring(pips) + ')')
// Coloring candles
TKLO = showLondon ? (not inLondon) : true
LONY = showNewYork ? (not inNewYork) : true
NYSY = showSydney ? (not inSydney) : true
SYTK = showTokyo ? (not inTokyo) : true
barcolor((colorcandles or displayType=='Candles') and not merge and showTokyo and inTokyo and inRange ? color.new(TokyoCol, 40) : na, editable = false)
barcolor((colorcandles or displayType=='Candles') and not merge and showLondon and inLondon and inRange ? color.new(LondonCol, 40) : na, editable = false)
barcolor((colorcandles or displayType=='Candles') and not merge and showNewYork and inNewYork and inRange ? color.new(NewYorkCol, 40) : na, editable = false)
barcolor((colorcandles or displayType=='Candles') and not merge and showSydney and inNewYork and inRange ? color.new(SydneyCol, 40) : na, editable = false)
barcolor((colorcandles or displayType=='Candles') and merge and showTokyo and inTokyo and TKLO and inRange ? color.new(TokyoCol, 40) : na, editable = false)
barcolor((colorcandles or displayType=='Candles') and merge and showLondon and inLondon and LONY and inRange ? color.new(LondonCol, 40) : na, editable = false)
barcolor((colorcandles or displayType=='Candles') and merge and showNewYork and inNewYork and NYSY and inRange ? color.new(NewYorkCol, 40) : na, editable = false)
barcolor((colorcandles or displayType=='Candles') and merge and showSydney and inSydney and SYTK and inRange ? color.new(SydneyCol, 40) : na, editable = false)
// Coloring background if displayType=='Zones'
TokyoT = time(timeframe.period, TokyoTime)
LondonT = time(timeframe.period, LondonTime)
NewYorkT = time(timeframe.period, NewYorkTime)
SydneyT = time(timeframe.period, SydneyTime)
bgcolor(displayType == 'Zones' and not merge and showTokyo and inRange and time == TokyoT ? TokyoCol : na, editable = false)
bgcolor(displayType == 'Zones' and not merge and showLondon and inRange and time == LondonT ? LondonCol : na, editable = false)
bgcolor(displayType == 'Zones' and not merge and showNewYork and inRange and time == NewYorkT ? NewYorkCol : na, editable = false)
bgcolor(displayType == 'Zones' and not merge and showSydney and inRange and time == SydneyT ? SydneyCol : na, editable = false)
bgcolor(displayType == 'Zones' and merge and not inLondon and showTokyo and inRange and time == TokyoT ? TokyoCol : na, editable = false)
bgcolor(displayType == 'Zones' and merge and not inNewYork and showLondon and inRange and time == LondonT ? LondonCol : na, editable = false)
bgcolor(displayType == 'Zones' and merge and not inSydney and showNewYork and inRange and time == NewYorkT ? NewYorkCol : na, editable = false)
bgcolor(displayType == 'Zones' and merge and not inTokyo and showSydney and inRange and time == SydneyT ? SydneyCol : na, editable = false)
// Plotting sessions in Timeline form
plotshape(displayType=='Timeline' and (merge and showLondon ? (showTokyo and inTokyo and not inLondon) : showTokyo and inTokyo), style=shape.square, color=TokyoCol, location = location.bottom, size=size.auto)
plotshape(displayType=='Timeline' and (merge and showNewYork ? (showLondon and inLondon and not inNewYork) : showLondon and inLondon), style=shape.square, color=LondonCol, location = location.bottom, size=size.auto)
plotshape(displayType=='Timeline' and (merge and showSydney ? (showNewYork and inNewYork and not inSydney) : showNewYork and inNewYork), style=shape.square, color=NewYorkCol, location = location.bottom, size=size.auto)
plotshape(displayType=='Timeline' and (merge and showTokyo ? (showSydney and inSydney and not inTokyo) : showSydney and inSydney), style=shape.square, color=SydneyCol, location = location.bottom, size=size.auto)
// Creating alerts
alertcondition(inTokyo and not inTokyo[1], 'Tokyo Open', 'The Tokyo Session has started')
alertcondition(inLondon and not inLondon[1], 'London Open', 'The London Session has started')
alertcondition(inNewYork and not inNewYork[1], 'New York Open', 'The New York Session has started')
alertcondition(inSydney and not inSydney[1], 'Sydney Open', 'The Sydney Session has started')
alertcondition(high > TokyoHighPrice[0] and inTokyo, 'Tokyo Session - New High', 'New High in Tokyo Session')
alertcondition(high > LondonHighPrice[0] and inLondon, 'London Session - New High', 'New High in London Session')
alertcondition(high > NewYorkHighPrice[0] and inNewYork, 'New York Session - New High', 'New High in New York Session')
alertcondition(high > SydneyHighPrice[0] and inSydney, 'Sydney Session - New High', 'New High in Sydney Session')
alertcondition(low > TokyoLowPrice[0] and inTokyo, 'Tokyo Session - New Low', 'New Low in Tokyo Session')
alertcondition(low > LondonLowPrice[0] and inLondon, 'London Session - New Low', 'New Low in London Session')
alertcondition(low > NewYorkLowPrice[0] and inNewYork, 'New York Session - New Low', 'New Low In New York Session')
alertcondition(low > SydneyLowPrice[0] and inSydney, 'Sydney Session - New Low', 'New Low In Sydney Session')
|
Moving Average Cross and RSI | https://www.tradingview.com/script/qlTPeMWO-Moving-Average-Cross-and-RSI/ | Uniden202 | https://www.tradingview.com/u/Uniden202/ | 40 | 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/
// © Uniden202
//Version 15 adds the condition to the define long and short. Added and rsi_ema >= upper ; rsi_ema <= lower.
//Version 16 changed condition of long/short from rsi_ema to rsi and removed offset from within the plot of the dots to algin with original ema mac cross
//Version 17 changed condition to add the ta.cross therefore it only signals when all 3 conditons are met and does not repeat
//Version 18 Added shapes to candles for entry/exits
//@version=5
indicator('Moving Average Cross and RSI', overlay=true, precision=0)
//variable
var indicatorshort = 0.0
var indicatorlong = 0.0
// Define variables for RSI
rsi_length = 8
rsi_source = hl2
rsi_ema_length = 3
// Calculate RSI
rsi = ta.rsi(rsi_source, rsi_length)
upper = 64
lower = 30
// Calculate EMA for RSI
rsi_ema = ta.ema(rsi, rsi_ema_length)
// Plot RSI and EMA and Vwap
plot(rsi, style=plot.style_line, color=color.rgb(32, 146, 240), linewidth=2, title='RSI', editable = true)
plot(rsi_ema, style=plot.style_line, color=color.rgb(255, 82, 82), linewidth=2, title='EMA(RSI)', editable = true)
plot(upper, title='Overbought', color=color.rgb(218, 218, 218), linewidth=1, style=plot.style_circles)
plot(lower, title='Overbought', color=color.rgb(218, 218, 218), linewidth=1, style=plot.style_circles)
plot(indicatorshort, 'Short Dot', color=color.rgb(240, 77, 113), style=plot.style_circles, linewidth=3)
plot(indicatorlong, 'Long Dot', color=color.rgb(36, 250, 17, 17), style=plot.style_circles, linewidth=3)
plotshape(indicatorlong, 'Long X', color=color.rgb(36, 250, 17, 17), location = location.abovebar, size=size.small)
plotshape(indicatorshort, 'Short X', color=color.rgb(240, 7, 113), location = location.belowbar, size=size.small)
plot(ta.vwap(hlc3), title = "VWAP", color=color.rgb(255, 255, 255), linewidth = 2)
// Define variables for MAC
ema8 = ta.ema(close, 10)
ema24 = ta.ema(close, 30)
SMMA = ta.sma(hlc3, 21)
// Plot EMAs
plot(ema8, title = "ema8", color=color.rgb(255, 82, 82, 100), editable = true)
plot(ema24, title = "ema24", color=color.rgb(33, 150, 243, 100), editable = true)
// Define condition to long
longcondition = ema8 > ema24 and rsi >= upper and ta.cross(ema8,ema24) and close[1] > ta.vwap(hlc3)
if longcondition
indicatorlong := 100
else
indicatorlong := na
// Define Condition to Short
Shortcondition = ema8 < ema24 and rsi <= lower and ta.cross(ema8,ema24) and close[1] < ta.vwap(hlc3)
if Shortcondition
indicatorshort := 1
else
indicatorshort := na
// Entry and Exit conditions for the trade
long_entry = ema8 > ema24 and ema8[1] <= ema24[1]
short_entry = ema8 < ema24 and ema8[1] >= ema24[1]
closelong = ema8 < ema24 and not long_entry[2]
closeshort = ema8 > ema24 and not short_entry[2]
// Plot the direction of the trade
plot(indicatorshort, title='indicatorshort', color=color.rgb(78, 177, 81, 100))
plot(indicatorlong, title='indicatorlong', color=color.rgb(78, 177, 81, 100))
|
True Range Momentum | https://www.tradingview.com/script/DNqrXNMh-True-Range-Momentum/ | maksumit | https://www.tradingview.com/u/maksumit/ | 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/
// © maksumit
//@version=5
indicator("True Range Momentum", "TRM")
HL = input.bool(true, "High/Low")
D = input.bool(true, "Delay")
len = input.int(10, "Length", 1)
alen = input.int(5, "ATR Length", 1)
mult = input.float(3, "ATR Multiplier")
stoplag = input.int(10, "Stop Lag", 1)
tableC = input.color(color.gray, "Table Color")
tableT = input.color(color.white, "Table Text Color")
tableP = input.string(position.bottom_right, "Position", [position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right])
//ATR
atr = ta.ema(ta.tr, alen)
//LONG STOP
h = ta.highest(HL ? high:close,len)
pls = (D ? h[1]:h) - (atr * mult)
ls = ta.highest(pls, stoplag)
//SHORT STOP
l = ta.lowest(HL ? low:close,len)
pss = (D ? l[1]:l) + (atr * mult)
ss = ta.lowest(pss, stoplag)
//ATR MOMENTUM
lM = (close - ls)
sM = (ss - close)
//Allocation
lA = lM > 0 and sM < 0 ? 100:lM > 0 and sM > 0 ? 50:0
sA = sM > 0 and lM < 0 ? 100:lM > 0 and sM > 0 ? 50:0
//PLOTS
plot(lM, "M+", color.green)
plot(sM, "M-", color.red)
hline(0, "0", color.white, hline.style_dashed)
var table myTable = table.new(tableP, 2, 7, border_width=1)
if barstate.islast
//Table Cells
table.cell(myTable, 0,1, "Long: " + str.tostring(lA), text_color = tableT, bgcolor = tableC)
table.cell(myTable, 1,1, "Short: " + str.tostring(sA), text_color = tableT, bgcolor = tableC)
|
Setup Max e Min Larry Willians | https://www.tradingview.com/script/8NzbY68T/ | Cavuca-Trader | https://www.tradingview.com/u/Cavuca-Trader/ | 204 | 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/
///\\===============================================================================//\\\
//████████╗██████╗ █████╗ ██████╗ ██╗███╗ ██╗ ██████╗ ██╗ ██╗██╗███████╗██╗ ██╗\\
//╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗██║████╗ ██║██╔════╝ ██║ ██║██║██╔════╝██║ ██║\\
// ██║ ██████╔╝███████║██║ ██║██║██╔██╗ ██║██║ ███╗██║ ██║██║█████╗ ██║ █╗ ██║\\
// ██║ ██╔══██╗██╔══██║██║ ██║██║██║╚██╗██║██║ ██║╚██╗ ██╔╝██║██╔══╝ ██║███╗██║\\
// ██║ ██║ ██║██║ ██║██████╔╝██║██║ ╚████║╚██████╔╝ ╚████╔╝ ██║███████╗╚███╔███╔╝\\
// ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═══╝ ╚═╝╚══════╝ ╚══╝╚══╝ \\
//\\==============================================================================//\\ \\
// ----------------------------------------------------------------------------------- \\
// Setup Max e Min Larry Willians : Developed by Cavuca-Trader \\
// ----------------------------------------------------------------------------------- \\
// ................................................................................... \\
// Name : Setup Max e Min Larry Willians \\
// Surname : Setup Max Min \\
// Description : Technical Analysis Setup Scalper \\
// Info : Setup for quick operations following the asset trend. \\
// Creation Date : 01/02/2023 \\
// Version TradingView : 5 \\
// ................................................................................... \\
// v1.0 - release = TradingView = Ok \\
// v2.0 - fixed system stop indication \\
// v3.0 - fixed corrected documentation \\
//=====================================================================================\\
// © Cavuca-Trader
// @version=5
indicator(title="Setup Max e Min Larry Willians", shorttitle="Setup Max Min", overlay=true)
// Creating var
var int sma1 = 3
var int sma2 = 3
var int sma3 = 21
var bool stp = false
var bool stpX = false
// Creating moving averages
ma1 = ta.sma(high,sma1)
ma2 = ta.sma(low,sma2)
ma3 = ta.sma(close,sma3)
// Moving average coloring
m_col = color.gray
if ma3 < ma2 and ma3 < ma1
m_col := color.rgb(7, 249, 15)
if ma3 > ma2 and ma3 > ma1
m_col :=color.rgb(247, 8, 8)
// System Disable
if ma3 > ma2 and ma3[1] < ma2[1] and stp
stpX := true
stp := false
else
if ma3 < ma1 and ma3[1] > ma1[1] and stp
stpX := true
stp := false
else
stpX := false
// Coloring Rule Entry
Cwbar = close != open
Cgbar = ma3 < ma2 and ma3 < ma1 and low <= ma2 and stp == false
Crbar = ma3 > ma1 and ma3 > ma1 and high >= ma1 and stp == false
// Stop enable
if Cgbar
stp := true
else
if Crbar
stp := true
// Stop Rule
StopCgbar = ma3 < ma2 and ma3 < ma1 and high >= ma1 and stp
StopCrbar = ma3 > ma1 and ma3 > ma1 and low <= ma2 and stp
if StopCgbar
stp := false
else
if StopCrbar
stp := false
// Color of candles
barcolor(Cgbar ? color.green : na)
barcolor(Crbar ? color.red: na)
barcolor(Cwbar ? color.white : na)
// Trade indication
plotshape(Cgbar, style=shape.triangleup, color=color.rgb(7, 249, 15), location=location.belowbar, size=size.small)
plotshape(StopCgbar, style=shape.triangledown, color=color.rgb(247, 8, 8), location=location.abovebar, size=size.small)
plotshape(Crbar, style=shape.triangledown, color=color.rgb(247, 8, 8), location=location.abovebar, size=size.small)
plotshape(StopCrbar, style=shape.triangleup, color=color.rgb(7, 249, 15), location=location.belowbar, size=size.small)
plotshape(stpX, style=shape.xcross, color=color.purple, location=location.belowbar, size=size.small)
// Moving average plots
plot(ma1,color = color.purple,linewidth = 1)
plot(ma2,color = color.blue,linewidth = 1)
plot(ma3,color = m_col,linewidth = 2) |
Liquidity Swings [LuxAlgo] | https://www.tradingview.com/script/1S2VOnJP-Liquidity-Swings-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 9,429 | 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("Liquidity Swings [LuxAlgo]"
, overlay = true
, max_lines_count = 500
, max_labels_count = 500
, max_boxes_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input(14, 'Pivot Lookback')
area = input.string('Wick Extremity', 'Swing Area', options = ['Wick Extremity', 'Full Range'])
intraPrecision = input(false, 'Intrabar Precision', inline = 'intrabar')
intrabarTf = input.timeframe('1', '' , inline = 'intrabar')
filterOptions = input.string('Count', 'Filter Areas By', options = ['Count', 'Volume'], inline = 'filter')
filterValue = input.float(0, '' , inline = 'filter')
//Style
showTop = input(true, 'Swing High' , inline = 'top', group = 'Style')
topCss = input(color.red, '' , inline = 'top', group = 'Style')
topAreaCss = input(color.new(color.red, 50), 'Area', inline = 'top', group = 'Style')
showBtm = input(true, 'Swing Low' , inline = 'btm', group = 'Style')
btmCss = input(color.teal, '' , inline = 'btm', group = 'Style')
btmAreaCss = input(color.new(color.teal, 50), 'Area', inline = 'btm', group = 'Style')
labelSize = input.string('Tiny', 'Labels Size', options = ['Tiny', 'Small', 'Normal'], group = 'Style')
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
n = bar_index
get_data()=> [high, low, volume]
[h, l, v] = request.security_lower_tf(syminfo.tickerid, intrabarTf, get_data())
get_counts(condition, top, btm)=>
var count = 0
var vol = 0.
if condition
count := 0
vol := 0.
else
if intraPrecision
if n > length
if array.size(v[length]) > 0
for [index, element] in v[length]
vol += array.get(l[length], index) < top and array.get(h[length], index) > btm ? element : 0
else
vol += low[length] < top and high[length] > btm ? volume[length] : 0
count += low[length] < top and high[length] > btm ? 1 : 0
[count, vol]
set_label(count, vol, x, y, css, lbl_style)=>
var label lbl = na
var label_size = switch labelSize
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
target = switch filterOptions
'Count' => count
'Volume' => vol
if ta.crossover(target, filterValue)
lbl := label.new(x, y, str.tostring(vol, format.volume)
, style = lbl_style
, size = label_size
, color = #00000000
, textcolor = css)
if target > filterValue
label.set_text(lbl, str.tostring(vol, format.volume))
set_level(condition, crossed, value, count, vol, css)=>
var line lvl = na
target = switch filterOptions
'Count' => count
'Volume' => vol
if condition
if target[1] < filterValue[1]
line.delete(lvl[1])
else if not crossed[1]
line.set_x2(lvl, n - length)
lvl := line.new(n - length, value, n, value
, color = na)
if not crossed[1]
line.set_x2(lvl, n+3)
if crossed and not crossed[1]
line.set_x2(lvl, n)
line.set_style(lvl, line.style_dashed)
if target > filterValue
line.set_color(lvl, css)
set_zone(condition, x, top, btm, count, vol, css)=>
var box bx = na
target = switch filterOptions
'Count' => count
'Volume' => vol
if ta.crossover(target, filterValue)
bx := box.new(x, top, x + count, btm
, border_color = na
, bgcolor = css)
if target > filterValue
box.set_right(bx, x + count)
//-----------------------------------------------------------------------------}
//Global variables
//-----------------------------------------------------------------------------{
//Pivot high
var float ph_top = na
var float ph_btm = na
var bool ph_crossed = na
var ph_x1 = 0
var box ph_bx = box.new(na,na,na,na
, bgcolor = color.new(topAreaCss, 80)
, border_color = na)
//Pivot low
var float pl_top = na
var float pl_btm = na
var bool pl_crossed = na
var pl_x1 = 0
var box pl_bx = box.new(na,na,na,na
, bgcolor = color.new(btmAreaCss, 80)
, border_color = na)
//-----------------------------------------------------------------------------}
//Display pivot high levels/blocks
//-----------------------------------------------------------------------------{
ph = ta.pivothigh(length, length)
//Get ph counts
[ph_count, ph_vol] = get_counts(ph, ph_top, ph_btm)
//Set ph area and level
if ph and showTop
ph_top := high[length]
ph_btm := switch area
'Wick Extremity' => math.max(close[length], open[length])
'Full Range' => low[length]
ph_x1 := n - length
ph_crossed := false
box.set_lefttop(ph_bx, ph_x1, ph_top)
box.set_rightbottom(ph_bx, ph_x1, ph_btm)
else
ph_crossed := close > ph_top ? true : ph_crossed
if ph_crossed
box.set_right(ph_bx, ph_x1)
else
box.set_right(ph_bx, n+3)
if showTop
//Set ph zone
set_zone(ph, ph_x1, ph_top, ph_btm, ph_count, ph_vol, topAreaCss)
//Set ph level
set_level(ph, ph_crossed, ph_top, ph_count, ph_vol, topCss)
//Set ph label
set_label(ph_count, ph_vol, ph_x1, ph_top, topCss, label.style_label_down)
//-----------------------------------------------------------------------------}
//Display pivot low levels/blocks
//-----------------------------------------------------------------------------{
pl = ta.pivotlow(length, length)
//Get pl counts
[pl_count, pl_vol] = get_counts(pl, pl_top, pl_btm)
//Set pl area and level
if pl and showBtm
pl_top := switch area
'Wick Extremity' => math.min(close[length], open[length])
'Full Range' => high[length]
pl_btm := low[length]
pl_x1 := n - length
pl_crossed := false
box.set_lefttop(pl_bx, pl_x1, pl_top)
box.set_rightbottom(pl_bx, pl_x1, pl_btm)
else
pl_crossed := close < pl_btm ? true : pl_crossed
if pl_crossed
box.set_right(pl_bx, pl_x1)
else
box.set_right(pl_bx, n+3)
if showBtm
//Set pl zone
set_zone(pl, pl_x1, pl_top, pl_btm, pl_count, pl_vol, btmAreaCss)
//Set pl level
set_level(pl, pl_crossed, pl_btm, pl_count, pl_vol, btmCss)
//Set pl labels
set_label(pl_count, pl_vol, pl_x1, pl_btm, btmCss, label.style_label_up)
//-----------------------------------------------------------------------------} |
Candle Levels | https://www.tradingview.com/script/AvCM1CbS-Candle-Levels/ | syntaxgeek | https://www.tradingview.com/u/syntaxgeek/ | 66 | 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/
// © syntaxgeek
//@version=5
indicator("Candle Levels", overlay=true)
// <inputs>
i_candleTime = input.time(0, "Candle Time", confirm=true)
i_timeframe = input.timeframe("", "Timeframe", confirm=true)
i_note = input.string("", "Note", tooltip="Provide short note to display on label if desired.", confirm=true)
i_bullishHigh = input.color(color.green, "Bullish High", group="Style Bullish")
i_bullishLow = input.color(color.red, "Bullish Low", group="Style Bullish")
i_bearishHigh = input.color(color.red, "Bearish High", group="Style Bearish")
i_bearishLow = input.color(color.green, "Bearish Low", group="Style Bearish")
i_closeColor = input.color(color.blue, "Close", group="Style Neutral", inline="close")
i_closeTextColor = input.color(color.white, "Text", group="Style Neutral", inline="close")
i_openColor = input.color(color.lime, "Open", group="Style Neutral", inline="open")
i_openTextColor = input.color(color.white, "Text", group="Style Neutral", inline="open")
i_bodyMidColor = input.color(color.orange, "Body Mid", group="Style Neutral", inline="bodyMid")
i_bodyMidTextColor = input.color(color.white, "Text", group="Style Neutral", inline="bodyMid")
i_midColor = input.color(color.white, "Mid", group="Style Neutral", inline="mid")
i_midTextColor = input.color(color.black, "Text", group="Style Neutral", inline="mid")
i_highQuarterMidColor = input.color(color.olive, "High Quarter Mid", group="Style Neutral", inline="highQuarterMid")
i_highQuarterMidTextColor = input.color(color.white, "Text", group="Style Neutral", inline="highQuarterMid")
i_lowQuarterMidColor = input.color(color.olive, "Low Quarter Mid", group="Style Neutral", inline="lowQuarterMid")
i_lowQuarterMidTextColor = input.color(color.white, "Text", group="Style Neutral", inline="lowQuarterMid")
i_highWickMidColor = input.color(color.purple, "High Wick Mid", group="Style Neutral", inline="highWickMid")
i_highWickMidTextColor = input.color(color.white, "Text", group="Style Neutral", inline="highWickMid")
i_lowWickMidColor = input.color(color.purple, "Low Wick Mid", group="Style Neutral", inline="lowWickMid")
i_lowWickMidTextColor = input.color(color.white, "Text", group="Style Neutral", inline="lowWickMid")
i_showLabels = input.bool(false, "Show Labels?", confirm=true, group="Labels")
i_showTime = input.bool(false, "Show Time In Labels?", confirm=true, group="Labels")
i_showPrice = input.bool(true, "Show Price In Labels?", confirm=true, group="Labels")
i_showHighLabel = input.bool(true, "Show High Label?", group="Labels")
i_showLowLabel = input.bool(true, "Show Low Label?", group="Labels")
i_showCloseLabel = input.bool(true, "Show Close Label?", group="Labels")
i_showOpenLabel = input.bool(true, "Show Open Label?", group="Labels")
i_showBodyMidLabel = input.bool(true, "Show Body Mid Label?", group="Labels")
i_showMidLabel = input.bool(true, "Show Mid Label?", group="Labels")
i_showHighQuarterMidLabel = input.bool(true, "Show High Quarter Mid Label?", group="Labels")
i_showLowQuarterMidLabel = input.bool(true, "Show Low Quarter Mid Label?", group="Labels")
i_showHighWickMidLabel = input.bool(true, "Show High Wick Mid Label?", group="Labels")
i_showLowWickMidLabel = input.bool(true, "Show Low Wick Mid Label?", group="Labels")
// </inputs>
// <funcs>
f_sourceFromBarOnTimeframe(exp) =>
indexHighTF = barstate.isrealtime ? 1 : 0
indexCurrTF = barstate.isrealtime ? 0 : 1
request.security(ticker.modify(syminfo.tickerid, session=session.extended), i_timeframe, exp[indexHighTF])[indexCurrTF]
f_plotLabel(y, displayText, identifier, color, textColor) =>
formattedLabelText = identifier + " " + displayText
if i_note != ""
formattedLabelText := formattedLabelText + " (" + i_note + ")"
formattedLabelText := formattedLabelText + " @ " + str.tostring(y)
var lbl = label.new(bar_index, y, style=label.style_label_lower_left, text=formattedLabelText, color=color, textcolor=textColor)
label.set_xy(lbl, bar_index, y)
label.set_color(lbl, color)
label.set_text(lbl, formattedLabelText)
f_timeframePrettyPrint(tf) =>
v_printed = str.tostring(year(tf)) + "-" + str.tostring(month(tf), "00") + "-" + str.tostring(dayofmonth(tf), "00")
if i_showTime
v_printed := v_printed + " " + str.tostring(hour(tf), "00") + ":" + str.tostring(minute(tf), "00") + ":" + str.tostring(second(tf), "00")
v_printed
// </funcs>
// <vars>
v_candleClose = f_sourceFromBarOnTimeframe(ta.valuewhen(time == i_candleTime, close, 0))
v_candleOpen = f_sourceFromBarOnTimeframe(ta.valuewhen(time == i_candleTime, open, 0))
v_candleHigh = f_sourceFromBarOnTimeframe(ta.valuewhen(time == i_candleTime, high, 0))
v_candleLow = f_sourceFromBarOnTimeframe(ta.valuewhen(time == i_candleTime, low, 0))
v_candleHighWickMid = v_candleClose > v_candleOpen ? ((v_candleHigh - v_candleClose) / 2) + v_candleClose : ((v_candleHigh - v_candleOpen) / 2) + v_candleOpen
v_candleLowWickMid = v_candleClose > v_candleOpen ? ((v_candleOpen - v_candleLow) / 2) + v_candleLow : ((v_candleClose - v_candleLow) / 2) + v_candleLow
v_candleBodyMid = v_candleClose > v_candleOpen ? v_candleClose - ((v_candleClose - v_candleOpen) / 2) : v_candleOpen - ((v_candleOpen - v_candleClose) / 2)
v_candleMid = v_candleHigh - ((v_candleHigh - v_candleLow) / 2)
v_candleHighQuarterMid = v_candleMid + ((v_candleHigh - v_candleMid) / 2)
v_candleLowQuarterMid = v_candleMid - ((v_candleMid - v_candleLow) / 2)
v_candleIsBullish = v_candleClose > v_candleOpen
v_candleHighColor = v_candleIsBullish ? i_bullishHigh : i_bearishHigh
v_candleLowColor = v_candleIsBullish ? i_bullishLow : i_bearishLow
var v_timeframePrettyPrint = f_timeframePrettyPrint(i_candleTime)
// </vars>
// <plots>
if i_showLabels
if i_showHighLabel
f_plotLabel(v_candleHigh, v_timeframePrettyPrint, "High", v_candleHighColor, color.white)
if i_showLowLabel
f_plotLabel(v_candleLow, v_timeframePrettyPrint, "Low", v_candleLowColor, color.white)
if i_showCloseLabel
f_plotLabel(v_candleClose, v_timeframePrettyPrint, "Close", i_closeColor, i_closeTextColor)
if i_showOpenLabel
f_plotLabel(v_candleOpen, v_timeframePrettyPrint, "Open", i_openColor, i_openTextColor)
if i_showBodyMidLabel
f_plotLabel(v_candleBodyMid, v_timeframePrettyPrint, "Body Mid", i_bodyMidColor, i_bodyMidTextColor)
if i_showMidLabel
f_plotLabel(v_candleMid, v_timeframePrettyPrint, "Mid", i_midColor, i_midTextColor)
if i_showHighQuarterMidLabel
f_plotLabel(v_candleHighQuarterMid, v_timeframePrettyPrint, "High Quarter Mid", i_highQuarterMidColor, i_highQuarterMidTextColor)
if i_showLowQuarterMidLabel
f_plotLabel(v_candleLowQuarterMid, v_timeframePrettyPrint, "Low Quarter Mid", i_lowQuarterMidColor, i_lowQuarterMidTextColor)
if i_showHighWickMidLabel
f_plotLabel(v_candleHighWickMid, v_timeframePrettyPrint, "High Wick Mid", i_highWickMidColor, i_highWickMidTextColor)
if i_showLowWickMidLabel
f_plotLabel(v_candleLowWickMid, v_timeframePrettyPrint, "Low Wick Mid", i_lowWickMidColor, i_lowWickMidTextColor)
plot(v_candleHigh, "High", color=v_candleHighColor)
plot(v_candleLow, "Low", color=v_candleLowColor)
plot(v_candleClose, "Close", color=i_closeColor)
plot(v_candleOpen, "Open", color=i_openColor)
plot(v_candleBodyMid, "Body Mid", color=i_bodyMidColor)
plot(v_candleMid, "Mid", color=i_midColor)
plot(v_candleHighQuarterMid, "High Quarter Mid", color=i_highQuarterMidColor)
plot(v_candleLowQuarterMid, "Low Quarter Mid", color=i_lowQuarterMidColor)
plot(v_candleHighWickMid, "High Wick Mid", color=i_highWickMidColor)
plot(v_candleLowWickMid, "Low Wick Mid", color=i_lowWickMidColor)
// </plots> |
ANTEYA Profiling | https://www.tradingview.com/script/HxaL9yg5-ANTEYA-Profiling/ | moebius1977 | https://www.tradingview.com/u/moebius1977/ | 11 | 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/
// © moebius1977
// A framework for finding the fastest working code by calling it multiple times in a loop (with random values)
// and measuring how much time it takes.
// The script runs the test code within a loop for fixed time until a certain time or iterations limit.
// Paste the code to be tested within THE LOOP (see below) as option 1 and 2.
//@version=5
indicator("ANTEYA Profiling", overlay = true)
//======================================================================================
// USER DEFINED TYPES
//====================================================================================== {
// This wierd UDT is excessive - I originally planned to encapsulate string buffer into 'debugger' type, but
// it turned ourt that UDT's cannot be 'varip'. Still left it this way - once turned into library debugger object of
// exported type can be used to pass parameters to functions within the debugger library.
// also dbgLabel object may be used in future with overloaded functions
//@type dbgTable
//@field buffer buffer of lines to be printed. *** NB *** temporarily out of order, looks like no varip UDT objects
// an assignment of a varip array to a property of a var UDT object alone makes the array non-varip
//@field tbl table to print to
//@field txtColor text color
type dbgTable
string[] buffer
table tbl // fixed label
color txtColor
// END OF USER DEFINED TYPES }
//======================================================================================
// CONSTANTS
//====================================================================================== {
// -------- Colors ----------{
var MAX_LOOP_TIME = 100 // Maximum time loop is allowed to run. Pine Script's limit is 500ms
var ARDEBUGS_MAX_SIZE = 20 // number of lines in debug label (= elemnents ib debug array)
// END OF COLORS}
// var DEFAULT_TXT_COLOR = color.rgb(34, 203, 39)
var DEFAULT_TXT_COLOR = #22CB27
// END OF CONSTANTS}
//======================================================================================
// DEBUGGER INPUT & INIT
//====================================================================================== {
var TL = "Time elapsed", var IL = "Number of iterations"
i_limitType = input.string(TL, "When to stop", [TL, IL])
i_limitTime = 1000 * input.float(0.2, "Time limit, sec", minval = 0.01, inline = "limits")
i_limitIterations = input.int(10000, "Iterations limit", minval = 0, inline = "limits")
i_tblTxtColor = input.color(DEFAULT_TXT_COLOR, "Text color")
i_option2 = input.bool(false, "Test option 2 code")
// END OF DEBUGGER INPITS AND INIT}
//======================================================================================
// DEBUG FUNCTIONS
//======================================================================================{
f_initDebugger(dbgTable _db, color _txtColor = #22CB27) =>
// *** !!! *** as a 'varip' _dbBuffer persists during realtime bars
var _tbl = table.new(position.bottom_right, 1, 2, bgcolor = color.black, frame_color = color.gray)
_db.tbl := _tbl
// Table headers
table.cell(_tbl,0,0,text="Bar index: | Loop: | Iterations: | Loop time,s:", text_color = _txtColor, text_font_family = font.family_monospace, text_halign = text.align_left)
// table.cell(_tbl,1,0,text="Loop:", text_color = i_tblTxtColor, text_font_family = font.family_monospace)
// table.cell(_tbl,2,0,text="Iterations:", text_color = i_tblTxtColor, text_font_family = font.family_monospace)
// table.cell(_tbl,3,0,text="Time per loop,s:", text_color = i_tblTxtColor, text_font_family = font.family_monospace)
f_updateDebugger(dbgTable _db, string _s, color _txtColor = #22CB27) =>
table.cell(_db.tbl, 0, 1, text = _s, text_color = _txtColor, text_font_family = font.family_monospace, text_halign = text.align_left )
f_dbPrint(string[] dbBuffer, string _s) =>
// var c = 0
// c += 1
// array.unshift(dbBuffer, str.tostring(c) + " " + _s)
array.unshift(dbBuffer, _s)
if array.size(dbBuffer) > ARDEBUGS_MAX_SIZE
array.pop(dbBuffer)
// END OF DEBUG FUNCTIONS}
//======================================================================================
// INIT DEBUGGER
//====================================================================================== {
// create and init debugger
// *** !!! *** declaring this object as varip results in "Variables with varip modifier cannot have type dbgLabel" error
var db = dbgTable.new()
// unfortunately, no way to make buffer array a field in db object, since UDT objects cannot be varip
varip string[] dbBuffer = array.new<string>() // needs to be varip to persist during realtime bar
var debugS = "" // for debug messages
varip float[] loopIterations= array.new<float>() // number of iterations for each loop
// loop variables
varip loopStartTime = timenow
varip loopsPerBar = 0
varip iterationsPerLoop = 0
varip loopTime =0 // time in the loop
// option dependent results
varip progressChar1 = "⏳"
varip progressChar2 = ""
varip int totalTime1 =0
varip int totalTime2 =0
varip totalIterations1 = 0
varip totalIterations2 = 0
varip avgIterationsPerSec1 = 0
varip avgIterationsPerSec2 = 0
varip endCondition = false // true upon completion
varip option = 1 // test 1 and 2nd optioins then finish
varip numOptions = i_option2 ? 2 : 1
f_initDebugger(db, i_tblTxtColor)
// END OF INIT DEBUGGER}
//======================================================================================
// TEST CODE INPUT & INIT
//====================================================================================== {
var tfMs = 1000*timeframe.in_seconds()
l = ta.sma(high-low, 50)
// line to be deleted and set_xy
var _ln = line.new(time,high,time + -5*tfMs, (high-low), xloc = xloc.bar_time,color = color.yellow, width = 4 )
// ******** TEST CODE INPUT & INIT ********}
//======================================================================================
// THE LOOP AND RESULT CALCULATION
//======================================================================================{
// reset loopCounter
if barstate.isnew
loopsPerBar := 0
if barstate.isrealtime
loopsPerBar += 1
// switch option. Once option > 2 finish
if endCondition
endCondition := false
f_dbPrint(dbBuffer, str.format("-------------------- END OF OPTION {0} ---------------------", option))
switch option
1 =>
progressChar1 := "✅"
progressChar2 := numOptions > 1 ? "⏳" : ""
2 =>
progressChar2 := "✅"
option += 1
// test until all options tested endCondition does not matter
if not (barstate.isconfirmed or option > numOptions)
iterationsPerLoop := 0 // loop iterations
loopStartTime := timenow // loop start time
loopTime := 0
// ---------------------------- <<<-->>> ----------------------------
// ============================ THE LOOP ============================
// ---------------------------- <<<-->>> ----------------------------
// loop to measure, Pine Script's limit on loop time is 500ms, so capping it to MAX_LOOP_TIME
while not
// (time_close - timenow > MAX_LOOP_TIME // only start if we have time to complete the loop before time_close
(timenow - loopStartTime > MAX_LOOP_TIME
or barstate.isconfirmed
or endCondition)
iterationsPerLoop += 1 // loop cycles counter
// ---------------------------- <<<----------->>> ----------------------------
// ---------------------------- CODE TO BE TESTED ----------------------------{
switch option
1 =>
// OPTION 1
line.set_xy1(_ln, time, high)
line.set_xy2(_ln, time, high + l * math.random(0,1,1))
2 =>
// OPTION 2
line.delete(_ln)
_ln := line.new(time, high, time, high + l * math.random(0,1,1), xloc = xloc.bar_time,color = color.yellow, width = 1)
// ---------------------------- <<<------------------------->>> ----------------------------}
// ---------------------------- <<< END OF CODE TO BE TESTED >>> ----------------------------
// ---------------------------- <<<------------------------->>> ----------------------------
endCondition := i_limitType == TL ?
(option == 1 ? totalTime1 : totalTime2) + timenow -loopStartTime > i_limitTime
: (option == 1 ? totalIterations1 : totalIterations2) + iterationsPerLoop > i_limitIterations
loopTime := timenow-loopStartTime
switch option
1 =>
totalTime1 += loopTime
totalIterations1 += iterationsPerLoop
avgIterationsPerSec1 := totalIterations1 / (totalTime1 / 1000)
2 =>
totalTime2 += loopTime
totalIterations2 += iterationsPerLoop
avgIterationsPerSec2 := totalIterations2 / (totalTime2 / 1000)
// ======= END OF THE LOOP =======
// print results of the loop: Loop#: Cycles in loop: time per loop
_s = str.format("{0, number,000,000,000} | {1, number, 0} | {2, number,000,000,000} |. {3,time,s.S}", bar_index, loopsPerBar, iterationsPerLoop, loopTime)
// f_dbPrint(dbBuffer, str.tostring(bar_index)+": " + _s)
f_dbPrint(dbBuffer, _s)
// END OF THE LOOP AND RESULT CALCULATION }
//======================================================================================
// OUTPUT RESULTS
//======================================================================================{
// -------- RESULTS TABLE --------{
tbl = table.new(position.bottom_left, 4, 3, bgcolor = color.black, frame_color = color.gray)
// Table headers
table.cell(tbl,0,0,text="Option:", text_color = i_tblTxtColor, text_font_family = font.family_monospace)
table.cell(tbl,1,0,text="Total time:", text_color = i_tblTxtColor, text_font_family = font.family_monospace)
table.cell(tbl,2,0,text="No of iterations:", text_color = i_tblTxtColor, text_font_family = font.family_monospace)
table.cell(tbl,3,0,text="Iterations/sec (avg):", text_color = i_tblTxtColor, text_font_family = font.family_monospace)
// Option 1
table.cell(tbl,0,1,text="Option 1:", text_color = i_tblTxtColor, text_font_family = font.family_monospace)
table.cell(tbl,1,1,text=str.format("{0, time, s.S}", totalTime1), text_color = i_tblTxtColor, text_font_family = font.family_monospace)
table.cell(tbl,2,1,text=str.format("{0, number, #,##0}", totalIterations1), text_color = i_tblTxtColor, text_font_family = font.family_monospace)
table.cell(tbl,3,1,text=str.format("{0, number, #,##0} {1}", avgIterationsPerSec1, progressChar1), text_color = i_tblTxtColor, text_font_family = font.family_monospace)
// Option 2
if numOptions > 1
table.cell(tbl,0,2,text="Option 2:", text_color = i_tblTxtColor, text_font_family = font.family_monospace)
table.cell(tbl,1,2,text=str.format("{0, time, s.S}", totalTime2), text_color = i_tblTxtColor, text_font_family = font.family_monospace)
table.cell(tbl,2,2,text=str.format("{0, number, #,##0}", totalIterations2), text_color = i_tblTxtColor, text_font_family = font.family_monospace)
table.cell(tbl,3,2,text=str.format("{0, number, #,##0} {1}", avgIterationsPerSec2, progressChar2), text_color = i_tblTxtColor, text_font_family = font.family_monospace)
// END OF RESULTS TABLE}
// -------- DEBUGGER TABLE --------{
debugS := array.join(dbBuffer, "\n")
// prints each loop result to the debugger table
f_updateDebugger(db, debugS, i_tblTxtColor)
// END OF DEBUGGER TABLE}
|
Setup 123 Scalper | https://www.tradingview.com/script/w8h6Oynm/ | Cavuca-Trader | https://www.tradingview.com/u/Cavuca-Trader/ | 683 | 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/
///\\===============================================================================//\\\
//████████╗██████╗ █████╗ ██████╗ ██╗███╗ ██╗ ██████╗ ██╗ ██╗██╗███████╗██╗ ██╗\\
//╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗██║████╗ ██║██╔════╝ ██║ ██║██║██╔════╝██║ ██║\\
// ██║ ██████╔╝███████║██║ ██║██║██╔██╗ ██║██║ ███╗██║ ██║██║█████╗ ██║ █╗ ██║\\
// ██║ ██╔══██╗██╔══██║██║ ██║██║██║╚██╗██║██║ ██║╚██╗ ██╔╝██║██╔══╝ ██║███╗██║\\
// ██║ ██║ ██║██║ ██║██████╔╝██║██║ ╚████║╚██████╔╝ ╚████╔╝ ██║███████╗╚███╔███╔╝\\
// ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═══╝ ╚═╝╚══════╝ ╚══╝╚══╝ \\
//\\==============================================================================//\\ \\
// ----------------------------------------------------------------------------------- \\
// Setup 123 Scalper: Developed by Cavuca-Trader \\
// ----------------------------------------------------------------------------------- \\
// ................................................................................... \\
// Name : Setup 123 \\
// Surname : Scalper \\
// Description : Technical Analysis Setup Scalper \\
// Info : Setup for quick operations following the asset trend. \\
// Creation Date : 28/01/2023 \\
// Version TradingView : 5 \\
// ................................................................................... \\
// v1.0 - release = TradingView = Ok \\
// v2.0 - correction of moving averages \\
// v3.0 - corrected documentation \\
//=====================================================================================\\
// © Cavuca-Trader
// @version=5
indicator(title="Setup 123 Scalper", shorttitle="Setup-123", overlay=true)
// Creating var
var int sma1 = 9
var int sma2 = 21
var int sma3 = 200
// Creating moving averages
ma1 = ta.sma(close,sma1)
ma2 = ta.sma(close,sma2)
ma3 = ta.sma(close,sma3)
// Candle coloring rule scalper
Cwbar = close != open
Cgbar = ma1 > ma2 and high[2] > high[1] and high[1] < high[0] and low[2] > low[1] and low[1] < low[0]
Crbar = ma1 < ma2 and high[2] < high[1] and high[1] > high[0] and low[2] < low[1] and low[1] > low[0]
// Color of candles
barcolor(Cgbar ? color.green : na)
barcolor(Crbar ? color.red: na)
barcolor(Cwbar ? color.white : na)
// Moving average coloring
m_col = color.gray
if ma1 > ma2
m_col := color.rgb(7, 249, 15)
if ma1 < ma2
m_col :=color.rgb(247, 8, 8)
// Moving average plots
plot(ma1,color = color.yellow,linewidth = 1)
plot(ma2,color = m_col,linewidth = 2)
plot(ma3,color = color.purple,linewidth = 3) |
Democratic Fibonacci McGinley Dynamics | https://www.tradingview.com/script/W0bVTysJ-Democratic-Fibonacci-McGinley-Dynamics/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 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/
// © LeafAlgo
//@version=5
indicator("Democratic Fibonacci McGinley Dynamics", 'DFMG', overlay=true)
src = input.source(ohlc4, 'Source')
mg3 = 0.0
mg5 = 0.0
mg8 = 0.0
mg13 = 0.0
mg21 = 0.0
mg34 = 0.0
mg55 = 0.0
mg89 = 0.0
mg144 = 0.0
mg233 = 0.0
mg3 := na(mg3[1]) ? ta.ema(src, 3) : mg3[1] + (src - mg3[1]) / (3 * math.pow(src/mg3[1], 4))
plot(mg3, title='Fib. MG (3)', color=color.white, linewidth=2)
mg5 := na(mg5[1]) ? ta.ema(src, 5) : mg5[1] + (src - mg5[1]) / (5 * math.pow(src/mg5[1], 4))
plot(mg5, title='Fib. MG (5)')
mg8 := na(mg8[1]) ? ta.ema(src, 8) : mg8[1] + (src - mg8[1]) / (8 * math.pow(src/mg8[1], 4))
plot(mg8, title='Fib. MG (8)')
mg13 := na(mg13[1]) ? ta.ema(src, 13) : mg13[1] + (src - mg13[1]) / (13 * math.pow(src/mg13[1], 4))
plot(mg13, title='Fib. MG (13)')
mg21 := na(mg21[1]) ? ta.ema(src, 21) : mg21[1] + (src - mg21[1]) / (21 * math.pow(src/mg21[1], 4))
plot(mg21, title='Fib. MG (21)')
mg34 := na(mg34[1]) ? ta.ema(src, 34) : mg34[1] + (src - mg34[1]) / (34 * math.pow(src/mg34[1], 4))
plot(mg34, title='Fib. MG (34)')
mg55 := na(mg55[1]) ? ta.ema(src, 55) : mg55[1] + (src - mg55[1]) / (55 * math.pow(src/mg55[1], 4))
plot(mg55, title='Fib. MG (55)')
mg89 := na(mg89[1]) ? ta.ema(src, 89) : mg89[1] + (src - mg89[1]) / (89 * math.pow(src/mg89[1], 4))
plot(mg89, title='Fib. MG (89)')
mg144 := na(mg144[1]) ? ta.ema(src, 144) : mg144[1] + (src - mg144[1]) / (144 * math.pow(src/mg144[1], 4))
plot(mg144, title='Fib. MG (144)')
mg233 := na(mg233[1]) ? ta.ema(src, 233) : mg233[1] + (src - mg233[1]) / (233 * math.pow(src/mg233[1], 4))
plot(mg233, title='Fib. MG (233)',color=color.white, linewidth = 2)
dfmg = (mg3 + mg5 + mg8 + mg13 + mg21 + mg34 + mg55 + mg89 + mg144 + mg233) / 10
plot(dfmg, 'DFMG', color=(dfmg > mg233) ? color.lime : color.red, linewidth=4)
var string GP2 = 'Display'
string tableYposInput = input.string("bottom", "Panel position", inline = "11", options = ["top", "middle", "bottom"], group = GP2)
string tableXposInput = input.string("right", "", inline = "11", options = ["left", "center", "right"], group = GP2)
color bullColorInput = input.color(color.new(color.green, 20), "Bull", inline = "12", group = GP2)
color bearColorInput = input.color(color.new(color.red, 20), "Bear", inline = "12", group = GP2)
color neutColorInput = input.color(color.new(color.gray, 20), "Neutral", inline = "12", group = GP2)
var table panel = table.new(tableYposInput + "_" + tableXposInput, 2, 12)
if barstate.islast
table.cell(panel, 0, 0, 'Fib. Number', bgcolor = neutColorInput, text_color = color.black)
table.cell(panel, 1, 0, 'MG Value', bgcolor = neutColorInput, text_color = color.black)
bgc1 = close > mg3 ? open < mg3 ? neutColorInput : bullColorInput : open > mg3 ? neutColorInput : bearColorInput
table.cell(panel, 0, 1, str.tostring(3), bgcolor = bgc1, text_color = color.black)
table.cell(panel, 1, 1, str.tostring(mg3, format.mintick), bgcolor = bgc1, text_color = color.black)
bgc2 = close > mg5 ? open < mg5 ? neutColorInput : bullColorInput : open > mg5 ? neutColorInput : bearColorInput
table.cell(panel, 0, 2, str.tostring(5), bgcolor = bgc2, text_color = color.black)
table.cell(panel, 1, 2, str.tostring(mg5, format.mintick), bgcolor = bgc2, text_color = color.black)
bgc3 = close > mg8 ? open < mg8 ? neutColorInput : bullColorInput : open > mg8 ? neutColorInput : bearColorInput
table.cell(panel, 0, 3, str.tostring(8), bgcolor = bgc3, text_color = color.black)
table.cell(panel, 1, 3, str.tostring(mg8, format.mintick), bgcolor = bgc3, text_color = color.black)
bgc4 = close > mg13 ? open < mg13 ? neutColorInput : bullColorInput : open > mg13 ? neutColorInput : bearColorInput
table.cell(panel, 0, 4, str.tostring(13), bgcolor = bgc4, text_color = color.black)
table.cell(panel, 1, 4, str.tostring(mg13, format.mintick), bgcolor = bgc4, text_color = color.black)
bgc5 = close > mg21 ? open < mg21 ? neutColorInput : bullColorInput : open > mg21 ? neutColorInput : bearColorInput
table.cell(panel, 0, 5, str.tostring(21), bgcolor = bgc5, text_color = color.black)
table.cell(panel, 1, 5, str.tostring(mg21, format.mintick), bgcolor = bgc5, text_color = color.black)
bgc6 = close > mg34 ? open < mg34 ? neutColorInput : bullColorInput : open > mg34 ? neutColorInput : bearColorInput
table.cell(panel, 0, 6, str.tostring(34), bgcolor = bgc6, text_color = color.black)
table.cell(panel, 1, 6, str.tostring(mg34, format.mintick), bgcolor = bgc6, text_color = color.black)
bgc7 = close > mg55 ? open < mg55 ? neutColorInput : bullColorInput : open > mg55 ? neutColorInput : bearColorInput
table.cell(panel, 0, 7, str.tostring(55), bgcolor = bgc7, text_color = color.black)
table.cell(panel, 1, 7, str.tostring(mg55, format.mintick), bgcolor = bgc7, text_color = color.black)
bgc8 = close > mg89 ? open < mg89 ? neutColorInput : bullColorInput : open > mg89 ? neutColorInput : bearColorInput
table.cell(panel, 0, 8, str.tostring(89), bgcolor = bgc8, text_color = color.black)
table.cell(panel, 1, 8, str.tostring(mg89, format.mintick), bgcolor = bgc8, text_color = color.black)
bgc9 = close > mg144 ? open < mg144 ? neutColorInput : bullColorInput : open > mg144 ? neutColorInput : bearColorInput
table.cell(panel, 0, 9, str.tostring(144), bgcolor = bgc9, text_color = color.black)
table.cell(panel, 1, 9, str.tostring(mg144, format.mintick), bgcolor = bgc9, text_color = color.black)
bgc10 = close > mg233 ? open < mg233 ? neutColorInput : bullColorInput : open > mg233 ? neutColorInput : bearColorInput
table.cell(panel, 0, 10, str.tostring(233), bgcolor = bgc10, text_color = color.black)
table.cell(panel, 1, 10, str.tostring(mg233, format.mintick), bgcolor = bgc10, text_color = color.black)
bgc11 = close > dfmg ? open < dfmg ? neutColorInput : bullColorInput : open > dfmg ? neutColorInput : bearColorInput
table.cell(panel, 0, 11, 'DFMG', bgcolor = bgc11, text_color = color.black)
table.cell(panel, 1, 11, str.tostring(dfmg, format.mintick), bgcolor = bgc11, text_color = color.black)
|
Moon Phases + Daily, Weekly, Monthly, Quarterly & Yearly Breaks | https://www.tradingview.com/script/2BMqtiSV-Moon-Phases-Daily-Weekly-Monthly-Quarterly-Yearly-Breaks/ | Yatagarasu_ | https://www.tradingview.com/u/Yatagarasu_/ | 141 | 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/
// 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/
//@version=5
indicator("Moon + DWMQY • Yata",
overlay = true,
scale=scale.none)
// --------------------
groupMP = "Moon Phases"
// --------------------
new = input.time(defval=timestamp("2021-01-13:05:00"), title="Reference Date", inline="D", group=groupMP)
show_moon = input.bool(true, title="Show Moons |", inline="MO", group=groupMP)
show_bg = input.bool(true, title="Background |", inline="MO", group=groupMP)
show_vl = input.bool(false, title="Lines", inline="MO", group=groupMP)
buy = input.string("Full Moon", options=["New Moon", "Full Moon", "Higher Moon", "Lower Moon"], title="", inline="MO1", group=groupMP)
sell = input.string("New Moon", options=["New Moon", "Full Moon", "Higher Moon", "Lower Moon"], title="", inline="MO2", group=groupMP)
nmooncol = input.color(color.new(color.black, 20), title="", inline="MO2", group=groupMP)
fmooncol = input.color(color.new(color.silver, 20), title="", inline="MO1", group=groupMP)
longcol = input.color(color.new(color.silver, 90), title="|", inline="MO1", group=groupMP)
shortcol = input.color(color.new(color.silver, 95), title="|", inline="MO2", group=groupMP)
longvlcol = input.color(color.new(color.silver, 80), title="|", inline="MO1", group=groupMP)
shortvlcol = input.color(color.new(color.silver, 80), title="|", inline="MO2", group=groupMP)
// --------------------
n = bar_index
cycle = 2551442876.8992
day = 8.64e+7
diff = (new + time + day * 2) % cycle / cycle
// --------------------
newmoon = ta.crossover(diff, .5)
fullmoon = diff < diff[1]
plotshape(show_moon and newmoon ? low : na, "New Moon", shape.circle, location.bottom, nmooncol, size=size.small)
plotshape(show_moon and fullmoon ? high : na, "Full Moon", shape.circle, location.top, fmooncol, size=size.small)
plot(show_vl and newmoon ? 1 : na, style=plot.style_histogram, color=longvlcol, title="New Moon")
plot(show_vl and fullmoon ? 1 : na, style=plot.style_histogram, color=shortvlcol, title="Full Moon")
// --------------------
msrc = close
var bool long = na
var bool short = na
if buy == "New Moon"
long := newmoon
long
else if buy == "Full Moon"
long := fullmoon
long
else if buy == "Higher Moon"
long := ta.valuewhen(newmoon or fullmoon, msrc, 0) > ta.valuewhen(newmoon or fullmoon, msrc, 1)
long
else
long := ta.valuewhen(newmoon or fullmoon, msrc, 0) < ta.valuewhen(newmoon or fullmoon, msrc, 1)
long
// --------------------
if sell == "New Moon"
short := newmoon
short
else if sell == "Full Moon"
short := fullmoon
short
else if sell == "Higher Moon"
short := ta.valuewhen(newmoon or fullmoon, msrc, 0) > ta.valuewhen(newmoon or fullmoon, msrc, 1)
short
else
short := ta.valuewhen(newmoon or fullmoon, msrc, 0) < ta.valuewhen(newmoon or fullmoon, msrc, 1)
short
// --------------------
var pos = 0
if long
pos := 1
if short
pos := -1
bgcolor(show_bg and pos == 1 ? longcol : show_bg ? shortcol : na)
// ------------------------------
groupCA = "D, W, M, Q & Y Breaks"
// ------------------------------
color_d = input.color(color.new(color.silver, 80) , title="" , inline="d", group=groupCA)
color_w = input.color(color.new(#42a5f5, 60) , title="" , inline="w", group=groupCA)
color_m = input.color(color.new(#388e3c, 50) , title="" , inline="m", group=groupCA)
color_q = input.color(color.new(#fbc02d, 40) , title="" , inline="q", group=groupCA)
color_y = input.color(color.new(#d32f2f, 20) , title="" , inline="y", group=groupCA)
show_d = input.bool(false, title="Show Daily" , inline="d", group=groupCA)
show_w = input.bool(false, title="Show Weekly" , inline="w", group=groupCA)
show_m = input.bool(true, title="Show Monthly" , inline="m", group=groupCA)
show_q = input.bool(true, title="Show Quarterly" , inline="q", group=groupCA)
show_y = input.bool(true, title="Show Yearly" , inline="y", group=groupCA)
// ------------------------------
is_new(resolution) =>
t = time(resolution)
not na(t) and (na(t[1]) or t > t[1])
is_new_year() =>
is_new("12M")
is_new_quarter() =>
is_new("3M") and (timeframe.isweekly or timeframe.isdaily or timeframe.isintraday)
is_new_month() =>
is_new("M") and not timeframe.ismonthly
is_new_week() =>
is_new("W") and not timeframe.isweekly and not timeframe.ismonthly
is_new_day() =>
is_new("D")
is_minutes() =>
timeframe.isminutes
// ------------------------------
plot_year() =>
is_new_year()
plot_quarter() =>
is_new_quarter() //not is_new_year() and is_new_quarter()
plot_month() =>
is_new_month() //not is_new_year() and not is_new_quarter() and is_new_month()
plot_week() =>
is_new_week() //not is_new_year() and not is_new_quarter() and not is_new_month() and is_new_week()
plot_day() =>
is_new_day() and is_minutes() //not is_new_year() and not is_new_quarter() and not is_new_month() and not is_new_week() and is_new_day() and is_minutes()
plot(show_y and plot_year() ? 1 : na , style=plot.style_histogram, linewidth=2, color=color_y, title="Year Break")
plot(show_q and plot_quarter() ? 1 : na , style=plot.style_histogram, linewidth=1, color=color_q, title="Quarter Break")
plot(show_m and plot_month() ? 1 : na , style=plot.style_histogram, linewidth=1, color=color_m, title="Month Break")
plot(show_w and plot_week() ? 1 : na , style=plot.style_histogram, linewidth=1, color=color_w, title="Week Break")
plot(show_d and plot_day() ? 1 : na , style=plot.style_histogram, linewidth=1, color=color_d, title="Day Break") |
Simple Range | https://www.tradingview.com/script/ilaDGmwW-Simple-Range/ | finallynitin | https://www.tradingview.com/u/finallynitin/ | 696 | 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/
// © finallynitin
//credits to theapextrader7, wrpteam2020, LazyBear, alpine_trader & TheScrutiniser
//@version=5
indicator('Simple Range', overlay=false)
//Display Inputs
string GRP0 = "════════ Display Options ═════════"
toggleDarkColors = input(title="Dark Mode", defval=false, group=GRP0)
toggleADR = input(title="Plot ADR", defval=false, group=GRP0)
toggleSQZ = input(title="Display Squeeze Colors", defval=true, group=GRP0)
toggleBB = input(title="Display Big Bar Shapes", defval=true, group=GRP0)
//Length Inputs
string GRP1 = "════════ Numerical Inputs ═════════"
NRlen = input.int(title='Narrow Range', defval=7, group=GRP1)
WRlen = input.int(title='Wide Range', defval=20, group=GRP1)
BBlen = input.int(title='Big Bars % Range', defval=5, group=GRP1)
BBvol = input.int(title='Big Bars Volume', defval=500000, group=GRP1)
ADRlen = input.int(20, title='ADR length', group=GRP1)
//Squeeze Colors
string GRP2 = "════════ Squeeze Options ═════════"
colorRed = input.color(color.red, 'High-compression Squeeze', group=GRP2)
//colorRed = toggleDarkColors ? color.new(color.red,80) : color.new(color.red,20)
colorOrange = input.color(color.orange, 'Mid-compression Squeeze', group=GRP2)
colorYellow = input.color(color.yellow, 'Low-compression Squeeze', group=GRP2)
colorGreen = input.color(color.green, 'Fired Squeeze', group=GRP2)
colorBlue = input.color(color.blue, 'No Squeeze', group=GRP2)
//Range Colors
string GRP3 = "════════ Range Options ═════════"
colorgreyer = toggleDarkColors ? input(color.new(color.white,20), "Neutral-range (dark-mode)", group=GRP3) : input(color.new(color.black,0), "Neutral-range (light-mode)", group=GRP3)
colorOranger = input.color(color.orange, 'Narrow Range', group=GRP3)
colorGreener = input.color(color.green, 'Wide Range up', group=GRP3)
colorRedder = input.color(color.red, 'Wide Range down', group=GRP3)
//--------00 Range------
Range = (high - low) * 100 / high
//--------01 Narrow Range------
//original concept from Thomas Bulkowski
//modified from "NR4 & NR7 Indicator" script by theapextrader7 https://in.tradingview.com/script/pXcafX0I-NR4-NR7-Indicator/
NR_Check(range_1) =>
range_1 < ta.lowest(range_1, NRlen - 1)[1] ? true : false
range_NR_Prep = high - low
range_isCurrentLowest = NR_Check(range_NR_Prep)
//--------02 Wide Range------
//modified from "WR - BC Identifier" script by wrpteam2020 https://in.tradingview.com/script/dOmlAmFZ-WR-BC-Identifier/
//C_Body = math.abs(close - open)
C_Bullish = close > open
C_Bearish = close < open
// Find the maximum percentage range in the last 20 bars
max_percentage_range = ta.highest(Range, 20)
// Determine if the current bar has the maximum percentage range in the last 20 bars
range_isCurrentHighest = Range == max_percentage_range
//--------PLOT------
//iff_1 = (showbb ? bcu : na) ? colorGreener : colorgreyer
//iff_2 = (showbb ? bcd : na) ? colorRedder : iff_1
iff_3 = range_isCurrentHighest and C_Bearish ? colorRedder : colorgreyer
iff_4 = range_isCurrentHighest and C_Bullish ? colorGreener : iff_3
rcolor = range_isCurrentLowest ? colorOranger : iff_4
// Plot histogram for wide range bars
plot(range_isCurrentHighest or range_isCurrentLowest? Range : na, title="Uncommon Range Bars", color=rcolor, style=plot.style_histogram, linewidth=4)
plot(not range_isCurrentHighest and not range_isCurrentLowest? Range : na, title="Common Range Bars", color=rcolor, style=plot.style_histogram, linewidth=1)
//--------03 Big Bars------
// this identifies big bars i.e. which are greater than equal to a pre-defined (default is 5%) high to low range
// on higher than a pre-defined volume level (default is 500000)
bbrange = math.abs(ta.roc(close, 1)) >= BBlen
bbvolume = volume >= BBvol
plotshape(toggleBB ? bbrange and bbvolume :na, style=shape.circle, color=colorgreyer, location=location.top)
//--------04 SQUEEZE------
// original concept from John Carter's book "Mastering the Trade"
// based on LazyBear's script (Squeeze Momentum Indicator) https://in.tradingview.com/script/nqQ1DT5a-Squeeze-Momentum-Indicator-LazyBear/
ma = ta.sma(close, 20)
devBB = ta.stdev(close, 20)
devKC = ta.sma(ta.tr, 20)
//Bollinger 2x
upBB = ma + devBB * 2
lowBB = ma - devBB * 2
//Keltner 2x
upKCWide = ma + devKC * 2
lowKCWide = ma - devKC * 2
//Keltner 1.5x
upKCNormal = ma + devKC * 1.5
lowKCNormal = ma - devKC * 1.5
//Keltner 1x
upKCNarrow = ma + devKC
lowKCNarrow = ma - devKC
sqzOnWide = lowBB >= lowKCWide and upBB <= upKCWide //Low-compression Squeeze: YELLOW
sqzOnNormal = lowBB >= lowKCNormal and upBB <= upKCNormal //Mid-compression Squeeze: ORANGE
sqzOnNarrow = lowBB >= lowKCNarrow and upBB <= upKCNarrow //High-compression Squeeze: RED
sqzOffWide = lowBB < lowKCWide and upBB > upKCWide //Fired Squeeze: GREEN
noSqz = sqzOnWide == false and sqzOffWide == false //No Squeeze: BLUE
sq_color = noSqz ? colorBlue : sqzOnNarrow ? colorRed : sqzOnNormal ? colorOrange : sqzOnWide ? colorYellow : colorGreen
bgcolor(toggleSQZ ? toggleDarkColors? color.new(sq_color, 30): color.new(sq_color, 80): na)
//--------05 ADR%------
// original idea by alpine_trader
// Modified from "ADR% - Average Daily Range % by MikeC" script by TheScrutiniser https://in.tradingview.com/script/6KVjtmOY-ADR-Average-Daily-Range-by-MikeC-AKA-TheScrutiniser/
//var table rangeTable = table.new(position=position.middle_right, columns=2, rows=2, frame_color=color.gray, frame_width=1, border_width=1, border_color=color.black)
dhigh = request.security(syminfo.tickerid, 'D', high)
dlow = request.security(syminfo.tickerid, 'D', low)
ADR = 100 * (ta.sma(dhigh / dlow, ADRlen) - 1)
plot(toggleADR ? ADR:na, title="ADR", color=colorgreyer, style=plot.style_line, linewidth=1)
//--------TABLE------
string GRP4 = "════════ Table Options ═════════"
string tablesize = input.string("small", "Size", inline = "21", group = GRP4, options = ["tiny", "small", "normal", "large", "huge", "auto"])
string tableposY = input.string("middle", "↕", inline = "21", group = GRP4, options = ["top", "middle", "bottom"])
string tableposX = input.string("right", "↔", inline = "21", group = GRP4, options = ["left", "center", "right"])
ColorBackground = toggleDarkColors ? input(color.new(color.black, 0), "Background Color (dark-mode)", inline = "21",group=GRP4) : input(color.new(color.white, 0), "Background Color (light-mode)", inline = "21", group=GRP4)
TextCol = toggleDarkColors ? input(color.new(color.white, 0), "Text Color (dark-mode)", inline = "21",group=GRP4) : input(color.new(color.black, 0), "Text Color (light-mode)", inline = "21", group=GRP4)
ColorGreenText = toggleDarkColors ? color.new(color.white, 0) : color.new(color.green, 0)
ColorOrangeText = toggleDarkColors ? color.new(color.white, 0) : color.new(color.orange, 0)
var table rangeTable = table.new(tableposY + "_" + tableposX, 3, 3, frame_color=color.new(#999999, 50), frame_width=1,border_color=color.new(#999999, 50), border_width=1)
if barstate.islast
table.cell(rangeTable, 0, 1, text="ADR", text_halign=text.align_center, bgcolor=ColorBackground, text_color=TextCol, text_size=tablesize)
table.cell(rangeTable, 0, 2, text="Range", text_halign=text.align_center, bgcolor=ColorBackground, text_color=TextCol, text_size=tablesize)
table.cell(rangeTable, 1, 1, text=na(ADR) ? '-' : str.tostring(math.round(ADR,1)) +" "+ "%", text_halign=text.align_center, bgcolor=ColorBackground, text_color=TextCol, text_size=tablesize)
table.cell(rangeTable, 1, 2, text=na(Range) ? '-' : str.tostring(math.round(Range,1)) +" "+ "%", text_halign=text.align_center, bgcolor=ColorBackground, text_color=TextCol, text_size=tablesize)
|
cankardesler stoploss v2 | https://www.tradingview.com/script/6xK9lhTi-cankardesler-stoploss-v2/ | efedoracankardes | https://www.tradingview.com/u/efedoracankardes/ | 20 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © efedoracankardes
//@version=5
indicator("cankardesler stoploss v2", overlay=true)
ys = high-open
as0 = close - low
ts = close - (2*ta.atr(14))
tsry = ((ts-(ta.stdev(as0,5))))
tsye = math.min(ts,tsry)
plot(tsye, color=color.red)
ts2 = close + (2*ta.atr(14))
tsra = ((ts2+(ta.stdev(ys,5))))
tsae = math.max(ts2,tsra)
plot(tsae, color=color.green) |
Simple Zigzag UDT | https://www.tradingview.com/script/FLrM2CsC-Simple-Zigzag-UDT/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 491 | 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
//@version=5
indicator('Simple Zigzag UDT', 'SZU', true, max_bars_back = 500)
// 0. Inputs
// 1. Types
// 2. Switches
// 3. Variables and arrays
// 4. Custom Functions
// 5. Execution
// 6. Constructs
//#region ———————————————————— 0. Inputs
T0 = 'Zigzag values\nDefault : 14\nMin : 2\nMax : 50'
T1 = 'Short\nExample : L or LL\nLong\nExample : Low or Lower Low'
T2 = 'Constrast : Constrast color of chart background\nCustom : Input color\nNone : Color follow Trend Color'
T3 = 'Small font size recommended for mobile app or multiple layout'
T4 = 'Default\nStyle : Solid\nWidth : 4'
length = input.int( 14, 'Length', minval = 2, maxval = 50, tooltip = T0)
colorUp = input.color(color.lime,'Trend Color', inline = '0')
colorDn = input.color( color.red, '', inline = '0')
showLabel = input.bool( true, 'Label', group = 'Show / hide', inline = '1')
showLine = input.bool( true, 'Line', group = 'Show / hide', inline = '1')
displayLabel = input.string( 'HHLL', 'Text', group = 'Label', inline = '2', options = ['HHLL', 'HL'])
nameHL = input.string( 'Short', '', group = 'Label', inline = '2', options = ['Short', 'Long'], tooltip = T1)
colorLabel = input.string( 'Trend', 'Color', group = 'Label', inline = '3', options = ['Contrast', 'Custom', 'Trend'])
customLabel = input.color(color.blue, '', group = 'Label', inline = '3', tooltip = T2)
sizeLabel = input.string( 'normal', 'Size', group = 'Label', inline = '4', options = ['tiny', 'small', 'normal', 'large', 'huge'], tooltip = T3)
lineType = input.string( 'solid', 'Display', group = 'Line', inline = '5', options = ['dash', 'dot', 'solid', 'arrow right', 'arrow left'])
width = input.int( 4, '', group = 'Line', inline = '5', minval = 1, maxval = 4, tooltip = T4)
colorLine = input.string( 'Trend', 'Color', group = 'Line', inline = '6', options = ['Contrast', 'Custom', 'Trend'])
customLine = input.color(color.blue, '', group = 'Line', inline = '6', tooltip = T2)
//#endregion
//#region ———————————————————— 1. Types
// @type Used for label
// @field Hi Float value of high
// @field Lo Float value of low
type HL
string Hi = na
string Lo = na
// @type Used for point especially for array
// @field x int value for bar_index
// @field y float value for price
// @field sty label style
// @field col color for text label
// @field str high or low string
type point
int x = na
float y = na
string sty = na
color col = na
string str = na
// @type Used for initial setup
// @field hi high value
// @field lo low value
// @field colorHi color for high value
// @field colorLo color for low value
// @field strHi string for high value
// @field strLo string for low value
type startUp
float hi = na
float lo = na
color colorHi = na
color colorLo = na
string strHi = na
string strLo = na
//#endregion
//#region ———————————————————— 2. Switches
[H, L] = switch nameHL
'Short' => [ 'H', 'L']
'Long' => ['HIGH', 'LOW']
[Hi, Lo] = switch nameHL
'Short' => [ 'H', 'L']
'Long' => ['HIGHER\n', 'LOWER\n']
switchLine = switch lineType
'dash' => line.style_dashed
'dot' => line.style_dotted
'solid' => line.style_solid
'arrow right' => line.style_arrow_right
'arrow left' => line.style_arrow_left
switchLabelColor = switch colorLabel
'Contrast' => chart.fg_color
'Custom' => customLabel
switchLineColor = switch colorLine
'Contrast' => chart.fg_color
'Custom' => customLine
//#endregion
//#region ———————————————————— 3. Variables and arrays
float ph = na, ph := ta.highestbars(high, length) == 0 ? high : na
float pl = na, pl := ta.lowestbars( low, length) == 0 ? low : na
var dir = 0, dir := ph and na(pl) ? 1 : pl and na(ph) ? -1 : dir
var zigzag = array.new<point>(0)
oldzigzag = zigzag.copy()
dirchanged = ta.change(dir)
hiLo = HL.new(Hi, Lo)
varSetup = startUp.new(ph, pl, colorUp, colorDn, H, L)
//#endregion
//#region ———————————————————— 4. Custom Functions
// @function variable for point
// @param setup type containing ternary conditional operator
// @returns newPoint to be used later in initialize
method dirVariables(startUp setup = na) =>
var point newPoint = na
x = bar_index
y = dir == 1 ? setup.hi : setup.lo
sty = dir == 1 ? label.style_label_down : label.style_label_up
col = dir == 1 ? setup.colorHi : setup.colorLo
str = dir == 1 ? setup.strHi : setup.strLo
newPoint := point.new(x, y, sty, col, str)
newPoint
// @function initialize zigzag array
// @param setup type containing ternary conditional operator
// @param maxSize maximum array size
// @returns zigzag array after cleanup
method initialize(point[] zigzag = na, startUp setup = na, int maxSize = 10)=>
newPoint = setup.dirVariables()
zigzag.unshift(newPoint)
if zigzag.size() > maxSize
zigzag.pop()
// @function update zigzag array
// @param setup type containing ternary conditional operator
// @param maxSize maximum array size
// @param dir direction value
// @returns zigzag array after cleanup
method update(point[] zigzag = na, startUp setup = na, maxSize = 10, int dir = na)=>
if array.size(zigzag) == 0
zigzag.initialize(setup, maxSize)
else
newPoint = setup.dirVariables()
dirOver = dir == 1 and newPoint.y > zigzag.get(0).y
dirLess = dir == -1 and newPoint.y < zigzag.get(0).y
if dirOver or dirLess
zigzag.set(0, newPoint)
point.new(na, na, na, na, na)
// @function compare zigzag
// @param zigzag original array
// @param oldzigzag copied array
// @returns boolOr Or statement
// @returns boolAnd And statement
method boolPoint(point[] zigzag = na, point[] oldzigzag = na, int offset = 0) =>
boolOr = zigzag.get(offset + 0).x != oldzigzag.get(offset + 0).x or zigzag.get(offset + 0).y != oldzigzag.get(offset + 0).y
boolAnd = zigzag.get(offset + 1).x == oldzigzag.get(offset + 1).x and zigzag.get(offset + 1).y == oldzigzag.get(offset + 1).y
[boolOr, boolAnd]
// @function create label based on zigzag array
// @param zigzag original array
// @param size font size
// @param offset default value zero
// @returns new label
method createLabel(point[] zigzag = na, string size = na, int offset = 0) =>
label.new( x = int(zigzag.get(offset + 0).x),
y = zigzag.get(offset + 0).y,
text = zigzag.get(offset + 0).str,
xloc = xloc.bar_index,
color = color.new(color.blue, 100),
style = zigzag.get(offset + 0).sty,
textcolor = zigzag.get(offset + 0).col,
size = size,
tooltip = zigzag.get(offset + 0).str + '\n' + str.tostring(zigzag.get(offset + 0).y))
// @function create line based on zigzag array
// @param zigzag original array
// @param width line thickness
// @param style line style
// @param offset default value zero
// @returns new line
method createLine(point[] zigzag = na, int width = na, string style = na, int offset = 0) =>
line.new(x1 = int(zigzag.get(offset + 1).x),
y1 = zigzag.get(offset + 1).y,
x2 = int(zigzag.get(offset + 0).x),
y2 = zigzag.get(offset + 0).y,
xloc = xloc.bar_index,
color = zigzag.get(offset + 0).col,
style = style,
width = width)
// @function create line based on zigzag array
// @param zigzag original array
// @param hiLo switch value
// @param offset default value zero
// @returns ternary conditional of hiLo
method compareHL(point[] zigzag = na, HL hiLo = na, int offset = 0) =>
dir == 1 ? zigzag.get(offset + 0).y > zigzag.get(offset + 2).y ? hiLo.Hi : hiLo.Lo :
zigzag.get(offset + 0).y < zigzag.get(offset + 2).y ? hiLo.Lo : hiLo.Hi
// @function set text and tooltip for label
// @param this original array
// @param str string value for text
// @param tip string value for tooltip
method textTip(label this = na, string str = na, string tip = na) =>
this.set_text( str)
this.set_tooltip(tip)
//#endregion
//#region ———————————————————— 5. Execution
if ph or pl
if dirchanged
zigzag.initialize( varSetup, 4)
else
zigzag.update(varSetup, 4, dir)
//#endregion
//#region ———————————————————— 6. Constructs
if zigzag.size() >= 3
var line dirLine = na
var label dirLabel = na
var string dirString = na
[boolOr, boolAnd] = zigzag.boolPoint(oldzigzag)
if boolOr
if boolAnd
dirLine.delete()
dirLabel.delete()
if showLabel
if displayLabel == 'HL' or displayLabel == 'HHLL'
dirLabel := zigzag.createLabel(sizeLabel)
if displayLabel == 'HHLL' and zigzag.size() >= 4
dirString := zigzag.compareHL(hiLo)
dirLabel.textTip(dirString + zigzag.get(0).str, dirString + zigzag.get(0).str + '\n' + str.tostring(zigzag.get(0).y))
if colorLabel != 'Trend'
dirLabel.set_textcolor(switchLabelColor)
if showLine
dirLine := zigzag.createLine(width, switchLine)
if colorLine != 'Trend'
dirLine.set_color(switchLineColor)
// //#endregion |
Sup/Res Levels [QuantVue] | https://www.tradingview.com/script/TzQgAQo4-Sup-Res-Levels-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 304 | 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/
// © QuantVue
//@version=5
indicator(title=' Support and Resistance Levels [QuantVue]', shorttitle=' Support and Resistance Levels [QuantVue]', overlay=true, max_bars_back=1000)
//
toggleBreaks = input(true, title='Breaks')
leftBars = input(20, title='Left Bars ')
rightBars = input(20, title='Right Bars')
volumeThresh = input(25, title='Volume Thres')
//
highUsePivot = fixnan(ta.pivothigh(leftBars, rightBars)[1])
lowUsePivot = fixnan(ta.pivotlow(leftBars, rightBars)[1])
r1 = plot(highUsePivot, color=ta.change(highUsePivot) ? na : #e08686, linewidth=2, offset=-(rightBars + 1), title='Resistance')
s1 = plot(lowUsePivot, color=ta.change(lowUsePivot) ? na : #7edb97, linewidth=2, offset=-(rightBars + 1), title='Support')
//Volume %
short = ta.ema(volume, 5)
long = ta.ema(volume, 10)
osc = 100 * (short - long) / long
//For breaks with volume
plotshape(toggleBreaks and ta.crossunder(close, lowUsePivot) and not(open - close < high - open) and osc > volumeThresh, title='Break', text='B', style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.white, 0), size=size.tiny)
plotshape(toggleBreaks and ta.crossover(close, highUsePivot) and not(open - low > close - open) and osc > volumeThresh, title='Break', text='B', style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), textcolor=color.new(color.white, 0), size=size.tiny)
//For bull / bear wicks
plotshape(toggleBreaks and ta.crossover(close, highUsePivot) and open - low > close - open, title='Break', text='Bull Wick', style=shape.labelup, location=location.belowbar, color=color.rgb(137, 178, 139), textcolor=color.new(color.white, 0), size=size.tiny, transp=0)
plotshape(toggleBreaks and ta.crossunder(close, lowUsePivot) and open - close < high - open, title='Break', text='Bear Wick', style=shape.labeldown, location=location.abovebar, color=color.rgb(236, 131, 131), textcolor=color.new(color.white, 0), size=size.tiny, transp=0)
alertcondition(ta.crossunder(close, lowUsePivot) and osc > volumeThresh, title='Support Broken', message='Support Broken')
alertcondition(ta.crossover(close, highUsePivot) and osc > volumeThresh, title='Resistance Broken', message='Resistance Broken')
|
Stock Relative Strength Power Index | https://www.tradingview.com/script/dIU5V4Tx-Stock-Relative-Strength-Power-Index/ | christoefert | https://www.tradingview.com/u/christoefert/ | 164 | 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/
// © christoefert
//@version=5
indicator(title="Relative Strength vs. Market Power Rating", shorttitle="Power Rating", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
//Get the Rates of Change
//Get Rate of Chage for Security
length = input.int(5, minval=1, title = "Current Ticker Length")
source = input(close, "Source")
roc = 100 * (source - source[length])/source[length]
//Get Rate of Change for Market
length2 = input.int(5, minval=1, title = "SPY Length")
MarketChange = request.security("SPY", "", close)
source2 = MarketChange
roc2 = 100 * (source2 - source2[length2])/source2[length2]
//Get Rate of Change for Sector Index
length3 = input.int(5, minval = 1, title = "Sector ETF")
SectorChange = (request.security(input.symbol(""), "", close))
source3 = SectorChange
roc3 = 100 * (source3 - source3[length3])/source3[length3]
//Get the Normalized ATRs
//Get Normalized ATR for Security
Normalized_ATR_Security = (ta.atr(length)/close) * 100
//Get Normalized ATR for Market
MarketATR = (request.security("SPY", "", ta.atr(length2)))
Normalized_ATR_Market = (MarketATR/MarketChange) * 100
//Get Normalized ATR for Sector ETF
SectorATR = (request.security(input.symbol(""), "", ta.atr(length3)))
Normalized_ATR_Sector = (SectorATR/SectorChange) * 100
//Plot Everything
hline(0, color=#787B86, title="Zero Line")
hline(1, color=color.green, title="Long Line")
hline(-1, color=color.red, title="ShortLine")
plot(roc/Normalized_ATR_Security, color=color.aqua, title = "Current Security")
plot(roc2/Normalized_ATR_Market, color=color.red, title = "SPY")
plot(roc3/Normalized_ATR_Sector, color=color.white, title = "Sector")
|
VolumeFlow | https://www.tradingview.com/script/3zG6BKnk-VolumeFlow/ | Options360 | https://www.tradingview.com/u/Options360/ | 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/
// © Options360
// This uses altered pieces of code from: Options360 "FibVIP" indicator, Tradingview "up / down volume" indicator, Tradingview "Accumulation/Distribution" indicator
//@version=5
indicator("VolumeFlow", shorttitle='VF')
////
normalize(src, min, max) =>
var historicMin = 10e10
var historicMax = -10e10
historicMin := math.min(nz(src, historicMin), historicMin)
historicMax := math.max(nz(src, historicMax), historicMax)
min + (max - min) * (src - historicMin) / math.max(historicMax - historicMin, 10e-10)
rescale(src, oldMin, oldMax, newMin, newMax) =>
newMin + (newMax - newMin) * (src - oldMin) / math.max(oldMax - oldMin, 10e-10)
//
UDVolume() =>
posVol = 0.0
negVol = 0.0
switch
close > open => posVol += volume
close < open => negVol -= volume
close >= close[1] => posVol += volume
close < close[1] => negVol -= volume
[posVol, negVol]
lowerTimeframe = switch
timeframe.isintraday => "1"
timeframe.isdaily => "5"
=> "60"
[upV, downV] = request.security_lower_tf(syminfo.tickerid, '1', UDVolume())
upVolume = array.sum(upV)
downVolume = array.sum(downV)
delta = upVolume + downVolume
//
v = ta.change(close) >= 0 ? volume : -volume
//
var cumVol = 0.
cumVol += nz(volume)
ad = ta.cum(close==high and close==low or high==low ? 0 : (((2*close-low-high)/(high-low))*volume)/1000)
//
delta11 = input(1,"+Volume-")
delta33 = input(2,"VolumeFast")
delta22 = input(3,"VolumeSlow")
delta44 = input(5,"Accumu/Dist")
delta55 = input(1,"Total")
//
delta1 = ta.sma(delta, delta11)
delta2 = ta.sma(ta.rsi(v, delta22), delta22)
delta3 = ta.rsi(v, delta33)
delta4 = ta.sma(ta.rsi(ad, delta44), delta44)
d1 = normalize(delta1, -100, 100)
d2 = rescale(delta2, 0, 100, -100, 100)
d3 = rescale(delta3, 0, 100, -100, 100)
d4 = rescale(delta4, 0, 100, -100, 100)
d5 = ta.sma((d1 + d2 + d3 + d4)/4, delta55)
//
plot(d1, "+Volume-", color = delta > 0 ? color.new(#3cfe12, 0) : color.new(#ff0202, 0), linewidth=2)
plot(d1, "track+Volume-", color = delta > 0 ? color.new(#3cfe12, 0) : color.new(#ff0202, 0), linewidth=2, trackprice=true, offset=-9999, display=display.none)
plot(d3, 'VolumeFast', color.new(#0e2be8, 0), linewidth=2)
plot(d3, 'trackVolumeFast', color.new(#0e2be8, 0), linewidth=2, trackprice=true, offset=-9999, display=display.none)
plot(d2, 'VolumeSlow', color = #ffffff, linewidth=2)
plot(d2, 'trackVolumeSlow', color = #ffffff, linewidth=2, trackprice=true, offset=-9999, display=display.none)
plot(d4, "Accumu/Dist", color=#7b4246, linewidth=2)
plot(d4, "trackAccumu/Dist", color=#7b4246, linewidth=2, trackprice=true, offset=-9999, display=display.none)
plot(d5, "Total", color=#ff7700, linewidth=2)
plot(d5, "trackTotal", color=#ff7700, linewidth=2, trackprice=true, offset=-9999, display=display.none)
//
hline(0, 'zero', color=#ffffff, linestyle=hline.style_dotted, linewidth=1)
h1 = hline(100, 'high', color=#ffffff, linestyle=hline.style_dotted, linewidth=1)
h2 = hline(-100, 'low', color=#ffffff, linestyle=hline.style_dotted, linewidth=1)
h3 = hline(50, 'up', color=#ffffff, linestyle=hline.style_dotted, linewidth=1)
h4 = hline(-50, 'down', color=#ffffff, linestyle=hline.style_dotted, linewidth=1)
fill(h3, h4, color=color.new(#acc2fc, 95), title='Background', display=display.none)
////
|
Card Dealer | https://www.tradingview.com/script/iS2iuA4G-Card-Dealer/ | BarefootJoey | https://www.tradingview.com/u/BarefootJoey/ | 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/
// © BarefootJoey
//
// ██████████████████████████████████████████████████████████████████████
// █▄─▄─▀██▀▄─██▄─▄▄▀█▄─▄▄─█▄─▄▄─█─▄▄─█─▄▄─█─▄─▄─███▄─▄█─▄▄─█▄─▄▄─█▄─█─▄█
// ██─▄─▀██─▀─███─▄─▄██─▄█▀██─▄███─██─█─██─███─███─▄█─██─██─██─▄█▀██▄─▄██
// █▄▄▄▄██▄▄█▄▄█▄▄█▄▄█▄▄▄▄▄█▄▄▄███▄▄▄▄█▄▄▄▄██▄▄▄██▄▄▄███▄▄▄▄█▄▄▄▄▄██▄▄▄██
//
//@version=5
indicator("Card Dealer", overlay=true)
// Input
position = input.string(position.top_right, "Location", [position.top_center, position.top_right, position.middle_right, position.bottom_right, position.bottom_center, position.bottom_left, position.middle_left, position.top_left])
size = input.string(size.huge, "Size", [size.tiny, size.small, size.normal, size.large, size.huge])
transp = input.int(0, "Transparency", minval=0, maxval=100)
// List of Numbers
q1 = 'A'
q2 = '2'
q3 = '3'
q4 = '4'
q5 = '5'
q6 = '6'
q7 = '7'
q8 = '8'
q9 = '9'
q10 = '10'
q11 = 'J'
q12 = 'Q'
q13 = 'K'
// List of Suits
s1 = '♠'
s2 = '♣'
s3 = '♥'
s4 = '♦'
// Card Randomizing Logic
r = math.round(math.random(1, 13))
numout =
r == 1 ? q1 : r == 2 ? q2 : r == 3 ? q3 : r == 4 ? q4 : r == 5 ? q5 : r == 6 ? q6 : r == 7 ? q7 : r == 8 ? q8 : r == 9 ? q9 :
r == 10 ? q10 : r == 11 ? q11 : r == 12 ? q12 : r == 13 ? q13 :
na
s = math.round(math.random(1, 4))
suitout =
s == 1 ? s1 : s == 2 ? s2 : s == 3 ? s3 : s == 4 ? s4 :
na
colout =
s == 1 ? color.black : s == 2 ? color.black : s == 3 ? color.red : s == 4 ? color.red :
na
// Table Output
var table quote = table.new(position, 1, 1, color.new(color.white, transp))
if barstate.isconfirmed
table.cell(quote, 0, 0, str.tostring(numout) + str.tostring(suitout), text_size = size, text_color = color.new(colout, transp), tooltip="🃏 Double click to access settings")
// EoS made w/ ❤ by @BarefootJoey ✌💗📈
|
Arron Meter With Alerts [Skiploss] | https://www.tradingview.com/script/rq4zeY4d-Arron-Meter-With-Alerts-Skiploss/ | Skiploss | https://www.tradingview.com/u/Skiploss/ | 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/
// © Skiploss
//@version=5
indicator(title = "Arron Meter With Alerts [Skiploss]", shorttitle = "AMWA v0.77")
// Setting
length = input(14, 'Length', group = 'Aroon Setting')
plotBull = input(title = "Plot Bullish", defval = true, group = 'Alert Settings')
plotBear = input(title = "Plot Bearish", defval = true, group = 'Alert Settings')
// Arron
upper = 100 * (ta.highestbars(high, length +1) + length) / length
lower = 100 * ( ta.lowestbars( low, length +1) + length) / length
// Style Setting
color_css_gradient_longmomentum = input(#bfcdcc, 'Aroon UP', group = 'Style Setting')
color_css_gradient_shortmomentum = input(#ff8e8e, 'Aroon Down', group = 'Style Setting')
// Aroon Meter
var meter = table.new(position.top_right,2,2)
if barstate.islast
// 1st Row
table.cell(meter, 0, 0, ' Aroon UP ', text_color = #787b86, bgcolor = na)
table.cell(meter, 1, 0, 'Aroon Down', text_color = #787b86, bgcolor = na)
// 2nd Row
table.cell(meter, 0, 1, str.tostring(upper, '#.##')+'%', text_color = color_css_gradient_longmomentum, bgcolor = color.new(color_css_gradient_longmomentum,90))
table.cell(meter, 1, 1, str.tostring(lower, '#.##')+'%', text_color = color_css_gradient_shortmomentum, bgcolor = color.new(color_css_gradient_shortmomentum,90))
// Plot Aroon
plot(upper, "Aroon Up", color=color_css_gradient_longmomentum)
plot(lower, "Aroon Down", color=color_css_gradient_shortmomentum)
// H Line
hline(115, color = #00000000)
hline(-15, color = #00000000)
// Signals
plotshape(plotBull == true and ta.crossover(upper,lower) and ta.hma(close, 250) < ta.ema(close, 12) and upper > 70 and lower < 70, title = "Bull", color = #8eff8e, textcolor = #000000, text = "Bull", style = shape.labelup, location = location.bottom, size = size.auto)
plotshape(plotBear == true and ta.crossunder(upper,lower) and ta.hma(close, 250) > ta.ema(close, 12) and lower > 70 and upper < 70, title = "Bear", color = #e8ff8e, textcolor = #000000, text = "Bear", style = shape.labeldown, location = location.top, size = size.auto)
// Alerts
alertcondition( ta.crossover(upper,lower) and ta.hma(close, 250) < ta.ema(close, 12) and upper > 70 and lower < 70, title = "Bullish Aroon", message = "Focus Long Position on {{exchange}}:{{ticker}}")
alertcondition(ta.crossunder(upper,lower) and ta.hma(close, 250) > ta.ema(close, 12) and lower > 70 and upper < 70, title = "Bearish Aroon", message = "Focus Short Position on {{exchange}}:{{ticker}}") |
Broadening Formations [TFO] | https://www.tradingview.com/script/RE1qjApP-Broadening-Formations-TFO/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 1,005 | 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/
// © tradeforopp
//@version=5
indicator("Broadening Formations [TFO]", overlay = true, max_lines_count = 500)
// -------------------- Inputs --------------------
var g1 = "Settings"
show_pivots = input.bool(true, "Show Fractal Pivots", group = g1)
show_tl_test = input.bool(true, "Show Deviations from Range", group = g1)
delete_old = input.bool(false, "Delete Old Trendlines", group = g1)
pivot_strength = input.int(20, minval = 1, maxval = 50, title = "Pivot Strength", tooltip = "Determines what fractal length is used for highs and lows", group = g1)
var g2 = "Style"
bf_color = input.color(color.gray, "Initial Color", group = g2)
deviation_color = input.color(color.red, "Deviation Color", group = g2)
line_style = input.string(defval = 'Solid', title = "Line Style", inline = "Pivot Style", options = ['Solid', 'Dotted', 'Dashed'], group = g2)
line_width = input.int(defval = 1, minval = 1, maxval = 5, title = "", inline = "Pivot Style", group = g2)
// -------------------- Inputs --------------------
// -------------------- Variables --------------------
fractal_idx = pivot_strength
max_candles_ago = 100
max_array_size = math.floor(max_candles_ago / 2)
// -------------------- Variables --------------------
// -------------------- Initializing --------------------
var pivot_lows = array.new_float(0)
var pivot_lows_idx = array.new_int(0)
var pivot_highs = array.new_float(0)
var pivot_highs_idx = array.new_int(0)
var line upper_tl = na
var line lower_tl = na
// -------------------- Initializing --------------------
// -------------------- Functions --------------------
get_line_type(style) =>
result = switch style
'Solid' => line.style_solid
'Dotted' => line.style_dotted
'Dashed' => line.style_dashed
result
fractal_high(i) =>
accumulator = true
for j = -i to i
if j != 0
accumulator := accumulator and high[i] > high[i + j]
result = accumulator
fractal_low(i) =>
accumulator = true
for j = -i to i
if j != 0
accumulator := accumulator and low[i] < low[i + j]
result = accumulator
append_array(a, x) =>
array.unshift(a, x)
if array.size(a) > max_array_size
array.pop(a)
// -------------------- Functions --------------------
// -------------------- Test Fractal Low/High --------------------
line_style := get_line_type(line_style)
is_fractal_high = fractal_high(fractal_idx)
is_fractal_low = fractal_low(fractal_idx)
new_low = false
new_high = false
if is_fractal_low
append_array(pivot_lows, low[fractal_idx])
append_array(pivot_lows_idx, fractal_idx)
if is_fractal_high
append_array(pivot_highs, high[fractal_idx])
append_array(pivot_highs_idx, fractal_idx)
plotshape(show_pivots and is_fractal_high, style = shape.circle, color = bf_color, location = location.abovebar, offset = -fractal_idx, size = size.tiny)
plotshape(show_pivots and is_fractal_low, style = shape.circle, color = bf_color, location = location.belowbar, offset = -fractal_idx, size = size.tiny)
// -------------------- Test Fractal Low/High --------------------
// -------------------- Plot Trendlines --------------------
if array.size(pivot_highs) > 1 and array.size(pivot_lows) > 1
low_new = array.get(pivot_lows, 0)
low_old = array.get(pivot_lows, 1)
low_new_idx = array.get(pivot_lows_idx, 0)
low_old_idx = array.get(pivot_lows_idx, 1)
high_new = array.get(pivot_highs, 0)
high_old = array.get(pivot_highs, 1)
high_new_idx = array.get(pivot_highs_idx, 0)
high_old_idx = array.get(pivot_highs_idx, 1)
if low_new < low_old
x1 = bar_index - low_old_idx
x2 = bar_index - fractal_idx
y1 = low_old
y2 = low_new
slope = (y2 - y1) / (x2 - x1)
valid_tl = true
for i = 0 to x2 - x1
curr_y = slope * i + low_old
if low[x2 - x1 + fractal_idx - i] < curr_y
valid_tl := false
break
if valid_tl
if not na(lower_tl) and delete_old
line.delete(lower_tl)
offset = slope * fractal_idx
lower_tl := line.new(bar_index - low_old_idx, low_old, bar_index - low_new_idx, low_new, style = line_style, color = bf_color, width = line_width)
array.set(pivot_lows, 0, na)
array.set(pivot_lows, 1, na)
if high_new > high_old
x1 = bar_index - high_old_idx
x2 = bar_index - fractal_idx
y1 = high_old
y2 = high_new
slope = (y2 - y1) / (x2 - x1)
valid_tl = true
for i = 0 to x2 - x1
curr_y = slope * i + high_old
if high[x2 - x1 + fractal_idx - i] > curr_y
valid_tl := false
break
if valid_tl
if not na(upper_tl) and delete_old
line.delete(upper_tl)
offset = slope * fractal_idx
upper_tl := line.new(bar_index - high_old_idx, high_old, bar_index - high_new_idx, high_new, style = line_style, color = bf_color, width = line_width)
array.set(pivot_highs, 0, na)
array.set(pivot_highs, 1, na)
// -------------------- Plot Trendlines --------------------
// -------------------- Deviation From Range --------------------
upper_test = false
lower_test = false
if not na(upper_tl)
x1 = line.get_x1(upper_tl)
x2 = line.get_x2(upper_tl)
y1 = line.get_y1(upper_tl)
y2 = line.get_y2(upper_tl)
slope = (y2 - y1) / (x2 - x1)
new_y = y2 + slope * (bar_index - x2)
if high > new_y
if delete_old
line.delete(upper_tl)
else
line.set_x2(upper_tl, bar_index)
line.set_y2(upper_tl, new_y)
line.set_color(upper_tl, deviation_color)
upper_tl := na
upper_test := true
if not na(lower_tl)
x1 = line.get_x1(lower_tl)
x2 = line.get_x2(lower_tl)
y1 = line.get_y1(lower_tl)
y2 = line.get_y2(lower_tl)
slope = (y2 - y1) / (x2 - x1)
new_y = y2 + slope * (bar_index - x2)
if low < new_y
if delete_old
line.delete(lower_tl)
else
line.set_x2(lower_tl, bar_index)
line.set_y2(lower_tl, new_y)
line.set_color(lower_tl, deviation_color)
lower_tl := na
lower_test := true
plotshape(show_tl_test and upper_test, style = shape.triangledown, color = deviation_color, size = size.small, location = location.abovebar)
plotshape(show_tl_test and lower_test, style = shape.triangleup, color = deviation_color, size = size.small, location = location.belowbar)
alertcondition(upper_test, "Upper Trendline Test")
alertcondition(lower_test, "Lower Trendline Test")
// -------------------- Deviation From Range --------------------
// -------------------- Fractal Low --------------------
if array.size(pivot_lows) > 0
for i = 0 to array.size(pivot_lows) - 1
low_idx = array.get(pivot_lows_idx, i)
// Increase every pivot bar index by 1
array.set(pivot_lows_idx, i, low_idx + 1)
// -------------------- Fractal Low --------------------
// -------------------- Fractal High --------------------
if array.size(pivot_highs) > 0
for i = 0 to array.size(pivot_highs) - 1
high_idx = array.get(pivot_highs_idx, i)
// Increase every pivot bar index by 1
array.set(pivot_highs_idx, i, high_idx + 1)
// -------------------- Fractal High -------------------- |
RedK TrendBeads: 3 x MA Crossover Signal with Preset Templates | https://www.tradingview.com/script/aeXSQs4p-RedK-TrendBeads-3-x-MA-Crossover-Signal-with-Preset-Templates/ | RedKTrader | https://www.tradingview.com/u/RedKTrader/ | 336 | 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/
// © RedKTrader
//@version=5
indicator('RedK TrendBeads', shorttitle='K-TrendBeads v1.0', overlay=true, timeframe='', timeframe_gaps=false)
// ---------------------------------------------------------------------------------------------------------------
// 3 MA-Line Ribbon on a slow MA filter line.. just a super simple set-up
//==============================================================================
// updated this version of LazyLine() to reflect a regular WMA for length < 5
f_LazyLine(_data, _length) =>
w1 = 0, w2 = 0, w3 = 0
L1 = 0.0, L2 = 0.0, L3 = 0.0
w = _length / 3
if _length > 4
w2 := math.round(w)
w1 := math.round((_length - w2) / 2)
w3 := int((_length - w2) / 2)
L1 := ta.wma(_data, w1)
L2 := ta.wma(L1, w2)
L3 := ta.wma(L2, w3)
else
L3 := ta.wma(_data, _length)
L3
//==============================================================================
// =============================================================================
f_getMA(source, length, type) =>
type == "SMA" ? ta.sma(source, length) :
type == "EMA" ? ta.ema(source, length) :
type == "WMA" ? ta.wma(source, length) :
type == "HMA" ? ta.hma(source, length) :
f_LazyLine(source, length)
// =============================================================================
// ------------------------------------------------------------------------------------------------
// Inputs
// ------------------------------------------------------------------------------------------------
grp_p = 'Use Preset MA Templates or Manually Customize Values'
grp_m = 'Price Proxy & MA Lines :'
grp_f = 'Filter MA :'
pset_1 = 'RedK_1: 8RSS / 15RSS / 21RSS / 30SMA'
pset_2 = 'RedK_2: 5WMA / 10SMA / 20SMA / 40SMA'
pset_3 = 'SWNG_1: 7EMA / 21EMA / 30EMA / 50SMA'
pset_4 = 'SWNG_2: 10EMA / 21EMA / 50SMA / 100SMA'
pset_5 = 'SWNG_3: 10EMA / 21EMA / 100SMA / 200SMA'
presets = input.bool(false, title = "Use Presets?", inline = 'presets', group = grp_p)
s_preset = input.string(pset_1, title = "", inline = 'presets', group = grp_p,
options = [pset_1, pset_2, pset_3, pset_4, pset_5])
Proxy_Src = input.source(close, title='Proxy Source', inline = 'Proxy', group = grp_m)
Proxy_Length = input.int(8, title = 'Length', minval = 1, inline = 'Proxy', group = grp_m)
Proxy_Type = input.string('RSS_WMA', title = 'Type', inline = 'Proxy',
options = ['RSS_WMA', 'WMA', 'EMA', 'SMA', 'HMA'], group = grp_m)
Fast_Src = input.source(close, title='Fast MA Source', inline = 'Fast', group = grp_m)
Fast_Length = input.int(15, title = 'Length', minval = 1, inline = 'Fast', group = grp_m)
Fast_Type = input.string('RSS_WMA', title = 'Type', inline = 'Fast',
options = ['RSS_WMA', 'WMA', 'EMA', 'SMA', 'HMA'], group = grp_m)
Slow_Src = input.source(close, title='Slow MA Source', inline = 'Slow', group = grp_m)
Slow_Length = input.int(21, title='Length', minval = 1, inline = 'Slow', group = grp_m)
Slow_Type = input.string('RSS_WMA', title = 'Type', inline = 'Slow',
options = ['RSS_WMA', 'WMA', 'EMA', 'SMA', 'HMA'], group = grp_m)
Fil_Src = input.source(close, title='Filter Source', inline = 'Filter', group = grp_f)
Fil_Length = input.int(40, title='Length', minval = 1, inline = 'Filter', group = grp_f)
Fil_Type = input.string('SMA', title = 'Type', inline = 'Filter', group = grp_f,
options = ['RSS_WMA', 'WMA', 'EMA', 'SMA', 'HMA'])
//==================================================================================
//f_UsePreset() => //function
iProxy_Src = close, iProxy_Length = 5 , iProxy_Type = "WMA"
iFast_Src = close, iFast_Length = 10, iFast_Type = "SMA"
iSlow_Src = close, iSlow_Length = 20, iSlow_Type = "SMA"
iFil_Src = close, iFil_Length = 50, iFil_Type = "SMA"
if presets
if s_preset == pset_1
iProxy_Src := close, iProxy_Length := 8 , iProxy_Type := "RSS_WMA"
iFast_Src := close, iFast_Length := 15, iFast_Type := "RSS_WMA"
iSlow_Src := close, iSlow_Length := 21, iSlow_Type := "RSS_WMA"
iFil_Src := close, iFil_Length := 30, iFil_Type := "SMA"
else if s_preset == pset_2
iProxy_Src := close, iProxy_Length := 5 , iProxy_Type := "WMA"
iFast_Src := close, iFast_Length := 10, iFast_Type := "SMA"
iSlow_Src := close, iSlow_Length := 20, iSlow_Type := "SMA"
iFil_Src := close, iFil_Length := 40, iFil_Type := "SMA"
else if s_preset == pset_3
iProxy_Src := close, iProxy_Length := 7 , iProxy_Type := "EMA"
iFast_Src := close, iFast_Length := 21, iFast_Type := "EMA"
iSlow_Src := close, iSlow_Length := 30, iSlow_Type := "EMA"
iFil_Src := close, iFil_Length := 50, iFil_Type := "SMA"
else if s_preset == pset_4
iProxy_Src := close, iProxy_Length := 10, iProxy_Type := "EMA"
iFast_Src := close, iFast_Length := 21, iFast_Type := "EMA"
iSlow_Src := close, iSlow_Length := 50, iSlow_Type := "SMA"
iFil_Src := close, iFil_Length := 100, iFil_Type := "SMA"
else
iProxy_Src := close, iProxy_Length := 10, iProxy_Type := "EMA"
iFast_Src := close, iFast_Length := 21, iFast_Type := "EMA"
iSlow_Src := close, iSlow_Length := 100, iSlow_Type := "SMA"
iFil_Src := close, iFil_Length := 200, iFil_Type := "SMA"
else
iProxy_Src := Proxy_Src, iProxy_Length := Proxy_Length, iProxy_Type := Proxy_Type
iFast_Src := Fast_Src, iFast_Length := Fast_Length, iFast_Type := Fast_Type
iSlow_Src := Slow_Src, iSlow_Length := Slow_Length, iSlow_Type := Slow_Type
iFil_Src := Fil_Src, iFil_Length := Fil_Length, iFil_Type := Fil_Type
// =======================================================================================// ------------------------------------------------------------------------------------------------
// Calculation
// ------------------------------------------------------------------------------------------------
LL1 = f_getMA(iProxy_Src, iProxy_Length, iProxy_Type)
LL2 = f_getMA(iFast_Src, iFast_Length, iFast_Type)
LL3 = f_getMA(iSlow_Src, iSlow_Length, iSlow_Type)
Filter = f_getMA(iFil_Src, iFil_Length, iFil_Type)
plot(LL1, "Proxy Line", color = color.white, display = display.none)
plot(LL2, "Fast MA", color = color.new(#00bcd4,0), display = display.none)
plot(LL3, "Slow MA", color = color.new(#2424f0,0), display = display.none)
Mode_Long = LL1 > LL2 and LL2 > LL3
Mode_Short = LL1 < LL2 and LL2 < LL3
c_Filter = Mode_Long ? color.new(#00bcd4,25) : Mode_Short ? color.new(#ff9800,25) : color.new(#5d606b,40)
plot(Filter, "Filter MA", linewidth = 3, color = c_Filter, style = plot.style_circles)
|
Momentum Deviation Bands [Loxx] | https://www.tradingview.com/script/R0pxzxfx-Momentum-Deviation-Bands-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 96 | 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("Momentum Deviation Bands [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxmas/1
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
bluecolor = #042dd2
lightgreencolor = #96E881
lightredcolor = #DF4F6C
lightbluecolor = #4f6cdf
darkGreenColor = #1B7E02
darkRedColor = #93021F
darkBlueColor = #021f93
_kalman(src, per, K, Sharpness)=>
velocity = 0.0
kfilt = 0.0
Distance = src - nz(kfilt[1], src)
Error = nz(kfilt[1], src) + Distance * math.sqrt(Sharpness*K/ 100)
velocity := nz(velocity[1], 0) + Distance*K / 100
kfilt := Error + velocity
kfilt
_vidya(src, per, histPer)=>
k = ta.stdev(src, per) / ta.stdev(src, histPer)
sc = 2 / (per + 1)
vidya = 0.0
vidya := nz(k * sc * src + (1 - k * sc) * vidya[1], 0)
vidya
_kama(src, len, kama_fastend, kama_slowend) =>
xvnoise = math.abs(src - src[1])
nfastend = kama_fastend
nslowend = kama_slowend
nsignal = math.abs(src - src[len])
nnoise = math.sum(xvnoise, len)
nefratio = nnoise != 0 ? nsignal / nnoise : 0
nsmooth = math.pow(nefratio * (nfastend - nslowend) + nslowend, 2)
nAMA = 0.0
nAMA := nz(nAMA[1]) + nsmooth * (src - nz(nAMA[1]))
nAMA
_ama(src, len, fl, sl)=>
flout = 2/(fl + 1)
slout = 2/(sl + 1)
hh = ta.highest(len + 1)
ll = ta.lowest(len + 1)
mltp = hh - ll != 0 ? math.abs(2 * src - ll - hh) / (hh - ll) : 0
ssc = mltp * (flout - slout) + slout
ama = 0.
ama := nz(ama[1]) + math.pow(ssc, 2) * (src - nz(ama[1]))
ama
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
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)"])
inpPeriod = input.int(60, "Period", group = "Basic Settings")
inpMomPeriod = input.int(2, "Momentum Period", group = "Basic Settings")
bl2_type = input.string("Hull Moving Average - HMA", "Moving Average Type",
options = [
"Adaptive Moving Average - AMA",
"ADXvma - Average Directional Volatility Moving Average",
"Ahrens Moving Average",
"Alexander Moving Average - ALXMA",
"Donchian",
"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 maout by Tim Tilson",
"Integral of Linear Regression Slope - ILRS",
"Instantaneous Trendline",
"Kalman Filter",
"Kaufman Adaptive Moving Average - KAMA",
"Laguerre Filter",
"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",
"T3",
"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",
"Variable Index Dynamic Average - VIDYA",
"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")
inpMultiplier1 = input.float(1.0, "Multiplier 1", group = "Basic Settings")
inpMultiplier2 = input.float(2.0, "Multiplier 2", group = "Basic Settings")
inpMultiplier3 = input.float(3.0, "Multiplier 3", group = "Basic Settings")
inpMultiplier4 = input.float(4.0, "Multiplier 4", group = "Basic Settings")
inpMultiplier5 = input.float(5.0, "Multiplier 5", group = "Basic Settings")
show1 = input.bool(true, "Show Level 1", group = "UI Options")
show2 = input.bool(true, "Show Level 2", group = "UI Options")
show3 = input.bool(true, "Show Level 3", group = "UI Options")
show4 = input.bool(true, "Show Level 4", group = "UI Options")
show5 = input.bool(true, "Show Level 5", 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 Filter (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")
t3hot = input.float(.7, "* T3 Only - T3 Hot", group = "Moving Average Inputs")
t3swt = input.string("T3 New", "* T3 Only - T3 Type", options = ["T3 New", "T3 Original"], group = "Moving Average Inputs")
histPer = input.int(30, "* Variable Index Dynamic Average (VIDYA) Only - Hist Period", group = "Moving Average Inputs")
Sharpness = input.float(1.0, "* Kalman Filter only - Sharpness", group = "Moving Average Inputs")
K = input.float(1.0, "* Kalman Filter only - K", group = "Moving Average Inputs")
haopen = (nz(open[1], open) + nz(close[1], close)) / 2
haclose = (open + close + high + low) / 4
hahigh = math.max(high, open, close)
halow = math.min(low, open, close)
hamedian = (hahigh + halow) / 2
hatypical = (hahigh + halow + haclose) / 3
haweighted = (hahigh + halow + haclose + haclose)/4
haaverage = (haopen + hahigh + halow + haclose)/4
inpMomPrice = 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
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "Donchian"
out = math.avg(ta.lowest(len), ta.highest(len))
trig := out
sig := out[1]
if type == "Adaptive Moving Average - AMA"
out = _ama(src, len, amafl, amasl)
trig := out
sig := out[1]
else if type == "Kaufman Adaptive Moving Average - KAMA"
t = _kama(src, len, kfl, ksl)
trig := t
sig := t[1]
else if type == "T3"
t = t3filter(src, len, t3hot, t3swt)
trig := t
sig := t[1]
else if type == "Kalman Filter"
t = _kalman(src, len, K, Sharpness)
trig := t
sig := t[1]
else if type == "Variable Index Dynamic Average - VIDYA"
t = _vidya(src, len, histPer)
sig := t
trig := t[1]
else 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 maout 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 Filter"
[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, close]
sum = 0.
sum := nz(sum[1])
sum := sum + nz(sum[1]) + inpMomPrice - nz(inpMomPrice[inpPeriod])
momentumSum = 0.
momentumSum := nz(momentumSum[1])
momentumSum := momentumSum + math.pow(ta.mom(inpMomPrice, inpMomPeriod), 2) - math.pow(nz(ta.mom(inpMomPrice, inpMomPeriod)[inpPeriod]), 2)
deviation = math.sqrt(momentumSum / inpPeriod)
[val, _] = variant(bl2_type, inpMomPrice, inpPeriod)
colorout = val > val[1] ? greencolor : redcolor
bandup1 = val + deviation * inpMultiplier1
banddn1 = val - deviation * inpMultiplier1
bandup2 = val + deviation * inpMultiplier2
banddn2 = val - deviation * inpMultiplier2
bandup3 = val + deviation * inpMultiplier3
banddn3 = val - deviation * inpMultiplier3
bandup4 = val + deviation * inpMultiplier4
banddn4 = val - deviation * inpMultiplier4
bandup5 = val + deviation * inpMultiplier5
banddn5 = val - deviation * inpMultiplier5
plot(val, "Moving Average", color = colorout, linewidth = 3)
plot(show1 ? bandup1 : na, "Level 1 Up", color = color.gray)
plot(show1 ? banddn1 : na, "Level 1 Down",color = color.gray)
plot(show2 ? bandup2 : na, "Level 2 Up",color = darkRedColor)
plot(show2 ? banddn2 : na, "Level 2 Down",color = darkGreenColor)
plot(show3 ? bandup3 : na, "Level 3 Up",color = redcolor, linewidth = 1)
plot(show3 ? banddn3 : na, "Level 3 Down",color = greencolor, linewidth = 1)
plot(show4 ? bandup4 : na, "Level 4 Up",color = lightredcolor, linewidth = 1)
plot(show4 ? banddn4 : na, "Level 4 Down",color = lightgreencolor, linewidth = 1)
plot(show5 ? bandup5 : na, "Level 5 Up",color = color.new(color.white, 50), linewidth = 1)
plot(show5 ? banddn5 : na, "Level 5 Down",color = color.new(color.white, 50), linewidth = 1)
|
Any Oscillator Underlay [TTF] | https://www.tradingview.com/script/wnJC2Czn-Any-Oscillator-Underlay-TTF/ | TheTrdFloor | https://www.tradingview.com/u/TheTrdFloor/ | 509 | 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/
// © TheTrdFloor
//@version=5
indicator(title="Any Oscillator Underlay [TTF]", shorttitle="AOU [TTF]", overlay=false) //, precision=8
//***** Shared Calculation Functions *****//
//
// Double EMA
dema(src, len) =>
de1 = ta.ema(src, len)
de2 = ta.ema(de1, len)
dema = 2 * de1 - de2
//
// Triple EMA
tema(src, len) =>
te1 = ta.ema(src, len)
te2 = ta.ema(te1, len)
te3 = ta.ema(te2, len)
tema = 3 * (te1 - te2) + te3
//
// Function to calculate smoothed moving average...
smoothedMovingAvg(src, len) =>
smma = 0.0
// TV will complain about the use of the ta.sma function use inside a function saying that it should be called on each calculation,
// but since we're only using it once to set the initial value for the smoothed MA (when the previous smma value is NaN - Not a Number)
// and using the previous smma value for each subsequent iteration, this can be safely ignored
smma := na(smma[1]) ? ta.sma(src, len) : (smma[1] * (len - 1) + src) / len
smma
//
// MA calculation
ma(source, length, type) =>
switch type
"Simple" => ta.sma(source, length)
"Exponential" => ta.ema(source, length)
"Weighted" => ta.wma(source, length)
"Volume-Weigehted" => ta.vwma(source, length)
"Smoothed" => smoothedMovingAvg(source, length)
"RMA" => ta.rma(source, length)
"Linear" => ta.linreg(source, length, 0)
"Hull" => ta.hma(source, length)
"ALMA" => ta.alma(source, length, 0.85, 6)
"Double EMA" => dema(source, length)
"Triple EMA" => tema(source, length)
//
//***** End Shared Calculation Functions *****//
//
//
//***** Shared Display Functions *****//
//
// For more information on the 'standardize' and 'normalize' functions and the math and reasoning behind their use,
// here are some additional references:
// * https://en.wikipedia.org/wiki/Feature_scaling
//
// Linear Scaling (min-max normalization - bounds values to a fixed range between 0 and 1): x' = (x - min(x)) / (max(x) - min(x))
//
// Dev Note: This probably won't be used terribly often as it highly-sensitive to outliers, which
// has the side-effect of shifting the mid-line on many indicators. Take the MACD for example.
// It's technically unbounded (range from -∞ to ∞ with a center-line of 0). The normalization
// process (binding it to a range between 0 and 1) should theoretically shift the center-line
// to 0.5, but that will only ever happen in practice if the average of the input 'data' series
// happens to be the exact mid-point of the max - min, which will be EXTREMELY improbable
// (especially in a market that is trending in any way at all).
//
normalize(data, normalizationLength) =>
float ret = na
lowest = ta.lowest(data, normalizationLength)
highest = ta.highest(data, normalizationLength)
ret := (data - lowest) / (highest - lowest)
ret
//
// Mean/Z-Score Normalization (standardization - transform data to have a mean of 0 and standard deviation of 1): z = (x - avg(x)) / stdev(x)
//
// Dev Note: We will generally be using this function over the 'normalize' function above as it is far less
// affected by outliers and generally preserves the mid-line of indicators. While this is still
// TECHNICALLY unbounded (range from -∞ to ∞ with a center-line/mean of 0), we gain the added
// limiter of having a fixed standard deviation of 1.
//
// While statistical purists will argue against the assumption that most oscillators will tend towards a normal distribution
// (and they are technically correct as trending markets will generally skew the sample distribution towards the positive or negative side),
// we can still generally assume that, over a large sample size, the result is close enough to a normal distribution to enable us to use
// the commonly-known rules of normally-distributed data with a high degree of confidence, along with retaining the behavior and mid-line
// that the un-scaled verion has as well. And while this still is unbound, we can effectively (conceptually) range-bind it by defining the
// range as a number of standard deviations the mean. Since the process of standardization makes it so that all data in the series will
// have a mean of 0 and a standard deviation of 1, we can effectively define our own scale (e.g. 5 std dev from the mean nets a range of
// -5 to +5 with a mean/mid-line of 0). Given the following table of distance from the mean in standard deviations (σ):
//
// Standard Deviations from Mean | Proportion (%) Inside | Proportion (%) Outside
// -----(Confidnece Interval)------|------------------------|-----------------------
// 1σ | 68.2689492% | 31.7310508%
// 2σ | 95.4499736% | 4.5500264%
// 2.575829σ | 99% | 1%
// 3σ | 99.7300204% | 0.2699796%
// 3.290527σ | 99.9% | 0.1%
// 3.890592σ | 99.99% | 0.01%
// 4σ | 99.993666% | 0.006334%
// 4.5σ | 99.9993204653751% | 0.0006795346249%
// 5σ | 99.9999426697% | 0.0000573303%
// 6σ | 99.9999998027% | 0.0000001973%
// 6.109410σ | 99.9999999% | 0.0000001%
// 6.466951σ | 99.99999999% | 0.00000001%
// 6.806502σ | 99.999999999% | 0.000000001%
// 7σ | 99.9999999997440% | 0.000000000256%
//
// we can see that a manually-defined range of +- 5σ should cover a smidge over 99.9999% of the total dataset, which
// should be more than sufficient for our purposes. Now, there will still be the occasional outlier that breaks out
// of that range, but it should be exceptionally rare (and generally triggered by an extreme market movement).
//
standardize(data, standardizationLength) =>
float ret = na
// The "official" formula simply states using an average. Normally we would translate that formula definition to mean
// using a Simple moving average, however since we can't look back far enough to get a true average of the entire
// population (i.e. all bars for all time), our mean for standardization will likely be just a hair off. As a result,
// we can get a slight mean-skew that can affect the accuracy of zero-line-cross-based signals by a candle or 2.
//
// In testing, we found that the Gaussian distribution weighting method used by the ALMA to do a pretty good job
// of balancing that skew out, thereby significantly improving the accuracy of "zero-line" crosses in the post-transformed
// output when compared to zero-line crosses of the original indicator with the same settings. It's worth noting that
// the Exponential and Hull moving averages also seemed to align pretty well with reference indicators, but the ALMA
// edged them out by a hair - especially when looking at segments where the reference oscillator is hovering right at the mid-line
// (small, frequent crosses above and below over the course of a dozen or so candles).
//
// At some point, we may refactor this indicator to make the standardization mean calculation method a configuration option,
// but odds are pretty high that most poeple will not fully understand the implications of changing this from the default.
mean = ma(data, standardizationLength, "ALMA")
stddev = ta.stdev(data, standardizationLength, false) // Last arg is to apply a bias
ret := (data - mean) / stddev
ret
//
// Basic function to re-scale data that has been standardized via the 'standardize' function above.
// The intent here is to target a potential value range of 100 and move the center-point from 0 to 50
//
// dataIn => The input data series to rescale
// scaleFactor => The number of standard deviations to use to define the upper and lower bounds
rescaleStandardizedData(dataIn, scaleFactor) =>
sf = (100 / (2 * scaleFactor))
ret = ((dataIn * sf) + 50)
ret
// An alternate method of dynamically rescaling for potential further investigation, based on
// dynamically determining the range of `dataIn` and deriving a scaling factor based on that input, is drafted below
// for future reference. It was decided to not implemented for the following reason:
//
// While it DID accomplish the goal of up-scaling the dataset while remaining in the defined upper and lower bounds,
// it had the side-effect of not properly representing the relative scale of the extremes in a sudden, massive movement in one direction,
// followed by a subsequent, massive move in the other direction (but not as extreme as the first).
//
// The observed behavior is that the peak from the boom and valley from the crash would appear to be equal in magnitude,
// even though the reference indicator showed the valley wasn't as severe as the preceeding peak. The fixed-factor rescaling did
// a much better job of retaining the relative strengh of those same movements when compared to the reference indicator,
// which is critical for any divergence-based oscillator strategy.
//
// maxDistFrom0 = math.abs(ta.highest(dataIn, 5000)) >= math.abs(ta.lowest(dataIn, 5000)) ? math.abs(ta.highest(dataIn, 5000)) : math.abs(ta.lowest(dataIn, 5000))
// sfDenomRounded = math.ceil((maxDistFrom0*11))/10
// sf2 = (98 / (2 * sfDenomRounded))
// ret2 = ((dataIn * sf2) + 50)
// ret2
//
// Basic function to rescale data that has gone through the 'normalize' function
// Since the output of the 'normalize' function is a fixed-range between 0 and 1,
// this is a pretty basic thing to do. Like the 'rescaleStandardizedData' above,
// the intent is to have a range 100.
//
// dataIn => The input data series to rescale
rescaleNormalizedData(dataIn) =>
ret = 100 * dataIn
ret
//
// Simple function to get the mid-point of the Y axis
// Since we have the functions above to help manipulate raw data of the various
// indicators/oscillators we intend to include in this indicator into a (relatively)
// known and shared fixed-range of 100 when needed, the only thing left to do is
// make a way to "stack" them in a non-overlapping manner... hopefully...
// See comments for the 'standardize' function above.
//
// With the above stated, this should be a relatively simple process of just doing a basic
// multiplier to the input series.
//
// Dev Note: This function should only be used on the primary series of an indicator (those
// that are directly tied to price, volume, etc.). Subsequent/supplementary calculations
// that are derived from a primary series (e.g. moving averages) should be applied
// to the repositioned series to ensure that the calculations accurately reflect
// the data that will be plotted for the primary series;
//
// dataIn => The input data series to reposition.
// This function assumes that the input series is already bound to a range of
// 100 - either by the nature of the indicator itself or by leveraging the
// other methods above to handle the rescaling.
// posIndex => Relative postion to place the input data series in the indicator "stack".
// Like most things in programming, we will define our base index point as 0
// and count up from there (which also aligns with how Pinescript indexes
// arrays - more on that later!).
repositionSeries(dataIn, posIndex) =>
ret = dataIn + (100 * posIndex)
ret
//
// Just semi-abusing the function above to define a convenient method to get the mid-point
// of the series
getIndicatorMidpoint(posIndex) =>
repositionSeries(50, posIndex)
//
// To try and be as user-friendly as possible, it'd be a nice touch to actually have some form
// of label/title for each sub-component displayed on the chart so that the user can easily
// see which indicator/oscillator is which. A single-cell table would have been nice, but
// unfortunately we have no way of locating those with absolute positioning, so we'll instead
// need to use another format that DOES support absolute positioning and custom inner text.
//
// The 'label' class supports all of those requirements, so we'll go with that. But that also
// means we'll need to calculate the exact X and Y coordinates to use to plot the titles...
//
// For the Y axis, we'll baseline off of 75 and increment by 100 - easy enough. The X axis
// will be the tricky one... We want to try and align it to the far-left side of the chart,
// but not SO far left that it gets cropped (which is what happens with the time-based built-in
// 'chart.left_visible_bar_time'). So we'll need to do a bit of Pinescript wizardry to derive
// the number of bars visible on the chart and back-calculate the left-most bar index, then apply
// an additional rightward offset. And while we're at it, let's also add that there's an additional
// fudge-factor of where on-screen the right-most bar is (mid-screen, all the way to the edge, or
// anywhere else in the visible range - we don't know) that can also affect how this text displays.
//
// This all sounds a bit complicated (and it is), but at least the X axis will remain constant for
// all the different oscillators/indicators we will have, so at least this is a calculation we only
// have to do once.
//
// So with all that said, let's just take it one step at a time. We'll start by defining some inputs
// to allow users to manually adjust the right-offset and text color as-needed.
//
titleOffsetScaleFactor = input.int(title="Title Offset Scaler:", defval=5, minval=0, maxval=100, step=1, group="General Settings - Titles", inline="s1")
titleColor = input.color(title="Color:", defval=color.rgb(200, 200, 200, 0), group="General Settings - Titles", inline="s1",
tooltip="The 'Title Offset Scaler' setting controls the left-offset of the sub-indicator titles. This number should generally equate to the number of candles from the left " +
"to use to center the sub-indicator titles.\n\n" +
"In most cases, a value between 3-10 should do.")
//
// And now to do the X-position calculation...
// This first one attempts to calculate the number of currently-visible bars on the chart. It
// should be pretty accurate (within 1-2 bars depending on how far out the chart zoom is).
chartBarCount = (chart.right_visible_bar_time - chart.left_visible_bar_time) / (1000 * timeframe.in_seconds())
//
// Now we use the value above to get the bar index of the leftmost bar, then apply our right-shift
// to address the text truncation issue noted earlier. We use the 'math.ceil' function here to force
// any remainder to round up as it's better to err on the right side (since this is a positive shift
// to the right).
titlePosX = (bar_index - chartBarCount) + math.ceil(chartBarCount / titleOffsetScaleFactor)
titlePosTime = (chart.left_visible_bar_time + (titleOffsetScaleFactor * (1000 * timeframe.in_seconds())))
//
// And now we can use the inputs and calculations to make a function to that will insert the desired
// title at the correct location. Since we intend to index our component indicators so that we can
// properly stack them, we'll include an 'index' argument as well to help maintain consistency.
//
// title => The desired title text
// index => The index number of the indicator to apply the title to, which alters the Y-axis position
insertTitle(title, index) =>
//tmplabel = label.new(x=titlePosX, xloc=xloc.bar_index, y=(85 + (int(index) * 100)), yloc=yloc.price, text=str.tostring(title), style=label.style_none, textcolor=titleColor, textalign=text.align_left)
tmplabel = label.new(x=titlePosTime, xloc=xloc.bar_time, y=(85 + (int(index) * 100)), yloc=yloc.price, text=str.tostring(title), style=label.style_none, textcolor=titleColor, textalign=text.align_left)
// This will delete the previous label and ensure that we only have a single 'title label' for any given index
label.delete(tmplabel[1])
//
// In keeping with the customization of styles, we'll add some user inputs
lineStyle = input.string(title="Line Style:", defval="Solid",
options=["Solid", "Dashed", "Dotted"],
group="General Settings - Separator", inline="s2",
tooltip="This setting controls the line style for the divider lines between the sub-indicators (including the upper and lower-most lines).")
lineWidth = input.int(title="Size/Width:", defval=2, minval=0, maxval=10, group="General Settings - Separator", inline="s1")
lineColor = input.color(title="Color:", defval=color.rgb(255, 255, 255, 0), group="General Settings - Separator", inline="s1",
tooltip="This setting controls the size and coloring of the divider lines noted above.")
//
// Simple function to convert our input linestyle into the corresponding real value needed for functions...
getLineStyle(styleIn) =>
tmpLineStyle = switch (styleIn)
"Solid" => line.style_solid
"Dashed" => line.style_dashed
"Dotted" => line.style_dotted
=> line.style_solid
tmpLineStyle
//
getHLineStyle(styleIn) =>
tmpLineStyle = switch (styleIn)
"Solid" => hline.style_solid
"Dashed" => hline.style_dashed
"Dotted" => hline.style_dotted
=> hline.style_solid
tmpLineStyle
//
// Function to draw divider lines to help separate the sub-indicators, again using indexes as our key.
// Similar to the 'insertTitle' above, we're using 'line' objects instead of the more common 'hline'
// as 'hline' only works in a global scope (and it helps maintain consistency).
//
// index => The index number of the indicator to apply the title to, which alters the Y-axis position
insertUpperLine(index) =>
tmpLineStyle = getLineStyle(lineStyle)
tmpline = line.new(x1=bar_index, x2=bar_index[1], y1=((100 * index) + 100), y2=((100 * index) + 100), extend=extend.both, color=lineColor, width=lineWidth, style=tmpLineStyle)
line.delete(tmpline[1])
// And to be visually consistent, if inserting an upper-line for index 0, add a matching lower line as well...
if (index == 0)
// Ideally we'd use recursion and call this same function via 'insertUpperLine(-1)', but Pinescript doesn't support recursion,
// so we have to code out the 2nd line manually
tmplineLower = line.new(x1=bar_index, x2=bar_index[1], y1=0, y2=0, extend=extend.both, color=lineColor, width=lineWidth, style=tmpLineStyle)
line.delete(tmplineLower[1])
//
// In keeping with the customization of styles, we'll add some user inputs
midLineStyle = input.string(title="Line Style:", defval="Dashed",
options=["Solid", "Dashed", "Dotted"],
group="General Display Settings - Mid Lines", inline="s2",
tooltip="This setting controls the line style for the mid-lines in the sub-indicators.")
midLineWidth = input.int(title="Size/Width:", defval=1, minval=0, maxval=10, group="General Display Settings - Mid Lines", inline="s1")
midLineColor = input.color(title="Color:", defval=color.rgb(216, 216, 216, 0), group="General Display Settings - Mid Lines", inline="s1",
tooltip="This setting controls the size and coloring of the mid-lines noted above.")
//
obosLineStyle = input.string(title="Line Style:", defval="Dotted",
options=["Solid", "Dashed", "Dotted"],
group="General Display Settings - OB/OS Lines", inline="s2",
tooltip="This setting controls the line style for the OB and OS lines in the sub-indicators.")
obosLineWidth = input.int(title="Size/Width:", defval=1, minval=0, maxval=10, group="General Display Settings - OB/OS Lines", inline="s1")
obosLineColor = input.color(title="Color:", defval=color.rgb(255, 255, 255, 15), group="General Display Settings - OB/OS Lines", inline="s1",
tooltip="This setting controls the size and coloring of the OB and OS lines noted above.")
//
// Now for mid-lines and OB/OS lines...
insertInnerLines(midpoint, obosOffset, inclMidline, inclOBOSLines) =>
tempOBOSLineStyle = getLineStyle(obosLineStyle)
tempMidLineStyle = getLineStyle(midLineStyle)
if (inclMidline)
tmpMidLine = line.new(x1=bar_index, x2=bar_index[1], y1=midpoint, y2=midpoint, extend=extend.both, color=midLineColor, width=midLineWidth, style=tempMidLineStyle)
line.delete(tmpMidLine[1])
if (inclOBOSLines)
tmpOBLevel = midpoint + obosOffset
tmpOSLevel = midpoint - obosOffset
tmpOBLine = line.new(x1=bar_index, x2=bar_index[1], y1=tmpOBLevel, y2=tmpOBLevel, extend=extend.both, color=obosLineColor, width=obosLineWidth, style=tempOBOSLineStyle)
tmpOSLine = line.new(x1=bar_index, x2=bar_index[1], y1=tmpOSLevel, y2=tmpOSLevel, extend=extend.both, color=obosLineColor, width=obosLineWidth, style=tempOBOSLineStyle)
line.delete(tmpOBLine[1])
line.delete(tmpOSLine[1])
//
//***** End Shared Display Functions *****//
//
//
//***** Moving the sub-indicator toggles higher up in the settings based on tester feedback *****//
//
//
g_MainIndicatorControl = "Sub-Indicator Display Toggles"
tsiDisplay = input.bool(title='Include TSI', defval=true, group=g_MainIndicatorControl, tooltip='If checked, will include the TSI in the composite indicator. Default value: checked')
rsiDisplay = input.bool(title='Include Twin RSI', defval=true, group=g_MainIndicatorControl, tooltip='If checked, will include the Twin RSI in the composite indicator. Default value: checked')
stochRSIDisplay = input.bool(title='Include Stochastic RSI', defval=true, group=g_MainIndicatorControl, tooltip='If checked, will include the Stochastic RSI in the composite indicator. Default value: checked')
stochDisplay = input.bool(title='Include Stochastic', defval=false, group=g_MainIndicatorControl, tooltip='If checked, will include the Stochastic in the composite indicator. Default value: unchecked')
uoDisplay = input.bool(title='Include Ultimate Oscillator (UO)', defval=true, group=g_MainIndicatorControl, tooltip='If checked, will include the UO in the composite indicator. Default value: checked')
aoDisplay = input.bool(title='Include Awesome Oscillator (AO)', defval=false, group=g_MainIndicatorControl, tooltip='If checked, will include the AO in the composite indicator. Default value: false')
macdDisplay = input.bool(title='Include MACD', defval=false, group=g_MainIndicatorControl, tooltip='If checked, will include the MACD in the composite indicator. Default value: unchecked')
orsiDisplay = input.bool(title='Include ORSI', defval=false, group=g_MainIndicatorControl, tooltip='If checked, will include the Outback RSI in the composite indicator.\n\n' +
'Note: This is a special-purpose indicator and covering how to use it is outside the scope of this help-text.\n\n' +
'Suffice it to say - if you know what this is, you\'ll know how to use it. If you don\'t know what it is, just don\'t use it (leave it disabled).\n\n' +
'Default value: unchecked')
//
//
//
//***** Begin Functional Code Section *****//
//
// In this "composite indicator" as I'll call it, we intend to include all of the following as options:
//
// * TSI
// * RSI
// * Stoch RSI
// * OG Stochastic
// * UO
// * AO
// * MACD
//
// We're going to be a bit "lazy" and take advantage of the fact that Pinescript evaluates in a linear fashion, so we
// don't need to explicitly manage and track each sub-component indicator individually. Instead, we will let the script
// simply run through and evaluate each component indicator individually (which will each have an option to enable/disable)
// whether or not it is displayed and track where/how to display each component indicator by using a basic array and the
// following rules:
// 1. An empty array will be initialized at the very start of the script execution, which will be "shared"
// by all the component indicators so that each can determine where in the "stack" they should display.
// 2. If a component indicator is enabled, it will first check the size of the array. This will give us
// the "index" to use for that component's display (taking advantage of the fact that array indexes
// start at 0, and an empty array will have a size of 0). For example, if the array size is 0, the
// component indicator will use the 0 index to display.
// 3. If a component indicator is enabled, once it has identified which index it should use,
// it will push a new entry into the array so that the next component indicator will get
// the next index.
displayIndexArray = array.new_int(0)
getCurrentIndex() => array.size(displayIndexArray)
addToIndexArray() => array.push(displayIndexArray, na)
//
// I'm a bit of a stickler for knowing that I'm using true-price for indicators like the ones
// we will be including here, and the most consistent way to ensure that is the case, regardless of
// which chart-type people may use, is to manually grab the information directly via the 'security' function.
//
// Explicitly define our ticker to help ensure that we're always getting ACTUAL price instead of relying on the input
// ticker info and input vars (as they tend to inherit the type from what's displayed on the current chart)
realPriceTicker = ticker.new(prefix=syminfo.prefix, ticker=syminfo.ticker)
// And now to grab the OHLC and Volume...
[o, h, l, c, vol] = request.security(symbol=realPriceTicker, timeframe='', expression=[open, high, low, close, volume], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
//
// And a quick-and-dirty function to convert 'input.source' price to the equivilent version using our real-price vars...
convertSourcePrice(src) =>
switch (src)
open => o
high => h
low => l
close => c
hl2 => (h + l) / 2
hlc3 => (h + l + c) / 3
hlcc4 => (h + l + c + c) / 4
ohlc4 => (o + h + l + c) / 4
=> c
//
// That should be all for the "shared" stuff... Now we'll get into all the component indicators.
// Normally I like to try and structure scripts by grouping all inputs and such together, but
// given the nature of this indicator, it seems more logical to group each component indicator
// as a single, atomic unit as much as possible, so that's the pattern we'll use instead.
//
//***** TSI ******//
//
// The TSI range is between -100 to +100 (range of 200) with a centerpoint of 0, so we will need
// to reposition the centerpoint to 100 (to make the range 0-200), then divide by 2 (which will
// reduce the scale to 0-100 and reposition the centerpoint to 50).
//
// Indicator inputs
g_TSISettings = 'TSI Settings'
tsiLong = input.int(title='Long-Preiod Length', defval=13, group=g_TSISettings, tooltip='Original default: 25')
tsiShort = input.int(title='Short-Period Length', defval=6, group=g_TSISettings, tooltip='Original default: 13')
tsiSignal = input.int(title='Signal Preiod Length', defval=4, group=g_TSISettings, tooltip='Original default: 13')
tsiPriceSource = input.source(title='Source for price', defval=close, group=g_TSISettings, tooltip='Source for Price information. Default: Close')
tsiShowHist = input.bool(title='Show TSI Histogram', defval=true, group=g_TSISettings, tooltip='Show the TSI Histogram along the middle line. Default value: checked')
tsiShowFill = input.bool(title='Show TSI colored fill', defval=true, group=g_TSISettings, tooltip='Fill the area between the TSI and the TSI Signal. Default fill color coding:\n' +
'Green: TSI is above the signal line\n' +
'Red: TSI is below the signal line.\n\n' +
'Default value: checked')
tsiShowFloatingMA = input.bool(title='Show floating TSI Moving Average', defval=true, group=g_TSISettings, tooltip='Show a floating moving average line for the TSI value. ')
tsiMAType = input.string(title='TSI Moving Average Calculation', group=g_TSISettings, options=["Simple", "Exponential", "Weighted", "Volume-Weigehted", "Smoothed", "RMA", "Linear", "Hull", "ALMA", "Double EMA", "Triple EMA"], defval='Exponential', tooltip='Type of moving average calculation to use (default is Exponential (EMA)). \n\n' +
'Only relevant when "Show floating TSI Moving Average" above is enabled.')
tsiMALength = input.int(title="TSI MA Length", defval=50, minval=1, step=1, group=g_TSISettings, tooltip="Number of historical TSI values to use for calculating the MA value. Lower numbers will react more quickly, while higher numbers will better depict Longer trends.")
//
tsiShowMidline = input.bool(title='Show Mid Line', defval=true, group=g_TSISettings,
tooltip='If enabled/checked, a mid-line is displayed for this sub-indicator.\n\n' +
'See "General Display Settings - Mid Lines" settings above to alter the mid-line color and style.')
tsiShowOBOS = input.bool(title='Show OB/OS ', defval=true, group=g_TSISettings, inline="obos")
tsiOBLevel = input.int(title=' Offset: ', defval=25, minval=1, maxval=50, step=1, group=g_TSISettings, inline="obos",
tooltip='If enabled/checked, a OB and OS lines are displayed for this sub-indicator.\n\n' +
'The offest parameter is defined as distance from the mid-line of the sub-indicator. A value here of "25" would set the OB line at the equivilent of "75" (a +25 offset), ' +
'and a OS line at the equivilent of "25" (a -25 offset).\n\n' +
'Note: Before using this setting, please make sure you understand the native range of the indicator and account for the fact that all sub-indicators have been rescaled to a 100-point range and adjust accordingly.\n\n' +
'See "General Display Settings - OB/OS Lines" settings above to alter the OB and OS line color and style.')
//
// Start with handling some of the precursor stuff...
tsiIndex = getCurrentIndex()
tsiPrice = convertSourcePrice(tsiPriceSource)
if (tsiDisplay)
insertUpperLine(tsiIndex)
insertTitle("TSI", tsiIndex)
addToIndexArray()
//
// We're going to handle the rescaling of the TSI manually since it is a
// fixed-range indicator, so it can be accurately converted to the range
// we want with some basic math.
tsi_rawValue = 50 * (1 + ta.tsi(tsiPrice, tsiShort, tsiLong))
tsi_value = repositionSeries(tsi_rawValue, tsiIndex)
tsi_midpoint = getIndicatorMidpoint(tsiIndex)
tsiSignal_line = ta.ema(tsi_value, tsiSignal)
// For the mid-line, we need to know our original mid-point and our indicator index
tsiHist = tsi_midpoint + (tsi_value - tsiSignal_line)
// Identify if TSI is above or below tsiSignal line
tsiBullish = tsi_value > tsiSignal_line
tsiBearish = tsi_value < tsiSignal_line
//
// Plot the histogram first so it will be layered behind the TSI and TSI Signal lines
//
// Since the normal base of a plot with an area style (the norm for histograms) defaults to a fill from the 0 line, we need to do some work-arounds to reposition
// this to the repositioned TSI mid-line. To do this, we'll create 2 hidden plot objects to house the TSI midpoint and the calculated histogram value offset from the midpoint,
// then use those 2 hidden plots with the 'fill' function to make our own "repositioned histogram".
p_hiddenTSIMidLine = plot(tsiShowHist and tsiDisplay ? tsi_midpoint : na, title='TSI Hidden Midpoint', color=color.rgb(0, 0, 0, 100), editable=false, display=display.none)
p_hiddenTSIHist = plot(tsiShowHist and tsiDisplay ? tsiHist : na, title='TSI Hidden Hist Line', color=color.rgb(0, 0, 0, 100), editable=false, display=display.none)
fill(p_hiddenTSIMidLine, p_hiddenTSIHist, title='TSI Histogram', color=tsiShowHist and tsiDisplay ? color.rgb(207, 80, 207, 70) : na)
//
// Define the colors for the TSI so we can re-use them in the fill zone as well...
tsiBullColor = color.rgb(0, 255, 0, 0)
tsiBearColor = color.rgb(255, 0, 0, 0)
//
// Plot the midline and OB/OS lines
if (tsiDisplay)
insertInnerLines(tsi_midpoint, tsiOBLevel, tsiShowMidline, tsiShowOBOS)
// Plot the TSI and TSI Signal lines
p_TSISignal = plot(tsiDisplay ? tsiSignal_line : na, title='TSI Signal Line', color=color.rgb(0, 127, 255, 0))
p_TSI = plot(tsiDisplay ? tsi_value : na, title='TSI', color=tsiBullish ? tsiBullColor : tsiBearish ? tsiBearColor : color.rgb(127, 127, 127, 0), display=display.all)
//
// TSI MA fun
tsiFloatingMA = ma(tsi_value, tsiMALength, tsiMAType)
p_TSIFloatingMA = plot(tsiShowFloatingMA and tsiDisplay ? tsiFloatingMA : na, title="TSI Floating MA", color=color.rgb(255, 255, 0, 0))
//
// An added bonus - area fill between the TSI and the signal line, shaded to
// indicate whether the TSI is above or below the signal line...
//
// Similar to the histogram, plot this first so that the lines end up on top of it...
tsiFillColor = tsiBullish ? color.new(tsiBullColor, 63) : tsiBearish ? color.new(tsiBearColor, 63) : na
fill(p_TSI, p_TSISignal, color=tsiShowFill and tsiDisplay ? tsiFillColor : na, title='TSI Fill Color')
//
//
//***** END TSI ******//
//
//
//***** BEGIN Twin RSI ******//
//
// The RSI range is between 0 and 100 with a mid-point of 50 naturally, so no rescaling is needed.
// We will still need to handle the repositioning.
//
// Indicator inputs
g_RSISettings = "Twin RSI Settings"
//
// Fast RSI
rsiShowFast = input.bool(title='Show Fast RSI', defval=true, group=g_RSISettings, tooltip='If checked, will include the Fast RSI in the composite indicator. Default value: checked')
rsiFastLengthInput = input.int(title="Fast RSI Length", minval=1, maxval=100, defval=4, step=1, group=g_RSISettings, tooltip='Select the lenght for the fast RSI. Lower values will respond quicker, but may lead ' +
'to false signals. The sweet-spot generally tends to be a bit less than 50% (half) of the "Slow RSI Length" below')
rsiFastSourceInput = input.source(title="Fast RSI Price Source", defval=ohlc4, group=g_RSISettings, tooltip='Price source for the fast RSI. ' +
'The most common setting for this short of a RSI length is OHLC4 (default), as this tends be a better representation of price action/momentum for shorter RSI lengths.')
// Slow RSI
rsiSlowLengthInput = input.int(title="Slow RSI Length", minval=1, defval=10, step=1, group=g_RSISettings, tooltip='Select the lenght for the slow RSI. Lower values will respond quicker, but may lead ' +
'to false signals. The sweet-spot generally tends to be between 8-20 for scalping-style strats, and and in the 50-100 range for swing-trading style strats.')
rsiSlowSourceInput = input.source(title="Slow RSI Price Source", defval=close, group=g_RSISettings, tooltip='Price source for the slow RSI. ' +
'The most common setting for this length is close (default) as there is generally a larger sample size of price points to analyze.')
rsiShowFill = input.bool(title='Show Twin RSI colored fill', defval=true, group=g_RSISettings, tooltip='Fill the area between the Fast and Slow RSI. Default fill color coding:\n' +
'Dark Red: Fast RSI < Slow RSI & Slow RSI < RSI MA\n' +
'Light Red: Fast RSI < Slow RSI & Slow RSI > RSI MA\n' +
'Dark Green: Fast RSI > Slow RSI & Slow RSI < RSI MA\n' +
'Light Green: Fast RSI > Slow RSI & Slow RSI > RSI MA\n\n' +
'Default value: checked')
//
// RSI Midline and OB/OS settings
rsiShowMidline = input.bool(title='Show Mid Line', defval=true, group=g_RSISettings, tooltip='If enabled/checked, a mid-line is displayed for this sub-indicator.\n\n' +
'See "General Display Settings - Mid Lines" settings above to alter the mid-line color and style.')
rsiShowOBOS = input.bool(title='Show OB/OS ', defval=true, group=g_RSISettings, inline="obos")
rsiOBLevel = input.int(title='Offset', defval=25, minval=1, maxval=50, step=1, group=g_RSISettings, inline="obos",
tooltip='If enabled/checked, a OB and OS lines are displayed for this sub-indicator.\n\n' +
'The offest parameter is defined as distance from the mid-line of the sub-indicator (slow RSI specifically in this case). A value here of "25" would set the OB line at the equivilent of "75" (a +25 offset), ' +
'and a OS line at the equivilent of "25" (a -25 offset).\n\n' +
'Note: Before using this setting, please make sure you understand the native range of the indicator and account for the fact that all sub-indicators have been rescaled to a 100-point range and adjust accordingly.\n\n' +
'See "General Display Settings - OB/OS Lines" settings above to alter the OB and OS line color and style.')
//
// MA settings
g_RSIMASettings = "RSI MA Settings"
rsiMATypeInput = input.string(title="MA Type", options=["Simple", "Smoothed", "Exponential", "Double EMA", "Triple EMA", "RMA", "Weighted", "Volume-Weigehted", "Hull", "ALMA", "Linear"], defval="Simple", group=g_RSIMASettings, tooltip='Moving Average calculation method to use as a bias/reversal filter.\n\n' +
'This MA is calculated on the Slow RSI.')
rsiMALengthInput = input.int(title="MA Length", defval=30, minval=1, step=1, group=g_RSIMASettings, tooltip='MA length. This is used to help define a MA filter for the slow RSI. Sweet spot tends to be 2-3x more than the RSI Slow Length.\n\n' +
'This MA is calculated on the Slow RSI.')
//
// Start with handling some of the precursor stuff...
rsiIndex = getCurrentIndex()
rsiSlowPrice = convertSourcePrice(rsiSlowSourceInput)
rsiFastPrice = convertSourcePrice(rsiFastSourceInput)
if (rsiDisplay)
insertUpperLine(rsiIndex)
insertTitle("Twin RSI", rsiIndex)
addToIndexArray()
//
rsiMidpoint = getIndicatorMidpoint(rsiIndex)
// Fast RSI
//
fastRSIRawValue = ta.rsi(rsiFastPrice, rsiFastLengthInput)
fastRSI = repositionSeries(fastRSIRawValue, rsiIndex)
fastRSIMA = ma(fastRSI, rsiMALengthInput, rsiMATypeInput)
//
// Slow RSI
slowRSIRawValue = ta.rsi(rsiSlowPrice, rsiSlowLengthInput)
slowRSI = repositionSeries(slowRSIRawValue, rsiIndex)
slowRSIMA = ma(slowRSI, rsiMALengthInput, rsiMATypeInput)
// Define some colors...
rsiColorBullish = color.rgb(0, 255, 0, 25)
rsiColorBearish = color.rgb(255, 0, 0, 25)
getRSIFillColor(fastRSI, slowRSI, rsiMA) =>
retColor = color.rgb(0, 0, 0, 100)
slowRSIBelowMA = slowRSI < rsiMA ? true : false
// Fast RSI > Slow RSI will be green.
if (rsiShowFast and rsiShowFill)
if (fastRSI >= slowRSI)
retColor := slowRSIBelowMA ? color.rgb(0, 127, 0, 0) : color.rgb(0, 255, 0, 0)
else
retColor := slowRSIBelowMA ? color.rgb(255, 0, 0, 0) : color.rgb(255, 127, 127, 0)
retColor
// Plot the midline and OB/OS lines
if (rsiDisplay)
insertInnerLines(rsiMidpoint, rsiOBLevel, rsiShowMidline, rsiShowOBOS)
p_FastRSI = plot(rsiDisplay and rsiShowFast ? fastRSI : na, title="Fast RSI", color=color.rgb(128, 128, 255, 0))
p_SlowRSI = plot(rsiDisplay ? slowRSI : na, title="Slow RSI", color=color.rgb(0, 0, 255, 0))
fill(p_FastRSI, p_SlowRSI, color=getRSIFillColor(fastRSI, slowRSI, slowRSIMA), title="Fast/Slow Twin RSI Fill")
plot(rsiDisplay ? slowRSIMA : na, "RSI-based MA", color=color.rgb(255, 255, 0, 35))
//
//
//***** END Twin RSI ******//
//
//
//***** BEGIN Stoch RSI ******//
//
// The Stoch RSI range is between 0 and 100 with a mid-point of 50 naturally, so no rescaling is needed.
// We will still need to handle the repositioning.
//
// Indicator inputs
g_StochRSISettings = "Stochastic RSI Settings"
//
stochRSILengthInput = input.int(title="RSI Length", minval=1, maxval=100, defval=14, step=1, group=g_StochRSISettings, tooltip='This setting controls the length to use for calculating the RSI, which is the base for the Stochastic RSI.')
stochRSISourceInput = input.source(title="Price Source", defval=close, group=g_StochRSISettings, tooltip='Price source for the calculating the RSI. ' +
'The most common setting for this is close (default).')
stochRSIStochLengthInput = input.int(title="Stochastic Length", minval=1, maxval=100, defval=14, step=1, group=g_StochRSISettings, tooltip='This setting controls the length to use when calculating the raw stochastic value of the RSI.')
stochRSIKLength = input.int(title="K Length", minval=1, maxval=100, defval=3, step=1, group=g_StochRSISettings, inline='sr1')
stochRSIDLength = input.int(title="D Length", minval=1, maxval=100, defval=3, step=1, group=g_StochRSISettings, inline='sr1', tooltip='The K length is the lenght to use for the MA calculation of the "fast" (K) line.\n\n' +
'The D lenght is the length to use for the MA of the K line for the "slow" (D) line.')
//
// Stoch RSI Midline and OB/OS settings
stochRSIShowMidline = input.bool(title='Show Mid Line', defval=true, group=g_StochRSISettings, tooltip='If enabled/checked, a mid-line is displayed for this sub-indicator.\n\n' +
'See "General Display Settings - Mid Lines" settings above to alter the mid-line color and style.')
stochRSIShowOBOS = input.bool(title='Show OB/OS ', defval=true, group=g_StochRSISettings, inline="obos")
stochRSIOBLevel = input.int(title='Offset', defval=30, minval=1, maxval=50, step=1, group=g_StochRSISettings, inline="obos",
tooltip='If enabled/checked, a OB and OS lines are displayed for this sub-indicator.\n\n' +
'The offest parameter is defined as distance from the mid-line of the sub-indicator. A value here of "25" would set the OB line at the equivilent of "75" (a +25 offset), ' +
'and a OS line at the equivilent of "25" (a -25 offset).\n\n' +
'Note: Before using this setting, please make sure you understand the native range of the indicator and account for the fact that all sub-indicators have been rescaled to a 100-point range and adjust accordingly.\n\n' +
'See "General Display Settings - OB/OS Lines" settings above to alter the OB and OS line color and style.')
//
// Start with handling some of the precursor stuff...
stochRSIIndex = getCurrentIndex()
stochRSIPrice = convertSourcePrice(stochRSISourceInput)
if (stochRSIDisplay)
insertUpperLine(stochRSIIndex)
insertTitle("Stoch RSI", stochRSIIndex)
addToIndexArray()
//
stochRSIMidpoint = getIndicatorMidpoint(stochRSIIndex)
//
stochRSI_RawRSI = ta.rsi(stochRSIPrice, stochRSILengthInput)
stochRSI_k = repositionSeries(ta.sma(ta.stoch(stochRSI_RawRSI, stochRSI_RawRSI, stochRSI_RawRSI, stochRSIStochLengthInput), stochRSIKLength), stochRSIIndex)
stochRSI_d = ta.sma(stochRSI_k, stochRSIDLength)
// Plot the midline and OB/OS lines
if (stochRSIDisplay)
insertInnerLines(stochRSIMidpoint, stochRSIOBLevel, stochRSIShowMidline, stochRSIShowOBOS)
//
plot(stochRSIDisplay ? stochRSI_k : na, "Stoch RSI K", color=color.rgb(41, 98, 255, 0))
plot(stochRSIDisplay ? stochRSI_d : na, "Stoch RSI D", color=color.rgb(255, 109, 0, 0))
//
//
//***** END Stoch RSI ******//
//
//
//***** BEGIN OG Stochastic ******//
//
// OG Stochastic range is between 0 and 100 with a mid-point of 50 naturally, so no rescaling is needed.
// We will still need to handle the repositioning.
//
// Indicator inputs
g_StochSettings = "Stochastic Settings"
//
//stochLengthInput = input.int(title="Stochastic Length", minval=1, maxval=100, defval=14, step=1, group=g_StochSettings, tooltip='')
stochStochLengthInput = input.int(title="Stochastic Length", minval=1, maxval=100, defval=14, step=1, group=g_StochSettings, tooltip='This setting controls the length to use when calculating the raw price stochastic')
stochKLength = input.int(title="K Length", minval=1, maxval=100, defval=1, step=1, group=g_StochSettings, inline='sr1')
stochDLength = input.int(title="D Length", minval=1, maxval=100, defval=3, step=1, group=g_StochSettings, inline='sr1', tooltip='The K length is the lenght to use for the MA calculation of the "fast" (K) line.\n\n' +
'The D lenght is the length to use for the MA of the K line for the "slow" (D) line.')
//
// Stochastic Midline and OB/OS settings
stochShowMidline = input.bool(title='Show Mid Line', defval=true, group=g_StochSettings, tooltip='If enabled/checked, a mid-line is displayed for this sub-indicator.\n\n' +
'See "General Display Settings - Mid Lines" settings above to alter the mid-line color and style.')
stochShowOBOS = input.bool(title='Show OB/OS ', defval=true, group=g_StochSettings, inline="obos")
stochOBLevel = input.int(title='Offset', defval=25, minval=1, maxval=50, step=1, group=g_StochSettings, inline="obos",
tooltip='If enabled/checked, a OB and OS lines are displayed for this sub-indicator.\n\n' +
'The offest parameter is defined as distance from the mid-line of the sub-indicator. A value here of "25" would set the OB line at the equivilent of "75" (a +25 offset), ' +
'and a OS line at the equivilent of "25" (a -25 offset).\n\n' +
'Note: Before using this setting, please make sure you understand the native range of the indicator and account for the fact that all sub-indicators have been rescaled to a 100-point range and adjust accordingly.\n\n' +
'See "General Display Settings - OB/OS Lines" settings above to alter the OB and OS line color and style.')
//
// Start with handling some of the precursor stuff...
stochIndex = getCurrentIndex()
if (stochDisplay)
insertUpperLine(stochIndex)
insertTitle("Stoch", stochIndex)
addToIndexArray()
//
stochMidpoint = getIndicatorMidpoint(stochIndex)
//
stoch_k = repositionSeries(ta.sma(ta.stoch(c, h, l, stochStochLengthInput), stochKLength), stochIndex)
stoch_d = ta.sma(stoch_k, stochDLength)
// Plot the midline and OB/OS lines
if (stochDisplay)
insertInnerLines(stochMidpoint, stochOBLevel, stochShowMidline, stochShowOBOS)
//
plot(stochDisplay ? stoch_k : na, "Stochastic K", color=color.rgb(41, 98, 255, 0))
plot(stochDisplay ? stoch_d : na, "Stochastic D", color=color.rgb(255, 109, 0, 0))
//
//
//***** END OG Stochastic ******//
//
//
//***** BEGIN UO ******//
//
// UO range is between 0 and 100 with a mid-point of 50 naturally, so no rescaling is needed.
// We will still need to handle the repositioning.
//
// There are three steps to calculating the Ultimate Oscillator. This example uses 7, 14, 28 parameters:
// 1. Before calculating the Ultimate Oscillator, two variable need to be defined; Buying Pressure and True Range.
//
// Buying Pressure (BP) = Close - Minimum (Lowest between Current Low or Previous Close)
// True Range (TR) = Maximum (Highest between Current High or Previous Close) - Minimum (Lowest between Current Low or Previous Close)
// 2. The Ultimate Oscillator then uses these figures over three time periods:
//
// Average7 = (7 Period BP Sum) / (7 Period TR Sum)
// Average14 = (14 Period BP Sum) / (14 Period TR Sum)
// Average28 = (28 Period BP Sum) / (28 Period TR Sum)
// 3. The final Ultimate Oscillator calculations can now be made:
//
// UO = 100 x [(4 x Average7)+(2 x Average14)+Average28]/(4+2+1)
// Indicator inputs
g_UOSettings = "Ultimate Oscillator Settings"
//
uoLength1 = input.int(title="Fast Length", minval=1, maxval=100, defval=7, step=1, group=g_UOSettings, tooltip='Length to use for the fast calculation of BP/TR')
uoLength2 = input.int(title="Middle Length", minval=1, maxval=100, defval=14, step=1, group=g_UOSettings, tooltip='Length to use for the middle calculation of BP/TR')
uoLength3 = input.int(title="Slow Length", minval=1, maxval=100, defval=28, step=1, group=g_UOSettings, tooltip='Length to use for the slow calculation of BP/TR')
//
// UO Midline and OB/OS settings
uoShowMidline = input.bool(title='Show Mid Line', defval=true, group=g_UOSettings, tooltip='If enabled/checked, a mid-line is displayed for this sub-indicator.\n\n' +
'See "General Display Settings - Mid Lines" settings above to alter the mid-line color and style.')
uoShowOBOS = input.bool(title='Show OB/OS ', defval=true, group=g_UOSettings, inline="obos")
uoOBLevel = input.int(title='Offset', defval=25, minval=1, maxval=50, step=1, group=g_UOSettings, inline="obos",
tooltip='If enabled/checked, a OB and OS lines are displayed for this sub-indicator.\n\n' +
'The offest parameter is defined as distance from the mid-line of the sub-indicator. A value here of "25" would set the OB line at the equivilent of "75" (a +25 offset), ' +
'and a OS line at the equivilent of "25" (a -25 offset).\n\n' +
'Note: Before using this setting, please make sure you understand the native range of the indicator and account for the fact that all sub-indicators have been rescaled to a 100-point range and adjust accordingly.\n\n' +
'See "General Display Settings - OB/OS Lines" settings above to alter the OB and OS line color and style.')
//
// MA settings
g_UOMASettings = "UO MA Settings"
uoIncludeMA = input.bool(title='Include Moving Average', defval=true, group=g_UOMASettings, tooltip='If checked, will include a Moving Average of the UO. Default value: checked')
uoMATypeInput = input.string(title="MA Type", options=["Simple", "Smoothed", "Exponential", "Double EMA", "Triple EMA", "RMA", "Weighted", "Volume-Weigehted", "Hull", "ALMA", "Linear"], defval="Simple", group=g_UOMASettings,
tooltip='Moving Average calculation method to use as a bias/reversal filter. Only applies if "Include Moving Average" above is checked/enabled.')
uoMALengthInput = input.int(title="MA Length", defval=30, minval=1, step=1, group=g_UOMASettings, tooltip='Number of historical UO values to use for calculating the MA value. Lower numbers will react more quickly, while higher numbers will better depict Longer trends.')
uoShowFill = input.bool(title='Include UO/MA Fill', defval=false, group=g_UOMASettings, tooltip='If checked, will include a color-coded fill between the UO and the UO MA. Default value: unchecked')
//
// Start with handling some of the precursor stuff...
uoIndex = getCurrentIndex()
if (uoDisplay)
insertUpperLine(uoIndex)
insertTitle("UO", uoIndex)
addToIndexArray()
//
uoMidpoint = getIndicatorMidpoint(uoIndex)
//
// Some functions specific to the UO...
//
// Buying Pressure (BP) = Close - Minimum (Lowest between Current Low or Previous Close)
getBuyingPressure() =>
ret = c - math.min(l, c[1])
ret
//
// True Range (TR) = Maximum (Highest between Current High or Previous Close) - Minimum (Lowest between Current Low or Previous Close)
getTrueRange() =>
ret = math.max(h, c[1]) - math.min(l, c[1])
ret
//
// UO Stub Average = (X-length BP Sum) / (X-length TR Sum)
getUOAverageStub(length) =>
ret = 0.0
uoBPSum = math.sum(getBuyingPressure(), length)
uoTRSum = math.sum(getTrueRange(), length)
ret := uoBPSum / uoTRSum
ret
//
// UO = 100 x [(4 x Average7)+(2 x Average14)+Average28]/(4+2+1)
getUOAverage(lenShort, lenMedium, lenLong) =>
ret = 0.0
uoShortAvg = getUOAverageStub(lenShort)
uoMediumAvg = getUOAverageStub(lenMedium)
uoLongAvg = getUOAverageStub(lenLong)
ret := 100 * (((4 * uoShortAvg) + (2 * uoMediumAvg) + (1 * uoLongAvg)) / (4 + 2 + 1))
ret
//
// Now to get the UO and handle the repositioning...
uoOut = repositionSeries(getUOAverage(uoLength1, uoLength2, uoLength3), uoIndex)
uoMA = ma(uoOut, uoMALengthInput, uoMATypeInput)
// Plot the midline and OB/OS lines
if (uoDisplay)
insertInnerLines(uoMidpoint, uoOBLevel, uoShowMidline, uoShowOBOS)
//
p_UO = plot(uoDisplay ? uoOut : na, title="UO", color=color.rgb(0, 255, 255, 35))
p_UOMA = plot(uoDisplay and uoIncludeMA ? uoMA : na, title="UO MA", color=color.rgb(255, 255, 0, 0))
getUOFillColor(uo, uoMA) =>
retColor = color.rgb(0, 0, 0, 100)
if (uoShowFill)
if (uo >= uoMA)
retColor := color.rgb(0, 255, 0, 0)
else
retColor := color.rgb(255, 0, 0, 0)
retColor
fill(p_UO, p_UOMA, color=getUOFillColor(uoOut, uoMA), title="Ultimate Oscillator Fill")
//
//
//***** END UO ******//
//
//
//***** BEGIN AO ******//
//
// Range is technically infinite (unbounded), and actual values will be based on security price,
// so we will need to rescale this indicator. The mid-line is at 0 (which is common for unbounded)
// oscillators like this), so we need to keep that in mind as well.
//
// Indicator inputs
g_AOSettings = "Awesome Oscillator Settings"
//
aoScalingMethod = input.string(title="Rescaling Method", defval="Standardization", options=["Standardization","Normalization"], group=g_AOSettings, tooltip='This setting controls how the indicator rescaling is handled.\r\r' +
"Since the AO (like the MACD) isn't range-bound by default, we need to apply some transformation math to get it to fit in our 'indicator stack' slot. Taking a page from 'Feature Scaling' commonly used in " +
"Machine Learning, we have 2 methods we can use to achieve this:\n\n" +
"Standardization (default): Applies an algorithm that will result in a data series with a mean of 0 and standard deviation of 1. While this still TECHNICALLY still results in a infinte range, we can use " +
"the fixed standard deviation size and that it will have a shape very similar to a normal distribution (perhaps with some skew based on trend direction and strength, and some shifts in kurtosis ('tail size') based on recent volatility)." +
"This method has the benefit of retaining an accurate/true mid-line.\n\n" +
"Normalization: Applies an algorithm that will result in a data series with a fixed-range between 0 and 1. While this method will retain all the original behavior of the oscillator itself, the act of forcing the data into a fixed-range " +
"in this manner does have the side-effect of often resulting in the pre-rescaled mid-line being shifted away from the true middle as well. This makes this method of rescaling fine for techniques like divergence analysis, but would effectively " +
"invalidate any techniques that rely on an accurate mid-line (e.g. mid-line crosses or the use of Overbought/Oversold levels).")
aoStandardizationFactor = input.float(title="Standardization Scaling Factor", minval=0.1, maxval=25, defval=3.5, step=0.1, group=g_AOSettings, tooltip='This setting equates to the number of standard deviations we want to use for scaling data output from the ' +
"'Standardization' rescaling method.\n\n" +
"Since the output of the 'Standardization' scaling is defined as a mean of 0 and standard deviation of 1, the 'normal' resulting range would generally be around a range of 10 (from -5 to +5), which is much narrower than our desired range of 100. " +
"To help scale up closer to our desired range of 100, we apply a multiplier based on the number of standard deviations we are from the mean (mid-point) of 0.\n\n" +
"If you find the component indicator is 'spilling over' the lines defnining it's range, increasing this scaling factor will result in 'shrinking' the plots back into the intended range. Conversely, if you feel it's too 'cramped', you can decrease " +
"this scaling factor to expand the plots to take up more of the allocated range space.\n\n" +
"Most of the time, a scaling factor between 2.5 and 5 is sufficient to 'fill the space' without 'spilling over' into other components.")
aoSource = input.source(title="Price Source", defval=hl2, group=g_AOSettings, tooltip='The price source to use for the MA calculation used by the AO. The most common setting for this is hl2 (default).')
aoLength1 = input.int(title="Short Length", minval=1, maxval=100, defval=5, step=1, group=g_AOSettings, tooltip='This controls the length for the fast MA used for the AO calculation')
aoLength2 = input.int(title="Long Length", minval=1, maxval=100, defval=34, step=1, group=g_AOSettings, tooltip='This controls the length for the slow MA used for the AO calculation')
aoShowAsHist = input.bool(title='Display AO in Histogram style', defval=true, group=g_AOSettings, tooltip='If checked, will plot the AO in a Histogram-style plot. Default value: checked')
//
// AO Midline and OB/OS settings
aoShowMidline = input.bool(title='Show Mid Line', defval=true, group=g_AOSettings, tooltip='If enabled/checked, a mid-line is displayed for this sub-indicator.\n\n' +
'See "General Display Settings - Mid Lines" settings above to alter the mid-line color and style.')
// As a traditionally unbound indicator, the AO doesn't have a traditional concept of fixed OB/OS levels
//aoShowOBOS = input.bool(title='Show OB/OS ', defval=true, group=g_AOSettings, inline="obos")
aoShowOBOS = false
//aoOBLevel = input.int(title='Offset', defval=25, minval=1, maxval=50, step=1, group=g_AOSettings, inline="obos", tooltip='')
aoOBLevel = 0
//
// MA settings
g_AOMASettings = "AO MA Settings"
aoIncludeMA = input.bool(title='Include Moving Average', defval=false, group=g_AOMASettings, tooltip='If checked, will include a Moving Average of the AO itself. Default value: checked')
aoMATypeInput = input.string(title="MA Type", options=["Simple", "Smoothed", "Exponential", "Double EMA", "Triple EMA", "RMA", "Weighted", "Volume-Weigehted", "Hull", "ALMA", "Linear"], defval="Simple", group=g_AOMASettings,
tooltip='Moving Average calculation method to use as a bias/reversal filter. Only applies if "Include Moving Average" above is checked/enabled.')
aoMALengthInput = input.int(title="MA Length", defval=30, minval=1, step=1, group=g_AOMASettings, tooltip='Number of historical AO values to use for calculating the MA value. Lower numbers will react more quickly, while higher numbers will better depict Longer trends.')
aoShowFill = input.bool(title='Include AO/MA Fill', defval=true, group=g_AOMASettings, tooltip='If checked, will include a color-coded fill between the AO and the AO MA. Default value: checked')
//
// Start with handling some of the precursor stuff...
aoIndex = getCurrentIndex()
if (aoDisplay)
insertUpperLine(aoIndex)
insertTitle("AO", aoIndex)
addToIndexArray()
//
aoPrice = convertSourcePrice(aoSource)
aoMidpoint = getIndicatorMidpoint(aoIndex)
aoShort = ma(aoPrice, aoLength1, "Simple")
aoLong = ma(aoPrice, aoLength2, "Simple")
//
aoOutUnscaled = (aoShort - aoLong)
aoOutScaled = switch aoScalingMethod
"Standardization" => rescaleStandardizedData(standardize(aoOutUnscaled, 4850), aoStandardizationFactor)
"Normalization" => rescaleNormalizedData(normalize(aoOutUnscaled, 4850))
aoOutRepositioned = repositionSeries(aoOutScaled, aoIndex)
aoMA = ma(aoOutRepositioned, aoMALengthInput, aoMATypeInput)
// Plot the midline and OB/OS lines
if (aoDisplay)
insertInnerLines(aoMidpoint, aoOBLevel, aoShowMidline, aoShowOBOS)
//
getAOFillColor(ao, aoRef) =>
retColor = color.rgb(0, 0, 0, 100)
if (ao >= aoRef)
retColor := color.rgb(0, 255, 0, 0)
else
retColor := color.rgb(255, 0, 0, 0)
retColor
//
plotcandle(aoMidpoint, math.max(aoMidpoint, aoOutRepositioned), math.min(aoMidpoint, aoOutRepositioned), aoOutRepositioned, title="AO Pseudo-Histogram", color=getAOFillColor(aoOutUnscaled, aoOutUnscaled[1]), bordercolor=getAOFillColor(aoOutUnscaled, aoOutUnscaled[1]), wickcolor=getAOFillColor(aoOutUnscaled, aoOutUnscaled[1]), display=(aoDisplay and aoShowAsHist ? display.all : display.none))
//
p_AO = plot(aoDisplay and not aoShowAsHist ? aoOutRepositioned : na, title="AO", color=color.rgb(0, 255, 255, 15))
p_AOMA = plot(aoDisplay and aoIncludeMA ? aoMA : na, title="AO MA", color=color.rgb(255, 255, 0, 0))
//
fill(p_AO, p_AOMA, color=(aoShowFill and not aoShowAsHist ? getAOFillColor(aoOutRepositioned, aoMA) : na), title="Awesome Oscillator Fill")
//
//
//***** END AO ******//
//
//
//***** BEGIN MACD ******//
//
// Range is technically infinite (unbounded), and actual values will be based on security price,
// so we will need to rescale this indicator. The mid-line is at 0 (which is common for unbounded)
// oscillators like this), so we need to keep that in mind as well.
//
// Indicator inputs
g_MACDSettings = "MACD Settings"
//
macdScalingMethod = input.string(title="Rescaling Method", defval="Standardization", options=["Standardization","Normalization"], group=g_MACDSettings, tooltip='This setting controls how the indicator rescaling is handled.\n\n' +
"Since the MACD (like the AO) isn't range-bound by default, we need to apply some transformation math to get it to fit in our 'indicator stack' slot. Taking a page from 'Feature Scaling' commonly used in " +
"Machine Learning, we have 2 methods we can use to achieve this:\n\n" +
"Standardization (default): Applies an algorithm that will result in a data series with a mean of 0 and standard deviation of 1. While this still TECHNICALLY still results in a infinte range, we can use " +
"the fixed standard deviation size and that it will have a shape very similar to a normal distribution (perhaps with some skew based on trend direction and strength, and some shifts in kurtosis ('tail size') based on recent volatility)." +
"This method has the benefit of retaining an accurate/true mid-line.\n\n" +
"Normalization: Applies an algorithm that will result in a data series with a fixed-range between 0 and 1. While this method will retain all the original behavior of the oscillator itself, the act of forcing the data into a fixed-range " +
"in this manner does have the side-effect of often resulting in the pre-rescaled mid-line being shifted away from the true middle as well. This makes this method of rescaling fine for techniques like divergence analysis, but would effectively " +
"invalidate any techniques that rely on an accurate mid-line (e.g. mid-line crosses or the use of Overbought/Oversold levels).")
macdStandardizationFactor = input.float(title="Standardization Scaling Factor", minval=0.1, maxval=25, defval=3.5, step=0.1, group=g_MACDSettings, tooltip='This setting equates to the number of standard deviations we want to use for scaling data output from the ' +
"'Standardization' rescaling method.\n\n" +
"Since the output of the 'Standardization' scaling is defined as a mean of 0 and standard deviation of 1, the 'normal' resulting range would generally be around a range of 10 (from -5 to +5), which is much narrower than our desired range of 100. " +
"To help scale up closer to our desired range of 100, we apply a multiplier based on the number of standard deviations we are from the mean (mid-point) of 0.\n\n" +
"If you find the component indicator is 'spilling over' the lines defnining it's range, increasing this scaling factor will result in 'shrinking' the plots back into the intended range. Conversely, if you feel it's too 'cramped', you can decrease " +
"this scaling factor to expand the plots to take up more of the allocated range space.\n\n" +
"Most of the time, a scaling factor between 2.5 and 5 is sufficient to 'fill the space' without 'spilling over' into other components.")
macdSource = input.source(title="Price Source", defval=close, group=g_MACDSettings, tooltip='Price source to use for calculating the MA components of the MACD. The most common setting for this is close (default).')
macdFastLength = input.int(title="Fast Length", minval=1, maxval=100, defval=12, step=1, group=g_MACDSettings, tooltip='This setting controls the length used for the fast MA component of the MACD')
macdSlowLength = input.int(title="Slow Length", minval=1, maxval=100, defval=26, step=1, group=g_MACDSettings, tooltip='This setting controls the length used for the slow MA component of the MACD')
macdBaseMATypeInput = input.string(title="MACD MA Type", options=["Simple", "Smoothed", "Exponential", "Double EMA", "Triple EMA", "RMA", "Weighted", "Volume-Weigehted", "Hull", "ALMA", "Linear"], defval="Exponential", group=g_MACDSettings,
tooltip='This setting controls the MA calculation method used for calculating the 2 MA components of the MACD')
macdSignalMATypeInput = input.string(title="MACD Signal MA Type", options=["Simple", "Smoothed", "Exponential", "Double EMA", "Triple EMA", "RMA", "Weighted", "Volume-Weigehted", "Hull", "ALMA", "Linear"], defval="Exponential", group=g_MACDSettings,
tooltip='This setting controls the MA calculation method used for calculating the MACD Signal line')
macdSignalLength = input.int(title="MACD Signal Smoothing", minval=1, maxval=50, defval=9, step=1, group=g_MACDSettings, tooltip='This setting controls the MA length when calculating the MACD Signal line')
//
// MACD Midline and OB/OS settings
macdShowMidline = input.bool(title='Show Mid Line', defval=true, group=g_MACDSettings, tooltip='If enabled/checked, a mid-line is displayed for this sub-indicator.\n\n' +
'See "General Display Settings - Mid Lines" settings above to alter the mid-line color and style.')
// As a traditionally unbound indicator, the MACD doesn't have a traditional concept of fixed OB/OS levels
//macdShowOBOS = input.bool(title='Show OB/OS ', defval=true, group=g_MACDSettings, inline="obos")
macdShowOBOS = false
//macdOBLevel = input.int(title='Offset', defval=25, minval=1, maxval=50, step=1, group=g_MACDSettings, inline="obos", tooltip='')
macdOBLevel = 0
//
// Start with handling some of the precursor stuff...
macdIndex = getCurrentIndex()
if (macdDisplay)
insertUpperLine(macdIndex)
insertTitle("MACD", macdIndex)
addToIndexArray()
//
macdPrice = convertSourcePrice(macdSource)
macdMidpoint = getIndicatorMidpoint(macdIndex)
macdFastMA = ma(macdPrice, macdFastLength, macdBaseMATypeInput)
macdSlowMA = ma(macdPrice, macdSlowLength, macdBaseMATypeInput)
macdUnscaled = (macdFastMA - macdSlowMA)
macdScaled = switch macdScalingMethod
"Standardization" => rescaleStandardizedData(standardize(macdUnscaled, 4850), macdStandardizationFactor)
"Normalization" => rescaleNormalizedData(normalize(macdUnscaled, 4850))
macdRepositioned = repositionSeries(macdScaled, macdIndex)
macdSignal = ma(macdRepositioned, macdSignalLength, macdSignalMATypeInput)
hist = macdMidpoint + (macdRepositioned - macdSignal)
// Plot the midline and OB/OS lines
if (macdDisplay)
insertInnerLines(macdMidpoint, macdOBLevel, macdShowMidline, macdShowOBOS)
//
p_MACD = plot(macdDisplay ? macdRepositioned : na, title="MACD", color=color.rgb(0, 255, 255, 15))
p_MACDSignal = plot(macdDisplay ? macdSignal : na, title="MACD Signal", color=color.rgb(255, 255, 0, 0))
//
//
//***** END MACD ******//
//
//
//***** BEGIN Outback RSI ******//
//
g_ORSISettings = "Outback RSI Settings"
orsiLengthInput = input.int(title="RSI Length", defval=618, minval=1, group=g_ORSISettings)
orsiSourceInput = input.source(title="RSI Source", defval=close, group=g_ORSISettings)
orsiTrigger = input.int(title="RSI Trigger Level", defval=50, minval=1, maxval=99, group=g_ORSISettings, tooltip="RSI Trigger Level for safe entry")
orsiUseTrigger = input.bool(title="Display Safe Entries", defval=false, group=g_ORSISettings, tooltip="If activated, background coloring will differentiate between risk entry and safe entry (RSI above/below RSI trigger level")
orsiMATypeInput = input.string(title="MA Type", defval="Simple", options=["Simple", "Smoothed", "Exponential", "Double EMA", "Triple EMA", "RMA", "Weighted", "Volume-Weigehted", "Hull", "ALMA", "Linear"], group=g_ORSISettings)
orsiMALengthInput = input.int(title="MA Length", defval=200, group=g_ORSISettings)
orsiHullLength = input.int(title='MA Length', defval=227, group = g_ORSISettings)
orsiHullMult = input.float(title="Length multiplier", defval=2.0, step=0.1, minval=1.0, maxval=5.0, group = g_ORSISettings)
// Start with handling some of the precursor stuff...
orsiIndex = getCurrentIndex()
if (orsiDisplay)
insertUpperLine(orsiIndex)
insertTitle("O-RSI", orsiIndex)
addToIndexArray()
//
orsiPrice = convertSourcePrice(orsiSourceInput)
orsiMidpoint = getIndicatorMidpoint(orsiIndex)
orsiRawValue = ta.rsi(orsiPrice, orsiLengthInput)
orsiRepositioned = repositionSeries(orsiRawValue, orsiIndex)
orsiTriggerReositioned = repositionSeries(orsiTrigger, orsiIndex)
orsiMA = ma(orsiRepositioned, orsiMALengthInput, orsiMATypeInput)
orsiHMALength = math.floor(orsiHullLength * orsiHullMult)
orsiHMA = ma(orsiRepositioned, orsiHMALength, "Hull")
// Will be used for "invisible plots" to allow us to use the 'fill()' function to apply our "background" color-coding
orsiUpperBound = orsiMidpoint + 49
orsiLowerBound = orsiMidpoint - 49
//
// And the "invisible plots"...
p_ORSIUpper = plot(orsiDisplay ? orsiUpperBound : na, color=color.rgb(0, 0, 0, 100), editable=false, display=display.none, title="ORSI Upper Bound")
p_ORSILower = plot(orsiDisplay ? orsiLowerBound : na, color=color.rgb(0, 0, 0, 100), editable=false, display=display.none, title="ORSI Lower Bound")
orsiRiskEntryLong = orsiUseTrigger ? (orsiRepositioned > orsiMA and orsiRepositioned > orsiHMA and orsiRepositioned < orsiTriggerReositioned ? true : false) : orsiRepositioned > orsiMA and orsiRepositioned > orsiHMA ? true : false
orsiEntryLong = orsiRepositioned > orsiMA and orsiRepositioned > orsiHMA and orsiRepositioned > orsiTriggerReositioned ? true : false
orsiRiskEntryShort = orsiUseTrigger ? (orsiRepositioned < orsiMA and orsiRepositioned < orsiHMA and orsiRepositioned > orsiTriggerReositioned ? true : false) : orsiRepositioned < orsiMA and orsiRepositioned < orsiHMA ? true : false
orsiEntryShort = orsiRepositioned < orsiMA and orsiRepositioned < orsiHMA and orsiRepositioned < orsiTriggerReositioned ? true : false
getORSIFillColor() =>
ret = color.rgb(0, 0, 0, 100)
if (orsiRiskEntryLong)
ret := color.rgb(5, 102, 86, 50)
if (orsiEntryLong and orsiTrigger)
ret := color.rgb(0, 51, 42, 50)
if (orsiRiskEntryShort)
ret := color.rgb(255, 152, 0, 50)
if (orsiEntryShort and orsiTrigger)
ret := color.rgb(230, 81, 0, 50)
ret
fill(p_ORSIUpper, p_ORSILower, color=orsiDisplay ? getORSIFillColor() : na, title="Outback RSI Entry Signals")
//
//
//***** END Outback RSI ******//
|
Composite Cosmetic Candles | https://www.tradingview.com/script/kMDHehn7-Composite-Cosmetic-Candles/ | EsIstTurnt | https://www.tradingview.com/u/EsIstTurnt/ | 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/
// © EsIstTurnt
//@version=5
indicator("Composite Cosmetic Candles",overlay=true)
//Inputs
src = input.source(close,'Source',group="Oscillator")
osctype = input.string("RSI",options=["RSI","CCI","COG","MFI","CMO","TSI","COPPOCK","VOLUME","OC Range","HL Range","BOP","BBP"],group="Oscillator")
len = input.int(16,'Length',group="Oscillator")
levels = input.int(5,'Sections',options=[2,3,4,5,6,7,8,9,10],group='Measurement Meter')
transp = input.int(50,'Transparency',group='Appearance')
topbot = input.bool(false,'Plot Candle Open+Close along with Dividing Levels',group="Measurement Meter")
label = input.bool(true,'Show Value Label',group="Measurement Meter")
osc_col = input.bool(false,'Bar Color uses Oscillator Instead',group='Appearance')
solidfill = input.bool(false,'Single Color Bar Fill',group='Appearance')
showosc = input.bool(true,'Fill Bar Partially based on Oscillator Values',group='Appearance')
float osc = switch osctype // Switch selecting oscillator type to use
"RSI" => ta.rsi(src, len)
"CCI" => ta.cci(src, len)
"COG" => ta.cog(src, len)
"MFI" => ta.mfi(src, len)
"CMO" => ta.cmo(src, len)
"TSI" => ta.tsi(src, len,len*2)
"COPPOCK" => ta.wma(ta.roc(src,math.round(1.1*len))+ta.roc(src,math.round(1.4*len)),len)
"VOLUME" => volume-volume[1]
"OC Range"=> (math.max(open,close)-math.min(open,close))/ta.highest(math.max(open,close)-math.min(open,close),len )
"HL Range"=> (high-low)/(ta.highest(high-low,len))
"BOP" => (close - open) / (high - low)
"BBP" => (high - ta.ema(close, len))+(low - ta.ema(close, len))
candles(float src,int lb = 0)=> //Oscillator Candle Function - Open,High,Low will remain the same, but close is going to be a percentage of the actual bars close based upon the oscillator divided by the max value
max=lb == 0?ta.max(src):ta.highest(src,lb)// \
min=lb == 0?ta.min(src):ta.lowest (src,lb)// - Converting Oscillator Value to a float value
dif=max-min// /
pct=min>=0?src/max:((src-min)/dif)// /
bar=math.max(open,close)-math.min(open,close) //Absolute Value of close-open
dir=open>close // Do we subtract or add?
lev=dir?math.max(open,close)-(pct*bar):math.min(open,close)+(pct*bar) // Checks candle direction, then multiplies the float value by the actual candle body's difference to get the oscillator fill level
_open=open //\
_high=high// - Values Are left the Same
_low=low// /
_close=lev// Oscillator Close Value
[_open,_high,_low,_close]
[_open,_high,_low,_close]=candles(osc)//Now assign Variables using above function (name kept same for simplicity)
s= showosc?math.abs(_close-_open)/3:math.abs(close-open)/3// Using the absolute value of close-open or _close-open, divide it by three (Could be more but I Ran out of plots ahem* TradingView...) for candle fill levels
l1=close>open?_open+(1*s):_open-(1*s)// \
l2=close>open?_open+(2*s):_open-(2*s)// - Level # * value from above added or subtracted to the candle's open, depending on which direction the bar moved.
l3=close>open?_open+(3*s):_open-(3*s)// /
//
sections(num)=> //Candle Dividing Level Function - up to 9 levels but theoretically you can have as many as TV will allow if you want by adding more
span=math.max(open,close)-math.min(open,close) //Absolute difference between Open and Close values
divi=1/num //1 divided by user input # of levels to give us a float value of what each individual level should be a multiple of
bool=open>close //Down Candle?
lev1=bool?num>=2 ?open-span*(1 *divi):na:num>=2 ?open+(span*(divi*1 )):na///
lev2=bool?num>=3 ?open-span*(2 *divi):na:num>=3 ?open+(span*(divi*2 )):na///\
lev3=bool?num>=4 ?open-span*(3 *divi):na:num>=4 ?open+(span*(divi*3 )):na// \
lev4=bool?num>=5 ?open-span*(4 *divi):na:num>=5 ?open+(span*(divi*4 )):na// \
lev5=bool?num>=6 ?open-span*(5 *divi):na:num>=6 ?open+(span*(divi*5 )):na// Checks If candle is green or red, then if the selected # of levels is greater than or equal to the level #
lev6=bool?num>=7 ?open-span*(6 *divi):na:num>=7 ?open+(span*(divi*6 )):na// / of each line, if so then adds or subtracts the product of the float value multiplied by the corresponding
lev7=bool?num>=8 ?open-span*(7 *divi):na:num>=8 ?open+(span*(divi*7 )):na// / level to give us another float value which is then multiplied by the actual candle body's difference, na
lev8=bool?num>=9 ?open-span*(8 *divi):na:num>=9 ?open+(span*(divi*8 )):na//// if selected # of levels is lower
lev9=bool?num>=10?open-span*(9 *divi):na:num>=10?open+(span*(divi*9 )):na///
top=math.max(open,close) // \
// Actual Candle Body's Open and Close, for plotting them as steplines aswell if selected
bot=math.min(open,close) // /
[lev1,lev2,lev3,lev4,lev5,lev6,lev7,lev8,lev9,top,bot,num]
//
[lev1,lev2,lev3,lev4,lev5,lev6,lev7,lev8,lev9,top,bot,num]= sections(levels)//Now assign Variables using above function (name kept same for simplicity)
//Colors
up_col=color.new(#acfb00,transp)
dn_col=color.new(#ff0000,transp)
osccolor =osc_col ?color.new(osc>osc[1]?up_col:dn_col,transp) :color.new(_open<_close?up_col:dn_col,transp*1)
color1 =osc_col ?color.new(osc>osc[1]?#0CFA36:#E90606,transp*1 ) :color.new(_open<_close?#0CFA36:#E90606,transp*1 )//\
color2 =osc_col ?color.new(osc>osc[1]?#35FA0C:#E90606,transp*1.11) :color.new(_open<_close?#35FA0C:#E90606,transp*1.11)// \
color3 =osc_col ?color.new(osc>osc[1]?#5DFA0C:#D90616,transp*1.22) :color.new(_open<_close?#5DFA0C:#D90616,transp*1.22)// Colors for Candle Fills
color4 =osc_col ?color.new(osc>osc[1]?#AFFA0C:#C90626,transp*1.33) :color.new(_open<_close?#AFFA0C:#C90626,transp*1.33)// /
//Plots
divider1=plot(lev1,'Level 1',style=plot.style_stepline,color=color.new(color.from_gradient(lev1,_low,_high,dn_col,up_col),transp))//\
divider2=plot(lev2,'Level 2',style=plot.style_stepline,color=color.new(color.from_gradient(lev2,_low,_high,dn_col,up_col),transp))// \
divider3=plot(lev3,'Level 3',style=plot.style_stepline,color=color.new(color.from_gradient(lev3,_low,_high,dn_col,up_col),transp))// \
divider4=plot(lev4,'Level 4',style=plot.style_stepline,color=color.new(color.from_gradient(lev4,_low,_high,dn_col,up_col),transp))// \
divider5=plot(lev5,'Level 5',style=plot.style_stepline,color=color.new(color.from_gradient(lev5,_low,_high,dn_col,up_col),transp))// -Plot Candle Dividers
divider6=plot(lev6,'Level 6',style=plot.style_stepline,color=color.new(color.from_gradient(lev6,_low,_high,dn_col,up_col),transp))// /
divider7=plot(lev7,'Level 7',style=plot.style_stepline,color=color.new(color.from_gradient(lev7,_low,_high,dn_col,up_col),transp))// /
divider8=plot(lev8,'Level 8',style=plot.style_stepline,color=color.new(color.from_gradient(lev8,_low,_high,dn_col,up_col),transp))// /
divider9=plot(lev9,'Level 9',style=plot.style_stepline,color=color.new(color.from_gradient(lev9,_low,_high,dn_col,up_col),transp))///
topplot =plot(topbot?top:na,'Top',linewidth=2,style=plot.style_stepline,color=open>close?dn_col:up_col)
botplot =plot(topbot?bot:na,'Bottom',linewidth=2,style=plot.style_stepline,color=open>close?dn_col:up_col)
plotcandle( solidfill==false?na:_open,_high,_low,_close,color=osccolor,wickcolor=osccolor,bordercolor = osccolor)//Plot Solid Candle
plotcandle( solidfill? na :_open,_high,_low ,l1 ,'open-l1 Candle' ,color=color4 ,wickcolor=color4 ,bordercolor = color4)// \
plotcandle( solidfill? na :l1 ,_high,_low ,l2 ,'l1-l2 Candle' ,color=color3 ,wickcolor=color3 ,bordercolor = color3)// \
// Plot Gradient Candles which together, produce a nicer looking
plotcandle( solidfill? na :l2 ,_high,_low ,l3 ,'l2-l3 Candle' ,color=color2 ,wickcolor=color2 ,bordercolor = color2)// / candle with the same extremeties as above
plotcandle( solidfill? na :l3 ,_high,_low ,_close,'l3-close Candle',color=color1 ,wickcolor=color1 ,bordercolor = color1)// /
//Labeling, self explanitory
//Text for lables
string rf = osc>osc[1]?"(Rising)":"(Falling)"
var label1 = label?label.new (bar_index, _close, "", style=label.style_none):na
var label2 = label?label.new (bar_index, _close- (0.05*close), "", style=label.style_none):na
label.set_xloc(label1, time, xloc.bar_time)
label.set_xloc(label2, time, xloc.bar_time)
label.set_text(label1, text= osctype +"="+ str.tostring(math.round_to_mintick(osc))+rf)
label.set_text(label2, text= "(max = " + str.tostring(math.round(ta.max(osc))) + " min = " + str.tostring(math.round(ta.min(osc)) ) + ")")
label.set_y(label1, ta.highest(high,8))
label.set_y(label2, ta.lowest(low,8))
label.set_textcolor(label1,color1)
|
VWAP 3x Session Reset | https://www.tradingview.com/script/5VUFEunj-VWAP-3x-Session-Reset/ | EternallyCurious | https://www.tradingview.com/u/EternallyCurious/ | 95 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EternallyCurious
//@version=5
indicator(title="VWAP 3x Session Reset", shorttitle="VWAP 3xReset", overlay=true)
session1 = input.session("1700-0200", "Session 1")
session2 = input.session("0200-0830", "Session 2")
session3 = input.session("0830-1600", "Session 3")
timeZone = input.string("America/Chicago", "Time Zone")
stdevMultiplierInput = 2
// Detects the beginning of a session
sessionBegins(sess) =>
t = time("", sess, timeZone)
timeframe.isintraday and (not barstate.isfirst) and na(t[1]) and not na(t)
sessionIsActive(session) =>
not na(time("", session, timeZone)) ? true : false
sessionStart = sessionBegins(session1) or sessionBegins(session2) or sessionBegins(session3)
plotValue = not sessionStart and (sessionIsActive(session1) or sessionIsActive(session2) or sessionIsActive(session3))
[vwap, upper, lower] = ta.vwap(open, sessionStart, stdevMultiplierInput)
plot(vwap, color = plotValue? color.yellow : color.rgb(0, 0, 0, 100), display=display.all-display.price_scale)
plot(upper, color = plotValue? color.green : color.rgb(0, 0, 0, 100), display=display.all-display.price_scale)
plot(lower, color = plotValue? color.green : color.rgb(0, 0, 0, 100), display=display.all-display.price_scale) |
Market Trend | https://www.tradingview.com/script/0I9YswyU-Market-Trend/ | morzor61 | https://www.tradingview.com/u/morzor61/ | 129 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © morzor61
//@version=5
indicator("Trend Analysis")
//#region - Trend Selectin -----------------------------------------------------------------------//
TREND_GROUP = "Trend Analysis"
PRICE_SCREENER = "PRICE"
MA_SCREENER = "MA Trend"
RSI_SCREENER = "RSI Trend"
MACD_SCREENER = "MACD Trend"
analysis_type = input.string(title = "Analysis", defval = RSI_SCREENER, options = [RSI_SCREENER, MA_SCREENER, MACD_SCREENER, PRICE_SCREENER], group = TREND_GROUP)
//#endregion
//#region - RSI ----------------------------------------------------------------------------------//
RSI_GROUP = "RSI //////////////////////////////"
RSI_TREND = "Uptrend or Downtrend", RSI_VALUE = "RSI > 50", RSI_DIRECTION = "Advance or Decline"
rsi_selection = input.string(title = "RSI", defval = RSI_TREND, options = [RSI_TREND, RSI_VALUE, RSI_DIRECTION], group = RSI_GROUP)
rsi_period = input.int(title='period, ma, signal', defval = 14, group = RSI_GROUP, inline = "RSI")
rsima_period = input.int(title='', defval =9, group = RSI_GROUP, inline = "RSI")
rsisignal_period = input.int(title='', defval =14, group = RSI_GROUP, inline = "RSI")
//#endregion
//#region - MOVING AVERAGE -----------------------------------------------------------------------//
MA_GROUP = "Moving Average ////////////////////"
MA_CLOSE_TO_5D = "Close to Moving Average"
MA_CROSS_OVER = "MA Cross Over"
ma_selection = input.string(title = "Moving Average", defval = MA_CLOSE_TO_5D, options = [MA_CLOSE_TO_5D, MA_CROSS_OVER], group=MA_GROUP)
fast_ma_period = input.int(title = "Fast/Slow MA", defval = 5, group=MA_GROUP, inline = "MA")
slow_ma_period = input.int(title = "", defval = 14, group=MA_GROUP, inline = "MA")
//#endregion
//#region - Calculation --------------------------------------------------------------------------//
MACDGROUP = "MACD "
MACDCROSSOVER = "CROSS OVER"
MACDZEROLINE = "MACD OVER ZERO LINE"
MACDDIRECTION = "DIRECTION"
macd_selection = input.string(title = "MACD", defval = MACDCROSSOVER, options = [MACDCROSSOVER, MACDZEROLINE,MACDDIRECTION], group=MACDGROUP)
fastmacdperiod = input.int(title = "Fast/slow/signal", defval = 12, group=MACDGROUP, inline = "macd")
slowmacdperiod = input.int(title = "", defval = 26, group=MACDGROUP, inline = "macd")
signalperiod = input.int(title = "", defval = 9, group=MACDGROUP, inline = "macd")
//#endregion
//#region - Color --------------------------------------------------------------------------------//
COLOR_GROUP = "COLOR ///////"
POSITIVE_COLOR = input.color(defval = color.new(#00ff08, 30), title = "Positve/Negative Trend", group = COLOR_GROUP, inline="COLOR")
NEGATIVE_COLOR = input.color(defval = color.new(#ff0707, 70), title = "", group = COLOR_GROUP, inline="COLOR")
//#endregion
//#region - Function -----------------------------------------------------------------------------//
getprice(symbol)=>
// get price of each security.
request.security(symbol, timeframe.period, close)
//
changescreener(src)=>
trend = (
src > src[1] ? 1 :-1 )
rsiscreener(src, analysis)=>
// RSI
// Uptrend or Downtrend : RSI MA greater than RSI Signal
// > 50 : RSI MA greater than 50%
// Advance or Decline : RSI MA gretter than RSI MA[1]
rsi = ta.rsi(src, rsi_period)
rsima= ta.sma(rsi, rsima_period)
rsisig = ta.sma(rsima, rsisignal_period)
rsi_trend = analysis == RSI_TREND ? rsima > rsisig ? 1 : -1 : analysis == RSI_VALUE ? rsima > 50 ? 1 : -1 : rsima > rsima[1] ? 1 : -1 //"advance" : "decline"
rsi_trend
//
mascreener(src, analysis)=>
// MOVING AVERAGE
// Close vs 5D MA : Close higher than 5D MA
// 5MA vs 14MA. : 5D MA higher than 14D MA
// 14MA vs 200MA. : 14D MA higher than 200D MA
fast_ma = ta.sma(src, fast_ma_period)
slow_ma = ta.sma(src, slow_ma_period)
matrend = analysis == MA_CLOSE_TO_5D ? src > fast_ma ? 1 : -1 : fast_ma > slow_ma ? 1 : -1
matrend
//
macdscreener(src, analysis)=>
f = ta.sma(src, fastmacdperiod)
s = ta.sma(src, slowmacdperiod)
macd = f-s
sign = ta.sma(macd, signalperiod)
macdtrend = (
analysis == MACDCROSSOVER ? (macd > sign ? 1 : -1) :
analysis == MACDZEROLINE ? (macd > 0 ? 1 : -1) :
(macd > macd[1] ? 1 : -1)
)
//-----------------------------------------------------------------------------------------------------------------------//
trendanalysis(symbol, type_of_analysis)=>
screener = (
type_of_analysis == RSI_SCREENER ?
rsiscreener(getprice(symbol), rsi_selection) :
type_of_analysis == MA_SCREENER ?
mascreener(getprice(symbol), ma_selection) :
type_of_analysis == MACD_SCREENER ?
macdscreener(getprice(symbol), macd_selection) :
changescreener(getprice(symbol))
)
//#endregion
//#region - Symbol Input -------------------------------------------------------------------------//
symbol01 =input.symbol( 'SET:DELTA' )
symbol02 =input.symbol( 'SET:AOT' )
symbol03 =input.symbol( 'SET:PTT' )
symbol04 =input.symbol( 'SET:PTTEP' )
symbol05 =input.symbol( 'SET:GULF' )
symbol06 =input.symbol( 'SET:CPALL' )
symbol07 =input.symbol( 'SET:ADVANC' )
symbol08 =input.symbol( 'SET:BDMS' )
symbol09 =input.symbol( 'SET:SCC' )
symbol10 =input.symbol( 'SET:SCB' )
symbol11 =input.symbol( 'SET:KBANK' )
symbol12 =input.symbol( 'SET:EA' )
symbol13 =input.symbol( 'SET:CPN' )
symbol14 =input.symbol( 'SET:BBL' )
symbol15 =input.symbol( 'SET:OR' )
symbol16 =input.symbol( 'SET:CRC' )
symbol17 =input.symbol( 'SET:KTB' )
symbol18 =input.symbol( 'SET:INTUCH' )
symbol19 =input.symbol( 'SET:IVL' )
symbol20 =input.symbol( 'SET:SCGP' )
symbol21 =input.symbol( 'SET:PTTGC' )
symbol22 =input.symbol( 'SET:CPF' )
symbol23 =input.symbol( 'SET:GPSC' )
symbol24 =input.symbol( 'SET:AWC' )
symbol25 =input.symbol( 'SET:HMPRO' )
symbol26 =input.symbol( 'SET:MINT' )
symbol27 =input.symbol( 'SET:BH' )
symbol28 =input.symbol( 'SET:TRUE' )
symbol29 =input.symbol( 'SET:BEM' )
symbol30 =input.symbol( 'SET:KTC' )
symbol31 =input.symbol( 'SET:TTB' )
symbol32 =input.symbol( 'SET:TOP' )
symbol33 =input.symbol( 'SET:DTAC' )
symbol34 =input.symbol( 'SET:LH' )
symbol35 =input.symbol( 'SET:BTS' )
symbol36 =input.symbol( 'SET:BGRIM' )
symbol37 =input.symbol( 'SET:BANPU' )
symbol38 =input.symbol( 'SET:CBG' )
symbol39 =input.symbol( 'SET:GLOBAL' )
symbol40 =input.symbol( 'SET:RATCH' )
// symbol41 =input.symbol( 'SET:EGCO'' )
// symbol42 =input.symbol( 'SET:OSP')
// symbol43 =input.symbol( 'SET:TISCO')
// symbol44 =input.symbol( 'SET:MTC' )
// symbol45 =input.symbol( 'SET:JMT'R' )
// symbol46 =input.symbol( 'SET:TU'' )
// symbol47 =input.symbol( 'SET:COM7')
// symbol48 =input.symbol( 'SET:TIDLOR' )
// symbol49 =input.symbol( 'SET:CENTEL')
// symbol50 =input.symbol( 'SET:JMART')
//#endregion
//#region - Calculation --------------------------------------------------------------------------//
// trendanalysis(symbol, type_of_analysis)
trend01 = trendanalysis( symbol01, analysis_type)
trend02 = trendanalysis( symbol02, analysis_type)
trend03 = trendanalysis( symbol03, analysis_type)
trend04 = trendanalysis( symbol04, analysis_type)
trend05 = trendanalysis( symbol05, analysis_type)
trend06 = trendanalysis( symbol06, analysis_type)
trend07 = trendanalysis( symbol07, analysis_type)
trend08 = trendanalysis( symbol08, analysis_type)
trend09 = trendanalysis( symbol09, analysis_type)
trend10 = trendanalysis( symbol10, analysis_type)
trend11 = trendanalysis( symbol11, analysis_type)
trend12 = trendanalysis( symbol12, analysis_type)
trend13 = trendanalysis( symbol13, analysis_type)
trend14 = trendanalysis( symbol14, analysis_type)
trend15 = trendanalysis( symbol15, analysis_type)
trend16 = trendanalysis( symbol16, analysis_type)
trend17 = trendanalysis( symbol17, analysis_type)
trend18 = trendanalysis( symbol18, analysis_type)
trend19 = trendanalysis( symbol19, analysis_type)
trend20 = trendanalysis( symbol20, analysis_type)
trend21 = trendanalysis( symbol21, analysis_type)
trend22 = trendanalysis( symbol22, analysis_type)
trend23 = trendanalysis( symbol23, analysis_type)
trend24 = trendanalysis( symbol24, analysis_type)
trend25 = trendanalysis( symbol25, analysis_type)
trend26 = trendanalysis( symbol26, analysis_type)
trend27 = trendanalysis( symbol27, analysis_type)
trend28 = trendanalysis( symbol28, analysis_type)
trend29 = trendanalysis( symbol29, analysis_type)
trend30 = trendanalysis( symbol30, analysis_type)
trend31 = trendanalysis( symbol31, analysis_type)
trend32 = trendanalysis( symbol32, analysis_type)
trend33 = trendanalysis( symbol33, analysis_type)
trend34 = trendanalysis( symbol34, analysis_type)
trend35 = trendanalysis( symbol35, analysis_type)
trend36 = trendanalysis( symbol36, analysis_type)
trend37 = trendanalysis( symbol37, analysis_type)
trend38 = trendanalysis( symbol38, analysis_type)
trend39 = trendanalysis( symbol39, analysis_type)
trend40 = trendanalysis( symbol40, analysis_type)
//-----------------------------------------------------------------------------------------------------------------------//
trend_count = (trend01 +trend02 + trend03 +trend04 + trend05 +
trend06 +trend07 +trend08 +trend09 +trend10 +trend11 +trend12 +trend13 +
trend14 +trend15 +trend16 +trend17 +trend18 +trend19 +trend20 +trend21 +
trend22 +trend23 +trend24 +trend25 +trend26 +trend27 +trend28 +trend29 +
trend30 +trend31 +trend32 +trend33 +trend34 +trend35 +trend36 +trend37 +
trend38 +trend39 +trend40 )
trend_ma = ta.rma(trend_count, 9)
positive = (40 + trend_count)/2
negative = 40 - positive
//#endregion
//#region - Plot ---------------------------------------------------------------------------------//
pos_line = plot(positive, title = "positive", color = color.green, style = plot.style_columns)
neg_line = plot(negative, title = "ngetive", color = color.red)
base_line = plot(0, title = "")
plot(ta.rma(trend_count,5), title = "Trend Cumulative", color= color.gray)
plot(trend_ma, title = "Trend MA", color = trend_count > trend_ma ? color.rgb(0, 255, 8) : color.rgb(255, 6, 6))
fill(pos_line, base_line, color = POSITIVE_COLOR)
fill(neg_line, base_line, color=NEGATIVE_COLOR )
// // plot(positive)
hline(20)
hline(40)
hline(-40)
hline(-20)
//#endregion
//------------------------------------------------------------------------------------------------//
|
[CLX] Progressbar - Logo | https://www.tradingview.com/script/Wi7xDrQR-CLX-Progressbar-Logo/ | cryptolinx | https://www.tradingview.com/u/cryptolinx/ | 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/
// © cryptolinx
//@version=5
// @description This script is part of the Library Progressbar - Showcase. You can find it under: https://www.tradingview.com/script/RRwvtQAQ-Progressbar/
indicator("[CLX] Scale - Logo", overlay = true)
import cryptolinx/Motion/11 as motion
// ———— User Inputs {
//
var int __OFFSET_X = input.int(0, 'Offset X-Axis', minval = 0, step = 1)
var int __Y = input.int(1000, 'Y-Axis', minval = 0, step = 1)
var string __LOGO_TEXT = input.string('SCALE.','Logo Text')
var string __TAGLINE1 = input.string('- A Pine Script™ Showcase -','Tagline #1')
var string __TAGLINE2 = input.string('v3.x','Tagline #2')
var string __SIZE_LOGO = input.string(size.huge, 'Size Logo', options=[size.small, size.tiny, size.normal, size.large, size.huge, size.auto])
var string __SIZE_TAG1 = input.string(size.normal, 'Size Tag #1', options=[size.small, size.tiny, size.normal, size.large, size.huge, size.auto])
var string __SIZE_TAG2 = input.string(size.small, 'Size Tag #2', options=[size.small, size.tiny, size.normal, size.large, size.huge, size.auto])
var color __COL_LOGO = input.color(#efe5ff, 'Color Logo Text')
var color __COL_DECOR = input.color(#7d1aff, 'Color Logo Decoration')
var color __COL_TAG1 = input.color(#CCCCCC, 'Color Logo')
var color __COL_TAG2 = input.color(color.rgb(194, 167, 225, 69), 'Color Logo')
// }
// ———— Simple Animated Logo/Tag Idea {
//
renderLogo(string _logo, string _tag1 = '', string _tag2 = '', string _sizeLogo = size.huge, string _sizeTag1 = size.normal, string _sizeTag2 = size.small,
color _colorLogo = #efe5ff, color _colorTag1 = #CCCCCC, color _colorTag2 = color.white, color _colorDecor = #7d1aff, int _x = bar_index, float _y = 0) =>
// >>
array.from(
// -- motion placholder
label.new(bar_index + _x, _y, text = '', size = _sizeTag1, color = #00000000, textcolor = _colorDecor, text_font_family = font.family_default, style = label.style_label_center, textalign = text.align_center),
// -- logo text
label.new(bar_index + _x, _y, text = _logo, size = _sizeLogo, color = #00000000, textcolor = _colorLogo, text_font_family = font.family_default, style = label.style_label_center, textalign = text.align_center),
// -- decoration
label.new(bar_index + _x, _y, text = '└', size = _sizeLogo, color = #00000000, textcolor = color.new(_colorDecor, 75), text_font_family = font.family_default, style = label.style_label_upper_right, textalign = text.align_left),
label.new(bar_index + _x, _y, text = '┘', size = _sizeLogo, color = #00000000, textcolor = color.new(_colorDecor, 75), text_font_family = font.family_default, style = label.style_label_upper_left, textalign = text.align_left),
label.new(bar_index + _x, _y, text = '┌', size = _sizeLogo, color = #00000000, textcolor = color.new(_colorDecor, 75), text_font_family = font.family_default, style = label.style_label_lower_right, textalign = text.align_left),
label.new(bar_index + _x, _y, text = '┐', size = _sizeLogo, color = #00000000, textcolor = color.new(_colorDecor, 75), text_font_family = font.family_default, style = label.style_label_lower_left, textalign = text.align_left),
// -- tag 1 + 2
label.new(bar_index + _x, _y, text = '\n\n\n\n\n' + _tag1, size = _sizeTag1, color = #00000000, textcolor = _colorTag1, text_font_family = font.family_default, style = label.style_label_up, textalign = text.align_left),
label.new(bar_index + _x, _y, text = _tag2 + '\n\n\n\n\n\n', size = _sizeTag2, color = #00000000, textcolor = _colorTag2, text_font_family = font.family_default, style = label.style_label_center, textalign = text.align_left))
// }
// ———— Simple Animated Logo/Tag Idea {
//
renderTag(string _tag, string _size = size.large, color _color, int _x = bar_index, float _y = -500) =>
// >>
array.from(
// -- motion placholder
label.new(bar_index + _x, _y, text = '', size = _size, color = #00000000, textcolor = _color, text_font_family = font.family_default, style = label.style_label_center, textalign = text.align_center),
// -- decoration
label.new(bar_index + _x, _y, text = '└', size = _size, color = #00000000, textcolor = color.new(_color, 75), text_font_family = font.family_default, style = label.style_label_upper_right, textalign = text.align_left),
label.new(bar_index + _x, _y, text = '┘', size = _size, color = #00000000, textcolor = color.new(_color, 75), text_font_family = font.family_default, style = label.style_label_upper_left, textalign = text.align_left),
label.new(bar_index + _x, _y, text = '┌', size = _size, color = #00000000, textcolor = color.new(_color, 75), text_font_family = font.family_default, style = label.style_label_lower_right, textalign = text.align_left),
label.new(bar_index + _x, _y, text = '┐', size = _size, color = #00000000, textcolor = color.new(_color, 75), text_font_family = font.family_default, style = label.style_label_lower_left, textalign = text.align_left))
// }
// ———— Update Logo {
//
update(array <label> _logo, string tag, int _x = bar_index, float _y = 200) =>
// --
if barstate.islast
for i = 0 to array.size(_logo) - 1
label.set_xy(array.get(_logo, i), _x, _y)
label.set_text(array.get(_logo, 0), tag)
// }
// ———— Motion 🪄 {
//
// ⚠️ IMPORTANT: TO GET EVERYTHING WELL, YOU HAVE TO USE `varip` keyword on variable decleration.
//
varip logoKf = motion.keyframe.new(3, 1)
// --
var array <label> LOGO = renderLogo(__LOGO_TEXT, __TAGLINE1 , __TAGLINE2 , __SIZE_LOGO, __SIZE_TAG1, __SIZE_TAG2, __COL_LOGO, __COL_TAG1, __COL_TAG2, __COL_DECOR)
string tag = '\n\n\n' + motion.transition(logoKf, _fx = 'marquee', _seq = '▰▱▱▱▰▱▱▱▰', _subLen = 3, _autoplay = true)
update(LOGO, tag)
// }
// #EOF |
XYZ Super Fibonacci Channel Cluster | https://www.tradingview.com/script/Up1KJYjk-XYZ-Super-Fibonacci-Channel-Cluster/ | akaes62 | https://www.tradingview.com/u/akaes62/ | 50 | study | 5 | MPL-2.0 | // This Suurce code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © akaes62
// XYZ Super Fibo Channel Expert V.1.0
//@version=5
indicator("XYZ Super Fibo Channel [satobe]", "XYZ Super Fibo", overlay=true)
//______________________________input set up____________________________________//
src = input.source(hlc3, "Source")
mult_u = input.float(2.618, "Upper Multiplier"
, options=[0.236, 0.38, 0.5, 0.618, 0.78, 1, 1.618, 2.618, 3.618, 4.23]
, tooltip = "Progressive Structure")
mult_i = input.float(1.618, "Lower Multiplier"
, options=[0.236, 0.38, 0.5, 0.618, 0.78, 1, 1.618, 2.618, 3.618, 4.23]
, tooltip = "Regressive Structure")
X_switch = input.bool(false
, "Enable X Channel"
, inline = "X Channel"
, tooltip = "X length")
X_leng = input(13
, "/"
, inline = "X Channel")
Y_switch = input.bool(false
, "Enable Y Channel"
, inline = "Y Channel"
, tooltip = "Y length")
Y_leng = input(21
, "/"
, inline = "Y Channel")
Z_switch = input.bool(false
, "Enable Z Channel"
, tooltip = "Z length = X length + Y Length [auto]")
Z_leng = X_leng + Y_leng
MA_switch = input.bool(true
, "Enable EMA [XYZ]")
S_switch = input.bool(true
, "Enable Super Channel"
, tooltip = "Super length = Z length + Y length [auto]")
S_leng = Z_leng + Y_leng
Ch_leng = input(1600
, "Channel Length")
//__________________________________XYZ factor____________________________________//
//________________________________Super Channel___________________________________//
fX_u = (mult_u*4.238)
fY_u = (mult_u*2.618)
fZ_u = (mult_u*1.618)
fX_i = (mult_i*4.238)
fY_i = (mult_i*2.618)
fZ_i = (mult_i*1.618)
Super_fibo_ch(src, X_leng, Y_leng, Z_leng, S_leng, mult_u, mult_i) =>
float X_bas = ta.ema(src, X_leng)
float X_rma = ta.ema(high-low, X_leng)
float Y_bas = ta.ema(src, Y_leng)
float Y_rma = ta.ema(high-low, Y_leng)
float Z_bas = ta.ema(src, Z_leng)
float Z_rma = ta.ema(high-low, Z_leng)
float S_bas = ta.ema(src, S_leng)
float S_rma = ta.ema(high-low, S_leng)
float X_u = X_bas + X_rma * mult_u
float Y_u = Y_bas + Y_rma * mult_u
float Z_u = Z_bas + Z_rma * mult_u
float X_i = X_bas - X_rma * mult_i
float Y_i = Y_bas - Y_rma * mult_i
float Z_i = Z_bas - Z_rma * mult_i
float SX_u = S_bas + S_rma * fX_u
float SY_u = S_bas + S_rma * fY_u
float SZ_u = S_bas + S_rma * fZ_u
float S_u = S_bas + S_rma * mult_u
float S_i = S_bas - S_rma * mult_i
float SZ_i = S_bas - S_rma * fZ_i
float SY_i = S_bas - S_rma * fY_i
float SX_i = S_bas - S_rma * fX_i
[X_u, Y_u, Z_u, SX_u, SY_u, SZ_u, S_u, X_bas, Y_bas, Z_bas, S_bas, S_i, SZ_i, SY_i, SX_i, Z_i, Y_i, X_i]
[X_u, Y_u, Z_u, SX_u, SY_u, SZ_u, S_u, X_bas, Y_bas, Z_bas, S_bas, S_i, SZ_i, SY_i, SX_i, Z_i, Y_i, X_i] = Super_fibo_ch( src, X_leng, Y_leng, Z_leng, S_leng, mult_u, mult_i)
//_______________________________Coloring______________________________________//
//------------------------overbought vs oversold-------------------------------//
col_super = X_bas > Y_bas and X_bas < S_bas ? color.new(color.lime,0) : X_bas > Y_bas and X_bas > S_bas ? color.new(color.yellow,0) : X_bas[1] < Y_bas and X_bas < S_bas ? color.new(color.maroon,0) : color.new(color.orange,0)
col_SX_u = X_bas > S_u ? color.new(color.yellow,23) : color.new(color.white,23)
col_SX_i = X_bas > S_i ? color.new(color.yellow,23) : color.new(color.white,23)
//___________________________Upper Lower________________________________________//
plot(X_switch ? X_u : na
, "Upper X [X-u]"
, color.new(color.yellow,38)
, show_last = Ch_leng)
plot(X_switch ? X_i : na
, "Lower X [X-i]"
, color.new(color.yellow,38)
, show_last = Ch_leng)
plot(Y_switch ? Y_u : na
, "Upper Y [Y-u]"
, color.new(color.silver,38)
, show_last = Ch_leng)
plot(Y_switch ? Y_i : na
, "Lower Y [Y-i]"
, color.new(color.silver,38)
, show_last = Ch_leng)
plot(Z_switch ? Z_u : na
, "Upper Z [Z-u]"
, color.new(color.fuchsia,38)
, show_last = Ch_leng)
plot(Z_switch ? Z_i : na
, "Lower Z [Z-i]"
, color.new(color.fuchsia,38)
, show_last = Ch_leng)
plot(MA_switch ? X_bas : na
, "Ema X"
, color.new(color.yellow,23))
plot(MA_switch ? Y_bas : na
, "Ema Y"
, color.new(color.silver,23))
plot(MA_switch ? Z_bas : na
, "Ema Z"
, color.new(color.fuchsia,23))
//_____________________________Super plots____________________________________//
plot(S_switch ? SX_u : na
, " Upper Super X [SX-u]"
, color.new(color.red,44)
, show_last = Ch_leng)
plot(S_switch ? SY_u : na
, "Upper Super Y [SY-u]"
, color.new(color.green,44)
, show_last = Ch_leng)
plot(S_switch ? SZ_u : na
, "Upper Super Z [SZ-u]"
, color.new(color.blue,44)
, show_last = Ch_leng)
plot(S_switch ? S_u : na
, "Upper Super [S-u]"
, color = col_SX_u
, linewidth = 2
, show_last = Ch_leng)
plot(S_switch ? S_bas : na
, "EMA Super [Basic]"
, color = col_super
, linewidth = 2)
plot(S_switch ? S_i : na
, "Lower Super [S-i]"
, color = col_SX_i
, linewidth = 2
, show_last = Ch_leng)
plot(S_switch ? SZ_i : na
, "Lower Super Z [SZ-i]"
, color.new(color.blue,44)
, show_last = Ch_leng)
plot(S_switch ? SY_i : na
, "Lower Super Y [SY-i]"
, color.new(color.green,44)
, show_last = Ch_leng)
plot(S_switch ? SX_i : na
, "Lower Super X [SX-i]"
, color.new(color.red,44)
, show_last = Ch_leng)
//_________________________________[satobe]__________________________________// |
VIX Oscillator | https://www.tradingview.com/script/DAooyURt-VIX-Oscillator/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 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/
// /$$$$$$ /$$ /$$
// /$$__ $$ | $$ | $$
//| $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$
//| $$$$$$|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$__ $$ /$$_____/|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$_____/
// \____ $$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$ \__/| $$$$$$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$$$$$
// /$$ \ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/| $$ \____ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/ \____ $$
//| $$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$| $$ /$$$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$ /$$$$$$$/
// \______/ \___/ \_______/ \_/ \_______/|__/ |_______/ \___/ \_______/ \_/ \_______/|_______/
// ___________________
// / \
// / _____ _____ \
// / / \ / \ \
// __/__/ \____/ \__\_____
//| ___________ ____|
// \_________/ \_________/
// \ /////// /
// \/////////
// © Steversteves
//@version=5
indicator("VIX Oscillator")
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// User Inputs ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
timeframe = input.timeframe("", title="Period Timeframe")
AvgLength = input.int(14, title="Average Length")
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Securities ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ticker = ticker.new(syminfo.prefix, syminfo.ticker, session.regular)
vix = request.security("CBOE:VIX", timeframe, close)
cl = request.security(ticker, timeframe, close, lookahead=barmerge.lookahead_on)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Z-Score Calculcation ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Z Score VIX
vixhx = ta.sma(vix, AvgLength)
vixsd = ta.stdev(vix, AvgLength)
z = (vix - vixhx) / vixsd
// Z Score Stock
stockhx = ta.sma(cl, AvgLength)
stocksd = ta.stdev(cl, AvgLength)
zs = (cl - stockhx) / stocksd
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Plots ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
plot(z, "VIX", linewidth=3)
plot(zs, "Ticker", color=color.purple, linewidth=3)
upperband = hline(2.5, "Upper Band", color=color.gray)
lowerband = hline(-2.5, "Lower Band", color=color.gray)
centreband = hline(0, "Centre Band", color=color.yellow)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Colours ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
color fillcolor = color.new(color.gray, 95)
color bear = color.new(color.red, 85)
color bull = color.new(color.green, 85)
bool bearish = z <= -2.5 and zs >= 2
bool bullish = z >= 2.5 and zs <= -2
color fills = bearish ? bear : bullish ? bull : fillcolor
fill(upperband, lowerband, color=fills)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Conditions ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bearishcondition = z <= -2.5 and zs >= 2.5
bullishcondition = z >= 2.5 and zs <= -2.5
alertcondition(bearishcondition, title="Bearish Condition", message="VIX is oversold and Ticker is overbought")
alertcondition(bullishcondition, title="Bullish Condition", message="VIX is overbought and Ticker is Oversold") |
Peer Performance - NIFTY36STOCKS | https://www.tradingview.com/script/S7M1SzaQ-Peer-Performance-NIFTY36STOCKS/ | AtulGoswami | https://www.tradingview.com/u/AtulGoswami/ | 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/
// © AtulGoswami
//@version=5
indicator("Peer Performance", overlay=true)
cymbol=syminfo.tickerid
period=input.timeframe(defval="",title="Time Period")
//tablo = table.new(position = position.top_right, columns = 10, rows = 10, bgcolor = color.black, border_width = 2, frame_width=1,frame_color = color.white, border_color=color.white)
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
//CEMENT INDUSTRY STOCKS
yearlyReturn= request.security(cymbol,period, ta.roc(close, 252))
yearlyReturn1= request.security("NSE:ACC",period, ta.roc(close, 252))
yearlyReturn2= request.security("NSE:ULTRACEMCO",period, ta.roc(close, 252))
yearlyReturn3= request.security("NSE:GRASIM",period, ta.roc(close, 252))
yearlyReturn4= request.security("NSE:AMBUJACEM",period, ta.roc(close, 252))
yearlyReturn5= request.security("NSE:SHREECEM",period, ta.roc(close, 252))
//AUTO INDUSTRY STOCKS
yr1= request.security("NSE:TATAMOTORS",period, ta.roc(close, 252))
yr2= request.security("NSE:BAJAJ_AUTO",period, ta.roc(close, 252))
yr3= request.security("NSE:HEROMOTOCO",period, ta.roc(close, 252))
yr4= request.security("NSE:EICHERMOT",period, ta.roc(close, 252))
yr5= request.security("NSE:MARUTI",period, ta.roc(close, 252))
yr6= request.security("NSE:M_M",period, ta.roc(close, 252))
//////////////////////////////////////////////////////////////////////////////
//BANKING INDUSTRY STOCKS
//yrB1= request.security(cymbol,period, ta.roc(close, 252))
yrB2= request.security("NSE:HDFCBANK",period, ta.roc(close, 252))
yrB3= request.security("NSE:ICICIBANK",period, ta.roc(close, 252))
yrB4= request.security("NSE:KOTAKBANK",period, ta.roc(close, 252))
yrB5= request.security("NSE:INDUSINDBK",period, ta.roc(close, 252))
yrB6= request.security("NSE:AXISBANK",period, ta.roc(close, 252))
yrB7= request.security("NSE:BANDHANBNK",period, ta.roc(close, 252))
yrB8= request.security("NSE:BANKBARODA",period, ta.roc(close, 252))
yrB9= request.security("NSE:SBIN",period, ta.roc(close, 252))
//////////////////////////////////////////////////////////////////////////////
//TECHNOLOGY INDUSTRY STOCKS
//yrT1= request.security(cymbol,period, ta.roc(close, 252))
yrT2= request.security("NSE:TCS",period, ta.roc(close, 252))
yrT3= request.security("NSE:INFY",period, ta.roc(close, 252))
yrT4= request.security("NSE:WIPRO",period, ta.roc(close, 252))
yrT5= request.security("NSE:MPHASIS",period, ta.roc(close, 252))
yrT6= request.security("NSE:HCLTECH",period, ta.roc(close, 252))
yrT7= request.security("NSE:TECHM",period, ta.roc(close, 252))
//yrT8= request.security("NSE:BANKBARODA",period, ta.roc(close, 252))
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//OIL & GAS INDUSTRY STOCKS
yrO1= request.security(cymbol,period, ta.roc(close, 252))
yrO2= request.security("NSE:ADANIGREEN",period, ta.roc(close, 252))
yrO3= request.security("NSE:ATGL",period, ta.roc(close, 252))
yrO4= request.security("NSE:ADANITRANS",period, ta.roc(close, 252))
yrO5= request.security("NSE:RELIANCE",period, ta.roc(close, 252))
yrO6= request.security("NSE:ONGC",period, ta.roc(close, 252))
yrO7= request.security("NSE:POWERGRID",period, ta.roc(close, 252))
yrO8= request.security("NSE:COALINDIA",period, ta.roc(close, 252))
yrO9= request.security("NSE:TATAPOWER",period, ta.roc(close, 252))
yrO10= request.security("NSE:IOC",period, ta.roc(close, 252))
yrO11= request.security("NSE:NTPC",period, ta.roc(close, 252))
float[] oil=array.from(yrO1, yrO2, yrO3, yrO4, yrO5, yrO6, yrO7, yrO8, yrO9, yrO10, yrO11)
i1="Stocks"
i2="YearlyReturn"
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
// CEMENT STOCKS
if (cymbol=="NSE:ACC") or (cymbol=="NSE:ULTRACEMCO") or (cymbol=="NSE:GRASIM") or (cymbol=="NSE:AMBUJACEM")
tablo = table.new(position = position.top_right, columns = 10, rows = 12, bgcolor = color.black, border_width = 2, frame_width=1,frame_color = color.white, border_color=color.white)
txt1=str.tostring(math.round_to_mintick(yearlyReturn))
txt2=str.tostring(math.round_to_mintick(yearlyReturn1))
txt3=str.tostring(math.round_to_mintick(yearlyReturn2))
txt4=str.tostring(math.round_to_mintick(yearlyReturn3))
txt5=str.tostring(math.round_to_mintick(yearlyReturn4))
txt6=str.tostring(math.round_to_mintick(yearlyReturn4))
table.cell(tablo,0,0,text=i1,bgcolor = color.black, text_color = color.white)
table.cell(tablo,1,0,text=i2,bgcolor = color.black, text_color = color.white)
table.cell(tablo,0,1,text="ACC",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,2,text="ULTRATECH",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,3,text="GRASIM",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,4,text="AMBUJA",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,5,text="SHREECEMENT",bgcolor= color.black, text_color = color.white)
table.cell(tablo,1,1,text=txt1,bgcolor=yearlyReturn1>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,2,text=txt2,bgcolor=yearlyReturn2>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,3,text=txt3,bgcolor=yearlyReturn3>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,4,text=txt4,bgcolor=yearlyReturn4<0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,5,text=txt5,bgcolor=yearlyReturn5<0? color.green:color.red, text_color = color.white)
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
// AUTO STOCKS
if (cymbol=="NSE:TATAMOTORS") or (cymbol=="NSE:BAJAJ_AUTO") or (cymbol=="HEROMOTOCO") or (cymbol=="NSE:EICHERMOT")or (cymbol=="NSE:MARUTI") or (cymbol=="NSE:M_M")
tablo = table.new(position = position.top_right, columns = 10, rows = 10, bgcolor = color.black, border_width = 2, frame_width=1,frame_color = color.white, border_color=color.white)
txt1=str.tostring(math.round_to_mintick(yr1))
txt2=str.tostring(math.round_to_mintick(yr2))
txt3=str.tostring(math.round_to_mintick(yr3))
txt4=str.tostring(math.round_to_mintick(yr4))
txt5=str.tostring(math.round_to_mintick(yr5))
txt6=str.tostring(math.round_to_mintick(yr6))
table.cell(tablo,0,0,text=i1,bgcolor = color.black, text_color = color.white)
table.cell(tablo,1,0,text=i2,bgcolor = color.black, text_color = color.white)
table.cell(tablo,0,1,text="TATAMOTORS",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,2,text="BAJAJ_AUTO",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,3,text="HEROMOTOCO",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,4,text="EICHERMOT",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,5,text="MARUTI",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,6,text="M&M",bgcolor= color.black, text_color = color.white)
table.cell(tablo,1,1,text=txt1,bgcolor= yr1>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,2,text=txt2,bgcolor=yr2>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,3,text=txt3,bgcolor= yr3>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,4,text=txt4,bgcolor=yr4>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,5,text=txt5,bgcolor= yr5>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,6,text=txt6,bgcolor= yr6>0? color.green:color.red, text_color = color.white)
// if (cymbol=="NSE:TATAMOTOR") or (cymbol=="NSE:BAJAJ_AUTO") or (cymbol=="HEROMOTOCO") or (cymbol=="NSE:EICHERMOT") OR (cymbol=="NSE:MARUTI") or (cymbol=="NSE:M_M")
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
// BANKING STOCKS
if (cymbol=="NSE:HDFCBANK") or(cymbol=="SBIN") or (cymbol=="NSE:ICICIBANK") or (cymbol=="KOTAKBANK") or (cymbol=="NSE:BANKBARODA")or (cymbol=="NSE:INDUSINDBK") or (cymbol=="NSE:AXISBANK") or (cymbol=="NSE:BANDHANBNK")
tablo = table.new(position = position.top_right, columns = 10, rows = 10, bgcolor = color.black, border_width = 2, frame_width=1,frame_color = color.white, border_color=color.white)
txt1=str.tostring(math.round_to_mintick(yrB2))
txt2=str.tostring(math.round_to_mintick(yrB3))
txt3=str.tostring(math.round_to_mintick(yrB4))
txt4=str.tostring(math.round_to_mintick(yrB5))
txt5=str.tostring(math.round_to_mintick(yrB6))
txt6=str.tostring(math.round_to_mintick(yrB7))
txt7=str.tostring(math.round_to_mintick(yrB8))
txt8=str.tostring(math.round_to_mintick(yrB9))
table.cell(tablo,0,0,text=i1,bgcolor = color.black, text_color = color.white)
table.cell(tablo,1,0,text=i2,bgcolor = color.black, text_color = color.white)
table.cell(tablo,0,1,text="HDFC BANK",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,2,text="ICICI BANK",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,3,text="KOTAK",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,4,text="INDUSIND BANK",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,5,text="AXIS BANK ",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,6,text="BANDHAN BANK ",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,7,text="BANK OF BARODA ",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,8,text="SBIN",bgcolor= color.black, text_color = color.white)
table.cell(tablo,1,1,text=txt1,bgcolor= yrB2>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,2,text=txt2,bgcolor=yrB3>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,3,text=txt3,bgcolor= yrB4>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,4,text=txt4,bgcolor=yrB5>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,5,text=txt5,bgcolor= yrB6>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,6,text=txt6,bgcolor=yrB7>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,7,text=txt7,bgcolor= yrB8>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,8,text=txt8,bgcolor= yrB9>0? color.green:color.red, text_color = color.white)
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
// IT STOCKS
if (cymbol=="NSE:TCS") or (cymbol=="NSE:INFY") or (cymbol=="WIPRO") or (cymbol=="NSE:MPHASIS")or (cymbol=="NSE:HCLTECH") or (cymbol=="NSE:TECHM")
tablo = table.new(position = position.top_right, columns = 10, rows = 12, bgcolor = color.black, border_width = 2, frame_width=1,frame_color = color.white, border_color=color.white)
txt1=str.tostring(math.round_to_mintick(yrT2))
txt2=str.tostring(math.round_to_mintick(yrT3))
txt3=str.tostring(math.round_to_mintick(yrT4))
txt4=str.tostring(math.round_to_mintick(yrT5))
txt5=str.tostring(math.round_to_mintick(yrT6))
txt6=str.tostring(math.round_to_mintick(yrT7))
//txt7=str.tostring(math.round_to_mintick(yrB8))
table.cell(tablo,0,0,text=i1,bgcolor = color.black, text_color = color.white)
table.cell(tablo,1,0,text=i2,bgcolor = color.black, text_color = color.white)
table.cell(tablo,0,1,text="TCS",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,2,text="INFOSYS",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,3,text="WIPRO",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,4,text="MPHASIS",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,5,text="HCLTECH ",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,6,text="TECHM ",bgcolor= color.black, text_color = color.white)
//table.cell(tablo,0,7,text="BANK OF BARODA ",bgcolor= color.black, text_color = color.white)
table.cell(tablo,1,1,text=txt1,bgcolor= yrT2>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,2,text=txt2,bgcolor=yrT3>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,3,text=txt3,bgcolor= yrT4>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,4,text=txt4,bgcolor=yrT5>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,5,text=txt5,bgcolor= yrT6>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,6,text=txt6,bgcolor=yrT7>0? color.green:color.red, text_color = color.white)
//table.cell(tablo,1,7,text=txt7,bgcolor= yr5>0? color.green:color.red, text_color = color.white)
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
// OIL -GAS & ENERGY STOCKS
if (cymbol=="NSE:ADANIGREEN") or (cymbol=="NSE:ATGL") or (cymbol=="ADANITRANS") or (cymbol=="NSE:RELIANCE")or (cymbol=="NSE:ONGC") or (cymbol=="NSE:COALINDIA") or (cymbol=="NSE:GAIL") or (cymbol=="NSE:POWERGRID")or (cymbol=="NSE:TATAPOWER")or (cymbol=="NSE:IOC")or (cymbol=="NSE:NTPC")
tablo = table.new(position = position.top_right, columns = 10, rows = 15, bgcolor = color.black, border_width = 2, frame_width=1,frame_color = color.white, border_color=color.white)
// for j=1 to 10 by 1
// txtj=str.tostring(math.round_to_mintick(array.get(oil, j)))
txt1=str.tostring(math.round_to_mintick(yrO1))
txt2=str.tostring(math.round_to_mintick(yrO2))
txt3=str.tostring(math.round_to_mintick(yrO3))
txt4=str.tostring(math.round_to_mintick(yrO4))
txt5=str.tostring(math.round_to_mintick(yrO5))
txt6=str.tostring(math.round_to_mintick(yrO6))
txt7=str.tostring(math.round_to_mintick(yrO7))
txt8=str.tostring(math.round_to_mintick(yrO8))
txt9=str.tostring(math.round_to_mintick(yrO9))
txt10=str.tostring(math.round_to_mintick(yrO10))
txt11=str.tostring(math.round_to_mintick(yrO11))
table.cell(tablo,0,0,text=i1,bgcolor = color.black, text_color = color.white)
table.cell(tablo,1,0,text=i2,bgcolor = color.black, text_color = color.white)
table.cell(tablo,0,1,text="ADANI GREEN",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,2,text="ATGL",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,3,text="ADANITRANSMISSION",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,4,text="RELIANCE",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,5,text="ONGC ",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,6,text="POWERGRID ",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,7,text="COALINDIA ",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,8,text="TATAPOWER ",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,9,text="IOC ",bgcolor= color.black, text_color = color.white)
table.cell(tablo,0,10,text="NTPC ",bgcolor= color.black, text_color = color.white)
//table.cell(tablo,0,11,text="NTPC ",bgcolor= color.black, text_color = color.white)
//table.cell(tablo,0,7,text="BANK OF BARODA ",bgcolor= color.black, text_color = color.white)
table.cell(tablo,1,1,text=txt2,bgcolor= yrO2>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,2,text=txt3,bgcolor=yrO3>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,3,text=txt4,bgcolor= yrO4>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,4,text=txt5,bgcolor=yrO5>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,5,text=txt6,bgcolor= yrO6>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,6,text=txt7,bgcolor=yrO7>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,7,text=txt8,bgcolor=yrO8>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,8,text=txt9,bgcolor=yrO9>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,9,text=txt10,bgcolor=yrO10>0? color.green:color.red, text_color = color.white)
table.cell(tablo,1,10,text=txt11,bgcolor=yrO11>0? color.green:color.red, text_color = color.white)
//table.cell(tablo,1,11,text=txt12,bgcolor=yrO11>0? color.green:color.red, text_color = color.white)
//table.cell(tablo,1,7,text=txt7,bgcolor= yr5>0? color.green:color.red, text_color = color.white) |
RS: Market Profile | https://www.tradingview.com/script/QZ1vuAtZ-RS-Market-Profile/ | RunStrat | https://www.tradingview.com/u/RunStrat/ | 1,808 | 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/
// © RunStrat
//@version=5
indicator("RS: Market Profile", shorttitle = "RS: MP", overlay = true, max_lines_count = 500, max_labels_count = 500)
G_POC_LABEL_IDX = 0
G_VP_POC_LABEL_IDX = 1
P_SESSION_OPEN = 0
P_SESSION_CLOSE = 1
P_IB_LOW = 2
P_IB_HIGH = 3
TPO_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
TPO_SQUARE = "◼"
TPO_CIRCLE = "⬤"
TPO_AZ = "A-Za-z"
TF_DAILY = "Daily"
TF_WEEKLY = "Weekly"
TF_MONTHLY = "Monthly"
TF_INTRADAY = "Intraday"
TF_FIXED = "Fixed"
MP_HL = "High/Low mid"
MP_TPOS = "Number of TPOs"
MAX_BARS_BACK = 5000
EXCHANGE = "Exchange"
ticks_input = input.float(defval = 10, title = "Ticks per letter", minval = 1, tooltip = "Experiment with this value to match your instrument's price")
show_vp_based_poc_input = input.bool(defval = true, title = "Highlight POC based on VP?", tooltip = "Has a limitation how far into the past it is calculated")
value_area_based_on_vp_input = input.bool(defval = true, title = "Use VP POC for Value Area?", tooltip = "Works only if VP POC is selected and is calculated")
show_session_vwap_input = input.bool(defval = false, title = "Highlight session VWAP?")
show_extension_lines_input = input.bool(defval = false, title = "Show extension lines?")
split_profile_input = input.bool(defval = false, title = "Split MP?", tooltip = "Applicable only if 'A-Za-z' is selected for rendering")
timeframe_input = input.string(defval = TF_DAILY, title = "Timeframe", options = [TF_INTRADAY, TF_DAILY, TF_WEEKLY, TF_MONTHLY, TF_FIXED], group = "Time")
timezone_input = input.string(defval = EXCHANGE, title = "Timezone", options = [
EXCHANGE, "UTC-10", "UTC-9", "UTC-8", "UTC-7", "UTC-6", "UTC-5", "UTC-4", "UTC-3", "UTC-2", "UTC-1", "UTC", "UTC+1",
"UTC+2", "UTC+3", "UTC+4", "UTC+5", "UTC+6", "UTC+7", "UTC+8", "UTC+9", "UTC+10", "UTC+11", "UTC+12", "UTC+13"
], group = "Time")
session_range_input = input.session(defval = "0830-1500", title = "Daily session", tooltip = "Applicable only if 'Daily' market profile timeframe is selected", group = "Time")
intraday_length_input = input.int(defval = 60, title = "Profile length in minutes", minval = 5, maxval = 24*60, tooltip = "Applicable only if 'Intraday' market profile timeframe is selected", group = "Intraday Profiles")
time_range_from_input = input.time(timestamp("15 Aug 2023 8:30 -0600"), "", inline = "fixed", group = "Fixed range")
time_range_till_input = input.time(timestamp("16 Aug 2023 15:00 -0600"), "", inline = "fixed", group = "Fixed range")
render_volumes_input = input.bool(defval = true, title = "Render volume numbers?", tooltip = "Applicable only if 'Fixed' market profile timeframe is selected", group = "Fixed range")
tpo_characters_input = input.string(defval = TPO_SQUARE, title = "TPO characters", options = [TPO_SQUARE, TPO_CIRCLE, TPO_AZ], group = "Rendering")
va_percent_input = input.int(defval = 70, title = "Value Area Percent", minval = 0, maxval = 100, group = "Rendering")
ib_periods_input = input.int(defval = 2, title = "IB periods", minval = 1, group = "Rendering")
ib_width_input = input.int(defval = 2, title = "IB line width", minval = 1, maxval = 3, group = "Rendering")
price_marker_width_input = input.int(defval = 2, title = "Price marker width", minval = 1, maxval = 5, group = "Rendering")
price_marker_length_input = input.int(defval = 1, title = "Price marker length", minval = 1, maxval = 5, group = "Rendering")
text_size_input = input.string(defval = "Normal", title = "Font size", options = ["Tiny", "Small", "Normal"], group = "Rendering")
mark_period_opens_input = input.string(defval = "No", title = "Mark period open?", options = ["No", "Swap case", "Use '0'"], tooltip = "Applicable only if 'A-Za-z' is selected for rendering", group = "Rendering")
midpoint_algo_input = input.string(defval = MP_HL, title = "Midpoint algo", options = [MP_HL, MP_TPOS], group = "Rendering")
default_tpo_color_input = input.color(defval = color.new(color.gray, 10), title = "Default", group = "Colors")
single_print_color_input = input.color(defval = color.new(#d56a6a, 0) , title = "Single Print", group = "Colors")
value_area_color_input = input.color(defval = color.new(color.white, 20) , title = "Value Area", group = "Colors")
poc_color_input = input.color(defval = color.new(#3f7cff, 0) , title = "POC", group = "Colors")
vp_poc_color_input = input.color(defval = color.new(#87c74c, 0) , title = "VP POC", group = "Colors")
open_color_input = input.color(defval = color.rgb(110, 173, 255), title = "Open", group = "Colors")
close_color_input = input.color(defval = color.red , title = "Close", group = "Colors")
ib_highlight_color_input = input.color(defval = color.rgb(110, 173, 255), title = "IB", group = "Colors")
ib_background_color_input = input.color(defval = color.rgb(96, 109, 121), title = "IB background", group = "Colors")
session_vwap_color_input = input.color(defval = color.rgb(255, 153, 37), title = "Session VWAP", group = "Colors")
poc_ext_color_input = input.color(defval = color.new(#87c74c, 50), title = "POC extension", group = "Colors")
vah_ext_color_input = input.color(defval = color.new(color.white, 70), title = "VAH extension ", group = "Colors")
val_ext_color_input = input.color(defval = color.new(color.white, 70), title = "VAL extension", group = "Colors")
high_color_input = input.color(defval = color.new(color.red, 100), title = "High extension", group = "Colors")
low_color_input = input.color(defval = color.new(color.green, 100), title = "Low extension", group = "Colors")
mid_color_input = input.color(defval = color.new(#7649ff, 100), title = "Midpoint extension", group = "Colors")
fixed_range_bg_color_input = input.color(defval = color.new(#3179f5, 80), title = "Fixed range background", group = "Colors")
var label [] vp_labels = array.new_label()
var string [] tpo_chars = array.new_string()
var label [] tpo_labels = array.new_label()
var label [] tpo_oc_labels = array.new_label()
var line [] lines = array.new_line()
var line [] extensions = array.new_line()
var line [] ext_cache = array.new_line()
var float [] tpo_highs = array.new_float()
var float [] tpo_lows = array.new_float()
var float [] opens = array.new_float(1440)
var int [] globals = array.from(na, na, 0)
var float [] prices = array.from(0.0, 0.0, 0.0, 0.0)
var float max = na
var float min = na
var int first_bar_index = na
var float [] lower_tf_highs = array.new_float()
var float [] lower_tf_lows = array.new_float()
var float [] lower_tf_volumes = array.new_float()
var float [] vp_volumes = array.new_float()
var float [] vp_prices = array.new_float()
var label [] last_label = array.new_label()
max_bars_back(time, MAX_BARS_BACK - 1)
tz = timezone_input == EXCHANGE ? syminfo.timezone : timezone_input
session_time = time(timeframe.period, '24x7', tz)
if timeframe_input == TF_DAILY
session_time := time(timeframe.period, session_range_input, tz)
vwap_reset = switch timeframe_input
TF_DAILY =>
not(session_time)
TF_WEEKLY =>
weekofyear[1] != weekofyear
TF_MONTHLY =>
month[1] != month
TF_FIXED =>
time >= time_range_from_input and time[1] < time_range_from_input
TF_INTRADAY =>
time % (60 * 1000 * intraday_length_input) == 0
session_vwap = ta.vwap(hlc3, vwap_reset)
font_size = switch text_size_input
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
font_family = font.family_monospace
should_process() =>
slack = math.floor((chart.right_visible_bar_time - chart.left_visible_bar_time) * 0.2)
not na(session_time)
and (session_time >= chart.left_visible_bar_time - slack
and session_time <= chart.right_visible_bar_time + slack)
and (timeframe.isintraday or timeframe.isdaily or ((timeframe_input == TF_MONTHLY or timeframe_input == TF_FIXED) and timeframe.isweekly))
and (timeframe_input == TF_FIXED ? time >= time_range_from_input and time <= time_range_till_input : true)
session_input_times() =>
times = str.split(session_range_input, "-")
hour_minute = array.get(times, 0)
h1 = str.tonumber(str.substring(hour_minute, 0, 2))
m1 = str.tonumber(str.substring(hour_minute, 2, 4))
hour_minute := array.get(times, 1)
h2 = str.tonumber(str.substring(hour_minute, 0, 2))
m2 = str.tonumber(str.substring(hour_minute, 2, 4))
[h1, m1, h2, m2]
is_first_bar_of_session() =>
switch timeframe_input
TF_DAILY =>
[h1, m1, h2, m2] = session_input_times()
open_ts = timestamp(tz, year(time), month(time), dayofmonth(time), int(h1), int(m1), 0)
time >= open_ts and time[1] < open_ts
TF_WEEKLY =>
weekofyear[1] != weekofyear
TF_MONTHLY =>
month[1] != month
TF_FIXED =>
time >= time_range_from_input and time[1] < time_range_from_input
TF_INTRADAY =>
time % (60 * 1000 * intraday_length_input) == 0
spaces(n, char) =>
spaces = ""
if n > 0
for i = 1 to n
spaces := spaces + char
spaces
openning_char() =>
array.get(tpo_chars, 0)
get_label_at(index) =>
array.get(tpo_labels, index)
get_text_at(index) =>
label.get_text(get_label_at(index))
create_tpo_label(x, y) =>
label.new(x, y, color = color.new(color.white, 100), textcolor = default_tpo_color_input,
size = font_size, style = label.style_label_left, xloc = xloc.bar_index,
text_font_family = font_family)
append_char(x, char) =>
label.set_text(array.get(tpo_labels, x), text = get_text_at(x) + char)
tpo_count() =>
count = 0
for tpo in tpo_labels
count += str.length(str.replace_all(label.get_text(tpo), " ", ""))
count
highlight_value_area() =>
value_area_idx = array.new_int()
vp_poc_id = array.get(globals, G_VP_POC_LABEL_IDX)
id = value_area_based_on_vp_input and not na(vp_poc_id) ? vp_poc_id : array.get(globals, G_POC_LABEL_IDX)
if id >= 0
label.set_textcolor(get_label_at(id), value_area_color_input)
value_area = id >= 0 ? str.length(str.replace_all(get_text_at(id), " ", "")) : 0
size = array.size(tpo_labels)
total_tpos = tpo_count()
i = id
j = id
while j > 0 or i < size - 1
i += 1
j -= 1
v1 = 0
v2 = 0
if i < size
v1 := str.length(str.replace_all(get_text_at(i), " ", ""))
if j >= 0
v2 := str.length(str.replace_all(get_text_at(j), " ", ""))
if v1 == v2 and v1 != 0
value_area := value_area + v1
label.set_textcolor(get_label_at(i), value_area_color_input)
value_area := value_area + v2
label.set_textcolor(get_label_at(j), value_area_color_input)
else if v1 > v2
value_area := value_area + v1
label.set_textcolor(get_label_at(i), value_area_color_input)
j += 1
else if v2 > v1
value_area := value_area + v2
label.set_textcolor(get_label_at(j), value_area_color_input)
i -=1
if value_area >= total_tpos * (va_percent_input / 100.0)
break
if show_extension_lines_input and i >= 0 and j >= 0 and i < size
va1 = label.get_y(get_label_at(i))
va2 = label.get_y(get_label_at(j))
ln1 = line.new(first_bar_index, va1, first_bar_index + 1, va1, color = vah_ext_color_input, width = 1, extend = extend.right)
ln2 = line.new(first_bar_index, va2, first_bar_index + 1, va2, color = val_ext_color_input, width = 1, extend = extend.right)
array.push(ext_cache, ln1)
array.push(ext_cache, ln2)
highlight_single_prints() =>
for tpo in tpo_labels
if str.length(str.replace_all(label.get_text(tpo), " ", "")) == 1
label.set_textcolor(tpo, single_print_color_input)
calculate_poc() =>
size = array.size(tpo_labels)
if size > 0
mid = math.floor(size / 2)
poc = array.get(tpo_labels, mid)
i = mid
j = mid
idx = mid
poc_length = 0
while j >= 0 or i < size - 1
if i < size
len1 = str.length(str.replace_all(get_text_at(i), " ", ""))
if len1 > poc_length
poc_length := len1
poc := get_label_at(i)
idx := i
if j >= 0
len2 = str.length(str.replace_all(get_text_at(j), " ", ""))
if len2 > poc_length
poc_length := len2
poc := get_label_at(j)
idx := j
i += 1
j -= 1
array.set(globals, G_POC_LABEL_IDX, idx)
highlight_poc() =>
vp_poc = na(array.get(globals, G_VP_POC_LABEL_IDX)) ? na : get_label_at(array.get(globals, G_VP_POC_LABEL_IDX))
poc = get_label_at(array.get(globals, G_POC_LABEL_IDX))
if na(vp_poc)
label.set_textcolor(poc, poc_color_input)
if show_vp_based_poc_input and not na(vp_poc)
label.set_textcolor(vp_poc, vp_poc_color_input)
if array.get(globals, G_VP_POC_LABEL_IDX) != array.get(globals, G_POC_LABEL_IDX)
if not na(vp_poc)
if str.length(str.replace_all(label.get_text(vp_poc), " ", "")) != str.length(str.replace_all(label.get_text(poc), " ", ""))
label.set_textcolor(poc, poc_color_input)
if show_extension_lines_input
y = label.get_y(na(vp_poc) ? poc : vp_poc )
ln = line.new(first_bar_index, y, first_bar_index + 1, y, color = poc_ext_color_input, width = 1, extend = extend.right)
array.push(ext_cache, ln)
reset() =>
array.clear(vp_labels)
array.clear(tpo_labels)
array.clear(tpo_oc_labels)
array.clear(lines)
array.clear(ext_cache)
array.clear(tpo_highs)
array.clear(tpo_lows)
array.clear(vp_volumes)
array.clear(vp_prices)
array.set(globals, G_POC_LABEL_IDX, na)
array.set(globals, G_VP_POC_LABEL_IDX, na)
array.set(prices, P_SESSION_OPEN, 0.0)
array.set(prices, P_SESSION_CLOSE, 0.0)
array.set(prices, P_IB_HIGH, 0.0)
array.set(prices, P_IB_LOW, 0.0)
delete_objects() =>
while array.size(vp_labels) > 0
label.delete(array.shift(vp_labels))
while array.size(tpo_labels) > 0
label.delete(array.shift(tpo_labels))
while array.size(tpo_oc_labels) > 0
label.delete(array.shift(tpo_oc_labels))
while array.size(lines) > 0
line.delete(array.shift(lines))
while array.size(ext_cache) > 0
line.delete(array.shift(ext_cache))
draw_ib_lines() =>
if ib_periods_input > 0
array.push(lines,
line.new(first_bar_index, min, first_bar_index, array.get(prices, P_IB_LOW), xloc.bar_index, extend.none, ib_background_color_input, line.style_solid, ib_width_input))
array.push(lines,
line.new(first_bar_index, array.get(prices, P_IB_LOW), first_bar_index, array.get(prices, P_IB_HIGH), xloc.bar_index, extend.none, ib_highlight_color_input, line.style_solid, ib_width_input))
array.push(lines,
line.new(first_bar_index, array.get(prices, P_IB_HIGH), first_bar_index, max, xloc.bar_index, extend.none, ib_background_color_input, line.style_solid, ib_width_input))
quantized_price(price, tick_multiplier) =>
step = tick_multiplier * syminfo.mintick
price - price % step
create_price_levels() =>
step = ticks_input * syminfo.mintick
for y = min to max by step
array.push(tpo_labels, create_tpo_label(first_bar_index, y))
get_label_index_at_price(price) =>
if price <= min
0
else
levels = array.size(tpo_labels)
step = ticks_input * syminfo.mintick
math.min(levels - 1, math.round((price - min) / step))
highlight_current_price_level_tpos() =>
if not na(session_time) and (not barstate.isconfirmed or barstate.isrealtime)
label.set_textcolor(get_label_at(get_label_index_at_price(close)), close_color_input)
highlight_open_tpo() =>
if array.size(tpo_labels) > 0 and tpo_characters_input == TPO_AZ
idx = get_label_index_at_price(array.get(prices, P_SESSION_OPEN))
if idx >= 0
lbl = get_label_at(idx)
if array.size(tpo_oc_labels) == 0
copy = label.copy(lbl)
array.push(tpo_oc_labels, copy)
length = str.length(label.get_text(copy))
open_char = str.substring(label.get_text(copy), 0, 1)
chars = label.get_text(lbl)
if str.length(chars) > 0
label.set_text(lbl, " " + str.substring(chars, 1, length))
label.set_text(copy, open_char)
label.set_text_font_family(copy, font_family)
label.set_textcolor(copy, open_color_input)
highlight_close_tpo() =>
if TPO_AZ == tpo_characters_input and array.size(last_label) > 0
lbl = array.shift(last_label)
copy = label.copy(lbl)
length = str.length(label.get_text(copy))
if length > 0
close_char = str.substring(label.get_text(copy), length - 1, length)
label.set_text(lbl, str.substring(label.get_text(lbl), 0, length - 1))
label.set_text(copy, spaces(length - 1, " ") + close_char + "◂")
label.set_text_font_family(copy, font_family)
label.set_textcolor(copy, close_color_input)
highlight_midpoint() =>
if show_extension_lines_input
y = switch midpoint_algo_input
MP_TPOS =>
mid = math.floor(tpo_count() / 2)
count = 0
y = 0.0
for tpo in tpo_labels
count += str.length(str.replace_all(label.get_text(tpo), " ", ""))
if count >= mid
y := label.get_y(tpo)
break
y
MP_HL =>
max - (max - min) / 2
ln = line.new(first_bar_index, y, first_bar_index + 1, y, color = mid_color_input, width = 1, extend = extend.right, style = line.style_dotted)
array.push(ext_cache, ln)
is_upper(string string) =>
u = str.upper(string)
u != str.lower(string) and string == u
render_tpos() =>
mark_open = switch mark_period_opens_input
"No" => na
"Swap case" => 1
"Use '0'" => 2
for i = 0 to array.size(tpo_highs) - 1
min_idx = get_label_index_at_price(array.get(tpo_lows, i))
max_idx = get_label_index_at_price(array.get(tpo_highs, i))
open_idx = mark_open and tpo_characters_input == TPO_AZ and i < array.size(opens) ? get_label_index_at_price(array.get(opens, i)) : na
for j = min_idx to max_idx
char = array.get(tpo_chars, i % (array.size(tpo_chars)))
if mark_open and tpo_characters_input == TPO_AZ and open_idx and j == open_idx
if mark_open == 1
char := is_upper(char) ? str.lower(char) : str.upper(char)
if mark_open == 2
char := "0"
append_char(j, char)
if split_profile_input and tpo_characters_input == TPO_AZ
for tpo in tpo_labels
len = str.length(label.get_text(tpo))
if len < i + 1
add_spaces = " "
label.set_text(tpo, label.get_text(tpo) + add_spaces)
calculate_volume_profile_based_poc() =>
if show_vp_based_poc_input and array.size(lower_tf_highs) > 0 and array.size(lower_tf_lows) > 0 and array.size(lower_tf_volumes) > 0
for i = 0 to array.size(lower_tf_highs) - 1
_min = quantized_price(array.get(lower_tf_lows, i), ticks_input)
_max = quantized_price(array.get(lower_tf_highs, i), ticks_input)
vol = array.get(lower_tf_volumes, i) / (1 + (_max - _min) / (ticks_input * syminfo.mintick))
for price = _min to _max by ticks_input * syminfo.mintick
index = array.indexof(vp_prices, price)
if index == -1
array.push(vp_prices, price)
array.push(vp_volumes, vol)
else
array.set(vp_volumes, index, array.get(vp_volumes, index) + vol)
poc = array.get(vp_prices, array.indexof(vp_volumes, array.max(vp_volumes)))
array.set(globals, G_VP_POC_LABEL_IDX, get_label_index_at_price(poc))
else
// all or nothing, please...
array.set(globals, G_VP_POC_LABEL_IDX, na)
array.clear(vp_prices)
array.clear(vp_volumes)
should_download_lower_tf() =>
should_process() and show_vp_based_poc_input and timeframe.in_seconds() > 60
lower_tf() =>
if timeframe.in_seconds() < 60 * 30
"1"
else if timeframe.in_seconds() >= 60 * 30 and timeframe.in_seconds() < 60 * 60
"3"
else if timeframe.in_seconds() == 60 * 60
"10"
else
"60"
highlight_vwap() =>
if show_session_vwap_input and not na(session_vwap)
vwap_index = get_label_index_at_price(session_vwap)
lbl = get_label_at(vwap_index)
label.set_textcolor(lbl, session_vwap_color_input)
volume_color(price, ratio) =>
percent = int(100*ratio)
if percent <= 8
color.new(single_print_color_input, 0)
else
color.new(value_area_color_input, math.max(0, 80 - percent))
render_volume_numbers() =>
if timeframe_input == TF_FIXED and render_volumes_input and array.size(vp_prices) > 0
for i = 0 to array.size(vp_prices) - 1
price = array.get(vp_prices, i)
vol = array.get(vp_volumes, i)
lbl = label.new(first_bar_index, price, str.tostring(math.round(vol)), color = color.new(color.white, 100), textcolor = volume_color(price, vol/array.max(vp_volumes)),
size = font_size, style = label.style_label_right, xloc = xloc.bar_index,
text_font_family = font_family)
array.push(vp_labels, lbl)
cache_last_label() =>
if tpo_characters_input == TPO_AZ
array.clear(last_label)
array.push(last_label, get_label_at(get_label_index_at_price(close)))
bg_color() =>
if timeframe_input == TF_FIXED and time >= time_range_from_input and time <= time_range_till_input
fixed_range_bg_color_input
else
color(na)
handle_extension_lines() =>
if array.size(extensions) > 0 and session_time
for i = 0 to array.size(extensions) - 1
if i >= array.size(extensions)
continue
ln = array.get(extensions, i)
y = line.get_y1(ln)
if y >= min and y <= max
line.set_x2(ln, first_bar_index)
line.set_extend(ln, extend.none)
array.remove(extensions, i)
lower_tf_highs := should_download_lower_tf() ? request.security_lower_tf(syminfo.ticker, lower_tf(), high) : array.new_float()
lower_tf_lows := should_download_lower_tf() ? request.security_lower_tf(syminfo.ticker, lower_tf(), low) : array.new_float()
lower_tf_volumes := should_download_lower_tf() ? request.security_lower_tf(syminfo.ticker, lower_tf(), volume) : array.new_float()
if timeframe.in_seconds() <= 60
lower_tf_highs := array.from(high)
lower_tf_lows := array.from(low)
lower_tf_volumes := array.from(volume)
if array.size(tpo_chars) == 0
chars = switch tpo_characters_input
TPO_SQUARE => TPO_SQUARE
TPO_CIRCLE => TPO_CIRCLE
TPO_AZ => TPO_CHARS
tpo_chars := str.split(chars, "")
if is_first_bar_of_session() and should_process()
if show_extension_lines_input
while array.size(ext_cache) > 0
array.push(extensions, array.shift(ext_cache))
reset()
max := high
min := low
first_bar_index := bar_index
array.set(opens, 0, open)
array.set(prices, P_SESSION_OPEN, open)
array.set(prices, P_SESSION_CLOSE, close)
array.push(tpo_highs, high)
array.push(tpo_lows, low)
if ib_periods_input > 0
array.set(prices, P_IB_LOW, low)
array.set(prices, P_IB_HIGH, high)
create_price_levels()
render_tpos()
array.push(lines, line.new(first_bar_index - price_marker_length_input, array.get(prices, P_SESSION_OPEN), first_bar_index, array.get(prices, P_SESSION_OPEN), xloc.bar_index, extend.none, color = open_color_input, width = price_marker_width_input))
array.push(lines, line.new(first_bar_index, array.get(prices, P_SESSION_CLOSE), first_bar_index + price_marker_length_input, array.get(prices, P_SESSION_CLOSE), xloc.bar_index, extend.none, color = close_color_input, width = price_marker_width_input))
draw_ib_lines()
calculate_poc()
calculate_volume_profile_based_poc()
highlight_open_tpo()
highlight_current_price_level_tpos()
if not is_first_bar_of_session() and should_process() and bar_index - first_bar_index < MAX_BARS_BACK
delete_objects()
max := math.max(high, max)
min := math.min(low, min)
if bar_index - first_bar_index < array.size(opens)
array.set(opens, bar_index - first_bar_index, open)
create_price_levels()
if bar_index - first_bar_index < ib_periods_input
ib_l = math.min(array.get(prices, P_IB_LOW), low)
ib_h = math.max(array.get(prices, P_IB_HIGH), high)
array.set(prices, P_IB_HIGH, ib_h)
array.set(prices, P_IB_LOW, ib_l)
array.set(prices, P_SESSION_CLOSE, close)
array.push(tpo_highs, high)
array.push(tpo_lows, low)
render_tpos()
array.push(lines, line.new(first_bar_index - price_marker_length_input, array.get(prices, P_SESSION_OPEN), first_bar_index, array.get(prices, P_SESSION_OPEN), xloc.bar_index, extend.none, color = open_color_input, width = price_marker_width_input))
array.push(lines, line.new(first_bar_index, array.get(prices, P_SESSION_CLOSE), first_bar_index + price_marker_length_input, array.get(prices, P_SESSION_CLOSE), xloc.bar_index, extend.none, color = close_color_input, width = price_marker_width_input))
draw_ib_lines()
calculate_poc()
calculate_volume_profile_based_poc()
highlight_value_area()
highlight_midpoint()
highlight_vwap()
highlight_poc()
highlight_single_prints()
highlight_current_price_level_tpos()
highlight_open_tpo()
render_volume_numbers()
cache_last_label()
if show_extension_lines_input
ln_high = line.new(first_bar_index, max, first_bar_index + 1, max, color = high_color_input, width = 1, extend = extend.right, style = line.style_dotted)
ln_low = line.new(first_bar_index, min, first_bar_index + 1, min, color = low_color_input, width = 1, extend = extend.right, style = line.style_dotted)
array.push(ext_cache, ln_high)
array.push(ext_cache, ln_low)
handle_extension_lines()
bgcolor(bg_color())
if is_first_bar_of_session() or not should_process()
highlight_close_tpo() |
LNL Keltner Candles | https://www.tradingview.com/script/9xTEuyzU-LNL-Keltner-Candles/ | lnlcapital | https://www.tradingview.com/u/lnlcapital/ | 210 | 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
//
// LNL Keltner Candles with Reversals
//
// Mean reversion reversal candles with custom painted candles based on the price touch or close above or below keltner channel limits (upper & lower bands).
//
// Can serve as an additional indicator or as the mean reversion tool.
//
// Created by L&L Capital
//
indicator("LNL Keltner Candles", shorttitle = "Keltner Candles", overlay=true)
// Inputs
length = input(defval=13, title="Length")
factor = input(defval=1.5, title="ATR Factor")
pricetypeUpper = input(high, title="Price Type Upper")
pricetypeLower = input(low, title="Price Type Lower")
// Keltner Channels Calculations
shift = factor * ta.atr(length)
average = ta.ema(close,length)
upperband = average + shift
lowerband = average - shift
upperlimit = pricetypeUpper > upperband
lowerlimit = pricetypeLower < lowerband
// Mean Reversion Arrows Calculations
UpBar = close > open
DnBar = close < open
AvgRange = 0.05 * math.avg(high - low, 20)
// Keltner Channels Plots & Colors
[middle, upper, lower] = ta.kc(close, length, factor)
plot(middle, color=color.new(#1848cc,0),title="Avg",display = display.none)
plot(upper, color=color.new(#1848cc,0),title="Upper Band",display = display.none)
plot(lower, color=color.new(#1848cc,0),title="Lower Band",display = display.none)
bar_color = upperlimit ? color.new(#ff0000,0) : lowerlimit ? color.new(#27c22e,0) : color.new(color.white,0)
barcolor(color=bar_color)
// Reversal Arrows Plots & Colors
SignalUp = DnBar[3] and DnBar[2] and DnBar[1] and UpBar[0] and close[3] >= close[2] and low[1] > open[0] and close[2] >= close[1] and low <= lowerband
plotshape(SignalUp,title='Reversal Up',style=shape.triangleup,location=location.belowbar,color=(color.purple),size=size.tiny)
SignalDown = UpBar[3] and UpBar[2] and UpBar[1] and DnBar[0] and close[3] <= close[2] and low[1] < open[0] and close[2] <= close[1] and high >= upperband
plotshape(SignalDown,title='Reversal Down',style=shape.triangledown,location=location.abovebar,color=(color.purple),size=size.tiny) |
Bar Magnifier | https://www.tradingview.com/script/xLVcx7n0-Bar-Magnifier/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 219 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
indicator("Bar Magnifier", max_lines_count = 500, max_boxes_count = 250)
barTime = input.time(0, title="Select Bar", confirm = true)
lowerTimeframe = input.timeframe("1", 'Lower Timeframe')
type ohlc
float o
float h
float l
float c
getOhlc()=>ohlc.new(open, high, low, close)
array<ohlc> ohlcArray = request.security_lower_tf(syminfo.tickerid, lowerTimeframe, getOhlc(), true)
bgcolor(time == barTime?color.aqua:na)
var int l = na
var int r = na
var float t = na
var float b = na
if(time == barTime)
lastClose = close[1]
for [i, ohlcValue] in ohlcArray
left = bar_index-3*(array.size(ohlcArray)-i)
right = left + 2
mid = left + 1
borderColor = ohlcValue.c > lastClose? color.green : color.red
lastClose := ohlcValue.c
bgcolor = ohlcValue.c > ohlcValue.o? na: borderColor
ocMax = math.max(ohlcValue.o, ohlcValue.c)
ocMin = math.min(ohlcValue.o, ohlcValue.c)
box.new(left, ocMax, right, ocMin, borderColor, 1, bgcolor=bgcolor)
line.new(mid, ocMax, mid, ohlcValue.h, color=borderColor)
line.new(mid, ocMin, mid, ohlcValue.l, color=borderColor)
leftMost = bar_index-3*(array.size(ohlcArray))
rightMost = bar_index
borderColor = close > close[1]? color.green : color.red
bodyColor = color.new(borderColor, 90)
box.new(leftMost, math.max(open, close), rightMost, math.min(open, close), borderColor, 0, line.style_dotted, extend.none, xloc.bar_index, bodyColor)
|
Subsets and Splits