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
|
---|---|---|---|---|---|---|---|---|
RSI + Divergences + Alerts [MisterMoTA] | https://www.tradingview.com/script/6Mgz1Dwf-RSI-Divergences-Alerts-MisterMoTA/ | MisterMoTA | https://www.tradingview.com/u/MisterMoTA/ | 181 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @author = MisterMoTA
// © MisterMoTA
//@version=5
indicator(title="RSI + Divergences + Alerts [MisterMoTA]", format=format.price)
len = input.int(title="RSI Period", minval=1, defval=14, group="RSI Settings")
src = input(title="RSI Source", defval=close, group="RSI Settings")
overBought = input.int(title="RSI Overbought", minval=60, defval=70, group="RSI Settings")
obXLevel = input.int(title="RSI Extreme Overbought", minval=70, defval=80, group="RSI Settings")
overSold = input.int(title="RSI Oversold", maxval=40, defval=30, group="RSI Settings")
osXLevel = input.int(title="RSI Extreme Oversold", maxval=30, defval=20, group="RSI Settings")
maTypeInput = input.string("WMA", title="MA Type", options=["SMA", "EMA", "RMA", "WMA"], group="MA Settings")
maLengthInput = input.int(14, title="MA Length", group="MA Settings")
emaBullColor = input(#00ff77, "Ema Rising Color", group="MA Settings", inline="Rising")
emaBearColor = input(#fc0202, "EMA Falling Color", group="MA Settings", inline="Falling")
showFill = input.bool(false, title="Fill the Rsi and Moving Average ?", group="RSI FILL")
col_grow_above = input(#26A69A, "Above Grow", group="RSI FILL", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="RSI FILL", inline="Above")
col_grow_below = input(#FFCDD2, "Below Grow", group="RSI FILL", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="RSI FILL", inline="Below")
lbR = input(title="Pivots to Lookback Right", defval=5, group="Divergences Settings")
lbL = input(title="Pivots to Lookback Left", defval=5, group="Divergences Settings")
rangeUpper = input(title="Max of Lookback Range", defval=60, group="Divergences Settings")
rangeLower = input(title="Min of Lookback Range", defval=5, group="Divergences Settings")
plotBull = input(title="Plot Bullish", defval=true, group="Divergences Settings")
plotHiddenBull = input(title="Plot Hidden Bullish", defval=true, group="Divergences Settings")
plotBear = input(title="Plot Bearish", defval=true, group="Divergences Settings")
plotHiddenBear = input(title="Plot Hidden Bearish", defval=true, group="Divergences Settings")
bearColor = input(#fc0202, "Bearish", group="Divergences colors", inline="Bear")
hiddenBearColor = input(#ffea00, "Hidden Bearish", group="Divergences colors", inline="Bear")
bullColor = input(#01820a, "Bullish", group="Divergences colors", inline="Bull")
hiddenBullColor =input(#001dfc, "Hidden Bulliish", group="Divergences colors", inline="Bull")
textColor = color.white
noneColor = color.new(color.white, 100)
txtcol_grow_above = input(#1a7b24, "Above Grow", group="Trend labels colors", inline="Above")
txtcol_fall_above = input(#672ec5, "Fall", group="Trend labels colors", inline="Above")
txtcol_grow_below = input(#F37121, "Below Grow", group="Trend labels colors", inline="Below")
txtcol_fall_below = input(#be0606, "Fall", group="Trend labels colors", inline="Below")
h0 = hline(0, title="Zero lime", color=#00000000)
h100 = hline(100, title="100 line", color=#00000000)
h40 = hline(40, title="Bearish line", color=col_fall_below)
h60 = hline(60, title="Bullish line", color=col_grow_above)
hline(50, title="Middle Line", color=#e78114a0, linestyle=hline.style_dashed)
obLevel = hline(80, title="Overbought", color=color.rgb(4, 214, 50, 90), linestyle=hline.style_dotted)
osLevel = hline(20, title="Oversold", color=color.rgb(243, 33, 100, 90), linestyle=hline.style_dotted)
ma(source, length, type) =>
switch type
"RMA" => ta.rma(source, length)
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"WMA" => ta.wma(source, length)
rsi = ta.rsi(src, len)
rsi2 = ta.rsi(src,2)
rsi5 = ta.rsi(src,5)
rsiMA = ma(rsi, maLengthInput, maTypeInput)
rsiMaColor = rsiMA >=rsiMA[1] ? emaBullColor : emaBearColor
hfill = (rsi > overBought) ? (rsi > overBought and rsi < obXLevel ? color.new(color.red,85) : #FF286858): (rsi < overSold) ? (rsi > osXLevel ? color.new(color.teal, 85) : rsi < osXLevel ? color.new(color.teal, 75) : na):na
fill(h0,h100, title="OB/OS Background", color=hfill)
fill(obLevel, h60, title="RSI Bullish Zone Background", color=color.new(color.teal, 85))
//fill(h40, h60, title="RSI Bearish Zone Background", color=color.rgb(1, 4, 45))
fill(osLevel, h40, title="RSI Background", color=color.rgb(255, 5, 84, 85))
fillColor = rsi > rsiMA and rsi >= rsi[1] ? col_grow_above : rsi > rsiMA and rsi < rsi[1] ? col_fall_above: rsi < rsiMA and rsi < rsi[1] ? col_fall_below : rsi < rsiMA and rsi >= rsi[1] ? col_grow_below : na
fillColor2 = rsi2 > rsiMA and rsi2 >= rsi2[1] ? col_grow_above : rsi2 > rsiMA and rsi2 < rsi2[1] ? col_fall_above: rsi2 < rsiMA and rsi2 < rsi2[1] ? col_fall_below : rsi2 < rsiMA and rsi2 >= rsi2[1] ? col_grow_below : na
fillColor5 = rsi5 > rsiMA and rsi5 >= rsi5[1] ? col_grow_above : rsi5 > rsiMA and rsi5 < rsi5[1] ? col_fall_above: rsi5 < rsiMA and rsi5 < rsi5[1] ? col_fall_below : rsi5 < rsiMA and rsi5 >= rsi5[1] ? col_grow_below : na
srsi = plot(rsi, title="RSI ", linewidth=4, color=fillColor)
fastRsi = plot(rsi2, title="RSI 2", linewidth=1, color=fillColor2)
medRsi = plot(rsi5, title="RSI 5", linewidth=2, color=fillColor5)
maPlot= plot(rsiMA , title="RSI MA", linewidth=3, color=rsiMaColor)
fill(srsi,maPlot, title="RSI/MA Fill Background", color=showFill == true ? fillColor: color.rgb(255, 255, 255, 100))
rsiText=(rsi > 50 ? (rsi >rsi[1]? " RSI > 50 and ▲ Growing, RSI = " + str.tostring(rsi[0], "#.##") :" RSI > 50 and ▼ Falling, RSI = " + str.tostring(rsi[0], "#.##") ) : (rsi > rsi[1] ? "RSI < 50 and ▲ Growing, RSI = " + str.tostring(rsi[0], "#.##"): " RSI < 50 and ▼ Falling, RSI = " + str.tostring(rsi[0], "#.##")))
oneDay = 24 * 60 * 60 * 1000
barsAhead = 3
tmf = if timeframe.ismonthly
barsAhead * oneDay * 30
else if timeframe.isweekly
barsAhead * oneDay * 7
else if timeframe.isdaily
barsAhead * oneDay
else if timeframe.isminutes
barsAhead * oneDay * timeframe.multiplier / 1440
else if timeframe.isseconds
barsAhead * oneDay * timeframe.multiplier / 86400
else
0
angle(_src) =>
rad2degree = 180 / 3.14159265359 //pi
ang = rad2degree * math.atan((_src[0] - _src[1]) / ta.atr(14))
ang
emae = angle(rsiMA)
emaanglestat = emae > emae[1] ? "▲ Growing": "▼ Falling"
rsiTextxxx = "Rsi MA/ATR angle value is " + str.tostring(emae, "#.##") + "° and is " + emaanglestat
rsicolorxxx = emae >0 and emae >=emae[1] ? txtcol_grow_above : txtcol_fall_below
// Label
label lpt1 = label.new(time, 40, text=rsiTextxxx[0], color=rsicolorxxx, xloc=xloc.bar_time, style=label.style_label_left, textcolor=color.white, textalign=text.align_left, size=size.normal)
label.set_x(lpt1, label.get_x(lpt1) + tmf)
label.delete(lpt1[1])
txtrsiColors = (rsi > 50 ? (rsi[1] < rsi ? txtcol_grow_above : txtcol_fall_above) : (rsi[1] < rsi ? txtcol_grow_below : txtcol_fall_below))
label lrsi1 = label.new(time, 60, text=rsiText[0], color=txtrsiColors, xloc=xloc.bar_time, style=label.style_label_left, textcolor=color.white, textalign=text.align_left, size=size.normal)
label.set_x(lrsi1, label.get_x(lrsi1) + tmf)
label.delete(lrsi1[1])
plFound = na(ta.pivotlow(rsi, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(rsi, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// rsi: Higher Low
rsiHL = rsi[lbR] > ta.valuewhen(plFound, rsi[lbR], 1) and _inRange(plFound[1])
// Price: Lower Low
priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL and rsiHL and plFound
plot(
plFound ? rsi[lbR] : na,
offset=-lbR,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? bullColor : noneColor),
display = display.pane
)
if bullCond
BCL = label.new(x=bar_index - lbL, y= rsi[lbR], color=bullColor, style =label.style_label_up , textcolor=textColor, size=size.small, text = " Bull ")
//------------------------------------------------------------------------------
// Hidden Bullish
// rsi: Lower Low
rsiLL = rsi[lbR] < ta.valuewhen(plFound, rsi[lbR], 1) and _inRange(plFound[1])
// Price: Higher Low
priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
hiddenBullCond = plotHiddenBull and priceHL and rsiLL and plFound
plot(
plFound ? rsi[lbR] : na,
offset=-lbR,
title="Hidden Bullish",
linewidth=2,
color=(hiddenBullCond ? hiddenBullColor : noneColor),
display = display.pane
)
if hiddenBullCond
HBLabel = label.new(x=bar_index - lbL, y= rsi[lbR], color=hiddenBullColor, style =label.style_label_up , textcolor=textColor, size=size.small, text=" H Bull ")
//------------------------------------------------------------------------------
// Regular Bearish
// rsi: Lower High
rsiLH = rsi[lbR] < ta.valuewhen(phFound, rsi[lbR], 1) and _inRange(phFound[1])
// Price: Higher High
priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
bearCond = plotBear and priceHH and rsiLH and phFound
plot(
phFound ? rsi[lbR] : na,
offset=-lbR,
title="Regular Bearish",
linewidth=2,
color=(bearCond ? bearColor : noneColor),
display = display.pane
)
if bearCond
RBearish = label.new(x=bar_index - lbL, y= rsi[lbR], color=bearColor, style =label.style_label_down , textcolor=textColor, size=size.small, text=" Bear ")
//------------------------------------------------------------------------------
// Hidden Bearish
// rsi: Higher High
rsiHH = rsi[lbR] > ta.valuewhen(phFound, rsi[lbR], 1) and _inRange(phFound[1])
// Price: Lower High
priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)
hiddenBearCond = plotHiddenBear and priceLH and rsiHH and phFound
plot(
phFound ? rsi[lbR] : na,
offset=-lbR,
title="Hidden Bearish",
linewidth=2,
color=(hiddenBearCond ? hiddenBearColor : noneColor),
display = display.pane
)
if hiddenBearCond
RBearish = label.new(x=bar_index - lbL, y= rsi[lbR], color=bearColor, style =label.style_label_down , textcolor=textColor, size=size.small, text=" H Bear ")
// Create alert condition
alertcondition(condition=bullCond,
title="Alert for Regular Bullish Divergence",
message="Regular Bullish Divergence Detected")
alertcondition(condition=hiddenBullCond,
title="Alert for Hidden Bullish Divergence",
message="Hidden Bullish Divergence Detected")
alertcondition(condition=bearCond,
title="Alert for Regular Bearish Divergence",
message="Regular Bearish Divergence Detected")
alertcondition(condition=hiddenBearCond,
title="Alert for Hidden Bearish Divergence",
message="Hidden Bearish Divergence Detected")
rsiOverbought = rsi > overBought
rsiXOverbought = rsi > obXLevel
rsiOversold = rsi < overSold
rsiXOversold = rsi < osXLevel
alertcondition(condition=rsiOverbought,
title="Alert for RSI Overbought",
message="RSI Overbought")
alertcondition(condition=rsiXOverbought,
title="Alert for RSI Extreme Overbought",
message="RSI Extreme Overbought")
alertcondition(condition=rsiOversold,
title="Alert for RSI Oversold",
message="RSI Oversold")
alertcondition(condition=rsiXOversold,
title="Alert for RSI Extreme Oversold",
message="RSI Extreme Oversold")
rsiAboveMA = rsi > rsiMA and rsi[1] < rsiMA[1]
rsiBelloweMA = rsi < rsiMA and rsi[1] > rsiMA[1]
alertcondition(condition=rsiAboveMA,
title="Alert for RSI Crossing Above RSI MA",
message="RSI Crossed Above RSI Moving average")
alertcondition(condition=rsiBelloweMA,
title="Alert for RSI Crossing Bellow RSI MA",
message="RSI Crossed Bellow RSI Moving average")
rsiAbove50 = rsi > 50 and rsi[1] <= 50
rsiBellowe50 = rsi < 50 and rsi[1] >= 50
alertcondition(condition=rsiAbove50,
title="Alert for RSI Crossing Above 50",
message="RSI Crossed Above 50")
alertcondition(condition=rsiBellowe50,
title="Alert for RSI Crossing Bellow 50",
message="RSI Crossed Bellow RSI 50") |
MarketSmith Volumes | https://www.tradingview.com/script/DRT8QZSp/ | Fred6724 | https://www.tradingview.com/u/Fred6724/ | 234 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Fred6724
//@version=5
indicator('MarketSmith Volumes', format = format.volume, max_labels_count = 500)
// Inputs
colUp = input(color.rgb(39,54,233,0), title='Up Volume Color', group = 'VOLUMES')
colDn = input(color.rgb(222,50,174,0), title='Down Volume Color', group = 'VOLUMES')
prevC = input(true, title='Color Based On Previous Close', group='VOLUMES')
trunc = input(false, title='Truncate for MarketSmith type display', group = 'DISPLAY')
labels = input(true, title='Labels on Volume', group = 'LABELS', inline='1')
labelC = input(color.rgb(0,0,0,0), title='Color', group = 'LABELS', inline='1')
colChg = input(color.rgb(39,54,233,0), title='', group = 'LABELS', inline='1')
percChg = input(true, title='%Change on Labels', group='LABELS')
labelS = input.string('Normal', 'Text Size', options = ['Tiny', 'Small', 'Normal', 'Large'], group = 'LABELS')
peakL = input(9, 'Peak Length', group='LABELS')
lenDa = input(50, 'Length Daily', group = 'MA', inline = '1')
lenWe = input(10, 'Weekly', group = 'MA', inline = '1')
colMa = input(color.red, title='MA Color', group = 'MA')
showLab = input(true, title='Label on Last Volume Bar', group = 'CURRENT BAR LABEL')
sizeLab = input.string('Normal', 'Size', options = ['Tiny', 'Small', 'Normal', 'Large'], group = 'CURRENT BAR LABEL')
//curDol = input(false, title='Average $ Volume', group = 'CURRENT BAR LABEL')
labCol = input(color.rgb(59,60,66,0), title = 'Label Color', group = 'CURRENT BAR LABEL')
volCol = input(color.white, title = 'Volume Color', group = 'CURRENT BAR LABEL')
posCol = input(color.lime, title='Positive Buzz Color', group = 'CURRENT BAR LABEL')
negCol = input(color.red, title='Negative Buzz Color', group = 'CURRENT BAR LABEL')
showTa = input(true, title='Show Table', group = 'Table')
sizeTa = input.string('Small', 'Table Size', options = ['Tiny', 'Small', 'Normal', 'Large'], group = 'Table')
volTa = input(false, title = 'Current Volume on Table', group = 'Table')
buzzTa = input(false, title = 'Vol. Buzz on Table', group = 'Table')
TabCol = input(color.rgb(59,60,66,0), title = 'Label Color', group = 'Table')
txtTCol = input(color.white, title = 'Volume Color', group = 'Table')
posTCol = input(color.lime, title='Positive Buzz Color', group = 'Table')
negTCol = input(color.red, title='Negative Buzz Color', group = 'Table')
tf = timeframe.period
ticker = syminfo.tickerid
// Switch Label Size
sLabel = switch labelS
'Normal' => size.normal
'Tiny' => size.tiny
'Small' => size.small
'Large' => size.large
sLabel2 = switch sizeLab
'Normal' => size.normal
'Tiny' => size.tiny
'Small' => size.small
'Large' => size.large
taSize = switch sizeTa
'Normal' => size.normal
'Tiny' => size.tiny
'Small' => size.small
'Large' => size.large
// Volume and MA calculation
s = ticker
vol = request.security(s, tf, volume)
// Color of Volumes
colr = close>=open ? colUp:colDn
if(prevC)
colr := close>=close[1] ? colUp:colDn
ma = timeframe.isweekly ? ta.sma(vol, lenWe) : ta.sma(vol, lenDa)
// Display in the style of MarketSmith
// Recalculation of the volume with limitation
vol2 = vol > 2*ma ? 2*ma:vol
// Display
plot(trunc ? vol2:vol, title = 'Volume' , color = colr, style = plot.style_histogram, linewidth = 3)
plot(ma, title = 'MA', color = colMa)
// Formatting Volume
uV = ''
volFormat = math.round(vol, 2)
if(volFormat >= 1000 and volFormat < 1000000)
volFormat := math.round(volFormat/1000, 2)
uV := 'K'
if(volFormat >= 1000000 and volFormat < 1000000000)
volFormat := math.round(volFormat/1000000, 2)
uV := 'M'
if(volFormat >= 1000000000)
volFormat := math.round(volFormat/1000000000, 2)
uV := 'B'
// Average Volume
advVol = math.round(ma, 0)
uVAvg = ''
if(advVol >= 1000 and advVol < 1000000)
advVol := math.round(advVol/1000, 2)
uVAvg := 'K'
if(advVol >= 1000000 and advVol < 1000000000)
advVol := math.round(advVol/1000000, 2)
uVAvg := 'M'
if(advVol >= 1000000000)
advVol := math.round(advVol/1000000000, 2)
uVAvg := 'B'
// Average $ Volume
advDol = math.round(close*ma, 0)
uVDoll = ''
if(advDol >= 1000 and advDol < 1000000)
advDol := math.round(advDol/1000, 0)
uVDoll := 'K'
if(advDol >= 1000000 and advDol < 1000000000)
advDol := math.round(advDol/1000000, 0)
uVDoll := 'M'
if(advDol >= 1000000000)
advDol := math.round(advDol/1000000000, 0)
uVDoll := 'B'
// Labels: Marked Highs Volume Bars Peak & %Variation Labels
// For Good Beat after the Peak Volume Bars Period
pivotHigh = ta.pivothigh(volume, peakL, peakL)
varPercent = 100*(vol[peakL]/ma[peakL])-100
var label volestvol = na
var label volestvolU = na
var label volestvol2 = na
var label volestvol2U = na
if(labels)
// If we have a good % beat in a period lower than the Peak Volume Bars Period
v = showLab ? 1:0 // If the label is visible, we don't want the last bar to have a text above
for i=peakL-1 to v
pivotHigh2 = ta.pivothigh(volume, peakL, i)
varPercent2 = 100*(vol[i]/ma[i])-100
if(barstate.islast and pivotHigh2 and varPercent2>25)
textvol9 = 'N/A'
textvol9U = 'N/A'
if(percChg)
textvol9 := str.tostring(volFormat[i], '0.0')+uV[i]+'\n'
textvol9U := '+'+str.tostring(varPercent2, '0')+'%'
if(not percChg)
textvol9 := str.tostring(volFormat[i], '0.0')+uV[i]
textvol9U := na
// Delete Previous Labels to avoid superposition
if not na(volestvol2)
label.delete(volestvol2)
if not na(volestvol2U)
label.delete(volestvol2U)
// Create Label
volestvol2 := label.new(bar_index-i, trunc ? vol2[i]:vol[i], xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, size = sLabel, text=textvol9 , textcolor=labelC)
volestvol2U := label.new(bar_index-i, trunc ? vol2[i]:vol[i], xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, size = sLabel, text=textvol9U, textcolor=colChg)
// For Label After the Peak Period
if (pivotHigh and varPercent>25)
string textvol9 = 'N/A'
string textvol9U = 'N/A'
if(percChg)
textvol9 := str.tostring(volFormat[peakL], '0.0')+uV[peakL]+'\n'
textvol9U := '+'+str.tostring(varPercent, '0')+'%'
if(not percChg)
textvol9 := str.tostring(volFormat[peakL], '0.0')+uV[peakL]
textvol9U := na
// Delete Previous Labels2 of the first part to avoid superposition
if not na(volestvol2)
label.delete(volestvol2)
if not na(volestvol2U)
label.delete(volestvol2U)
// Create Label
volestvol := label.new(bar_index-peakL, trunc ? vol2[peakL]:vol[peakL], xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, size= sLabel, text=textvol9, textcolor=labelC)
volestvolU := label.new(bar_index-peakL, trunc ? vol2[peakL]:vol[peakL], xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, size= sLabel, text=textvol9U, textcolor=colChg)
// Dynamique Label instead of a table
//Formatting Percentage Variation
volBuzz = 100*(vol/ma)-100
txtCol = volBuzz >= 0 ? posCol:negCol
// Text on labels
txtVol = str.tostring(volFormat)+uV+'\n'
txtDolVol = 'N/A'
txtVar = volBuzz >= 0 ? '\n+'+str.tostring(math.round(volBuzz))+'%':'\n'+str.tostring(math.round(volBuzz))+'%'
// Label Display
if barstate.islast and showLab
currentVol = label.new(bar_index, trunc?vol2:vol, xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_left, text=txtVol, textalign = text.align_left, size=sLabel2, color = labCol, textcolor=volCol)
currentBuz = label.new(bar_index, trunc?vol2:vol, xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_left, text=txtVar, textalign = text.align_left, size=sLabel2, color = color.rgb(0, 0, 0, 100), textcolor=txtCol)
label.delete(currentVol[1])
label.delete(currentBuz[1])
// Up/Down Volume Ratio ( Thanks Brandon ;) )
upVol = close > close[1] ? volume : 0
dnVol = close < close[1] ? volume : 0
sumUp = math.sum(upVol, 50)
sumDn = math.sum(dnVol, 50)
upDnVolRatio = sumUp / sumDn
// Table
// Display Table
table t = table.new(position.top_right, 2, 5, bgcolor=TabCol)
if barstate.islast and showTa
// Average Volume
table.cell(t, 0, 0, "Avg Vol: ", text_color=txtTCol, text_size=taSize)
table.cell(t, 1, 0, str.tostring(advVol, '0.00')+uVAvg, text_color =txtTCol, text_size=taSize)
table.cell_set_text_halign(t, 0, 0, text_halign = text.align_right)
table.cell_set_text_halign(t, 1, 0, text_halign = text.align_right)
// Average Dollar Volume
table.cell(t, 0, 1, "Avg $ Vol: ", text_color=txtTCol, text_size=taSize)
table.cell(t, 1, 1, str.tostring(advDol)+uVDoll, text_color =txtTCol, text_size=taSize)
table.cell_set_text_halign(t, 0, 1, text_halign = text.align_right)
table.cell_set_text_halign(t, 1, 1, text_halign = text.align_right)
// Up/Down Volume
table.cell(t, 0, 2, "U/D Vol: ", text_color=txtTCol, text_size=taSize)
table.cell(t, 1, 2, str.tostring(upDnVolRatio, '0.0'), text_color =txtTCol, text_size=taSize)
table.cell_set_text_halign(t, 0, 2, text_halign = text.align_right)
table.cell_set_text_halign(t, 1, 2, text_halign = text.align_right)
if volTa
table.cell(t, 0, 3, "Vol: ", text_color=txtTCol, text_size=taSize)
table.cell(t, 1, 3, str.tostring(volFormat, '0.00')+uV, text_color =txtTCol, text_size=taSize)
table.cell_set_text_halign(t, 0, 3, text_halign = text.align_right)
table.cell_set_text_halign(t, 1, 3, text_halign = text.align_right)
if buzzTa
table.cell(t, 0, 4, "Buzz: ", text_color=txtTCol, text_size=taSize)
table.cell(t, 1, 4, volBuzz >= 0 ? '+'+str.tostring(math.round(volBuzz))+'%':str.tostring(math.round(volBuzz))+'%', text_color =volBuzz >= 0 ? posTCol:negTCol, text_size=taSize)
table.cell_set_text_halign(t, 0, 4, text_halign = text.align_right)
table.cell_set_text_halign(t, 1, 4, text_halign = text.align_right) |
Bollinger Bands Liquidity Cloud [ChartPrime] | https://www.tradingview.com/script/dEaK9Qcv-Bollinger-Bands-Liquidity-Cloud-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 425 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime
//@version=5
indicator("Bollinger Bands Liquidity Cloud [ChartPrime]", overlay = true, max_boxes_count = 500)
show = input.bool(true, "Show Bollinger Bands", group = "Bands")
length = input.int(20, "Length", minval = 1, group = "Bands")
multiplier = input.float(2, "multiplier", minval = 0, maxval = 10, step = 0.125, group = "Bands")
style = input.string("Volume", "Style", ["Volume", "Z-Score"], group = "Main")
sample_size = input.int(50, "Sample Size", minval = 10, group = "Main")
window_size = input.int(150, "Window Size", minval = 0, tooltip = "Use this to adjust the window size of the heatmap. When style is set to Z-Score a value of 0 will use all data.", group = "Main")
look_back = input.int(50, "Lookback", minval = 0, group = "Main")
smoothing = input.int(1, "Smoothing", minval = 1, maxval = 20, group = "Main")
alpha = input.int(60, "Heat Map Alpha", minval = 0, maxval = 100, group = "Main")
score_enable = input.bool(true, "Weight Score Overlay", group = "Main")
high_color = input.color(#00ff00, "Color", group = "colour", inline = "Colour")
low_color = input.color(#FF0000, "", group = "colour", inline = "Colour")
dev_color = input.color(color.blue, "Bollinger Bands Color", group = "colour")
text_color = input.color(color.silver, "Text Color", group = "colour")
score(source, rank_75, rank_25, median, enable)=>
if enable
if source == 1
"S"
else if source < 1 and source >= rank_75
"A"
else if source < rank_75 and source >= median
"B"
else if source < median and source > rank_25
"C"
else
"D"
else
""
min_max(source, min, max)=>
(source - min)/(max - min)
rescale_invert(x, n) =>
inverted = 1 - x
rescaled = (1 - inverted) * n + inverted * 100
rescaled
price_from_z(z, average, stdev)=>
average + z * stdev
sq(source) => math.pow(source, 2)
sinc(source, bandwidth) =>
if source == 0
1
else
math.sin(math.pi * source / bandwidth) / (math.pi * source / bandwidth)
sinc_filter(source, length)=>
src_size = array.size(source)
estimate_array = array.new<float>(src_size)
float current_price = na
for i = 0 to src_size - 1
float sum = 0
float sumw = 0
for j = 0 to src_size - 1
diff = i - j
weight = sinc(diff, length)
sum += array.get(source, j) * weight
sumw += weight
current_price := sum / sumw
array.set(estimate_array, i, current_price >= 0 ? current_price : 0)
estimate_array
get_vol(a, b, x, y, vol) =>
if y < a or x > b
0
else if x > a and y < b
p_range = (y - x) / (b - a)
p_range * vol
else if x <= a and y >= b
p_bar = (b - a) / (y - x)
p_bar * vol
else if x < a and y <= b
p_bar = (y - a) / (y - x)
p_bar * vol
else if x >= a and y > b
p_bar = (b - x) / (y - x)
p_bar * vol
else
vol
type level
float start
float end
flag = bar_index > window_size
top_level = ta.highest(high, math.max(1, window_size))
bottom_level = ta.lowest(low, math.max(1, window_size))
step = (top_level - bottom_level) / sample_size
average = ta.sma(close, length)
stdev = ta.stdev(close, length)
bb_top = average + stdev * multiplier
bb_bottom = average - stdev * multiplier
boxes = array.new<box>(500)
if flag and barstate.islast and style == "Volume"
for n = look_back - 1 to 0
levels = array.new<level>(sample_size + 1)
for i = 0 to sample_size - 1
bottom = bottom_level[n]
step_n = step[n]
array.set(levels, i, level.new(bottom + step_n * i, bottom + step_n * (i + 1)))
volume_sum = array.new<float>(sample_size + 1, 0)
bullish_volume = array.new<float>(sample_size + 1, 0)
trimmed_volume = array.new<float>()
trimmed_levels = array.new<level>()
trimmed_ratio = array.new<float>()
for i = 0 to math.max(1, window_size) - 1
High = high[i + n]
Low = low[i + n]
Volume = volume[i + n]
state = open[i + n] < close[i + n]
for j = 0 to sample_size - 1
get_level = array.get(levels, j)
get_volume = get_vol(get_level.start, get_level.end, Low, High, Volume)
array.set(volume_sum, j, array.get(volume_sum, j) + get_volume)
if state
array.set(bullish_volume, j, array.get(bullish_volume, j) + get_volume)
filtered_volume = smoothing > 1 ? sinc_filter(volume_sum, smoothing) : volume_sum
min_volume = array.min(volume_sum)
max_volume = array.max(volume_sum)
min_volume_filter = array.min(filtered_volume)
max_volume_filter = array.max(filtered_volume)
for k = 0 to sample_size - 1
vol_sum = min_max(array.get(volume_sum, k), min_volume, max_volume)
vol_bull = min_max(array.get(bullish_volume, k), min_volume, max_volume)
vol_filt = min_max(array.get(filtered_volume, k), min_volume_filter, max_volume_filter)
get_level = array.get(levels, k)
mid_point = math.avg(get_level.end, get_level.start)
if mid_point >= bb_bottom[n] and mid_point <= bb_top[n]
array.push(trimmed_volume, vol_filt)
array.push(trimmed_ratio, vol_bull)
array.push(trimmed_levels, get_level)
if array.size(trimmed_volume) > 0
rank_75 = array.percentile_linear_interpolation(trimmed_volume, 75)
rank_25 = array.percentile_linear_interpolation(trimmed_volume, 30)
median = array.median(trimmed_volume)
for j = 0 to array.size(trimmed_volume) - 1
vol = array.get(trimmed_volume, j)
ratio = array.get(trimmed_ratio, j)
price = array.get(trimmed_levels, j)
colour = color.new(color.from_gradient(ratio, 0, 1, low_color, high_color), rescale_invert(vol, alpha))
test_box = box.new(bar_index - n, price.end, bar_index - n - 1, price.start, colour, bgcolor = colour, text = score(vol, rank_75, rank_25, median, score_enable), text_color = text_color)
array.unshift(boxes,
test_box
)
var source_distribution = array.new<int>()
var source_values = array.new<float>()
if flag and style == "Z-Score"
source = math.round((close - average)/stdev, 2)
if array.includes(source_values, source)
index = array.indexof(source_values, source)
array.set(source_distribution, index, array.get(source_distribution, index) + 1)
else
array.push(source_values, source)
array.push(source_distribution, 1)
if window_size > 0 and array.size(source_values) > window_size
array.shift(source_values)
array.shift(source_distribution)
if barstate.islast
for n = look_back - 1 to 0
sorted_source_distribution = array.new<int>()
sorted_source_values = array.new<float>()
for i = 0 to array.size(source_values) - 1
index = array.indexof(source_values, array.max(source_values, i))
array.push(sorted_source_values, array.get(source_values, index))
array.push(sorted_source_distribution, array.get(source_distribution, index))
sample_window = window_size == 0 or window_size > sample_size ? sample_size : window_size - 1
resampled_source_distribution = array.new<int>(sample_window + 1, 0)
resampled_source_values = array.new<level>(sample_window + 1, level.new(0, 0))
chunk_size = math.ceil((array.size(sorted_source_values) - 1) / (sample_window + 1))
if sample_window == sample_size
for i = 0 to sample_size //resample
start_idx = i * chunk_size
end_idx = math.min((i + 1) * chunk_size - 1, array.size(sorted_source_values) - 1)
total_distribution = 0
for j = start_idx to end_idx
total_distribution += array.get(sorted_source_distribution, j)
if end_idx >= array.size(sorted_source_values) - 1
break
array.set(resampled_source_distribution, i, total_distribution)
array.set(resampled_source_values, i, level.new(array.get(sorted_source_values, start_idx), array.get(sorted_source_values, end_idx)))
else
for i = 0 to sample_window
array.set(resampled_source_distribution, i, array.get(sorted_source_distribution, i))
array.set(resampled_source_values, i, level.new(array.get(sorted_source_values, i), array.get(sorted_source_values, math.min(i + 1, sample_window))))
filtered_distribution = smoothing > 1 ? sinc_filter(resampled_source_distribution, smoothing) : resampled_source_distribution
normalized_source_distribution = array.new<float>(sample_window)
max = array.max(filtered_distribution)
min = array.min(filtered_distribution)
for i = 0 to sample_window - 1
array.set(normalized_source_distribution, i, math.max(0, (array.get(filtered_distribution, i) - min) / (max - min)))
rank_75 = array.percentile_linear_interpolation(normalized_source_distribution, 75)
rank_25 = array.percentile_linear_interpolation(normalized_source_distribution, 30)
mean = array.median(normalized_source_distribution)
for i = 0 to array.size(normalized_source_distribution) - 1
value = array.get(resampled_source_values, i)
top = price_from_z(value.end, average[n], stdev[n])
bottom = price_from_z(value.start, average[n], stdev[n])
weight = array.get(normalized_source_distribution, i)
colour = color.new(color.from_gradient(weight, 0, 1, low_color, high_color), rescale_invert(weight, alpha))
if weight > 0
array.set(boxes, i,
box.new(bar_index - n, top, bar_index - n - 1, bottom, colour, bgcolor = colour, text = score(weight, rank_75, rank_25, mean, score_enable), text_color = text_color)
)
if flag and barstate.isconfirmed and array.size(boxes) > 1
for i = array.size(boxes) - 1 to 0
box.delete(array.get(boxes, i))
array.remove(boxes, i)
plot(show ? average : na, "Average", dev_color)
plot(show ? bb_top : na, "Top", dev_color)
plot(show ? bb_bottom : na, "Bottom", dev_color) |
Are stop orders making money? [yohtza] | https://www.tradingview.com/script/SEAjZtCZ-Are-stop-orders-making-money-yohtza/ | yohtza | https://www.tradingview.com/u/yohtza/ | 79 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © yohtza
//@version=5
indicator("Are stop orders making money? [yohtza]", overlay = true)
import yohtza/Bpa/12
scan_for_dojis = input.bool(true, "Scan for doji signal bars")
alerts = input.bool(false, "Recieve an alert once stop order makes money")
color bl_border_color = input.color(color.new(color.gray, 100), "Border color - bull")
color br_border_color = input.color(color.new(color.gray, 100), "Border color - bear")
color bl_bg_color = input.color(color.new(color.gray, 90), "Background color - bull")
color br_bg_color = input.color(color.new(color.gray, 90), "Background color - bear")
border_style = input.string(line.style_solid, "Border style", [line.style_solid, line.style_dotted, line.style_dashed])
ema_period = input.int(20, "Ema period", minval = 5, maxval=999)
tick = syminfo.mintick
ema = ta.ema(close, 20)
type BlTrade
float stop
float tp
int index
type BrTrade
float stop
float tp
int index
var bltrades = array.new<BlTrade>()
var brtrades = array.new<BrTrade>()
var bool blcondition = na
var bool brcondition = na
if scan_for_dojis
blcondition := barstate.isconfirmed and high < ema and (Bpa.isBullTrendBar() or Bpa.isDoji())
brcondition := barstate.isconfirmed and low > ema and (Bpa.isBearTrendBar() or Bpa.isDoji())
else
blcondition := barstate.isconfirmed and high < ema and (Bpa.isBullTrendBar() or Bpa.isDoji())
brcondition := barstate.isconfirmed and low > ema and (Bpa.isBearTrendBar() or Bpa.isDoji())
if blcondition
size = high - low
tp = high + size + tick
stop = low - tick
trade = BlTrade.new(stop, tp, bar_index)
bltrades.push(trade)
if brcondition
size = high - low
tp = low - size - tick
stop = high + tick
trade = BrTrade.new(stop, tp, bar_index)
brtrades.push(trade)
if bltrades.size() > 0
for [index, value] in bltrades
if high > value.tp
// bull made money
box.new(value.index -1, value.tp, value.index + 1, value.stop, border_color = bl_border_color, bgcolor = bl_bg_color, border_style = border_style)
bltrades.remove(index)
if alerts
alert("stop order bulls made money")
break
if low < value.stop
// stop hit
bltrades.remove(index)
if brtrades.size() > 0
for [index, value] in brtrades
if low < value.tp
// bears made money
box.new(value.index -1, value.tp, value.index + 1, value.stop, border_color = br_border_color, bgcolor = br_bg_color, border_style = border_style)
brtrades.remove(index)
if alerts
alert("stop order bears made money")
break
if high > value.stop
// stop hit
brtrades.remove(index)
|
Hybrid EMA AlgoLearner | https://www.tradingview.com/script/4jhuhtMN-Hybrid-EMA-AlgoLearner/ | Uldisbebris | https://www.tradingview.com/u/Uldisbebris/ | 123 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Uldisbebris
//@version=5
indicator("Hybrid EMA AlgoLearner", shorttitle="Hybrid EMA AlgoLearner", overlay=false)
// Parameters for EMAs
shortTermPeriod = 50
longTermPeriod = 200
// k-NN parameter
k = input.int(5, 'K - Number of neighbors')
// Calculate EMAs
shortTermEma = ta.ema(close, shortTermPeriod)
longTermEma = ta.ema(close, longTermPeriod)
// Custom k-NN Algorithm for weighted EMA
var float[] distances = array.new_float(0)
array.clear(distances)
for i = 1 to 100 by 1 // Loop through past 100 data points
distance = math.abs(shortTermEma - longTermEma[i])
array.push(distances, distance)
array.sort(distances)
k_distances = array.new_float(0)
for i = 0 to k - 1 by 1
array.push(k_distances, array.get(distances, i))
// Calculate weighted EMA based on closest k distances
weightShortTermEma = 0.0
totalWeight = 0.0
for i = 0 to k - 1 by 1
weight = array.get(k_distances, i)
weightShortTermEma += shortTermEma[i] * weight
totalWeight += weight
weightShortTermEma /= totalWeight
// Scale weightShortTermEma between 0 - 100
var float minEma = na
var float maxEma = na
// Instead of all the history, only look at the last N bars.
lookbackPeriod = input.int(400, 'lookbackPeriod')
minEma := ta.lowest(weightShortTermEma, lookbackPeriod)
maxEma := ta.highest(weightShortTermEma, lookbackPeriod)
scaledWeightShortTermEma = (weightShortTermEma - minEma) / (maxEma - minEma) * 100
//== plot
emaplot = plot(scaledWeightShortTermEma, title='Scaled Weighted Short-Term EMA', color = color.new(#a6a8a3, 0), linewidth = 1)
midLinePlot = plot(50, color = na, editable = false, display = display.none)
// Fill between plots and add horizontal lines
fill(emaplot, midLinePlot, 105, 85, top_color = color.new(#057ec4, 0), bottom_color = color.new(#6ca800, 100), title = "Overbought Gradient Fill")
fill(emaplot, midLinePlot, 15, -5, top_color = color.new(#a83c91, 100), bottom_color = color.new(#fcf801, 0), title = "Oversold Gradient Fill")
hline(15, color = color.new(#8b3131, 50))
hline(50, color = color.new(color.gray, 49))
hline(85, color = color.new(#2c5c2e, 50))
|
MA Directional Table | https://www.tradingview.com/script/UQqQ1GrD-MA-Directional-Table/ | angelh584 | https://www.tradingview.com/u/angelh584/ | 47 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Written by © angelh584
// idea by @Cooladoola
//@version=5
indicator("MA Directional Table", overlay=true)
//===== VARIABLES =====\\
var float histSeries = na
var color cloudColor = na
var int yellowCount = 0
var int greenCount = 0
var int redCount = 0
//===== GROUPS =====\\
g1="▶───────── MA Settings ─────────◀"
g2="▶───────── Table Settings ─────────◀"
g4="▶───────── Cloud Settings ─────────◀"
g5="▶───────── Extra MA ─────────◀"
g3="▶───────── Customize Table ─────────◀"
//===== INPUTS =====\\
//MA Cross
maType = input.string("EMA", title="Moving Average Type", options=["SMA", "EMA", "VWMA"], tooltip="MA type & lengths are calculated for table", group=g1)
shortTermLength = input.int(9, title="MA 1", group=g1, inline="1")
ma1Color = input.color(color.blue, title="ㅤ", group=g1, inline="1")
longTermLength = input.int(21, title="MA 2", group=g1, inline="2")
ma2Color = input.color(color.red, title="ㅤ", group=g1, inline="2")
//Table
position = input.string("top_right", title="Table Position", options=["top_left", "top_right", "bottom_left", "bottom_right"], group=g2)
orientation = input.string("horizontal", title="Table Orientation", options=["horizontal", "vertical"], group=g2)
usePriceCondition = input.bool(false, title="Use Price Condition", tooltip="The table color changes to yellow if the current price differs from the MA trend & crosses MA1.", group=g2)
//Cloud
showCloud = input.bool(false, title="Show MA Cloud", tooltip="Toggle to show or hide the moving average cloud.", group=g4)
cloudBullishColor = input.color(color.new(color.green, 90), title="Bullish Cloud Color", group=g4)
cloudBearishColor = input.color(color.new(color.red, 90), title="Bearish Cloud Color", group=g4)
//Extra MA
extraMAToggle = input.bool(false, title="Add Extra MAㅤ", inline ="4", group=g5)
includeExtraMATable = input.bool(false, title="Include In Table", group=g5, inline="4", tooltip="Value for Extra MA will be displayed on Table. Price Condition will still be displayed with background color")
extraMAType = input.string("SMA", title="Extra MA Type", options=["SMA", "EMA", "VWMA"], group=g5)
extraMALength = input.int(200, title="Extra MA Length", group=g5, inline="3")
extraMAColor = input.color(color.purple, title="ㅤ", group=g5, inline="3")
//Table Customize
bullishBackgroundColor = input.color(color.green, title="Bullish Status Color", tooltip="Choose the status color for bullish status in the table.", group=g3)
bearishBackgroundColor = input.color(color.red, title="Bearish Status Color", tooltip="Choose the status color for bearish status in the table.", group=g3)
neutralBackgroundColor = input.color(color.gray, title="Neutral Status Color", tooltip="Choose the status color for neutral status in the table.", group=g3)
priceConditionBackgroundColor = input.color(color.yellow, title="Price Condition Status Color", tooltip="Choose the status color for when the price condition is met.", group=g3)
tableHeaderColor = input.color(#c8e6c9, title="Table Header Color", tooltip="Sets the status color for the header row in the table. This color will be applied to cells like 'Timeframe' and 'Status'.", group=g3)
textColor = input.color(color.black, title="Table Text Color", group=g3, tooltip="Sets text color for table")
textSize = input.string("normal", title="Table Text Size", options=["small", "normal", "large"], group=g3)
//===== FUNCTIONS =====\\
calcMA(src, length) =>
ma = 0.0
if maType == "SMA"
ma := ta.sma(src, length)
else if maType == "EMA"
ma := ta.ema(src, length)
else if maType == "VWMA"
ma := ta.vwma(src, length)
ma
//===== CALCULATIONS =====\\
calcExtraMA(src, length) =>
ma = 0.0
if extraMAType == "SMA"
ma := ta.sma(src, length)
else if extraMAType == "EMA"
ma := ta.ema(src, length)
else if extraMAType == "VWMA"
ma := ta.vwma(src, length)
ma
maStatus(timeframe) =>
shortMA = request.security(syminfo.tickerid, timeframe, calcMA(close, shortTermLength), lookahead=barmerge.lookahead_off)
longMA = request.security(syminfo.tickerid, timeframe, calcMA(close, longTermLength), lookahead=barmerge.lookahead_off)
extraMAValue = request.security(syminfo.tickerid, timeframe, calcExtraMA(close, extraMALength), lookahead=barmerge.lookahead_off)
closePrice = request.security(syminfo.tickerid, timeframe, close, lookahead=barmerge.lookahead_off)
status = "neutral"
bgColor = neutralBackgroundColor
if shortMA > longMA
status := "bullish"
bgColor := usePriceCondition ? (closePrice < shortMA ? priceConditionBackgroundColor : bullishBackgroundColor) : bullishBackgroundColor
else if shortMA < longMA
status := "bearish"
bgColor := usePriceCondition ? (closePrice > shortMA ? priceConditionBackgroundColor : bearishBackgroundColor) : bearishBackgroundColor
if includeExtraMATable and extraMAToggle
status := str.tostring(math.round(extraMAValue * 100) / 100)
[status, bgColor]
isBullishTimeframe(tf) =>
[status, _] = maStatus(tf)
status == "bullish"
isBearishTimeframe(tf) =>
[status, _] = maStatus(tf)
status == "bearish"
//===== TABLE CREATION =====\\
rows = orientation == "horizontal" ? 7 : 1
cols = orientation == "horizontal" ? 2 : 14
var table panel = table.new(position, rows, cols)
table.cell(panel, 0, 0, "Timeframe", bgcolor=tableHeaderColor, text_size=textSize)
table.cell(panel, 0, 1, "Status", bgcolor=tableHeaderColor, text_size=textSize)
createTableCell(timeframe, row, col, label) =>
[status, colorCode] = maStatus(timeframe)
table.cell(panel, row, col, label, bgcolor=tableHeaderColor, text_color=textColor, text_size=textSize)
table.cell(panel, row, col + 1, status, bgcolor=colorCode, text_color=textColor, text_size=textSize)
if orientation == "horizontal"
createTableCell("1", 1, 0, "1 min")
createTableCell("5", 2, 0, "5 mins")
createTableCell("15", 3, 0, "15 mins")
createTableCell("60", 4, 0, "1 hour")
createTableCell("240", 5, 0, "4 hours")
createTableCell("D", 6, 0, "1 day")
else
createTableCell("1", 0, 2, "1 min")
createTableCell("5", 0, 4, "5 mins")
createTableCell("15", 0, 6, "15 mins")
createTableCell("60", 0, 8, "1 hour")
createTableCell("240", 0, 10, "4 hours")
createTableCell("D", 0, 12, "1 day")
//===== MAIN CALCULATIONS =====\\
shortMA_current = calcMA(close, shortTermLength)
longMA_current = calcMA(close, longTermLength)
cloudColor := shortMA_current > longMA_current ? cloudBullishColor : cloudBearishColor
allBullish = isBullishTimeframe("1") and isBullishTimeframe("5") and isBullishTimeframe("15") and isBullishTimeframe("60") and isBullishTimeframe("240") and isBullishTimeframe("D")
allBearish = isBearishTimeframe("1") and isBearishTimeframe("5") and isBearishTimeframe("15") and isBearishTimeframe("60") and isBearishTimeframe("240") and isBearishTimeframe("D")
bullishCount = (isBullishTimeframe("1") ? 1 : 0) + (isBullishTimeframe("5") ? 1 : 0) + (isBullishTimeframe("15") ? 1 : 0) + (isBullishTimeframe("60") ? 1 : 0) + (isBullishTimeframe("240") ? 1 : 0) + (isBullishTimeframe("D") ? 1 : 0)
bearishCount = 6 - bullishCount
//===== PLOT MA =====\\
plot1 = plot(shortMA_current, color=ma1Color, title="MA Length 1")
plot2 = plot(longMA_current, color=ma2Color, title="MA Length 2")
//===== FILL MA CLOUD =====\\
fillCondition = showCloud ? cloudColor : na
fill(plot1, plot2, color=fillCondition, title="MA Cloud")
//===== PLOT EXTRA MA =====\\
extraMA_current = extraMAToggle ? calcExtraMA(close, extraMALength) : na
plot(extraMA_current, color=extraMAColor, title="Extra MA")
//===== ALERT CONDITIONS =====\\
// Check for bullish or bearish crossover
crossAboveCondition = ta.crossover(shortMA_current, longMA_current)
crossBelowCondition = ta.crossunder(shortMA_current, longMA_current)
alertcondition(crossAboveCondition, title="Bullish Crossover", message="Bullish Cross!")
alertcondition(crossBelowCondition, title="Bearish Crossover", message="Bearish Cross!")
alertcondition(allBullish, title="All Timeframes Bullish", message="All timeframes are showing a bullish trend!")
alertcondition(allBearish, title="All Timeframes Bearish", message="All timeframes are showing a bearish trend!")
alertcondition(bullishCount >= 4, title="Most Timeframes Bullish", message="4 or more timeframes are bullish.")
alertcondition(bearishCount >= 4, title="Most Timeframes Bearish", message="4 or more timeframes are bearish.")
alertcondition(greenCount == 2 and redCount == 2 and yellowCount == 2, title="Coherence", message="Exactly 2 green, 2 red, and 2 yellow statuses across timeframes.") |
Global Liquidity Tav | https://www.tradingview.com/script/oGw3vukA-Global-Liquidity-Tav/ | tavishsri | https://www.tradingview.com/u/tavishsri/ | 3 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tav
//@version=5
indicator("Global Liquidity ", overlay=false)
// Calculate the global liquidity value using the formula
us = request.security("FRED:WALCL", 'M', close)
us_RRP = request.security("FRED:RRPONTSYD", 'M', close)
us_TGA = request.security("FRED:WTREGEN", 'M', close)
eu = request.security("FRED:ECBASSETSW", 'M', close)* request.security("FX:EURUSD", timeframe.period, close)
jp = request.security("FRED:JPNASSETS", 'M', close)/ request.security("FX:USDJPY", timeframe.period, close)
cn_m2 = request.security("ECONOMICS:CNM2", 'M', close) / request.security("FX:USDCNH", timeframe.period, close)
cn = cn_m2/9.22 //Approx of total assets from China's M2
us_funding_liquidity = (us - us_RRP - us_TGA)
global_ex_china = (us_funding_liquidity + eu + jp)/ 1000000000000
china = cn/1000000000000
global = global_ex_china + china
// Calculating percentage change from the previous period
percentChange = ((global - ta.valuewhen(true, global, 1)) / ta.valuewhen(true, global, 1)) * 100
cumulativePercentChange = ta.cum(percentChange)
length = 100 // Specify the length manually
lowestValue = ta.lowest(cumulativePercentChange, length)
highestValue = ta.highest(cumulativePercentChange, length)
oscillator = ((cumulativePercentChange - lowestValue) / (highestValue - lowestValue)) * 100
//plot(percentChange, "Percent change", color=color.blue, trackprice=true)
plot(global, "Global liquidity in $Bn", color=color.green, trackprice=true)
//plot(global_ex_china, "US-EU-JP", color =color.green, trackprice=true)
//plot(china, "China liquidity approx", color =color.red, trackprice=true)
|
Local Volatility | https://www.tradingview.com/script/G1TrcU9W-Local-Volatility/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 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/
// © RicardoSantos
//@version=5
indicator('Local Volatility')
//The traditional calculation of volatility involves computing the standard deviation of returns,
// which is based on the mean return. However, when the asset price exhibits a trending behavior,
// the mean return could be significantly different from zero, and changing the length of the time
// window used for the calculation could result in artificially high volatility values. This is because
// more returns would be further away from the mean, leading to a larger sum of squared deviations.
// To address this issue, our Local Volatility measure computes the standard deviation of the
// differences between consecutive asset prices, rather than their returns. This provides a measure of
// how much the price changes from one tick to the next, irrespective of the overall trend.
// ref: https://arxiv.org/abs/2308.14235
int length_01 = input(10)
int length_02 = input(15)
int length_03 = input(50)
slv (src, t) => math.sqrt(ta.sma(math.pow(src - src[1], 2.0), t))
clv (src) => math.sqrt(ta.cum(math.pow(src - src[1], 2.0) / (bar_index + 1)))
plot(slv(close, length_01), 'short therm', #ff0000)
plot(slv(close, length_02), 'short therm', #ff4800)
plot(slv(close, length_03), 'short therm', #ff9900)
plot(clv(close), 'long therm', #0080ff)
|
NQ vs ES | https://www.tradingview.com/script/A4oxDv7z-NQ-vs-ES/ | deivydas.rapalis | https://www.tradingview.com/u/deivydas.rapalis/ | 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/
// © deivydas.rapalis
//@version=5
indicator("NQ vs ES", overlay = true)
// Calculate the price change percentage for ES and NQ
esPriceChange = ((request.security("ES1!", "D", close) - request.security("ES1!", "D", close[1])) / request.security("ES1!", "D", close[1])) * 100
nqPriceChange = ((request.security("NQ1!", "D", close) - request.security("NQ1!", "D", close[1])) / request.security("NQ1!", "D", close[1])) * 100
// Calculate the spread between NQ and ES price change percentages
spread = nqPriceChange - esPriceChange
// Plot ES price change percentage
plot(esPriceChange, title = "ES", color = color.green)
// Plot NQ price change percentage
plot(nqPriceChange, title = "NQ", color = color.red)
// Plot spread between NQ and ES price change percentages
plot(spread, title = "Spread", color = color.yellow)
// Plot a 0 value line
hline(0, "Zero Line", color = color.gray)
|
Support & Resistance PRO | https://www.tradingview.com/script/s8ZjVeUE-Support-Resistance-PRO/ | AlexShech | https://www.tradingview.com/u/AlexShech/ | 223 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AlexShech
//@version=5
indicator("Support & Resistance PRO", overlay=true)
inpPeriod = input.int(defval = 30, title='Look Back Period')
inpRF = input.timeframe('D', "Medium Time Frame")
inpRF2 = input.timeframe('W', "Macro Time Frame")
inpShow1 = input.bool(defval=true,title='Show Medium Target')
inpShow2 = input.bool(defval=true,title='Show Macro Target')
PDH15 = request.security(syminfo.tickerid, inpRF, ta.highest(close, inpPeriod))
PDL15 = request.security(syminfo.tickerid, inpRF, ta.lowest(close, inpPeriod))
PDH15w = request.security(syminfo.tickerid, inpRF, ta.highest(high, inpPeriod))
PDL15w = request.security(syminfo.tickerid, inpRF, ta.lowest(low, inpPeriod))
PDH60 = request.security(syminfo.tickerid, inpRF2, ta.highest(close, inpPeriod))
PDL60 = request.security(syminfo.tickerid, inpRF2, ta.lowest(close, inpPeriod))
PDH60w = request.security(syminfo.tickerid, inpRF2, ta.highest(high, inpPeriod))
PDL60w = request.security(syminfo.tickerid, inpRF2, ta.lowest(low, inpPeriod))
var line pdh = na
var line pdl = na
var line pdhw = na
var line pdlw = na
var line pdh4 = na
var line pdl4 = na
var line pdh4w = na
var line pdl4w = na
if barstate.islast and inpShow1 == true
pdh := line.new(bar_index-1, PDH15, bar_index, PDH15, extend=extend.both, color=color.rgb(65, 255, 71))
pdl := line.new(bar_index-1, PDL15, bar_index, PDL15, extend=extend.both, color=color.rgb(251, 65, 65))
pdhw := line.new(bar_index-1, PDH15w, bar_index, PDH15w, extend=extend.both, color=color.rgb(100, 100, 100, 62))
pdlw := line.new(bar_index-1, PDL15w, bar_index, PDL15w, extend=extend.both, color=color.rgb(100, 100, 100, 59))
linefill.new(pdh,pdhw,color.rgb(73, 73, 73, 77))
linefill.new(pdl,pdlw,color.rgb(73, 73, 73, 75))
if barstate.islast and inpShow2 == true
pdh4 := line.new(bar_index-1, PDH60, bar_index, PDH60, extend=extend.both, color=color.rgb(255, 255, 255))
pdl4 := line.new(bar_index-1, PDL60, bar_index, PDL60, extend=extend.both, color=color.rgb(255, 255, 255))
pdh4w := line.new(bar_index-1, PDH60w, bar_index, PDH60w, extend=extend.both, color=color.rgb(127, 127, 127, 47))
pdl4w := line.new(bar_index-1, PDL60w, bar_index, PDL60w, extend=extend.both, color=color.rgb(127, 127, 127, 47))
linefill.new(pdh4,pdh4w,color.rgb(0, 13, 253, 90))
linefill.new(pdl4,pdl4w,color.rgb(0, 13, 253, 90))
line.delete(pdh[1])
line.delete(pdl[1])
line.delete(pdh4[1])
line.delete(pdl4[1])
line.delete(pdh4w[1])
line.delete(pdl4w[1])
// lastBig = request.security(syminfo.tickerid, inpBig, close[barstate.isrealtime ? 1 : 0]) //previous close
|
Multiple Ticker Stochastic RSI | https://www.tradingview.com/script/awz4VLuz-Multiple-Ticker-Stochastic-RSI/ | sxiong1111 | https://www.tradingview.com/u/sxiong1111/ | 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/
// © sxiong1111
// Script Created On: 8/29/2023
// Script Updated On: 8/29/2023
// Script Version: 1.0
// Research Source: https://www.investopedia.com/terms/s/stochrsi.asp
// Description: According to Investopedia, the Stochastic RSI is a technical indicator ranging between 0 and 100, based on applying the Stochastic oscillator formula to a set of relative strength index (RSI). This gives users a better
// sense of whether the current RSI value is overbought or oversold. When the value is above 80, the security's price is considered overbought. When the value is below 20, the security's price is considered oversold.
// The goal of this indicator is to compare 3 different tickers, averaging the resulting data and then outputting the results in a standard Stochastic RSI view.
// Formula: Stochastic RSI = (RSI - min[RSI]) / (max[RSI] - min[RSI])
//@version=5
indicator(title = "Multiple Ticker Stochastic RSI", shorttitle = "MTS RSI", format = format.price, precision = 2, timeframe = "", timeframe_gaps = true)
ticker1 = input.string(defval = "", title = "Ticker Symbol 1", tooltip = "This field is always locked to the ticker symbol for the current chart window that's in scope.\n\nAny text entries in this text field will have no effect. This means that if your current charting window is on SPY, this ticker will be SPY.", group = "Tickers")
ticker2 = input.symbol(defval = "NDAQ", title = "Ticker Symbol 2", tooltip = "User-defined ticker # 2", group = "Tickers")
ticker3 = input.symbol(defval = "DIA", title = "Ticker Symbol 3", tooltip = "User-defined ticker # 3", group = "Tickers")
kLineSetting = input.bool(defval = false, title = "Show K Lines Separately", tooltip = "If enabled, there will be three different K lines; each for the three different tickers. The single D line will be the average of all three tickers.\n\nIf disabled, the data from three different tickers will be averaged into a single K line.", group = "Stochastic RSI Settings")
smoothKDouble = input.bool(defval = false, title = "Apply Double K Smoothing", tooltip = "If enabled, the K data will have double smoothing, which can help you visualize the directional movement better with reduced sharp K and D lines. If disabled, the K data will retain its standard smoothing.\n\nAlso, note that if you enable this setting and the buy and/or sell visual indicator, you can potentially see an early buy/sell entry.", group = "Stochastic RSI Settings")
smoothK = input.int(defval = 3, title = "Smooth K", minval = 1, group = "Stochastic RSI Settings")
smoothD = input.int(defval = 3, title = "Smooth D", minval = 1, group = "Stochastic RSI Settings")
lengthRSI = input.int(defval = 14, title = "RSI Length", minval = 1, group = "Stochastic RSI Settings")
lengthStochastic = input.int(defval = 14, title = "Stochastic Length", minval = 1, group = "Stochastic RSI Settings")
bandUpper = input.int(defval = 80, title = "Overbought Line Level", minval = -50, maxval = 150, tooltip = "This is the Stochastic RSI overbought level. The default is 80.", group = "Stochastic RSI Settings")
bandMiddle = input.int(defval = 50, title = "Middle Line Level", minval = -50, maxval = 150, tooltip = "This is the Stochastic RSI middle level. The default is 50.", group = "Stochastic RSI Settings")
bandLower = input.int(defval = 20, title = "Oversold Line Level", minval = -50, maxval = 150, tooltip = "This is the Stochastic RSI oversold level. The default is 20.", group = "Stochastic RSI Settings")
maType = input.string(defval = "SMA", title = "Moving Average Calculation Type", options = ["SMA", "EMA", "HULL", "VOLUME WEIGHT"], tooltip = "You can choose either SMA, EMA, HULL or VOLUME WEIGHTED moving averages for the data calculations.", group = "Stochastic RSI Visual Settings")
smoothKColor1 = input.color(color.new(#FCCF3E, 10), title = "Smooth K Line Color (Ticker 1)", tooltip = "This is the K line color of the ticker in the current chart window.", group = "Stochastic RSI Visual Settings")
smoothKColor2 = input.color(color.new(#8AC287, 10), title = "Smooth K Line Color (Ticker 2)", tooltip = "This is the K line color of ticker #2.", group = "Stochastic RSI Visual Settings")
smoothKColor3 = input.color(color.new(#AA96C6, 10), title = "Smooth K Line Color (Ticker 3)", tooltip = "This is the K line color of ticker #3.", group = "Stochastic RSI Visual Settings")
smoothKColorA = input.color(color.new(#00A7E3, 10), title = "Smooth K Line Color (Average)", tooltip = "This is the average K line color, if you've disabled the 'Show K Lines Separately' settings above.", group = "Stochastic RSI Visual Settings")
smoothDColor = input.color(color.new(#ED6C00, 10), title = "Smooth D Line Color", tooltip = "This is the D line color.", group = "Stochastic RSI Visual Settings")
kLineStyle = input.int(defval = 1, title = "Smooth K Line Thickness", minval = 1, maxval = 10, tooltip = "This is the line thickness for the Smooth K line. The numerical value setting here affects all K lines.", group = "Stochastic RSI Visual Settings")
dLineStyle = input.int(defval = 1, title = "Smooth D Line Thickness", minval = 1, maxval = 10, tooltip = "This is the line thickness for the Smooth D line.", group = "Stochastic RSI Visual Settings")
ulBandLineColor = input.color(color.new(#9F9F99, 50), title = "Upper/Lower Band Line Color", tooltip = "This is the line color of both the upper and lower band lines.", group = "Stochastic RSI Visual Settings")
mmBandLineColor = input.color(color.new(#9F9F99, 80), title = "Middle Band Line Color", tooltip = "This is the line color of the middle band line.", group = "Stochastic RSI Visual Settings")
bandFillColor = input.color(color.new(#AE9183, 95), title = "Band Background Fill Color", tooltip = "This is the background fill color of the band.", group = "Stochastic RSI Visual Settings")
bandLineStyle = input.string(defval = "Dashed", title = "Upper/Lower Band Line Style", options = ["Solid", "Dotted", "Dashed"], tooltip = "This is the line style for the upper and lower bands.", group = "Stochastic RSI Visual Settings")
bandMiddleLineStyle = input.string(defval = "Dashed", title = "Middle Band Line Style", options = ["Solid", "Dotted", "Dashed"], tooltip = "This is the line style for the middle band.", group = "Stochastic RSI Visual Settings")
showBuySignal = input.bool(defval = false, title = "Show Potential Buy Signals", tooltip = "If enabled, the potential buy signals are shown.\n\nPlease note that the potential buy signals only work off the average K all 3 tickers. This is irrespective if you choose to show all 3 K lines separately or not.", group = "Stochastic RSI Visual Settings")
showSellSignal = input.bool(defval = false, title = "Show Potential Sell Signals", tooltip = "If enabled, the potential sell signals are shown.\n\nPlease note that the potential sell signals only work off the average K all 3 tickers. This is irrespective if you choose to show all 3 K lines separately or not.", group = "Stochastic RSI Visual Settings")
buySignalColor = input.color(color.new(#42B9AC, 20), title = "Potential Buy Signal Color", tooltip = "This is the potential buy signal color.", group = "Stochastic RSI Visual Settings")
sellSignalColor = input.color(color.new(#CD4479, 20), title = "Potential Sell Signal Color", tooltip = "This is the potential sell signal color.", group = "Stochastic RSI Visual Settings")
buySellSignalSize = input.int(defval = 5, title = "Potential Buy/Sell Signal Visual Indicator Size", minval = 1, maxval = 20, tooltip = "This is the user-defined size of the potential buy/sell visual indicator.", group = "Stochastic RSI Visual Settings")
src1 = close
src2 = request.security(ticker2, timeframe.period, close)
src3 = request.security(ticker3, timeframe.period, close)
bLineStyle = hline.style_dashed
if (bandLineStyle == "Solid")
bLineStyle := hline.style_solid
if (bandLineStyle == "Dotted")
bLineStyle := hline.style_dotted
bmLineStyle = hline.style_dashed
if (bandMiddleLineStyle == "Solid")
bmLineStyle := hline.style_solid
if (bandMiddleLineStyle == "Dotted")
bmLineStyle := hline.style_dotted
rsi = 0.00
k = 0.00
k1 = 0.00
k2 = 0.00
k3 = 0.00
d = 0.00
dAVG = 0.00
avgSRC = math.avg(src1, src2, src3)
enableAVG = true
if (maType == "EMA")
if (kLineSetting == true)
rsi1 = ta.rsi(src1, lengthRSI)
k1 := ta.ema(ta.stoch(rsi1, rsi1, rsi1, lengthStochastic), smoothK)
if (smoothKDouble == true)
k1 := ta.ema(k1, smoothK)
d1 = ta.ema(k1, smoothD)
rsi2 = ta.rsi(src2, lengthRSI)
k2 := ta.ema(ta.stoch(rsi2, rsi2, rsi2, lengthStochastic), smoothK)
if (smoothKDouble == true)
k2 := ta.ema(k2, smoothK)
d2 = ta.ema(k2, smoothD)
rsi3 = ta.rsi(src3, lengthRSI)
k3 := ta.ema(ta.stoch(rsi3, rsi3, rsi3, lengthStochastic), smoothK)
if (smoothKDouble == true)
k3 := ta.ema(k3, smoothK)
d3 = ta.ema(k3, smoothD)
dAVG := math.avg(d1, d2, d3)
else
enableAVG := false
rsi := ta.rsi(avgSRC, lengthRSI)
k := ta.ema(ta.stoch(rsi, rsi, rsi, lengthStochastic), smoothK)
if (smoothKDouble == true)
k := ta.ema(k, smoothK)
d := ta.ema(k, smoothD)
else if (maType == "SMA")
if (kLineSetting == true)
rsi1 = ta.rsi(src1, lengthRSI)
k1 := ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStochastic), smoothK)
if (smoothKDouble == true)
k1 := ta.sma(k1, smoothK)
d1 = ta.sma(k1, smoothD)
rsi2 = ta.rsi(src2, lengthRSI)
k2 := ta.sma(ta.stoch(rsi2, rsi2, rsi2, lengthStochastic), smoothK)
if (smoothKDouble == true)
k2 := ta.sma(k2, smoothK)
d2 = ta.sma(k2, smoothD)
rsi3 = ta.rsi(src3, lengthRSI)
k3 := ta.sma(ta.stoch(rsi3, rsi3, rsi3, lengthStochastic), smoothK)
if (smoothKDouble == true)
k3 := ta.sma(k3, smoothK)
d3 = ta.sma(k3, smoothD)
dAVG := math.avg(d1, d2, d3)
else
enableAVG := false
rsi := ta.rsi(avgSRC, lengthRSI)
k := ta.sma(ta.stoch(rsi, rsi, rsi, lengthStochastic), smoothK)
if (smoothKDouble == true)
k := ta.sma(k, smoothK)
d := ta.sma(k, smoothD)
else if (maType == "HULL")
if (kLineSetting == true)
rsi1 = ta.rsi(src1, lengthRSI)
k1 := ta.hma(ta.stoch(rsi1, rsi1, rsi1, lengthStochastic), smoothK)
if (smoothKDouble == true)
k1 := ta.hma(k1, smoothK)
d1 = ta.hma(k1, smoothD)
rsi2 = ta.rsi(src2, lengthRSI)
k2 := ta.hma(ta.stoch(rsi2, rsi2, rsi2, lengthStochastic), smoothK)
if (smoothKDouble == true)
k2 := ta.hma(k2, smoothK)
d2 = ta.hma(k2, smoothD)
rsi3 = ta.rsi(src3, lengthRSI)
k3 := ta.hma(ta.stoch(rsi3, rsi3, rsi3, lengthStochastic), smoothK)
if (smoothKDouble == true)
k3 := ta.hma(k3, smoothK)
d3 = ta.hma(k3, smoothD)
dAVG := math.avg(d1, d2, d3)
else
enableAVG := false
rsi := ta.rsi(avgSRC, lengthRSI)
k := ta.hma(ta.stoch(rsi, rsi, rsi, lengthStochastic), smoothK)
if (smoothKDouble == true)
k := ta.hma(k, smoothK)
d := ta.hma(k, smoothD)
else
if (kLineSetting == true)
rsi1 = ta.rsi(src1, lengthRSI)
k1 := ta.vwma(ta.stoch(rsi1, rsi1, rsi1, lengthStochastic), smoothK)
if (smoothKDouble == true)
k1 := ta.vwma(k1, smoothK)
d1 = ta.vwma(k1, smoothD)
rsi2 = ta.rsi(src2, lengthRSI)
k2 := ta.vwma(ta.stoch(rsi2, rsi2, rsi2, lengthStochastic), smoothK)
if (smoothKDouble == true)
k2 := ta.vwma(k2, smoothK)
d2 = ta.vwma(k2, smoothD)
rsi3 = ta.rsi(src3, lengthRSI)
k3 := ta.vwma(ta.stoch(rsi3, rsi3, rsi3, lengthStochastic), smoothK)
if (smoothKDouble == true)
k3 := ta.vwma(k3, smoothK)
d3 = ta.vwma(k3, smoothD)
dAVG := math.avg(d1, d2, d3)
else
enableAVG := false
rsi := ta.rsi(avgSRC, lengthRSI)
k := ta.vwma(ta.stoch(rsi, rsi, rsi, lengthStochastic), smoothK)
if (smoothKDouble == true)
k := ta.vwma(k, smoothK)
d := ta.vwma(k, smoothD)
buyCrossOver = ta.crossover(k, d)
sellCrossOver = ta.crossunder(k, d)
buyCrossOverBand = false
sellCrossOverBand = false
if ((k >= d) and ta.cross(k, bandLower))
buyCrossOverBand := true
if ((k <= d) and ta.cross(k, bandUpper))
sellCrossOverBand := true
alertcondition(buyCrossOver, title = "Stochastic RSI Buy", message = "{{ticker}}: Stochastic RSI Crossed Over D")
alertcondition(buyCrossOver, title = "Stochastic RSI Sell", message = "{{ticker}}: Stochastic RSI Crossed Under D")
alertcondition(buyCrossOverBand, title = "Stochastic RSI Buy Oversold", message = "{{ticker}}: Stochastic RSI Crossed Over both D and Oversold Level")
alertcondition(sellCrossOverBand, title = "Stochastic RSI Sell Overbought", message = "{{ticker}}: Stochastic RSI Crossed Under both D and Overbought Level")
plot(enableAVG == true ? k1 : na, title = "Smooth K1", color = smoothKColor1, linewidth = kLineStyle, style = plot.style_line)
plot(enableAVG == true ? k2: na, title = "Smooth K2", color = smoothKColor2, linewidth = kLineStyle, style = plot.style_line)
plot(enableAVG == true ? k3 : na, title = "Smooth K3", color = smoothKColor3, linewidth = kLineStyle, style = plot.style_line)
plot(enableAVG == true ? dAVG : na, title = "Smooth D", color = smoothDColor, linewidth = dLineStyle, style = plot.style_line)
plot(enableAVG == false ? k : na, title = "Smooth K", color = smoothKColorA, linewidth = kLineStyle, style = plot.style_line)
plot(enableAVG == false ? d : na, title = "Smooth D", color = smoothDColor, linewidth = dLineStyle, style = plot.style_line)
LU = hline(bandUpper, title = "Band Upper", color = ulBandLineColor, linewidth = 1, linestyle = bLineStyle)
LL = hline(bandLower, title = "Band Lower", color = ulBandLineColor, linewidth = 1, linestyle = bLineStyle)
hline(bandMiddle, title = "Band Middle", color = mmBandLineColor, linewidth = 1, linestyle = bmLineStyle)
fill(LU, LL, title = "Fill Color", color = bandFillColor)
plot(buyCrossOverBand == true and showBuySignal == true ? bandLower : na, title = "Buy Signal", color = buySignalColor, linewidth = buySellSignalSize, style = plot.style_circles)
plot(sellCrossOverBand == true and showSellSignal == true ? bandUpper : na, title = "Sell Signal", color = sellSignalColor, linewidth = buySellSignalSize, style = plot.style_circles)
|
Bollinger Bands Heatmap (BBH) | https://www.tradingview.com/script/xA0P85kO-Bollinger-Bands-Heatmap-BBH/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 58 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("Bollinger Bands Heatmap", "BBH", true, max_boxes_count = 500)
min_max(source, min, max)=>
(source - min)/(max - min)
rescale_invert(x, n) =>
inverted = 1 - x
rescaled = (1 - inverted) * n + inverted * 100
rescaled
gaussian(x, mu, sigma) =>
(1.0 / (sigma * math.sqrt(2.0 * math.pi))) * math.exp(-((x - mu)*(x - mu)) / (2.0 * sigma * sigma))
scale = input.float(1, "Scale", minval = 0.125, step = 0.125, tooltip = "Scale the size of the heatmap.")
atr_length = input.int(100, "Scale ATR Length", minval = 5, tooltip = "The ATR used to scale the heatmap boxes.")
offset1 = input.float(0, "Offset", tooltip = "Offset mean by ATR.")
multiplier = input.float(2, "Multiplier", minval = 0, step = 0.2, tooltip = "Bollinger Bands Multiplier")
length = input.int(20, "Length", tooltip = "Length of SMA.")
alpha = input.int(60, "Heat Map Alpha", minval = 0, maxval = 100)
high_color = input.color(#2962ff, "Color", inline = "Colour")
low_color = input.color(#880e4f, "", inline = "Colour")
average = ta.sma(close, length)
sigma = ta.stdev(close, length) * multiplier
atr = ta.cum(high - low)/bar_index
mu = average + (offset1 > 0 ? atr/4 * offset1 : -(atr/4 * -offset1))
step = ta.atr(atr_length) * scale
boxes = array.new<box>()
source_distribution = array.new<float>()
source_values = array.new<float>()
flag = bar_index > length
if flag
max_val = gaussian(mu, mu, sigma)
float p = 1
int k = 0
while p != 0
value_start = average + step * k
value_end = average + step * (k + 1)
p := gaussian(value_start, mu, sigma)
colour = color.new(color.from_gradient(p, 0, max_val, low_color, high_color), rescale_invert(p/max_val, alpha))
array.push(boxes,
box.new(bar_index, value_end - step/2, bar_index - 1, value_start - step/2, colour, bgcolor = colour)
)
k += 1
k := 0
p := 1
while p != 0
value_start = average - step * k
value_end = average - step * (k + 1)
p := gaussian(value_start, mu, sigma)
colour = color.new(color.from_gradient(p, 0, max_val, low_color, high_color), rescale_invert(p/max_val, alpha))
array.push(boxes,
box.new(bar_index, value_end - step/2, bar_index - 1, value_start - step/2, colour, bgcolor = colour)
)
k += 1
|
Intraday Volatility Bars | https://www.tradingview.com/script/h8JqtFfy-Intraday-Volatility-Bars/ | weak_hand | https://www.tradingview.com/u/weak_hand/ | 15 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © weak_hand
//@version=5
indicator("Intraday Volatility Bars")
// ----------------------------------------------}
// INPUT AND VARIABLES
// ----------------------------------------------{
int bars_per_day = math.ceil(1440 / timeframe.multiplier)
var bars_count = int(0)
int length = input.int(14, "Length", 1, tooltip = "How many days back should be taken into account.")
var cumulative_volatility_bars = matrix.new<float>(bars_per_day, length)
var cumulative_volatility = float(0)
float true_range = ta.tr(false)
// ----------------------------------------------}
// CALCULATIONS
// ----------------------------------------------{
if session.isfirstbar
bars_count := 0
cumulative_volatility := high - low
cumulative_volatility_bars.add_col(0)
cumulative_volatility_bars.remove_col(length)
else
cumulative_volatility := cumulative_volatility + true_range
bars_count += 1
cumulative_volatility_bars.set(bars_count, 0, cumulative_volatility)
float[] volatility_rows = cumulative_volatility_bars.row(bars_count)
// ----------------------------------------------}
// OUTPUTS
// ----------------------------------------------{
plot(volatility_rows.avg(), "Average", color.gray, style = plot.style_columns)
plot(cumulative_volatility, "IVB", linewidth = 2, style = plot.style_circles)
|
Crypto/DXY Scoring | https://www.tradingview.com/script/bFHHWPJP-Crypto-DXY-Scoring/ | MXWLL-Capital-Trading | https://www.tradingview.com/u/MXWLL-Capital-Trading/ | 59 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KioseffTrading
//@version=5
indicator("Crypto/DXY Scoring", precision = 10, overlay = false, format = format.inherit, max_labels_count = 500, max_boxes_count = 500, max_lines_count = 500)
import HeWhoMustNotBeNamed/arraymethods/1
import RicardoSantos/MathOperator/2
sym = input.symbol(defval = "DXY", title = "Comparison Symbol")
back = input.int (defval = 3000, title = "Bars Back", minval = 5)
zlook = input.int (defval = 20, title = "General Z-Score Lookback (Affects Columns)", minval = 10)
lenco = input.int (defval = 100, title = "Comparator Lookback", minval = 10)
zord = input.string(defval = "Hedges' G", title = "Comparison Calc", options = ["Hedges' G", "Z Compare", "Glass's D", "Cliff D"])
col1 = input.color( defval = #6929F2, title = "Chart Crypto Color", inline = "a")
col2 = input.color( defval = #14D990, title = "Comparison Symbol Color", inline = "a")
dcol = input.color( defval = #18d720, title = "Reversal Up Col ", inline = "b")
ucol = input.color( defval = color.red, title = "Reversal Down Col ", inline = "b")
show = input.bool (defval = true, title = "Show Alternative RRG" , group = "Quadrant" )
len = input.int (defval = 100, minval = 5, title = "Relative Strength Length" , group = "Quadrant", inline = "1" )
lenx = input.int (defval = 5, minval = 5, title = "RS MOM Length" , group = "Quadrant", inline = "1" )
neon = input.bool (defval = true, title = "Show Neon" , group = "Quadrant" )
impcol = input.color(defval = color.blue, title = "Improving Color " , group = "Quadrant", inline = "20")
leacol = input.color(defval = color.green, title = "Leading Color" , group = "Quadrant", inline = "20")
detcol = input.color(defval = color.yellow, title = "Deteriorating Color" , group = "Quadrant", inline = "21"), barCond = float(last_bar_index - bar_index)
lagcol = input.color(defval = color.red, title = "Lagging Color" , group = "Quadrant", inline = "21"), recent = barCond.under_equal(back)
[index, i2, i1] = request.security(sym, timeframe.period, [math.log(close / close[zlook]), math.log(close / close[5]), math.log(close / close[1])])
type RSvalues
matrix <float> performances
matrix <float> rs
matrix <float> roc
var rsv = RSvalues.new(matrix.new<float>(29, 0), matrix.new<float>(29, 0), matrix.new<float>(29, 0))
var z3 = array.new_float() , var z4 = array.new_float(), var avgs = matrix.new<float>(4, 0)
var stringArr = array.from("BTC" , "ETH" , "BNB" , "XRP",
"ADA" , "DOGE" , "SOL" , "TRX",
"DOT" , "MATIC", "SHIB", "TON",
"LTC" , "WBTC" , "BCH" , "LEO",
"AVAX", "XLM" , "LINK", "UNI",
"OKB" , "XMR" , "ATOM", "ETC",
"HBAR", "ICP" , "FIL" , "MNT",
"APT"
)
req( string ) =>
logClose = request.security( string , timeframe.period, math.log(close / close[1]))
method float(int id) =>
float(id)
if barCond.under_equal(len.float().multiply(2))
if rsv.performances.columns().float().over(len)
rsv.performances.remove_col(0)
rsv.rs .remove_col(0)
rsv.roc .remove_col(0)
rsv.performances.add_col(rsv.performances.columns(), array.from( req("BTCUSD" ), req("ETHUSD" ), req("BNBUSD" ), req("XRPUSD"),
req("ADAUSD" ), req("DOGEUSD" ), req("SOLUSD" ), req("TRXUSD"),
req("DOTUSD" ), req("MATICUSD"), req("SHIBUSD"), req("TONUSD"),
req("LTCUSD" ), req("WBTCUSD" ), req("BCHUSD" ), req("LEOUSD"),
req("AVAXUSD"), req("XLMUSD" ), req("LINKUSD"), req("UNIUSD"),
req("OKBUSD") , req("XMRUSD" ), req("ATOMUSD"), req("ETCUSD"),
req("HBARUSD"), req("ICPUSD" ), req("FILUSD" ), req("MNTUSD"),
req("APTUSD")))
rsv.rs .add_col(rsv.rs.columns())
rsv.roc.add_col(rsv.roc.columns())
rows = rsv.performances.rows() - 1
if rsv.rs.columns().float().equal(1)
for i = 0 to rows
rsv.rs .set(i, rsv.rs.columns() - 1, rsv.performances.row(i).last().divide(rsv.performances.col(0).avg()))
rsv.roc.set(i, rsv.roc.columns() - 1, 0)
else
for i = 0 to rows
rsv.rs.set(i, rsv.rs.columns() - 1, rsv.performances.row(i).avg())
indexAvg = rsv.rs.col(rsv.rs.columns() - 1).avg()
for i = 0 to rows
rsv.rs.set (i, rsv.rs .columns() - 1, rsv.rs.get(i, rsv.rs.columns() - 1) / indexAvg)
rsv.roc.set(i, rsv.roc.columns() - 1, rsv.rs.get(i, rsv.rs.columns() - 1) / rsv.rs.get(i, rsv.rs.columns() - 2) - 1)
method append (matrix <float> id) =>
if recent
id.add_col(id.columns(), array.from(math.log(close / close[zlook]), index, i2, math.log(close / close[1])))
if id.columns().float().over(lenco)
id.remove_col(0)
method zScoreInd (array <float> id) =>
if recent
(id.last() - id.avg()) / id.stdev()
method gcorrect (matrix <float> id) =>
if recent
n = id.columns()
pooled = math.sqrt(((n - 1) * id.row(0).variance() + (n - 1) * id.row(1).variance()) / (n + n - 2))
correct = ((n - 3) / (n - 2.25)) * math.sqrt((n - 2) / n)
((id.row(0).avg() - id.row(1).avg()) / pooled) * correct
method zcomp(matrix<float> id) =>
if recent
n = id.columns()
pooled = math.sqrt((math.pow(id.row(0).stdev(), 2) + math.pow(id.row(1).stdev(), 2)) / 2)
z = (id.row(0).avg() - id.row(1).avg()) / pooled
method glass (matrix<float> id) =>
if recent
(id.row(0).avg() - id.row(1).avg()) / id.row(0).stdev()
method cliff (matrix<float> id) =>
if recent
ngt = 0, nlt = 0
sampleA = id.row(0), sampleB = id.row(1)
n = sampleA.size()
for i = 0 to n - 1
for x = 0 to n - 1
if sampleA.get(i) > sampleB.get(x)
ngt += 1
else if sampleA.get(i) < sampleB.get(x)
nlt += 1
cliffd = (ngt - nlt) / math.pow(n, 2)
avgs.append()
zArr = array.from(avgs.row(0).zScoreInd(), avgs.row(1).zScoreInd())
var i2arr = array.new_float(0, 0), i2arr.push(i2)
method plusMinusAdd(matrix<float> id) =>
if recent
last = i2arr.zScoreInd().over(0)
[val, val2] = switch last
true => [i2arr.zScoreInd() + math.max(zArr.first(), zArr.last(), 0), 0]
=> [0, math.min(zArr.first(), zArr.last(), 0) + i2arr.zScoreInd()]
id.add_col(id.columns(), array.from(val, val2))
if id.columns().float().over(1000)
id.remove_col(0)
method hedge(matrix<float> id) =>
if recent
id.add_col(id.columns(), array.from(math.log(close / close[1]), i1))
if id.columns().float().over(len)
id.remove_col(0)
id.row(0).covariance(id.row(1)) / id.row(1).variance()
method add100 (float id) => id + 100
method quick (color id, transp) => color.new(id, transp)
method determine (bool id, a, b) =>
switch id
true => a
=> b
var hedge = matrix.new<float>(2, 0)
var colArr = matrix.new<float>(2, 0)
colArr.plusMinusAdd(), colArr0 = colArr.row(0), colArr1 = colArr.row(1)
finCol = if recent
switch
i2arr.zScoreInd() <= 0 => colArr1.last().add100()
=> colArr0.last().add100()
else
100
nine = colArr0.percentile_nearest_rank(90)
ten = colArr1.percentile_nearest_rank(10)
[first100, last100] = switch recent
true => [zArr.first().add100(), zArr.last ().add100()]
=> [100, 100]
plotcandle(100, first100, first100, first100,
color = col1.quick(75),
bordercolor = col1.quick(10),
display = display.pane
)
plotcandle(100, last100, last100, last100,
color = col2.quick(75),
bordercolor = col2.quick(10),
display = display.pane
)
hedge100 = hedge.hedge().add100()
plo = switch
hedge100.over(100) => math.min(104, hedge100)
=> math.max( 96, hedge100)
plotVal = switch zord
"Hedges' G" => avgs.gcorrect()
"Z Compare" => avgs.zcomp()
"Glass's D" => avgs.glass()
"Cliff D" => avgs.cliff()
p1 = plot(plotVal.add100(), color = color.white, style = plot.style_stepline_diamond, display = display.pane, linewidth = 1),
p2 = plot(100, display = display.none),
p3 = plot(plo, display = display.none),
fill(p2, p3, 100, 96, #00000000, hedge100.under(100).determine(color.lime.quick(50), #00000000)),
fill(p2, p3, 104, 100, hedge100.over(100).determine(color.red.quick(50), #00000000), #00000000)
allOver() => zArr.last().over(0) and i2arr.zScoreInd().over (0) and zArr.last().over (zArr.first())
allUndr() => zArr.last().under(0) and i2arr.zScoreInd().under(0) and zArr.last().under(zArr.first())
[finGradientBG, finGradientBO] = switch
allOver() => [color.from_gradient(colArr0.last(), 0, nine, #00000000, ucol.quick(75)),
color.from_gradient(colArr0.last(), 0, nine, #00000000, ucol.quick(10))]
allUndr() => [color.from_gradient(colArr1.last(), ten, 0, dcol.quick(75), #00000000),
color.from_gradient(colArr1.last(), ten, 0, dcol.quick(10), #00000000)]
=> [color(na), color(na)]
plotcandle(
i2arr.zScoreInd().over(0).determine(math.max(zArr.first(), zArr.last(), 0).add100(), math.min(zArr.first(), zArr.last(), 0).add100()),
finCol, finCol, finCol,
color = finGradientBG,
bordercolor = finGradientBO,
wickcolor = na,
display = display.pane
),
styl = neon.determine(label.style_text_outline, label.style_none)
type quadrants
float xcoord
float ycoord
string symbol
method coordinateSet (matrix <quadrants> id, xval, yval, sval) =>
id.add_col(id.columns(), array.from(
quadrants.new(xcoord = xval.add100()),
quadrants.new(ycoord = yval.add100()),
quadrants.new(symbol = sval )
))
method normalize (matrix <quadrants> id, int , float , int2, float2, color ) =>
if id.columns().float().over(0)
values = array.from(-1e8, 1e8, -1e8, 1e8)
for i = 0 to id.columns() - 1
values.set(0, math.max(values.first(), id.get(0, i).xcoord))
values.set(1, math.min(values.get (1), id.get(0, i).xcoord))
values.set(2, math.max(values.get (2), id.get(1, i).ycoord))
values.set(3, math.min(values.last (), id.get(1, i).ycoord))
xmin = values.get(1), xrange = values.first() - xmin
ymin = values.last(), yrange = values.get(2) - ymin
for i = 0 to id.columns() - 1
id.set(0, i, quadrants.new(xcoord = ((id.get(0, i).xcoord - xmin) / xrange) * (int - int2 ) + int2))
id.set(1, i, quadrants.new(ycoord = ((id.get(1, i).ycoord - ymin) / yrange) * (float - float2 ) + float2))
label.new(int(bar_index + id.get(0, i).xcoord), id.get(1, i).ycoord, text = id.get(2, i).symbol,
textcolor = neon.determine(color.white, color ),
color = color ,
size = size.tiny,
style = styl
)
if barstate.islast
box.all.flush(), label.all.flush(), line.all.flush()
for i = 0 to 1
[ycoord, col] = switch
i.float().equal(0) => [nine.add100(), ucol.quick(50)]
i.float().equal(1) => [ten .add100(), dcol.quick(50)]
line.new(bar_index - 1, ycoord, bar_index, ycoord, color = col, style = line.style_dotted, extend = extend.left)
if show
rslast = rsv.rs.col(rsv.rs.columns() - 1)
q1 = matrix.new<quadrants>(3, 0), q2 = matrix.new<quadrants>(3, 0)
q3 = matrix.new<quadrants>(3, 0), q4 = matrix.new<quadrants>(3, 0)
for i = 0 to rsv.roc.rows() - 1
cols = rsv.roc.columns()
xval = rslast .get (i)
yval = rsv.roc.row(i).slice(cols-lenx, cols).avg()
switch
xval.over_equal(0) and yval.over_equal(0) => q1.coordinateSet(xval, yval, stringArr.get(i))
xval.over_equal(0) and yval.under (0) => q2.coordinateSet(xval, yval, stringArr.get(i))
xval.under (0) and yval.over_equal(0) => q3.coordinateSet(xval, yval, stringArr.get(i))
xval.under (0) and yval.under (0) => q4.coordinateSet(xval, yval, stringArr.get(i))
q1.normalize(190, 103.50, 60, 102.50, leacol), q3.normalize(190, 99.50, 60, 98.50 , detcol)
q2.normalize(190, 101.50, 60, 100.50, impcol), q4.normalize(190, 97.50, 60, 96.50 , lagcol)
for i = 0 to 3
[x, y, x2, y2, col] = switch
i.float().equal(0) => [50, 100, 200, 102 , impcol.quick(75)]
i.float().equal(1) => [50, 102, 200, 104 , leacol.quick(75)]
i.float().equal(2) => [50, 96 , 200, 98 , lagcol.quick(75)]
i.float().equal(3) => [50, 98 , 200, 100 , detcol.quick(75)]
box.new(bar_index + x, y, bar_index + x2, y2, col, bgcolor = col, border_color = col, border_style = line.style_solid, border_width = 2)
[x3, y3, text, colx] = switch
i.float().equal(0) => [25, 101 , "Improving" , impcol]
i.float().equal(1) => [25, 103 , "Leading" , leacol]
i.float().equal(2) => [25, 97 , "Lagging" , lagcol]
i.float().equal(3) => [25, 99 , "Deteriorating", detcol]
label.new(bar_index + x3, y3, text, color = colx, textcolor = neon.determine(color.white, colx), size = size.small, style = styl)
label.new(bar_index + 125 , 95.5, "RS", color = #000000,
textcolor = color.white,
size = size.small,
style = styl
)
label.new(bar_index + 210, 100, text = "R\nS\n\nM\no\nm\ne\nn\nt\nu\nm",
color = #000000,
textcolor = color.white,
size = size.small,
style = styl
)
box.new(bar_index + 50, 104, bar_index + 200, 96,
bgcolor = na,
border_color = color.white,
border_width = 2
)
|
Realtime Divergence for Any Indicator - By John Bartle | https://www.tradingview.com/script/KfYCBk92-Realtime-Divergence-for-Any-Indicator-By-John-Bartle/ | JohnBartlesAccount | https://www.tradingview.com/u/JohnBartlesAccount/ | 120 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © JohnBartlesAccount
//@version=5
indicator("Realtime Divergence for Any Indicator - By John Bartle", overlay=true, max_lines_count=500, max_labels_count = 500, max_bars_back = 300)
prc_AllBulls = input.source(low, "Price Chart Bulls Source", group = "Sources", tooltip = "The data source for both hidden bull and regular bull")
prc_AllBears = input.source(high, "Price Chart Bears Source", group = "Sources", tooltip = "The data source for both hidden bear and regular bear")
osc_AllBulls = input.source(low, "Oscillator Chart Bulls Source", group = "Sources", tooltip = "The data source for both hidden bull and regular bull")
osc_AllBears = input.source(high, "Oscillator Chart Bears Source", group = "Sources", tooltip = "The data source for both hidden bear and regular bear")
applyToPriceChart = input(false, "Apply To Price Chart", tooltip="You must choose whether price chart(or substitute) lines or oscillator lines are diplayed. Only one can be displayed at a time. FYI, A price chart can be substituted with an oscillator. Also you must still set the \'Oscillator Chart Source\' Input to the desired source", group = "General Display Settings")
visibleDivsPosAdjustment = input.int( 0, "Beginning of Visible Range of Divergences", step = 100, maxval = 0, tooltip="This setting shifts the range of visible divergences along the chart. The purpose for this is that the number of visible lines and labels possible in Pinescript is limited. So this is useful if the chart is longer than the visible range. Also, as the quantity of drawn lines increase your chart's performance slows", group = "General Display Settings")
plotBull = input( true, title = "Bull Lines", group="General Display Settings")
plotHiddenBull = input( true, title = "Hidden Bull Lines", group="General Display Settings")
plotBear = input( true, title = "Bear Lines", group="General Display Settings")
plotHiddenBear = input( true, title = "Hidden Bear Lines", group="General Display Settings")
plotBullLabels = input( true, title = "Bull Label", group="General Display Settings")
plotHidBullLabels = input( true, title = "Hidden Bull Label", group="General Display Settings")
plotBearLabels= input( true, title = "Bear Label", group="General Display Settings")
plotHidBearLabels = input( true, title = "Hidden Bear Label", group="General Display Settings")
bullColor = input.color(color.rgb(0, 255, 0, 0), title = "Bullish Color", group="General Display Settings")
hiddenBullColor = input.color(color.rgb(0, 255, 0, 80), title = "Hidden Bullish Color", group="General Display Settings")
bearColor = input.color(color.rgb(255, 0, 0, 0), title = "Bearish Color", group="General Display Settings")
hiddenBearColor = input.color(color.rgb(255, 0, 0, 80), title = "Hidden Bearish Color", group="General Display Settings")
textColor = input.color(color.rgb(255, 255, 255, 0), title = "Text Color", group="General Display Settings")
useLabelText = input( false, title = "Use Label Text", group="General Display Settings")
divAngleColor = input.color(color.rgb(0, 255, 0, 0), title = "Divergence Angle Color", group="General Display Settings")
divIntersectColor = input.color(color.rgb(136, 159, 232), title = "Divergence Intersection Color", group="General Display Settings")
YAdditive = input.float(defval = 0.0000, title = "Alerts: Alert Label Y Location", step = 0.5000, tooltip = "The vertical distance above or below the current close price", group="Alert Display Settings")
XAdditive = input.int(defval = 2, title = "Alerts: Alert Label X Location", tooltip = "The horizontal distance from the current bar location", group="Alert Display Settings")
YSpacing = input.float(defval = 1.0000, title = "Alerts: Alert Label Y Spacing", step = 0.5000, tooltip = "The vertical distance between each Alert Label", group="Alert Display Settings")
pivotPattern = input.string( "Type 2", title = "Pivot Pattern", options = ["Type 1", "Type 2"], tooltip = "\'Type 1\' is either a pyramid or upside-down pyramid pattern depending on the type of divergence. Beginning from the pivot bar, each set of it's side bars is required to be either higher or lower than the bars nearer the pivot bar. \'Type 2\' permits all the side bars to be as high or as low as the pivot bar, depending on the type of divergence. This will produce more divergences",group = "Pivots")
rsDeviationAllowance = input.int(title="Rightside Misalignment Allowance", defval=0, minval=0, step=1, tooltip="The number of bars allowed for price and oscillator rightside pivots to misalign from one another. Note that only one of the two pivots are permitted to be deviated from the current evaluated bar. Rightside pivots between price and oscillator are sometimes slightly misaligned, but SOME should still possibly be considered a valid divergence", group = "Pivots")
RSPivRBars = input.int( 3, title = "Right Side Bars of Rightside Pivots", minval = 0, group = "Pivots")
RSPivLBars = input.int( 3, title = "Left Side Bars of Rightside Pivots", minval = 0, group = "Pivots")
rsPivErrAllowance = input.int( 0, title = "Rightside Pivot Error Allowance", minval = 0, tooltip = "The number of bars within a pivot that are allowed to deviate from a pivot pattern. This script offers two possible pivot patterns to choose from", group = "Pivots")
LSPivRBars = input.int( 3, title = "Right Side Bars of Leftside Pivots", minval = 0, group = "Pivots")
LSPivLBars = input.int( 3, title = "Left Side Bars of Leftside Pivots", minval = 0, group = "Pivots")
lsPivErrAllowance = input.int( 0, title = "Leftside Pivot Error Allowance", minval = 0, tooltip = "The number of bars within a pivot that are allowed to deviate from a pivot pattern. This script offers two possible pivot patterns to choose from", group = "Pivots")
doHistorical = input.bool(defval=true, title = "Historical Divergences", tooltip="Show historical divergences", group = "Divergences")
divMax = input.int( 60, title = "Max Length", minval = 2, tooltip="The maximum allowed length of the oscillator and price divergence lines", group = "Divergences")
divMin = input.int( 5, title = "Min Length", minval = 2, tooltip="The minimum allowed length of the oscillator and price divergence lines", group = "Divergences")
divergenceMax = divMax
divergenceMin = divMin
fullDivLenMax = divMax + RSPivRBars + LSPivLBars
fullDivLenMin = divMin + RSPivRBars + LSPivLBars
//The divLength* represents the total number of bars from the rightmost rightside side bar to the leftmost leftside side bar. The divMax and divMin represent only the number of bars from the leftside pivot bar to the rightside pivot bar.
if divMin > divMax
fullDivLenMin := fullDivLenMax
divergenceMin := divergenceMax
minDivLength = input.float(title = "Min Length Ratio Allowance", defval=50.00, minval=0.0, step=1.00, tooltip="The minimum percentage of the length of bars that the smaller line must compare to the larger line of the price chart or the oscillator. The formula is ((smaller_line / larger_line) * 100)", group = "Divergences")
useBestSlope = input(defval=true, title = "Use Only the Best Slope", tooltip="Depending on the type of divergence line, only the slope closest to 0 or the slope farthest from 0 will be used", group = "Divergences")
doAlerts = input.bool(defval=true, title = "Alerts: Divergences", tooltip="Recieve alerts to divergences that have right side bars for the rightside pivots. These alerts occur while the rightmost pivot is still developing", group = "Divergences")
alertTiming = input.bool(defval = true, title = "Alert Before Bar Close", tooltip = "If set, the alerts will execute immediately when a divergence occurs at any point of the bar formation and this would actually make the divergence only a potential. If unset, the alerts will execute at the close of the rightmost bar if a divergence occurs. WARNING, you must create a new alert and delete your current alert if you change this setting", group = "Divergences") ? alert.freq_once_per_bar : alert.freq_once_per_bar_close
interAllowancePrice = input.float(title = "Price: Allowance", defval=0.00, minval=0.0, step=1.00, tooltip="The relative percentage or absolute amount that the price is allowed to intersect the divergence line. If \'Relative Percentage\' is your \'Measurement Type\' then 1.0 equals 1% of the Y value of the divergence line at bar X. Sometimes bars may slightly intersect the divergence line but still be valid. Extremely different allowances MAY be best for different volatilities, timeframes and prices", group = "Divergences: Intersection Allowance")
interAllowanceOsc = input.float(title = "Oscillator: Allowance", defval=0.00, minval=0.0, step=1.00, tooltip="The relative percentage or absolute amount that the oscillator is allowed to intersect the divergence line. If \'Relative Percentage\' is your \'Measurement Type\' then 1.0 equals 1% of the Y value of the divergence line AT bar X. Sometimes bars may slightly intersect the divergence line but still be valid. Extremely different allowances MAY be best for different volatilities, timeframes and prices", group = "Divergences: Intersection Allowance")
intersectExclusion = input.int(defval = 1, title = "Bar Exclusions", minval = 0, tooltip = "Beginning from within a divergence line, the right side and left side set of inner bars excluded from evaluation for the settings: \'*: Intersection Allowance\'. The purpose of this setting is that too often a divergence line will have one or two inner bars directly next to the pivot bars that intersect the divergence line, and some people may want to ignore them", group = "Divergences: Intersection Allowance")
measureType = input.string( "Absolute Difference", title= "Measurement Type", options = ["Relative Percentage", "Absolute Difference"], tooltip = "Choose the measurment type for the settings \'*: Allowance\'. ",group = "Divergences: Intersection Allowance")
showDivIntersection = input.bool(defval=false, title="Show Intersection Allowance", tooltip="This displays the percentage or the absolute difference of the intersection. This can be used to help establish a visual idea of percentages or differences ", group = "Divergences: Intersection Allowance")
useSlopeAngExc = input.bool(defval = false, title = "Slope Angle Exclusion", group = "Divergences: Slope Angle Exclusion")
slopeMaxOsc = input.float(defval=0.0, title = "Oscillator: Upper Range ", minval = -1.0000, maxval = 90.0, step = 1.0000, tooltip="The upper limit of the excluded angle range for slopes within the oscillator. The values are in degrees of angles and in absolute values. Any divergence line between this range is excluded. -1 is always outside range", group = "Divergences: Slope Angle Exclusion")
slopeMinOsc = input.float(defval=0.0, title = "Oscillator: Lower Range", minval = -1.0000, maxval = 90.0, step = 1.0000, tooltip="The lower limit of the excluded angle range for slopes within the oscillator. The values are in degrees of angles and in absolute values. -1 is always outside range", group = "Divergences: Slope Angle Exclusion")
normFacOsc = input.string(defval="0.01", title = "Oscillator: Normalization Factor", tooltip="The factor by which the time scale is adjusted relative to the oscillator scale. You must decide what slope equals what degree. The time scale compared to oscillator scale can be drastically different and subsequently their slopes can be extremely and undesirably small or large. Normalization is necessary in order to reasonably represent slopes as angle degrees. I recommend using +/- powers of 10, but experiment and use whatever gives you the best dispersion of slope angles", group = "Divergences: Slope Angle Exclusion")
normalFactorOsc = str.tonumber(normFacOsc)
slopeMaxPrice = input.float(defval=0.0, title = "Price: Upper Range", minval = -1.0000, maxval = 90.0, step = 1.0000, tooltip="The upper limit of the excluded angle range for slopes within the price chart. The values are in degrees of angles and in absolute values. Any divergence line between this range is excluded. -1 is always outside range", group = "Divergences: Slope Angle Exclusion")
slopeMinPrice = input.float(defval=0.0, title = "Price: Lower Range", minval = -1.0000, maxval = 90.0, step = 1.0000, tooltip="The lower limit of the excluded angle range for slopes within the price chart. The values are in degrees of angles and in absolute values. -1 is always outside range", group = "Divergences: Slope Angle Exclusion")
normFacPrice = input.string(defval="0.01", title = "Price: Normalization Factor", tooltip="The factor by which the time scale is adjusted relative to the price scale. You must decide what slope equals what degree. The time scale compared to price scale can be drastically different and subsequently their slopes can be extremely and undesirably small or large. Normalization is necessary in order to reasonably represent slopes as angle degrees. I recommend using +/- powers of 10, but experiment and use whatever gives you the best dispersion of slope angles", group = "Divergences: Slope Angle Exclusion")
normalFactorPrice = str.tonumber(normFacPrice)
showAngles = input.bool(defval = false, title = "Show Divergence Line Angles", tooltip="View the angles of the divergence lines. This gives you a better idea of which divergences you'd like removed", group = "Divergences: Slope Angle Exclusion")
doRealtime = input.bool(defval=true, title = "Realtime Potential Divergences", tooltip="Show potential divergences as pivots are forming", group = "Divergences: REALTIME")
rtDivDisplayQuantity = input.int(defval=2, title = "Display Quantity", minval = 1, tooltip="The quantity of previous potential divergences to be displayed", group = "Divergences: REALTIME")
rtDivDisplayBarQuantity = input.int(defval=5, title = "Display Range", minval = 1, tooltip="The quantity of bars allowed to display previous potential divergences. Note that only the rightside pivots are required to be within this range in order for their entire realtime divergence lines to made visible. Note that there's a small bug in this feature, just increase the value to manage it if necessary", group = "Divergences: REALTIME")
doRTPotentialAlerts = input.bool(defval=true, title = "Alerts: Potential Divergences", tooltip="Recieve alerts to potential divergences that have zero right side bars for rightside pivots", group = "Divergences: REALTIME")
rtAlertTiming = input.bool(defval = true, title = "Alerts: Alert Before Bar Close", tooltip = "If set, the alerts will execute immediately when a divergence occurs at any point of the bar formation. If unset, the alerts will execute at the close of the bar if a divergence has occured. WARNING, you must create a new alert and delete your current alert if you change this setting") ? alert.freq_once_per_bar : alert.freq_once_per_bar_close
hack_addElements = input.float(defval=0.0, title = "Add More Array Elements", minval = 0, tooltip="To temporarily fix an ERROR that reads \'Error on bar xxx: in array.get() function. Index xxx is out of bounds\'. The purpose for this setting is that my code has a bug that I don\'t feel like fixing", group = "DEBUG and HACK")
//positionTEST = input.int(defval=1, title="Position TEST", tooltip="Show potential divergences as pivots are forming", group = "DEBUG and HACK")
divergenceCanceled = false
type ChartCoordinates
int x1
float y1
int x2
float y2
//This function returns 0, for the number of the current bar, when useCurrentBar is true and occurrence = 1 and the condition for the current bar is true.
barssince_custom(condition, occurrence, useCurrentBar) =>
count = 1
occurCount = 0
if useCurrentBar
count := 0
for i = count to bar_index
if condition[i]
occurCount := occurCount + 1
if occurCount == occurrence
// count := count + 1
break
count := count + 1
count
isPivotLow(src, lsLen, rsLen, errAllowance) =>
pivotLow = true
numErrOutToIn = 0
numErrInToOut = 0
type2Errors = 0
mostErrors = 0
if pivotPattern == "Type 1"
//Outward to Inward
if rsLen > 0
for i = 0 to (rsLen - 1)
for j = (i+1) to (rsLen)
if src[i] <= src[j]
numErrOutToIn := numErrOutToIn + 1
break
if lsLen > 0
for i = (rsLen + lsLen) to (rsLen + 1)
for j = (i-1) to rsLen
if src[i] <= src[j]
numErrOutToIn := numErrOutToIn + 1
break
//Inward to Outward THIS ONE removes label
if rsLen > 0
for i = rsLen to 1
for j = (i-1) to 0
if src[i] >= src[j]
numErrInToOut := numErrInToOut + 1
break
if lsLen > 0
for i = rsLen to (rsLen + lsLen - 1)
for j = (i+1) to (rsLen + lsLen)
if src[i] >= src[j]
numErrInToOut := numErrInToOut + 1
break
mostErrors := numErrOutToIn > numErrInToOut ? numErrOutToIn : numErrInToOut
if mostErrors > errAllowance
pivotLow := false
if pivotPattern == "Type 2"
if rsLen > 0
for i = 0 to (rsLen - 1)
if src[i] < src[rsLen]
type2Errors := type2Errors + 1
if lsLen > 0
for i = (rsLen + 1) to (rsLen + lsLen)
if src[i] < src[rsLen]
type2Errors := type2Errors + 1
if type2Errors > errAllowance
pivotLow := false
pivotLow
isPivotHigh(src, lsLen, rsLen, errAllowance) =>
pivotLow = true
numErrOutToIn = 0
numErrInToOut = 0
type2Errors = 0
mostErrors = 0
if pivotPattern == "Type 1"
//Outward to Inward
if rsLen > 0
for i = 0 to (rsLen - 1)
for j = (i+1) to (rsLen)
if src[i] >= src[j]
numErrOutToIn := numErrOutToIn + 1
break
if lsLen > 0
for i = (rsLen + lsLen) to (rsLen + 1)
for j = (i-1) to rsLen
if src[i] >= src[j]
numErrOutToIn := numErrOutToIn + 1
break
//Inward to Outward
if rsLen > 0
for i = rsLen to 1
for j = (i-1) to 0
if src[i] <= src[j]
numErrInToOut := numErrInToOut + 1
break
if lsLen > 0
for i = rsLen to (rsLen + lsLen - 1)
for j = (i+1) to (rsLen + lsLen)
if src[i] <= src[j]
numErrInToOut := numErrInToOut + 1
break
mostErrors := numErrOutToIn > numErrInToOut ? numErrOutToIn : numErrInToOut
if mostErrors > errAllowance
pivotLow := false
if pivotPattern == "Type 2"
if rsLen > 0
for i = 0 to (rsLen - 1)
if src[i] > src[rsLen]
type2Errors := type2Errors + 1
if lsLen > 0
for i = (rsLen + 1) to (rsLen + lsLen)
if src[i] > src[rsLen]
type2Errors := type2Errors + 1
if type2Errors > errAllowance
pivotLow := false
pivotLow
findPivots(rsPivLeftBars, rsPivRightBars, lsPivLeftBars, lsPivRightBars) =>
rsLows_Osc = isPivotLow(osc_AllBulls, rsPivLeftBars, rsPivRightBars, rsPivErrAllowance)
rsLows_Price = isPivotLow(prc_AllBulls, rsPivLeftBars, rsPivRightBars, rsPivErrAllowance)
rsHighs_Osc = isPivotHigh(osc_AllBears, rsPivLeftBars, rsPivRightBars, rsPivErrAllowance)
rsHighs_Price = isPivotHigh(prc_AllBears, rsPivLeftBars, rsPivRightBars, rsPivErrAllowance)
lsLows_Osc = isPivotLow(osc_AllBulls, lsPivLeftBars, lsPivRightBars, lsPivErrAllowance)
lsLows_Price = isPivotLow(prc_AllBulls, lsPivLeftBars, lsPivRightBars, lsPivErrAllowance)
lsHighs_Osc = isPivotHigh(osc_AllBears, lsPivLeftBars, lsPivRightBars, lsPivErrAllowance)
lsHighs_Price = isPivotHigh(prc_AllBears, lsPivLeftBars, lsPivRightBars, lsPivErrAllowance)
[rsLows_Osc, rsLows_Price, rsHighs_Osc, rsHighs_Price, lsLows_Osc, lsLows_Price, lsHighs_Osc, lsHighs_Price]
//Right side pivot deviations from the current bar
type PivotDeviations
int oscPLBar
int pricePLBar
int oscPHBar
int pricePHBar
findDeviatedRSPivots(rsPivLows_Osc, rsPivLows_Price, rsPivHighs_Osc, rsPivHighs_Price, rsBars) =>
PivotDeviations pd = PivotDeviations.new()
// The bar elements start at 0 not 1 for found pivots
pd.oscPLBar := barssince_custom(rsPivLows_Osc, 1, true) + rsBars
pd.pricePLBar := barssince_custom(rsPivLows_Price, 1, true) + rsBars
pd.oscPHBar := barssince_custom(rsPivHighs_Osc, 1, true) + rsBars
pd.pricePHBar := barssince_custom(rsPivHighs_Price, 1, true) + rsBars
pd
//chartType
PRICE_CHART = 1
OSC_CHART = 2
shouldDivergenceBeDisplayed(chartType, isDivergence, isRealtime) =>
display = true
//This controls the visible range of bars displayed on the chart
visibleDivsPos = (last_bar_index + visibleDivsPosAdjustment)
if (bar_index > (visibleDivsPos))
display := false
if (divergenceCanceled == true)
display := false
if chartType == PRICE_CHART and applyToPriceChart == false
display := false
if chartType == OSC_CHART and applyToPriceChart == true
display := false
if isDivergence == false
display := false
display
shouldPotentialDivBeAlerted(isDivergence) =>
isRtAlert = true
if rtAlertTiming == alert.freq_once_per_bar_close and isDivergence[1] == false
isRtAlert := false
if rtAlertTiming == alert.freq_once_per_bar and isDivergence == false
isRtAlert := false
// if (divergenceCanceled == true) and rtAlertTiming == alert.freq_once_per_bar
// isRtAlert := false
if doRTPotentialAlerts == false
isRtAlert := false
if bar_index != last_bar_index
isRtAlert := false
isRtAlert
shouldDivBeAlerted(isDivergence) =>
isAlert = true
if alertTiming == alert.freq_once_per_bar_close and isDivergence[1] == false
isAlert := false
if alertTiming == alert.freq_once_per_bar and isDivergence == false
isAlert := false
// if (divergenceCanceled == true) and rtAlertTiming == alert.freq_once_per_bar
// isRtAlert := false
if doAlerts == false
isAlert := false
if bar_index != last_bar_index
isAlert := false
isAlert
//equalityType
GREATER_THAN = 1
LESS_THAN = 2
compareBars(bar1, equalityType, bar2 ) =>
comparison = false
if equalityType == GREATER_THAN
comparison := bar1 > bar2
if equalityType == LESS_THAN
comparison := bar1 < bar2
comparison
PivotDeviations rsDevPivs = PivotDeviations.new()
PivotDeviations rt_rsDevPivs = PivotDeviations.new()//Realtime
//divType
REG_BULL = 1
HID_BULL = 2
REG_BEAR = 3
HID_BEAR = 4
ALL_BULLS = 5 //Represents both REG_BULL and HID_BULL
ALL_BEARS = 6 //Represents both REG_BEAR and HID_BEAR
areRSDivergencePreconditionsOK(divType, devPivs, isRealtime) =>
isCancelled = false
rsBars = 0
if isRealtime == false
rsBars := RSPivRBars
if divType == ALL_BULLS
if na(devPivs.pricePLBar) or na(devPivs.oscPLBar)
isCancelled := true
//If both the price and oscillator right side pivots are deviated from the current evaluated bar then cancel
if ((devPivs.pricePLBar - rsBars) > 0 and (devPivs.oscPLBar - rsBars) > 0)
isCancelled := true
if math.abs(devPivs.oscPLBar - devPivs.pricePLBar) > rsDeviationAllowance
isCancelled := true
if ((devPivs.pricePLBar + RSPivLBars) > (fullDivLenMax - 1)) or ((devPivs.oscPLBar + RSPivLBars) > (fullDivLenMax - 1))
isCancelled := true
if divType == ALL_BEARS
if na(devPivs.pricePHBar) or na(devPivs.oscPHBar)
isCancelled := true
//If both the price and oscillator right side pivots are deviated from the current evaluated bar then cancel
if ((devPivs.pricePHBar - rsBars) > 0 and (devPivs.oscPHBar - rsBars) > 0)
isCancelled := true
if math.abs(devPivs.oscPHBar - devPivs.pricePHBar) > rsDeviationAllowance
isCancelled := true
//If the left side most bar of the rightside pivot exceeds fullDivLenMax. "- 1" is necessary because pricePHBar and oscPHBar start at 0
if ((devPivs.pricePHBar + RSPivLBars) > (fullDivLenMax - 1)) or ((devPivs.oscPHBar + RSPivLBars) > (fullDivLenMax - 1))
isCancelled := true
isCancelled
//Within the function isDivIntersectedByXAmount() I get a warning "Warning at 1152:17 The function 'displayIntersectionAmount' should be called on each calculation for consistency. It is recommended to extract the call from this scope"
//The following section of code removes that warning
var priceAllBullsArray = array.new_float()
var priceAllBearsArray = array.new_float()
var osc_AllBullsArray = array.new_float()
var osc_AllBearsArray = array.new_float()
array.unshift(priceAllBullsArray, prc_AllBulls)
array.unshift(priceAllBearsArray, prc_AllBears)
array.unshift(osc_AllBullsArray, osc_AllBulls)
array.unshift(osc_AllBearsArray, osc_AllBears)
if bar_index > (fullDivLenMax + 1) + hack_addElements//FIX: This hack is absolutely arbitrary but a big extra number prevents an error.
array.pop(priceAllBullsArray)
array.pop(priceAllBearsArray)
array.pop(osc_AllBullsArray)
array.pop(osc_AllBearsArray)
isDivIntersectedByXAmount(chartType, divType, x1, y1, x2, y2) =>
isIntersecting = false
//Note that positive bar indexes refer to past left bars which is the opposite direction of the numbering of a typical line graph.
rise = y1 - y2
run = x1 - x2
x_point = 0
y_point = 0.0
riseOfPoint = 0.0
runOfPoint = 0.0
array<float> barsArray = na
if chartType == PRICE_CHART
if (divType == REG_BULL) or (divType == HID_BULL)
barsArray := priceAllBullsArray
if (divType == REG_BEAR) or (divType == HID_BEAR)
barsArray := priceAllBearsArray
else if chartType == OSC_CHART
if (divType == REG_BULL) or (divType == HID_BULL)
barsArray := osc_AllBullsArray
if (divType == REG_BEAR) or (divType == HID_BEAR)
barsArray := osc_AllBearsArray
numOfBars = (x1) - (x2) + 1 //This includes the bars beginning from the right side pivot bar to the left side pivot par
firstBar = (1 + intersectExclusion) //Begin evaluation at the very first inner bars + intersectEx
lastBar = numOfBars - 2 - intersectExclusion
//TODO: Test if RSPivRBars + 1 is the first bar after the left bars of the right side pivot bar
if firstBar <= lastBar
for i = firstBar to lastBar
riseOfPoint := ((rise * i)/numOfBars)
runOfPoint := ((run * i)/numOfBars)
y_point := y2 + riseOfPoint
x_point := x2 + math.floor(runOfPoint)
difference = (array.get(barsArray, x2 + i) - y_point)
intersectionAmount = 0.0
if measureType == "Relative Percentage"
intersectionAmount := (difference / y_point) * 100
else
intersectionAmount := difference
if difference < 0.0 and (divType == REG_BULL or divType == HID_BULL)
if math.abs(intersectionAmount) > (interAllowancePrice) and chartType == PRICE_CHART
isIntersecting := true
if math.abs(intersectionAmount) > (interAllowanceOsc) and chartType == OSC_CHART
isIntersecting := true
if difference > 0.0 and (divType == REG_BEAR or divType == HID_BEAR)
if math.abs(intersectionAmount) > (interAllowancePrice) and chartType == PRICE_CHART
isIntersecting := true
if math.abs(intersectionAmount) > (interAllowanceOsc) and chartType == OSC_CHART
isIntersecting := true
isIntersecting
type BiggestIntersection
int x
float y
float diff
float percent
displayIntersectionAmount(chartType, divType, x1, y1, x2, y2) =>
labelStyle = label.style_label_up
isIntersecting = false
formattedText = "$%"
//Note that positive bar indexes refer to past left bars which is the opposite direction of the numbering of a typical line graph.
rise = y1 - y2
run = x1 - x2
x_point = 0
y_point = 0.0
riseOfPoint = 0.0
runOfPoint = 0.0
array<float> barsArray = na
if chartType == PRICE_CHART
if (divType == REG_BULL) or (divType == HID_BULL)
barsArray := priceAllBullsArray
if (divType == REG_BEAR) or (divType == HID_BEAR)
barsArray := priceAllBearsArray
else if chartType == OSC_CHART
if (divType == REG_BULL) or (divType == HID_BULL)
barsArray := osc_AllBullsArray
if (divType == REG_BEAR) or (divType == HID_BEAR)
barsArray := osc_AllBearsArray
numOfBars = (x1) - (x2) //+ 1 //This includes the bars beginning from the right side pivot bar to the left side pivot par
firstBar = (1 ) //Begin evaluation at the very first inner bars + intersectExclusion
lastBar = numOfBars - 2
BiggestIntersection bi = BiggestIntersection.new()
bi.diff := 0.0
bi.x := 0
bi.y := 0.0
bi.percent := 0.0
if firstBar <= lastBar
for i = firstBar to lastBar
riseOfPoint := ((rise * i)/numOfBars)
runOfPoint := ((run * i)/numOfBars)
y_point := y2 + riseOfPoint
x_point := x2 + math.floor(runOfPoint)
difference = (array.get(barsArray, x2 + i) - y_point)
intersectionAmount = 0.0
if measureType == "Relative Percentage"
intersectionAmount := (difference / y_point) * 100
formattedText := "$%"
else
intersectionAmount := difference
formattedText := "$"
if difference < 0.0 and (divType == REG_BULL or divType == HID_BULL) //and difference < 0.0
if math.abs(bi.diff) < math.abs(difference)
bi.diff := difference
bi.x := i
bi.y := y_point
bi.percent := intersectionAmount
isIntersecting := true
if difference > 0.0 and (divType == REG_BEAR or divType == HID_BEAR)
if math.abs(bi.diff) < math.abs(difference)
bi.diff := difference
bi.x := i
bi.y := y_point
bi.percent := intersectionAmount
isIntersecting := true
if divType == REG_BULL or divType == HID_BULL
labelStyle := label.style_label_up
else if divType == REG_BEAR or divType == HID_BEAR
labelStyle := label.style_label_down
if isIntersecting and ((chartType == OSC_CHART and applyToPriceChart == false) or (chartType == PRICE_CHART and applyToPriceChart == true))
formattedText2 = str.replace(formattedText, "$", str.tostring(math.abs(bi.percent)), 0)
line.new(bar_index - bi.x - x2, array.get(barsArray, x2 + bi.x), bar_index - bi.x - x2, bi.y, color = divIntersectColor, width =3)
label.new(bar_index - bi.x - x2, array.get(barsArray, x2 + bi.x), color = divIntersectColor, text = formattedText2, style = labelStyle, textcolor = textColor)
isIntersecting
//DEBUG function - this needs updating too
// getPointOnLine(chartType, divType, x1, y1, x2, y2) =>
// isIntersecting = false
// //Note that increasingly positive bar indexes refer to past bars which is the opposite of the numbering of a typical line graph.
// rise = y1 - y2
// run = x1 - x2
// x_point = 0
// y_point = 0.0
// riseOfPoint = 0.0
// runOfPoint = 0.0
// barsArray = (chartType == PRICE_CHART) ? priceBarsArray : oscBarsArray
// numOfBars = (x1) - (x2) //+ 1 //This includes the bars beginning from the right side pivot bar to the left side pivot par
// firstBar = (1 ) //Begin evaluation at the very first inner bars + intersectEx
// lastBar = numOfBars - 2
// if firstBar <= lastBar
// for i = firstBar to lastBar
// riseOfPoint := ((rise * i)/numOfBars)
// runOfPoint := ((run * i)/numOfBars)
// y_point := y2 + riseOfPoint
// x_point := x2 + math.floor(runOfPoint)
// difference = (array.get(barsArray, x2 + i) - y_point)
// if applyToPriceChart == false and chartType == OSC_CHART and i == positionTEST
// label.new(bar_index - i - x2 , y_point, text = str.tostring(y_point), color = color.yellow)
// label.new(bar_index - i - x2 , array.get(barsArray, x2 + i), text = str.tostring(array.get(barsArray, x2 + i))) // str.tostring( ((array.get(barsArray, x2 + i) - y_point) / y_point ) * 100 ) )
// isIntersecting
isSlopeAngleInRange(x1, y1, x2, y2, chartType) =>
isInRange = false
rise = math.abs(y2 - y1)
run = math.abs(x2 - x1)
angle = 0.0
if chartType == OSC_CHART
angle := math.atan(rise/(run * normalFactorOsc)) * (180 / math.pi)
isInRange := (angle >= slopeMinOsc) and (angle <= slopeMaxOsc) and not (slopeMinOsc == -1 and slopeMaxOsc == -1)
else
angle := math.atan(rise/(run * normalFactorPrice)) * (180 / math.pi)
isInRange := (angle >= slopeMinPrice) and (angle <= slopeMaxPrice) and not (slopeMinPrice == -1 and slopeMaxPrice == -1)
isInRange
displayDivLineAngles(x1, y1, x2, y2, chartType, divType) =>
labelStyle = label.style_label_up
isInRange = false
angle = 0.0
rise = math.abs(y2 - y1)
run = math.abs(x2 - x1)
if chartType == OSC_CHART
angle := math.atan(rise/(run * normalFactorOsc)) * (180 / math.pi)
else
angle := math.atan(rise/(run * normalFactorPrice)) * (180 / math.pi)
if divType == REG_BULL or divType == HID_BULL
labelStyle := label.style_label_up
else if divType == REG_BEAR or divType == HID_BEAR
labelStyle := label.style_label_down
if showAngles and ((chartType == OSC_CHART and applyToPriceChart == false) or (chartType == PRICE_CHART and applyToPriceChart == true))
formattedAngle = str.replace("$°", "$", str.tostring(angle), 0)
label.new(bar_index - x1, y1, size =size.small, text = formattedAngle, style = labelStyle, textcolor = textColor, color = divAngleColor)
angle
//I've assumed the best slopes are best described with the following:
// Reg Bear PRICE
// as close to 0 as possible
// Reg Bear OSC
// as farthest from 0 as possible
// Hidden Bear PRICE
// as farthest from 0 as possible
// Hidden Bear OSC
// as close to 0 as possible
// Reg Bull PRICE
// as close to 0 as possible
// Reg Bull OSC
// as farthest from 0 as possible
// Hidden Bull PRICE
// as farthest from 0 as possible
// Hidden Bull OSC
// as close to 0 as possible
isCurrentSlopeBetter(past_x1, past_y1, past_x2, past_y2, x1, y1, x2, y2, chartType, divType) =>
isSlopeBest = false
rise = past_y2 - past_y1
run = past_x2 - past_x1
pastSlope = math.abs(rise / run)
rise := y2 - y1
run := x2 - x1
currentSlope = math.abs(rise / run)
if chartType == PRICE_CHART
if divType == REG_BEAR
isSlopeBest := currentSlope < pastSlope
if divType == HID_BEAR
isSlopeBest := currentSlope > pastSlope
if divType == REG_BULL
isSlopeBest := currentSlope < pastSlope
if divType == HID_BULL
isSlopeBest := currentSlope > pastSlope
if chartType == OSC_CHART
if divType == REG_BEAR
isSlopeBest := currentSlope > pastSlope
if divType == HID_BEAR
isSlopeBest := currentSlope < pastSlope
if divType == REG_BULL
isSlopeBest := currentSlope > pastSlope
if divType == HID_BULL
isSlopeBest := currentSlope < pastSlope
isSlopeBest
findDivergenceLines(rsPivBar, pivotsFound, chartType, divType, cancelDiv, bars, equalityType) =>
ChartCoordinates chartCoord = ChartCoordinates.new()
array<ChartCoordinates> chartCoords = array.new<ChartCoordinates>()
numberOfBars = 0
//The left side pivot analysis is SUPPOSED to begin in as little as just one bar left from the rightside pivot. The rsPivBar inherently already includes the first bar so (divergenceMin - 1) is necessary.
i_lsPivBar = (rsPivBar + (divergenceMin - 1))
//This construct prevents the error from series variables looking back further than the 1st bar. pivSearchLimit represents bar indexes which start at 0 and fullDivLenMax starts at 1
pivSearchLimit = (((fullDivLenMax - 1) - LSPivLBars) > bar_index) ? bar_index : ((fullDivLenMax - 1) - LSPivLBars)
// Price: Test for Lower low
while i_lsPivBar <= pivSearchLimit
if cancelDiv == true
break
//FIX: pivotsFound[i_lsPivBar - LSPivRBars] is the array problem. You have to work out the correct starting position for i_lsPivBar and also the correct minimum for LSPivRBars at the top
if pivotsFound[i_lsPivBar - LSPivRBars] == true
cancelLine = false
if compareBars(bars[i_lsPivBar], equalityType, bars[rsPivBar])
cancelLine := true
if cancelLine == false
chartCoord.x1 := i_lsPivBar
chartCoord.y1 := bars[i_lsPivBar]
chartCoord.x2 := rsPivBar
chartCoord.y2 := bars[rsPivBar]
array.push(chartCoords, ChartCoordinates.copy(chartCoord))//array.push() and also the assignment operator passes by reference or a pointer apparently. copy() is necessary.
i_lsPivBar := i_lsPivBar + 1
chartCoords
filterDivergenceLines(rsPivBar, cancelDiv, bars, divType, chartType, chartCoords) =>
chartCoordsTemp = array.copy(chartCoords)
for i = (array.size(chartCoordsTemp) - 1) to 0
if cancelDiv == true or array.size(chartCoordsTemp) == 0
break
chartCoordCur = array.get(chartCoordsTemp, i)
x1 = chartCoordCur.x1
y1 = chartCoordCur.y1
x2 = chartCoordCur.x2
y2 = chartCoordCur.y2
cancelLine = false
if isDivIntersectedByXAmount(chartType, divType, x1, y1, x2, y2) == true and (cancelLine == false)
array.remove(chartCoordsTemp, i)
cancelLine := true
if useBestSlope and ((i - 1) >= 0 ) and (array.size(chartCoordsTemp) > 1) and (cancelLine == false)
chartCoordPrev= array.get(chartCoordsTemp, i - 1)
x1_prev = chartCoordPrev.x1
y1_prev = chartCoordPrev.y1
x2_prev = chartCoordPrev.x2
y2_prev = chartCoordPrev.y2
if isCurrentSlopeBetter(x1_prev, y1_prev, x2_prev, y2_prev, x1, y1, x2, y2, chartType, divType) == true
array.remove(chartCoordsTemp, i - 1)
cancelLine := true
else
array.remove(chartCoordsTemp, i)
cancelLine := true
if useSlopeAngExc and isSlopeAngleInRange(x1, y1, x2, y2, chartType) and (cancelLine == false)
array.remove(chartCoordsTemp, i)
cancelLine := true
chartCoordsTemp
filterDivergenceLinesByLen(cancelDiv, chartCoords_Price, chartCoords_Osc) =>
chartCoordsPrice_Ret = array.copy(chartCoords_Price)
chartCoordsOsc_Ret = array.copy(chartCoords_Osc)
var ACCEPT = true
var REJECT = false
prc_score = array.new_bool()
osc_score = array.new_bool()
if (array.size(chartCoordsPrice_Ret) > 0) and (array.size(chartCoordsOsc_Ret) > 0) and cancelDiv == false
for i = 0 to (array.size(chartCoordsPrice_Ret) - 1)
array.push(prc_score, REJECT)
for i = 0 to (array.size(chartCoordsOsc_Ret) - 1)
array.push(osc_score, REJECT)
for i = 0 to (array.size(chartCoordsPrice_Ret) - 1)
for j = 0 to (array.size(chartCoordsOsc_Ret) - 1)
chartCoord_prc = array.get(chartCoordsPrice_Ret, i)
chartCoord_osc = array.get(chartCoordsOsc_Ret, j)
x1_prc = chartCoord_prc.x1
x2_prc = chartCoord_prc.x2
x1_osc = chartCoord_osc.x1
x2_osc = chartCoord_osc.x2
lenPrice = x1_prc - x2_prc
lenOsc = x1_osc - x2_osc
biggerLine = 0.0
smallerLine = 0.0
if (lenPrice > lenOsc)
biggerLine := lenPrice
smallerLine := lenOsc
else
biggerLine := lenOsc
smallerLine := lenPrice
if ((smallerLine / biggerLine) * 100) >= minDivLength
array.set(prc_score, i, ACCEPT)
array.set(osc_score, j, ACCEPT)
for i = (array.size(chartCoords_Price) - 1) to 0
if array.get(prc_score, i) == REJECT
array.remove(chartCoordsPrice_Ret, i)
for i = (array.size(chartCoords_Osc) - 1) to 0
if array.get(osc_score, i) == REJECT
array.remove(chartCoordsOsc_Ret, i)
[chartCoordsPrice_Ret, chartCoordsOsc_Ret]
display(divType, chartType, chartCoords, isDivergence, isRealtime) =>
lineAndLabelColor = bullColor
labelStyle = label.style_label_down
displayDivLines = false
displayDivLabels = false
labelText = ""
var array<line> rt_DivLines_Bull = array.new<line>()
var array<line> rt_DivLines_HidBull = array.new<line>()
var array<line> rt_DivLines_Bear = array.new<line>()
var array<line> rt_DivLines_HidBear = array.new<line>()
var array<label> rt_DivLabels_Bull = array.new<label>()
var array<label> rt_DivLabels_HidBull = array.new<label>()
var array<label> rt_DivLabels_Bear = array.new<label>()
var array<label> rt_DivLabels_HidBear = array.new<label>()
if shouldDivergenceBeDisplayed(chartType, isDivergence, isRealtime)
for chartCoord in chartCoords
x1 = chartCoord.x1
y1 = chartCoord.y1
x2 = chartCoord.x2
y2 = chartCoord.y2
array<line> rt_DivLines = na
array<label> rt_DivLabels = na
//Prepare the lines and labels for display
if divType == REG_BULL
rt_DivLines := rt_DivLines_Bull
rt_DivLabels := rt_DivLabels_Bull
labelText := "B"
lineAndLabelColor := bullColor
labelStyle := ((isRealtime and plotBull) or (isRealtime == false)) ? label.style_label_up : label.style_diamond//If lines are disabled then change label.style_ of realtime labels to distinguish them from historical labels
displayDivLines := plotBull
displayDivLabels := plotBullLabels
else if divType == HID_BULL
rt_DivLines := rt_DivLines_HidBull
rt_DivLabels := rt_DivLabels_HidBull
labelText := "HB"
lineAndLabelColor := hiddenBullColor
labelStyle := ((isRealtime and plotHiddenBull) or (isRealtime == false)) ? label.style_label_up : label.style_diamond
displayDivLines := plotHiddenBull
displayDivLabels := plotHidBullLabels
else if divType == REG_BEAR
rt_DivLines := rt_DivLines_Bear
rt_DivLabels := rt_DivLabels_Bear
labelText := "Br"
lineAndLabelColor := bearColor
labelStyle := ((isRealtime and plotBear) or (isRealtime == false)) ? label.style_label_down : label.style_diamond
displayDivLines := plotBear
displayDivLabels := plotBearLabels
else
rt_DivLines := rt_DivLines_HidBear
rt_DivLabels := rt_DivLabels_HidBear
labelText := "HBr"
lineAndLabelColor := hiddenBearColor
labelStyle := ((isRealtime and plotHiddenBear) or (isRealtime == false))? label.style_label_down : label.style_diamond
displayDivLines := plotHiddenBear
displayDivLabels := plotHidBearLabels
if useLabelText == false
labelText := ""
//FIX: This section of code is buggy. The quantity of lines displayed do not always match what they ought to be according to the settings.
//Also, I'm pretty sure there is some issue that probably has something to do with the line and label deletion. Something was left undone I think but I forget what
if isRealtime and (last_bar_index - bar_index) < rtDivDisplayBarQuantity
// array.push(rt_DivLines_Bull, line.new(bar_index - x1_, y1_, bar_index - x2_, y2_, color = lineAndLabelColor, width = 2, style = isRealtime ? line.style_dashed : line.style_solid))
if displayDivLines
array.push(rt_DivLines, line.new(bar_index - x1, y1, bar_index - x2, y2, color = lineAndLabelColor, width = 2, style = line.style_dashed))
if showAngles
displayDivLineAngles(x1, y1, x2, y2, chartType, divType)
if showDivIntersection
displayIntersectionAmount(chartType, divType, x1, y1, x2, y2)
//Delete unwanted past divergence lines
if array.size(rt_DivLines) > rtDivDisplayQuantity
length = array.size(rt_DivLines) - rtDivDisplayQuantity - 1
for i = 0 to length
line.delete(array.get(rt_DivLines, i))
if array.size(rt_DivLines) > rtDivDisplayQuantity
length = array.size(rt_DivLines) - rtDivDisplayQuantity - 1
for i = 0 to length
array.remove(rt_DivLines, 0)
if displayDivLabels
array.push(rt_DivLabels, label.new(bar_index - x2, y2, color = lineAndLabelColor, size = size.small, style = labelStyle, text = labelText, textcolor = textColor))
//Delete unwanted past divergence labels
if array.size(rt_DivLabels) > rtDivDisplayQuantity
length = array.size(rt_DivLabels) - rtDivDisplayQuantity - 1
for i = 0 to length
label.delete(array.get(rt_DivLabels, i))
if array.size(rt_DivLabels) > rtDivDisplayQuantity
length = array.size(rt_DivLabels) - rtDivDisplayQuantity - 1
for i = 0 to length
array.shift(rt_DivLabels)
else if isRealtime == false
if displayDivLines
line.new(bar_index - x1, y1, bar_index - x2, y2, color = lineAndLabelColor, width = 2)
if showAngles
displayDivLineAngles(x1, y1, x2, y2, chartType, divType)
if showDivIntersection
displayIntersectionAmount(chartType, divType, x1, y1, x2, y2)
if displayDivLabels
label.new(bar_index - x2, y2, color = lineAndLabelColor, size = size.small, style = labelStyle, text = labelText, textcolor = textColor)
isPotentialBullDiv = false
isPotentialHidBullDiv = false
isPotentialBearDiv = false
isPotentialHidBearDiv = false
realtimePotentialDivAlerts(divType, isDivergence) =>
labelText = ""
selectedColor = color.red
float YDeviation = 0.0000
var array<label> rt_AlertLabels_Bull = array.new<label>()
var array<label> rt_AlertLabels_HidBull = array.new<label>()
var array<label> rt_AlertLabels_Bear = array.new<label>()
var array<label> rt_AlertLabels_HidBear = array.new<label>()
array<label> rt_AlertLabels = array.new<label>()
if divType == REG_BULL
labelText := "Potential Regular Bull"
selectedColor := bullColor
YDeviation := YAdditive
rt_AlertLabels := rt_AlertLabels_Bull
else if divType == HID_BULL
labelText := "Potential Hidden Bull"
selectedColor := hiddenBullColor
YDeviation := YSpacing + YAdditive
rt_AlertLabels := rt_AlertLabels_HidBull
else if divType == REG_BEAR
labelText := "Potential Regular Bear"
selectedColor := bearColor
YDeviation := (YSpacing * 2.0) + YAdditive
rt_AlertLabels := rt_AlertLabels_Bear
else
labelText := "Potential Hidden Bear"
selectedColor := hiddenBearColor
YDeviation := (YSpacing * 3.0) + YAdditive
rt_AlertLabels := rt_AlertLabels_HidBear
if shouldPotentialDivBeAlerted(isDivergence)
array.push(rt_AlertLabels, label.new(last_bar_index + XAdditive, close + YDeviation, labelText, color = selectedColor, style = label.style_label_lower_left, textcolor = textColor) )
alert(labelText, alert.freq_once_per_bar)
else
array.push(rt_AlertLabels, na)
while array.size(rt_AlertLabels) >= 2
label.delete(array.first(rt_AlertLabels))
array.shift(rt_AlertLabels)
isBullDiv = false
isHidBullDiv = false
isBearDiv = false
isHidBearDiv = false
divAlerts(divType, isDivergence) =>
labelText = ""
selectedColor = color.red
float YDeviation = 0.0000
var array<label> rt_AlertLabels_Bull = array.new<label>()
var array<label> rt_AlertLabels_HidBull = array.new<label>()
var array<label> rt_AlertLabels_Bear = array.new<label>()
var array<label> rt_AlertLabels_HidBear = array.new<label>()
array<label> rt_AlertLabels = array.new<label>()
if divType == REG_BULL
labelText := "Regular Bull"
selectedColor := bullColor
YDeviation := YAdditive
rt_AlertLabels := rt_AlertLabels_Bull
else if divType == HID_BULL
labelText := "Hidden Bull"
selectedColor := hiddenBullColor
YDeviation := YSpacing + YAdditive
rt_AlertLabels := rt_AlertLabels_HidBull
else if divType == REG_BEAR
labelText := "Regular Bear"
selectedColor := bearColor
YDeviation := (YSpacing * 2) + YAdditive
rt_AlertLabels := rt_AlertLabels_Bear
else
labelText := "Hidden Bear"
selectedColor := hiddenBearColor
YDeviation := (YSpacing * 3) + YAdditive
rt_AlertLabels := rt_AlertLabels_HidBear
if shouldDivBeAlerted(isDivergence)
array.push(rt_AlertLabels, label.new(last_bar_index + XAdditive, close + YDeviation, labelText, color = selectedColor, style = label.style_label_lower_left, textcolor = textColor) )
alert(labelText, alert.freq_once_per_bar)
else
array.push(rt_AlertLabels, na)
while array.size(rt_AlertLabels) >= 2
label.delete(array.first(rt_AlertLabels))
array.shift(rt_AlertLabels)
[rsPivLows_Osc, rsPivLows_Price, rsPivHighs_Osc, rsPivHighs_Price, lsPivLows_Osc, lsPivLows_Price, lsPivHighs_Osc, lsPivHighs_Price] = findPivots(RSPivLBars, RSPivRBars, LSPivLBars, LSPivRBars)
[rt_rsPivLows_Osc, rt_rsPivLows_Price, rt_rsPivHighs_Osc, rt_rsPivHighs_Price, rt_lsPivLows_Osc, rt_lsPivLows_Price, rt_lsPivHighs_Osc, rt_lsPivHighs_Price] = findPivots(RSPivLBars, 0, LSPivLBars, LSPivRBars)
//TODO: Remove or deal with reduntant divergences right next to one another. The "Rightside Misalignment Allowance" leads to lots of reduntant divergences on screen right next to one another
rsDevPivs := findDeviatedRSPivots(rsPivLows_Osc, rsPivLows_Price, rsPivHighs_Osc, rsPivHighs_Price, RSPivRBars)
rt_rsDevPivs := findDeviatedRSPivots(rt_rsPivLows_Osc, rt_rsPivLows_Price, rt_rsPivHighs_Osc, rt_rsPivHighs_Price, 0)
//FIX: Does array.copy() even need to be used anywhere other than inside findDivergenceLines() ?
////////////------------------------------------------------------------------------------
////// Regular Bullish-----
if (plotBull or plotBullLabels) and doHistorical
divergenceCanceled := areRSDivergencePreconditionsOK(ALL_BULLS, rsDevPivs, false)
//Price: Test for lower low
chartCoords_PriceB1 = array.copy(findDivergenceLines(rsDevPivs.pricePLBar, lsPivLows_Price, PRICE_CHART, REG_BULL, divergenceCanceled , prc_AllBulls, LESS_THAN))
chartCoords_PriceB2 = array.copy(filterDivergenceLines(rsDevPivs.pricePLBar, divergenceCanceled , prc_AllBulls, REG_BULL, PRICE_CHART, chartCoords_PriceB1))
//Oscillator: Test for higher low
chartCoord_OscB1 = array.copy(findDivergenceLines(rsDevPivs.oscPLBar, lsPivLows_Osc, OSC_CHART, REG_BULL, divergenceCanceled , osc_AllBulls, GREATER_THAN))
chartCoord_OscB2 = array.copy(filterDivergenceLines(rsDevPivs.oscPLBar, divergenceCanceled , osc_AllBulls, REG_BULL, OSC_CHART, chartCoord_OscB1))
[chartCoords_PriceB3, chartCoord_OscB3] = filterDivergenceLinesByLen(divergenceCanceled, chartCoords_PriceB2, chartCoord_OscB2)
//If both the price chart and oscillator have at least one line each then it's an acceptable divergence
isBullDiv := (array.size(chartCoords_PriceB3) > 0 and array.size(chartCoord_OscB3) > 0)
display(REG_BULL, PRICE_CHART, chartCoords_PriceB3, isBullDiv, false)
display(REG_BULL, OSC_CHART, chartCoord_OscB3, isBullDiv, false)
divAlerts(REG_BULL, isBullDiv)
//Realtime
if (plotBull or plotBullLabels) and doRealtime
divergenceCanceled := areRSDivergencePreconditionsOK(ALL_BULLS, rt_rsDevPivs, true)
//Price: Test for lower low
chartCoords_PriceB1 = array.copy(findDivergenceLines(rt_rsDevPivs.pricePLBar, rt_lsPivLows_Price, PRICE_CHART, REG_BULL, divergenceCanceled , prc_AllBulls, LESS_THAN))
chartCoords_PriceB2 = array.copy(filterDivergenceLines(rt_rsDevPivs.pricePLBar, divergenceCanceled , prc_AllBulls, REG_BULL, PRICE_CHART, chartCoords_PriceB1))
//Oscillator: Test for higher low
chartCoord_OscB1 = array.copy(findDivergenceLines(rt_rsDevPivs.oscPLBar, rt_lsPivLows_Osc, OSC_CHART, REG_BULL, divergenceCanceled , osc_AllBulls, GREATER_THAN))
chartCoord_OscB2 = array.copy(filterDivergenceLines(rt_rsDevPivs.oscPLBar, divergenceCanceled , osc_AllBulls, REG_BULL, OSC_CHART, chartCoord_OscB1))
[chartCoords_PriceB3, chartCoord_OscB3] = filterDivergenceLinesByLen(divergenceCanceled, chartCoords_PriceB2, chartCoord_OscB2)
//If both the price chart and oscillator have at least one line each then it's an acceptable divergence
isPotentialBullDiv := (array.size(chartCoords_PriceB3) > 0 and array.size(chartCoord_OscB3) > 0)
display(REG_BULL, PRICE_CHART, chartCoords_PriceB3, isPotentialBullDiv, true)
display(REG_BULL, OSC_CHART, chartCoord_OscB3, isPotentialBullDiv, true)
realtimePotentialDivAlerts(REG_BULL, isPotentialBullDiv)
////////////------------------------------------------------------------------------------
////// Hidden Bullish-----
if (plotHiddenBull or plotHidBullLabels) and doHistorical
divergenceCanceled := areRSDivergencePreconditionsOK(ALL_BULLS, rsDevPivs, false)
//Price: Test for higher low
chartCoords_PriceHB1 = array.copy(findDivergenceLines(rsDevPivs.pricePLBar, lsPivLows_Price, PRICE_CHART, HID_BULL, divergenceCanceled , prc_AllBulls, GREATER_THAN))
chartCoords_PriceHB2 = array.copy(filterDivergenceLines(rsDevPivs.pricePLBar, divergenceCanceled , prc_AllBulls, HID_BULL, PRICE_CHART, chartCoords_PriceHB1))
//Oscillator: Test for lower low
chartCoord_OscHB1 = array.copy(findDivergenceLines(rsDevPivs.oscPLBar, lsPivLows_Osc, OSC_CHART, HID_BULL, divergenceCanceled , osc_AllBulls, LESS_THAN))
chartCoord_OscHB2 = array.copy(filterDivergenceLines(rsDevPivs.oscPLBar, divergenceCanceled , osc_AllBulls, HID_BULL, OSC_CHART, chartCoord_OscHB1))
[chartCoords_PriceHB3, chartCoord_OscHB3] = filterDivergenceLinesByLen(divergenceCanceled , chartCoords_PriceHB2, chartCoord_OscHB2)
//If both the price chart and oscillator have at least one line each then it's an acceptable divergence
isHidBullDiv := (array.size(chartCoords_PriceHB3) > 0 and array.size(chartCoord_OscHB3) > 0)
display(HID_BULL, PRICE_CHART, chartCoords_PriceHB3, isHidBullDiv, false)
display(HID_BULL, OSC_CHART, chartCoord_OscHB3, isHidBullDiv, false)
divAlerts(HID_BULL, isHidBullDiv)
//Realtime
if (plotHiddenBull or plotHidBullLabels) and doRealtime
divergenceCanceled := areRSDivergencePreconditionsOK(ALL_BULLS, rt_rsDevPivs, true)
//Price: Test for higher low
chartCoords_PriceHB1 = array.copy(findDivergenceLines(rt_rsDevPivs.pricePLBar, rt_lsPivLows_Price, PRICE_CHART, HID_BULL, divergenceCanceled , prc_AllBulls, GREATER_THAN))
chartCoords_PriceHB2 = array.copy(filterDivergenceLines(rt_rsDevPivs.pricePLBar, divergenceCanceled , prc_AllBulls, HID_BULL, PRICE_CHART, chartCoords_PriceHB1))
//Oscillator: Test for lower low
chartCoord_OscHB1 = array.copy(findDivergenceLines(rt_rsDevPivs.oscPLBar, rt_lsPivLows_Osc, OSC_CHART, HID_BULL, divergenceCanceled , osc_AllBulls, LESS_THAN))
chartCoord_OscHB2 = array.copy(filterDivergenceLines(rt_rsDevPivs.oscPLBar, divergenceCanceled , osc_AllBulls, HID_BULL, OSC_CHART, chartCoord_OscHB1))
[chartCoords_PriceHB3, chartCoord_OscHB3] = filterDivergenceLinesByLen(divergenceCanceled , chartCoords_PriceHB2, chartCoord_OscHB2)
//If both the price chart and oscillator have at least one line each then it's an acceptable divergence
isPotentialHidBullDiv := (array.size(chartCoords_PriceHB3) > 0 and array.size(chartCoord_OscHB3) > 0)
display(HID_BULL, PRICE_CHART, chartCoords_PriceHB3, isPotentialHidBullDiv, true)
display(HID_BULL, OSC_CHART, chartCoord_OscHB3, isPotentialHidBullDiv, true)
realtimePotentialDivAlerts(HID_BULL, isPotentialHidBullDiv)
////////////------------------------------------------------------------------------------
////// Regular Bearish-----
if (plotBear or plotBearLabels) and doHistorical
divergenceCanceled := areRSDivergencePreconditionsOK(ALL_BEARS, rsDevPivs, false)
//Price: Test for higher high
chartCoords_PriceBr1 = array.copy(findDivergenceLines(rsDevPivs.pricePHBar, lsPivHighs_Price, PRICE_CHART, REG_BEAR, divergenceCanceled , prc_AllBears, GREATER_THAN))
chartCoords_PriceBr2 = array.copy(filterDivergenceLines(rsDevPivs.pricePHBar, divergenceCanceled , prc_AllBears, REG_BEAR, PRICE_CHART, chartCoords_PriceBr1))
//Oscillator: Test for lower high
chartCoord_OscBr1 = array.copy(findDivergenceLines(rsDevPivs.oscPHBar, lsPivHighs_Osc, OSC_CHART, REG_BEAR, divergenceCanceled , osc_AllBears, LESS_THAN))
chartCoord_OscBr2 = array.copy(filterDivergenceLines(rsDevPivs.oscPHBar, divergenceCanceled , osc_AllBears, REG_BEAR, OSC_CHART, chartCoord_OscBr1))
[chartCoords_PriceBr3, chartCoord_OscBr3] = filterDivergenceLinesByLen(divergenceCanceled, chartCoords_PriceBr2, chartCoord_OscBr2)
//If both the price chart and oscillator have at least one line each then it's an acceptable divergence
isBearDiv := (array.size(chartCoords_PriceBr3) > 0 and array.size(chartCoord_OscBr3) > 0)
display(REG_BEAR, PRICE_CHART, chartCoords_PriceBr3, isBearDiv, false)
display(REG_BEAR, OSC_CHART, chartCoord_OscBr3, isBearDiv, false)
divAlerts(REG_BEAR, isBearDiv)
//Realtime
if (plotBear or plotBearLabels) and doRealtime
divergenceCanceled := areRSDivergencePreconditionsOK(ALL_BEARS, rt_rsDevPivs, true)
//Price: Test for higher high
chartCoords_PriceBr1 = array.copy(findDivergenceLines(rt_rsDevPivs.pricePHBar, rt_lsPivHighs_Price, PRICE_CHART, REG_BEAR, divergenceCanceled , prc_AllBears, GREATER_THAN))
chartCoords_PriceBr2 = array.copy(filterDivergenceLines(rt_rsDevPivs.pricePHBar, divergenceCanceled , prc_AllBears, REG_BEAR, PRICE_CHART, chartCoords_PriceBr1))
//Oscillator: Test for lower high
chartCoord_OscBr1 = array.copy(findDivergenceLines(rt_rsDevPivs.oscPHBar, rt_lsPivHighs_Osc, OSC_CHART, REG_BEAR, divergenceCanceled , osc_AllBears, LESS_THAN))
chartCoord_OscBr2 = array.copy(filterDivergenceLines(rt_rsDevPivs.oscPHBar, divergenceCanceled , osc_AllBears, REG_BEAR, OSC_CHART, chartCoord_OscBr1))
[chartCoords_PriceBr3, chartCoord_OscBr3] = filterDivergenceLinesByLen(divergenceCanceled, chartCoords_PriceBr2, chartCoord_OscBr2)
//If both the price chart and oscillator have at least one line each then it's an acceptable divergence
isPotentialBearDiv := (array.size(chartCoords_PriceBr3) > 0 and array.size(chartCoord_OscBr3) > 0)
display(REG_BEAR, PRICE_CHART, chartCoords_PriceBr3, isPotentialBearDiv, true)
display(REG_BEAR, OSC_CHART, chartCoord_OscBr3, isPotentialBearDiv, true)
realtimePotentialDivAlerts(REG_BEAR, isPotentialBearDiv)
////////////------------------------------------------------------------------------------
////// Hidden Bearish-----
if (plotHiddenBear or plotHidBearLabels) and doHistorical
divergenceCanceled := areRSDivergencePreconditionsOK(ALL_BEARS, rsDevPivs, false)
//Price: Test for lower high
chartCoords_PriceHBr1 = array.copy(findDivergenceLines(rsDevPivs.pricePHBar, lsPivHighs_Price, PRICE_CHART, HID_BEAR, divergenceCanceled , prc_AllBears, LESS_THAN))
chartCoords_PriceHBr2 = array.copy(filterDivergenceLines(rsDevPivs.pricePHBar, divergenceCanceled , prc_AllBears, HID_BEAR, PRICE_CHART, chartCoords_PriceHBr1))
//Oscillator: Test for higher high
chartCoord_OscHBr1 = array.copy(findDivergenceLines(rsDevPivs.oscPHBar, lsPivHighs_Osc, OSC_CHART, HID_BEAR, divergenceCanceled , osc_AllBears, GREATER_THAN))
chartCoord_OscHBr2 = array.copy(filterDivergenceLines(rsDevPivs.oscPHBar, divergenceCanceled , osc_AllBears, HID_BEAR, OSC_CHART, chartCoord_OscHBr1))
[chartCoords_PriceHBr3, chartCoord_OscHBr3] = filterDivergenceLinesByLen(divergenceCanceled, chartCoords_PriceHBr2, chartCoord_OscHBr2)
//If both the price chart and oscillator have at least one line each then it's an acceptable divergence
isHidBearDiv := (array.size(chartCoords_PriceHBr3) > 0 and array.size(chartCoord_OscHBr3) > 0)
display(HID_BEAR, PRICE_CHART, chartCoords_PriceHBr3, isHidBearDiv, false)
display(HID_BEAR, OSC_CHART, chartCoord_OscHBr3, isHidBearDiv, false)
divAlerts(HID_BEAR, isHidBearDiv)
//Realtime
if (plotHiddenBear or plotHidBearLabels) and doRealtime
divergenceCanceled := areRSDivergencePreconditionsOK(ALL_BEARS, rt_rsDevPivs, true)
//Price: Test for lower high
chartCoords_PriceHBr1 = array.copy(findDivergenceLines(rt_rsDevPivs.pricePHBar, rt_lsPivHighs_Price, PRICE_CHART, HID_BEAR, divergenceCanceled , prc_AllBears, LESS_THAN))
chartCoords_PriceHBr2 = array.copy(filterDivergenceLines(rt_rsDevPivs.pricePHBar, divergenceCanceled , prc_AllBears, HID_BEAR, PRICE_CHART, chartCoords_PriceHBr1))
//Oscillator: Test for higher high
chartCoord_OscHBr1 = array.copy(findDivergenceLines(rt_rsDevPivs.oscPHBar, rt_lsPivHighs_Osc, OSC_CHART, HID_BEAR, divergenceCanceled , osc_AllBears, GREATER_THAN))
chartCoord_OscHBr2 = array.copy(filterDivergenceLines(rt_rsDevPivs.oscPHBar, divergenceCanceled , osc_AllBears, HID_BEAR, OSC_CHART, chartCoord_OscHBr1))
[chartCoords_PriceHBr3, chartCoord_OscHBr3] = filterDivergenceLinesByLen(divergenceCanceled, chartCoords_PriceHBr2, chartCoord_OscHBr2)
//If both the price chart and oscillator have at least one line each then it's an acceptable divergence
isPotentialHidBearDiv := (array.size(chartCoords_PriceHBr3) > 0 and array.size(chartCoord_OscHBr3) > 0)
display(HID_BEAR, PRICE_CHART, chartCoords_PriceHBr3, isPotentialHidBearDiv, true)
display(HID_BEAR, OSC_CHART, chartCoord_OscHBr3, isPotentialHidBearDiv, true)
realtimePotentialDivAlerts(HID_BEAR, isPotentialHidBearDiv)
|
Liquidity Sentiment Profile (Auto-Anchored) [LuxAlgo] | https://www.tradingview.com/script/V30Sbp5O-Liquidity-Sentiment-Profile-Auto-Anchored-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,601 | 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 Sentiment Profile (Auto-Anchored) [LuxAlgo]", "LuxAlgo - Liquidity Sentiment Profile (Auto-Anchored)", true, max_bars_back = 5000, max_boxes_count = 500, max_lines_count = 500)
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
rpGR = 'Liquidity Sentiment Profile'
tfTP = 'The indicator resolution is set by the input of the Anchor Period. If the Anchor Period is set to AUTO, then the increased resolution is determined by the following algorithm:\n\n' +
' - for intraday resolutions up to 4 Hour, DAY (1D) is used\n - for intraday resolutions equal to 4 Hour, WEEK (1W) is used\n - for daily resolutions MONTH is used (1M)\n - for weekly resolution, 3-MONTH (3M) is used\n - for monthly resolution, 12-MONTH (12M) is used\n\n' +
'If the Anchor Period is set to Fixed Range then the period is defined in the \'Fixed Period\' option\n\n' +
'If the Anchor Period is set to Swing High or Swing Low then the length required to calculate Swing Levels is defined in the \'Swing Detection Length\' option\n\n' +
'Note : Difference between Session and Day\n - Day will take into account extended hours (if present on the chart), whereas\n - Session will assume only regular trading hours. Session is default value for AUTO Anchor Period'
tfIN = input.string('Fixed Range', 'Anchor Period', options=['Auto', 'Fixed Range', 'Swing High', 'Swing Low', 'Session', 'Day', 'Week', 'Month', 'Quarter', 'Year'], group = rpGR, tooltip = tfTP)
tfOT = tfIN == 'Session' or tfIN == 'Day' ? 'D' : tfIN == 'Week' ? 'W' : tfIN == 'Month' ? 'M' : tfIN == 'Quarter' ? '3M' : tfIN == 'Year' ? '12M' : timeframe.isintraday and timeframe.period != '240' ? 'D' : timeframe.period == '240' ? 'W' : timeframe.isdaily ? 'M' : timeframe.isweekly ? '3M' : '12M'
drpTT = 'Applicable if the Anchor Period is set to \'Fixed Range\' then the period of the profile is defined with this option\n\npossible min value [10]'
drpLN = input.int(360, 'Fixed Period', minval = 10, group = rpGR, tooltip = drpTT)
ppTT = 'Applicable if the Anchor Period is set to \'Swing High\' or \'Swing Low\' then the length required to detect the Swing Levels is defined with this option\n\npossible min value [1]'
ppLen = input.int(47, "Swing Detection Length", minval = 1, group = rpGR, tooltip = ppTT)
lpGR = 'Liquidity Profile'
vpTP = 'In trading, liquidity refers to the availability of orders at specific price points in the market, allowing transactions to occur smoothly, and the profile displays total trading activity (common interest, both buying and selling trading activity) over a specified time period at specific price levels\n\n' +
' - high volume node rows : high trading activity price levels - usually represents consolidation levels (value areas)\n' +
' - average volume node rows : average trading activity price levels\n' +
' - low volume node rows : low trading activity price levels - usually represents supply & demand levels or liquidity levels\n\n' +
'row lengths, indicates the amount of the traded activity'
vpSH = input.bool(true, 'Liquidity Profile', group = lpGR, tooltip = vpTP)
vpHVC = input.color(color.new(#ff9800, 11), 'High Traded Nodes', inline='VP1', group = lpGR)
vpHVT = input.int(53, 'Threshold %' , minval = 47, maxval = 99 , step = 1,inline='VP1', group = lpGR, tooltip = 'possible values [47-99]') / 100
vpAVC = input.color(color.new(#5d606b, 51), 'Average Traded Nodes', inline='VP3' , group = lpGR)
vpLVC = input.color(color.new(#2962ff, 11), 'Low Traded Nodes ', inline='VP2', group = lpGR)
vpLVT = input.int(27, 'Threshold %' , minval = 10, maxval = 47 , step = 1,inline='VP2', group = lpGR, tooltip = 'possible values [10-47]') / 100
spGR = 'Sentiment Profile'
spTP = 'displays the sentiment, the dominat party over a specified time period at the specific price levels\n\n' +
' - bullish node rows : buying trading activity is higher\n' +
' - barish node rows : selling trading activity is higher\n\n' +
'row lengths, indicates the strength of the buyers/sellers at the specific price levels'
spSH = input.bool(true, 'Sentiment Profile', group = spGR, tooltip = spTP)
spBLC = input.color(color.new(#26a69a, 73), 'Bullish Nodes', inline='SP', group = spGR)
spBRC = input.color(color.new(#ef5350, 73), 'Bearish Nodes', inline='SP', group = spGR)
sdGR = 'Buyside & Sellside Liquidity Zones'
sdTP = 'Typically refer to the resting orders in the market, such as limit orders, stop loss orders, and stop limit orders, which can be absorbed or targeted by banks or financial institutions. Those levels are also reffered as supply & demand levels in the market'
sdSH = input.bool(true, 'Buyside & Sellside Liquidity Zones', group = sdGR, tooltip = sdTP)
sdTH = input.int(13, 'Threshold %' , minval = 0, maxval = 31, group = sdGR, tooltip = 'possible threshold values [0-31]\n\nhigher values return wider areas') / 100
sdCR = input.color(color.new(#0094FF, 81), 'Buyside Liquidity Nodes', inline='low2', group = sdGR)
sdCS = input.color(color.new(#ec1313, 81), 'Sellside Liquidity Nodes', inline='low2', group = sdGR)
othGR = 'Other Settings'
pcTP = 'displays the changes of the price levels with the highest traded activity'
rpPC = input.bool(false, 'Level of Significance', inline='PoC', group = othGR, tooltip = pcTP)
rpPCC = input.color(color.new(#ff0000, 1), '', inline='PoC', group = othGR)
rpPCW = input.int(2, '', inline='PoC', group = othGR)
rpPL = input.bool(false, 'Price Levels, Color', inline='BBe', group = othGR)
rpPLC = input.color(color.new(#00bcd4, 1), '', inline='BBe', group = othGR)
rpLS = input.string('Small', "Size", options=['Tiny', 'Small', 'Normal'], inline='BBe', group = othGR)
rpS = switch rpLS
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
rpNR = input.int(123, 'Number of Rows' , minval = 10, maxval = 155 ,step = 5, group = othGR, tooltip = 'possible values [10-155]')
rpW = input.int(27, 'Profile Width %', minval = 10, maxval = 50, group = othGR, tooltip = 'possible values [10-50]') / 100
drpHO = input.int(13, 'Horizontal Offset', minval = 0, maxval = 100 ,group = othGR, tooltip = 'plotting by default will be performed on rightmost, where\nhorizontal offset option is for further adjustments\npossible values [0-100]')
rpBG = input.bool(true, 'Range Background Fill', inline ='BG', group = othGR)
rpBGC = input.color(color.new(#00bcd4, 95), '', inline ='BG', group = othGR)
//-----------------------------------------------------------------------------}
// User Defined Types
//-----------------------------------------------------------------------------{
// @type bar properties with their values
//
// @field o (float) open price of the bar
// @field h (float) high price of the bar
// @field l (float) low price of the bar
// @field c (float) close price of the bar
// @field v (float) volume of the bar
// @field i (int) index of the bar
type bar
float o = open
float h = high
float l = low
float c = close
float v = volume
int i = bar_index
// @type store pivot high/low and index data
//
// @field x (int) last pivot bar index
// @field h (float) last pivot high
// @field h1 (float) previous pivot high
// @field l (float) last pivot low
// @field l1 (float) previous pivot low
type pivotPoint
int x
float h
float h1
float l
float l1
//-----------------------------------------------------------------------------}
// Variables
//-----------------------------------------------------------------------------{
bar b = bar.new()
var pivotPoint pp = pivotPoint.new()
bull = b.c > b.o
nzV = nz(b.v)
rpVST = array.new_float(rpNR + 1, 0.)
rpVSB = array.new_float(rpNR + 1, 0.)
rpVSD = array.new_float(rpNR + 1, 0.)
var dRP = array.new_box()
var dPC = array.new_line()
var int x2 = 0
var float pir = na
var int pp_x = na
var float pp_y = na
//-----------------------------------------------------------------------------}
// Functions/methods
//-----------------------------------------------------------------------------{
// @function creates new label object and updates existing label objects
//
// @param details in Pine Script™ language reference manual
//
// @returns none, updated visual objects (labels)
f_drawLabelX(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) =>
var lb = label.new(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip)
lb.set_xy(_x, _y)
lb.set_text(_text)
lb.set_tooltip(_tooltip)
lb.set_textcolor(_textcolor)
//-----------------------------------------------------------------------------}
// Calculations
//-----------------------------------------------------------------------------{
pp_h = ta.pivothigh(ppLen, ppLen)
pp_l = ta.pivotlow (ppLen, ppLen)
if not na(pp_h) and tfIN == 'Swing High'
pp.h1 := pp.h
pp.h := pp_h
pp_y := pp_h
pp_x := b.i
if not na(pp_l) and tfIN == 'Swing Low'
pp.l1 := pp.l
pp.l := pp_l
pp_y := pp_l
pp_x := b.i
if tfOT == 'D' and tfIN == 'Day' ? dayofweek != dayofweek[1] : ta.change(time(tfOT))
x2 := b.i
rpLN = tfIN == 'Fixed Range' ? drpLN : barstate.islast ? tfIN == 'Swing High' or tfIN == 'Swing Low' ? last_bar_index - pp_x + ppLen : last_bar_index - x2 : 1
pHST = ta.highest(high, rpLN > 0 ? rpLN + 1 : 1)
pLST = ta.lowest (low , rpLN > 0 ? rpLN + 1 : 1)
pSTP = (pHST - pLST) / rpNR
if barstate.islast and nzV and timeframe.period != tfOT and rpLN > 1 and pSTP > 0 //and not timeframe.isseconds
if dRP.size() > 0
for i = 0 to dRP.size() - 1
box.delete(dRP.shift())
if dPC.size() > 0
for i = 0 to dPC.size() - 1
line.delete(dPC.shift())
for bI = rpLN to 0
l = 0
for pLL = pLST to pHST by pSTP
if b.h[bI] >= pLL and b.l[bI] < pLL + pSTP
rpVST.set(l, rpVST.get(l) + nzV[bI] * ((b.h[bI] - b.l[bI]) == 0 ? 1 : pSTP / (b.h[bI] - b.l[bI])) )
if bull[bI]
rpVSB.set(l, rpVSB.get(l) + nzV[bI] * ((b.h[bI] - b.l[bI]) == 0 ? 1 : pSTP / (b.h[bI] - b.l[bI])) )
l += 1
if rpPC
if bI == rpLN
pir := pLST + (rpVST.indexof(rpVST.max()) + .50) * pSTP
else
dPC.push(line.new(b.i[bI] - 1, pir, b.i[bI], pLST + (rpVST.indexof(rpVST.max()) + .50) * pSTP, color = rpPCC, width = rpPCW))
pir := pLST + (rpVST.indexof(rpVST.max()) + .50) * pSTP
for l = 0 to rpNR - 1
bbp = 2 * rpVSB.get(l) - rpVST.get(l)
rpVSD.set(l, rpVSD.get(l) + bbp * (bbp > 0 ? 1 : -1) )
if rpBG
dRP.push(box.new(b.i - rpLN, pLST, b.i, pHST, rpBGC, bgcolor = rpBGC ))
if rpPL
f_drawLabelX(b.i + drpHO + rpLN * rpW, pHST, str.tostring(pHST, format.mintick), xloc.bar_index, yloc.price, color(na), label.style_label_down, rpPLC, rpS, text.align_left, 'Profile High - ' + str.tostring(pHST, format.mintick) + '\n %' + str.tostring((pHST - pLST) / pLST * 100, '#.##') + ' higher than the Profile Low\n\nNumber of bars : ' + str.tostring(rpLN))
f_drawLabelX(b.i + drpHO + rpLN * rpW, pLST, str.tostring(pLST, format.mintick), xloc.bar_index, yloc.price, color(na), label.style_label_up , rpPLC, rpS, text.align_left, 'Profile Low - ' + str.tostring(pLST, format.mintick) + '\n %' + str.tostring((pHST - pLST) / pHST * 100, '#.##') + ' lower than the Profile High\n\nNumber of bars : ' + str.tostring(rpLN))
if tfIN == 'Swing High'
swH = pp.h > pp.h1 ? "HH" : pp.h < pp.h1 ? "LH" : na
f_drawLabelX(b.i[rpLN], pp.h, swH, xloc.bar_index, yloc.price, color(na), label.style_label_down, rpPLC, rpS, text.align_center, 'Swing High : ' + str.tostring(pp.h, format.mintick))
if tfIN == 'Swing Low'
swL = pp.l < pp.l1 ? "LL" : pp.l > pp.l1 ? "HL" : na
f_drawLabelX(b.i[rpLN], pp.l ,swL, xloc.bar_index, yloc.price, color(na), label.style_label_up , rpPLC, rpS, text.align_center, 'Swing Low : ' + str.tostring(pp.l, format.mintick))
for l = 0 to rpNR - 1
if vpSH
sBI = b.i - int(rpVST.get(l) / rpVST.max() * rpLN * rpW) + rpLN * rpW + drpHO
eBI = b.i + drpHO + rpLN * rpW
llC = rpVST.get(l) / rpVST.max() > vpHVT ? color.from_gradient(rpVST.get(l) / rpVST.max(), vpHVT, 1, vpAVC, vpHVC) : color.from_gradient(rpVST.get(l) / rpVST.max(), 0, vpLVT, vpLVC, vpAVC)
dRP.push(box.new(sBI, pLST + (l + 0.1) * pSTP, eBI, pLST + (l + 0.9) * pSTP, color(na), bgcolor = llC ))
//sBI := b.i - int( (rpVST.get(l) - rpVSB.get(l))/ rpVST.max() * rpLN * rpW) + rpLN * rpW + drpHO
//dRP.push(box.new(sBI, pLST + (l + 0.1) * pSTP, eBI, pLST + (l + 0.9) * pSTP, color(na), bgcolor = llC ))
if spSH
bbp = 2 * rpVSB.get(l) - rpVST.get(l)
sBI = b.i + int( rpVSD.get(l) / rpVSD.max() * rpLN * rpW / 2) + rpLN * rpW + drpHO
eBI = b.i + drpHO + rpLN * rpW
dRP.push(box.new(sBI, pLST + (l + 0.1) * pSTP, eBI, pLST + (l + 0.9) * pSTP, bbp > 0 ? spBLC : spBRC, bgcolor = bbp > 0 ? spBLC : spBRC ))
if sdSH and rpVST.get(l) / rpVST.max() < sdTH
dRP.push(box.new(b.i - rpLN, pLST + (l + 0.) * pSTP, b.i, pLST + (l + 1.) * pSTP, color(na), bgcolor = pLST + (l + .5) * pSTP > pLST + (rpVST.indexof(rpVST.max()) + .5) * pSTP ? sdCR : sdCS))
//-----------------------------------------------------------------------------} |
AI Channels (Clustering) [LuxAlgo] | https://www.tradingview.com/script/dLXvYOtT-AI-Channels-Clustering-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,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("AI Channels (Clustering) [LuxAlgo]", "LuxAlgo - AI Channels", overlay = true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input(30, 'Window Size')
K = input.int(5, 'Clusters', minval = 3, maxval = 10)
denoise = input(true, 'Denoise Channels')
asTs = input(false, 'As trailing Stop')
//Optimization
maxIter = input.int(500, 'Maximum Iteration Steps', minval = 0, group = 'Optimization')
maxData = input.int(5000, 'Historical Bars Calculation', minval = 0, group = 'Optimization')
//Style
upperCss = input(#00897B, 'Upper Zone', group = 'Style')
avgCss = input(#ff5d00, 'Average', group = 'Style')
lowerCss = input(#FF5252, 'Lower Zone', group = 'Style')
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type vector
array<float> out
//-----------------------------------------------------------------------------}
//K-means clustering
//-----------------------------------------------------------------------------{
data = array.new<float>(0)
//Populate data arrays
if last_bar_index - bar_index <= maxData
for i = 0 to length-1
data.push(close[i])
//Intitalize centroids using percentiles
centroids = array.new<float>(0)
for i = 1 to K
per = int(i/(K+1)*100)
centroids.push(data.percentile_linear_interpolation(per))
//Intialize clusters
var array<vector> clusters = na
if last_bar_index - bar_index <= maxData
for _ = 0 to maxIter
clusters := array.new<vector>(0)
for i = 0 to K-1
clusters.push(vector.new(array.new<float>(0)))
//Assign value to cluster
i = 0
for value in data
dist = array.new<float>(0)
for centroid in centroids
dist.push(math.abs(value - centroid))
idx = dist.indexof(dist.min())
if idx != -1
clusters.get(idx).out.push(value)
i += 1
//Update centroids
new_centroids = array.new<float>(0)
for cluster_ in clusters
new_centroids.push(cluster_.out.avg())
//Test if centroid changed
if new_centroids.get(0) == centroids.get(0) and new_centroids.get(1) == centroids.get(1) and new_centroids.get(2) == centroids.get(2)
break
centroids := new_centroids
//-----------------------------------------------------------------------------}
//Get channels
//-----------------------------------------------------------------------------{
var float upper = close
var float avg = close
var float lower = close
var float upper_dev = na
var float lower_dev = na
var float out_upper = na
var float out_avg = na
var float out_lower = na
var os = 0
if not na(clusters)
//Get centroids
upper := nz(centroids.get(K-1), upper)
avg := nz(centroids.get(int(math.avg(0, K-1))), avg)
lower := nz(centroids.get(0), lower)
os := close > upper ? 1 : close < lower ? 0 : os
upper_dev := clusters.get(K-1).out.stdev()
lower_dev := clusters.get(0).out.stdev()
if denoise
out_upper := nz(os ? math.max(upper, out_upper) : math.min(upper, out_upper), upper)
out_avg := nz(os ? math.max(avg, out_avg) : math.min(avg, out_avg), avg)
out_lower := nz(os ? math.max(lower, out_lower) : math.min(lower, out_lower), lower)
else
out_upper := upper
out_avg := avg
out_lower := lower
upper_min = out_upper - upper_dev
lower_max = out_lower + lower_dev
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
var bullCss = asTs ? lowerCss : upperCss
var bearCss = asTs ? upperCss : lowerCss
plot_upper = plot(asTs ? (os ? na : out_upper) : out_upper, 'Upper', bullCss
, style = plot.style_linebr)
plot(math.avg(out_upper, out_lower), 'Average', avgCss)
plot_lower = plot(asTs ? (os ? out_lower : na) : out_lower, 'Lower', bearCss
, style = plot.style_linebr)
//Cluster dispersion areas
plot_upper_min = plot(upper_min, color = na, editable = false)
plot_lower_max = plot(lower_max, color = na, editable = false)
fill(plot_upper, plot_upper_min, out_upper, upper_min, bullCss, color.new(bullCss, 90))
fill(plot_lower_max, plot_lower, lower_max, out_lower, color.new(bearCss, 90), bearCss)
//-----------------------------------------------------------------------------} |
RSI Screener Multi Timeframe [5ema] | https://www.tradingview.com/script/ZnIx7SIJ-RSI-Screener-Multi-Timeframe-5ema/ | vn5ema | https://www.tradingview.com/u/vn5ema/ | 44 | study | 5 | MPL-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 Screener Multi Timeframe [5ema]", overlay = true, shorttitle = "RSI Screener [5ema]")
// 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.")
/////// 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")
//////////
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 = timeframe.period, 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
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 (checkhdBull and checkOversold)
sgStrongSell = (checkBear and checkOverbought) or (checkhdBear and checkOverbought)
sgBuy_1 = checkhdBull and not checkOverbought
sgBuy_2 = checkBull and not checkOverbought
sgBuy = checkOversold or sgBuy_1 or sgBuy_2
sgSell_1 = checkhdBear and not checkOversold
sgSell_2 = checkBear and not checkOversold
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)
// 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 Screener - 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 Screener - 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 Screener - 5ema.vn)", freq = alert.freq_once_per_bar_close)
|
Smoothing ATR band | https://www.tradingview.com/script/MnT69yIM-Smoothing-ATR-band/ | khlin712 | https://www.tradingview.com/u/khlin712/ | 246 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © khlin712
//@version=5
indicator("Smoothing ATR band",shorttitle = 'SAB [khlin712]',overlay=true)
atrLen = input.int(title='Length', defval=20, minval=1)
smoothing = input.string(title='Smoothing', defval='RMA', options=['RMA', 'SMA', 'EMA', 'WMA'])
m = input.float(2, 'Multiplier')
src1 = high
src2 = low
pline = false
col1 = color.blue
col2 = color.teal
col3 = color.red
collong = color.teal
colshort = color.red
ma_function(source, atrLen) =>
if smoothing == 'RMA'
ta.rma(source, atrLen)
a = ma_function(ta.tr(true), atrLen) * m
ssl = ma_function(ta.tr(true), atrLen) * m + src1
lsl = src2 - ma_function(ta.tr(true), atrLen) * m
ma(source, atrLen, type) =>
switch type
"SMA" => ta.sma(source, atrLen)
"EMA" => ta.ema(source, atrLen)
"SMMA (RMA)" => ta.rma(source, atrLen)
"WMA" => ta.wma(source, atrLen)
"VWMA" => ta.vwma(source, atrLen)
typeMA = input.string(title = "Method", defval = "EMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
smoothingLength = input.int(title = "Length", defval = 8, minval = 1, group="Smoothing")
smoothingLineU = ma(ssl, smoothingLength, typeMA)
au=plot(smoothingLineU, title="Smoothing Line", color=color.new(#bd5be3, 30),linewidth=3)
plotshape(high>smoothingLineU and close<smoothingLineU,title='short',style=shape.labeldown,color=#db5e5e,location=location.abovebar,size=size.small)
smoothingLineD = ma(lsl, smoothingLength, typeMA)
ad=plot(smoothingLineD, title="Smoothing Line", color=color.new(#bd5be3,30),linewidth=3)
plotshape(low<smoothingLineD and close>smoothingLineD,title='long',style=shape.labelup,color=#68d94c,location=location.belowbar,size=size.small)
plot((smoothingLineU+smoothingLineD)/2, title="Base Line", color=color.new(#bd5be3, 30),linewidth=2,offset=1)
//alert
alertup=high>smoothingLineU and close<smoothingLineU==true
alertdown=low<smoothingLineD and close>smoothingLineD==true
// If you're free tradingview user, you are allowed to have one alert setting.
// Long and Short Opportunities will also trigger the alert
allert=alertup==true or alertdown==true
alertcondition(allert,title='SAB_alert(Recommended✅)',message='{{ticker}}, Price:{{close}}, Timeframe:{{interval}}, Trading Opportunity!')
// If setting many alerts is allowed,you can choose these two settings respectively.
alertcondition(alertup,title='SAB Long',message='{{ticker}}, Price:{{close}}, Timeframe:{{interval}}, SAB Long📈')
alertcondition(alertdown,title='SAB Short',message='{{ticker}}, Price:{{close}}, Timeframe:{{interval}}, SAB Short📉')
|
3M_RANGE/ErkOzi/ | https://www.tradingview.com/script/QeRWoouv/ | ErkOzi | https://www.tradingview.com/u/ErkOzi/ | 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/
// © ErkOzi
//@version=5
indicator(title='3M_RANGE', shorttitle='3M_RANGE', overlay=true)
// Define the range period
rangePeriod = '3M'
openPrice = request.security(syminfo.tickerid, rangePeriod, open)
highPrice = request.security(syminfo.tickerid, rangePeriod, high)
lowPrice = request.security(syminfo.tickerid, rangePeriod, low)
midPrice = (highPrice + lowPrice) / 2
// Function to check if it's Monday
isMonday() =>
dayofweek(time) == dayofweek.monday ? 1 : 0
// Store the 3-month range levels
var float mondayHighRange = na
var float mondayLowRange = na
if isMonday()
mondayHighRange := highPrice
mondayLowRange := lowPrice
// Plot the Monday open price levels
plot(isMonday() ? openPrice : na, title='3-M Eq / openPrice', style=plot.style_circles, linewidth=2, color=color.new(color.purple, 0))
// Extend the lines until the next Monday
var float nextMondayHigh = na
var float nextMondayLow = na
if isMonday()
nextMondayHigh := highPrice
nextMondayLow := lowPrice
else
nextMondayHigh := nz(nextMondayHigh[1], mondayHighRange)
nextMondayLow := nz(nextMondayLow[1], mondayLowRange)
// Plot the next 3-month high and low ranges
plot(nextMondayHigh, title='Next 3-M High Range', style=plot.style_linebr, linewidth=2, color=color.new(color.green, 0))
plot(nextMondayLow, title='Next 3-M Low Range', style=plot.style_linebr, linewidth=2, color=color.new(color.green, 0))
// Plot the 0.50 line
plot((nextMondayHigh + nextMondayLow) / 2, title='0.50', style=plot.style_linebr, linewidth=1, color=color.new(color.red, 0))
// Calculate Fibonacci levels
fib272 = nextMondayHigh + 0.272 * (nextMondayHigh - nextMondayLow)
fib414 = nextMondayHigh + 0.414 * (nextMondayHigh - nextMondayLow)
fib500 = nextMondayHigh + 0.5 * (nextMondayHigh - nextMondayLow)
fibNegative272 = nextMondayLow - 0.272 * (nextMondayHigh - nextMondayLow)
fibNegative414 = nextMondayLow - 0.414 * (nextMondayHigh - nextMondayLow)
fibNegative500 = nextMondayLow - 0.5 * (nextMondayHigh - nextMondayLow)
fibNegative1 = nextMondayLow - 1 * (nextMondayHigh - nextMondayLow)
fib2 = nextMondayHigh + 1 * (nextMondayHigh - nextMondayLow)
// Plot Fibonacci levels
plot(fib272, title='0.272 Fibonacci', style=plot.style_linebr, linewidth=1, color=color.new(color.blue, 0))
plot(fib414, title='0.414 Fibonacci', style=plot.style_linebr, linewidth=1, color=color.new(color.blue, 0))
plot(fib500, title='0.500 Fibonacci', style=plot.style_linebr, linewidth=1, color=color.new(color.red, 0))
plot(fibNegative272, title='-0.272 Fibonacci', style=plot.style_linebr, linewidth=1, color=color.new(color.blue, 0))
plot(fibNegative414, title='-0.414 Fibonacci', style=plot.style_linebr, linewidth=1, color=color.new(color.blue, 0))
plot(fibNegative500, title='-0.500 Fibonacci', style=plot.style_linebr, linewidth=1, color=color.new(color.red, 0))
plot(fibNegative1, title='-1 Fibonacci', style=plot.style_linebr, linewidth=1, color=color.new(color.white, 0))
plot(fib2, title='1 Fibonacci', style=plot.style_linebr, linewidth=1, color=color.new(color.white, 0))
// Calculate the values for lines 0.25 above and below
var float lineAbove = na
var float lineBelow = na
lineAbove := (nextMondayHigh + nextMondayLow) / 2 + 0.25 * (nextMondayHigh - nextMondayLow)
lineBelow := (nextMondayHigh + nextMondayLow) / 2 - 0.25 * (nextMondayHigh - nextMondayLow)
// Plot lines 0.25 above and below with dashed line style
plot(lineAbove, title='0.25 Above', color=color.new(color.yellow, 0), linewidth=1, style=plot.style_stepline)
plot(lineBelow, title='0.25 Below', color=color.new(color.yellow, 0), linewidth=1, style=plot.style_stepline)
|
CE - 42MACRO Fixed Income and Macro | https://www.tradingview.com/script/I3G3EqPk-CE-42MACRO-Fixed-Income-and-Macro/ | Celestial-Eye | https://www.tradingview.com/u/Celestial-Eye/ | 90 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Celestial-Eye
// QUICK GUIDE: https://docs.google.com/document/d/1b-ZVyQghSqDETX_GF_-OSIBCa4e0CBGqENbdfId9I-s/edit?usp=sharing
//@version=5
indicator("🌌 CE - 42MACRO Fixed Income and Macro 🌌", "🌌 CE - FIM 🌌")
showPerfTab = input.bool(true, "Show Performance Table", tooltip = "Plots the Performance table", group = "🌌 Table Settings Performance 🌌")
rocPeriod = input.int (30, "ROC Period", minval=1, tooltip = "Defines the time horizon for the Performance Table", group = "🌌 Table Settings Performance 🌌")
CalcType = input.string("Rate of Change", "Choose different Calculations", ["Rate of Change", "Sharpe Ratio", "Sortino Ratio", "Omega Ratio", "Normalization"], group = "🌌 Table Settings Performance 🌌")
useRelative = input.bool(false, "Use Relative Asset Calculation", tooltip = "Calculates Asset values in comparison to all other Assets", group = "🌌 Table Settings Performance 🌌")
reg = input.bool(false, "Show calculated regimes", group = "Visuals - USE ONE AT A TIME FOR BEST EXPERIENCE")
colx = input.bool(false, "Visualize Risk On and Off Phases", group = "Visuals - USE ONE AT A TIME FOR BEST EXPERIENCE")
ultimateGRID = input.bool(false, "Show ULTIMATE GRID regimes", tooltip = "Uses all different calculations to find the average regimes", group = "Visuals - USE ONE AT A TIME FOR BEST EXPERIENCE")
ultimateRISK = input.bool(false, "Show ULTIMATE RISK Phases", tooltip = "Uses all different calculations to find the Risk On/OFF phase", group = "Visuals - USE ONE AT A TIME FOR BEST EXPERIENCE")
barcRisk = input.bool(false, "Barcolor Risk Phases", tooltip = "Barcolors Risk On/OFF phases if either one is enabled", group = "Visuals - USE ONE AT A TIME FOR BEST EXPERIENCE")
barcGRID = input.bool(false, "Barcolor GRID regimes", tooltip = "Barcolors GRID regimes if either one is enabled", group = "Visuals - USE ONE AT A TIME FOR BEST EXPERIENCE")
f_calc(name) =>
request.security(name, "D", close, barmerge.gaps_off)
//Fixed Income
CWB = f_calc("CWB") // CWB (Convertibles)
BKLN = f_calc("BKLN") // BKLN (Leveraged Loans)
HYG = f_calc("HYG") // HYG (High Yield Credit)
PFF = f_calc("PFF") // PFF (Preferreds)
EMB = f_calc("EMB") // EMB (Emerging Market US$ Bonds)
TLT = f_calc("TLT") // TLT (Long Bond)
IEF = f_calc("IEF") // IEF (5-10yr Treasurys)
TIP = f_calc("TIP") // TIP (5-10yr TIPS)
STIP = f_calc("STIP") // STIP (0-5yr TIPS)
EMLC = f_calc("EMLC") // EMLC (EM Local Currency Bonds)
BIZD = f_calc("AMEX:BIZD") // BIZD (BDCs)
AGG = f_calc("AGG") // AGG (Barclays Agg)
LQD = f_calc("LQD") // LQD (Investment Grade Credit)
MBB = f_calc("MBB") // MBB (MBS)
SHY = f_calc("SHY") // SHY (1-3yr Treasurys)
//Macro
BITO = f_calc("BITO") // BITO (Bitcoin)
DBB = f_calc("DBB") // DBB (Industrial Metals)
DBC = f_calc("DBC") // DBC (Commodities)
GLD = f_calc("GLD") // GLD (Gold)
VIXM = f_calc("VIXM") // VIXM (Equity Volatility)
PFIX = f_calc("PFIX") // PFIX (Interest Rate Volatility)
USO = f_calc("USO") // USO (Energy)
DBP = f_calc("DBP") // DBP (Precious Metals)
DBA = f_calc("DBA") // DBA (Agriculture)
UUP = f_calc("UUP") // UUP (US Dollar)
UDN = f_calc("UDN") // UDN (Inverse US Dollar)
// Fixed Income(Yield) Calculation
// Top 5 Fixed Income Factors Top 5 Fixed Income Factors Top 5 Fixed Income Factors Top 5 Fixed Income Factors
// Convertibles (CWB) Leveraged Loans (BKLN) 1-3yr Treasurys (SHY) 1-3yr Treasurys (SHY)
// Leveraged Loans (BKLN) Convertibles (CWB) 0-5yr TIPS (STIP) 5-10yr Treasurys (IEF)
// High Yield Credit (HYG) High Yield Credit (HYG) 5-10yr Treasurys (IEF) Barclays Agg (AGG)
// Preferreds (PFF) 0-5yr TIPS (STIP) 5-10yr TIPS (TIP) MBS (MBB)
// Emerging Market US$ Bonds (EMB) BDCs (BIZD) Long Bond (TLT) Investment Grade Credit (LQD)
// Bottom 5 Fixed Income Factors Bottom 5 Fixed Income Factors Bottom 5 Fixed Income Factors Bottom 5 Fixed Income Factors
// Long Bond (TLT) Long Bond (TLT) Convertibles (CWB) Preferreds (PFF)
// 5-10yr Treasurys (IEF) 5-10yr Treasurys (IEF) BDCS (BIZD) BDCs (BIZD)
// 5-10yr TIPS (TIP) Barclays Agg (AGG) EM Local Currency Bonds (EMLC) EM Local Currency Bonds (EMLC)
// 0-5yr TIPS (STIP) Investment Grade Credit (LQD) Preferreds (PFF) High Yield Credit (HYG)
// EM Local Currency Bonds (EMLC) MBS (MBB) Investment Grade Credit (LQD) Leveraged Loans (BKLN)
// <<HOW TO CALCULATE YIELDS...>>
// -> Beware that I changed that part and don't actually use Yield Calculation as I initially planned....
// Reason beeing that the time horizon is too long and it negatively effects time coherence
// Trailing 12-Month Yield: This metric represents the income generated by the ETF's underlying assets over the past 12 months, expressed as a percentage of the ETF's net asset value.
// SEC Yield: The SEC yield is an annualized yield calculation required by the U.S. Securities and Exchange Commission (SEC) for certain ETFs and mutual funds.
//It is calculated based on the income earned by the ETF's holdings over the past 30 days and adjusted for any expense ratios or fees.
// Distribution Yield: The distribution yield is a measure of the ETF's income distribution, typically expressed as a percentage of its net asset value.
//It considers dividends, interest payments, and any other distributions made by the ETF.
// Current Yield: The current yield is a simple yield calculation that measures the annual income generated by the ETF based on its current market price.
//It is calculated by dividing the ETF's annual income (dividends and interest) by its current market price.
// Yield-to-Maturity (YTM): For bond ETFs, you can use the YTM metric to estimate the yield based on the bonds held by the ETF and their respective yields to maturity.
// Yield-to-Worst (YTW): For bond ETFs holding callable bonds, YTW estimates the lowest potential yield if the issuer calls the bonds before their maturity date.
////////////////////////////////////*********************************************************************** This is how it would look like
// CWB_sym = "AMEX:CWB"
// BKLN_sym = "AMEX:BKLN"
// HYG_sym = "AMEX:HYG"
// PFF_sym = "NASDAQ:PFF"
// EMB_sym = "NASDAQ:EMB"
// TLT_sym = "NASDAQ:TLT"
// IEF_sym = "NASDAQ:IEF"
// TIP_sym = "AMEX:TIP"
// STIP_sym = "AMEX:STIP"
// EMLC_sym = "AMEX:EMLC"
// BIZD_sym = "AMEX:BIZD"
// AGG_sym = "AMEX:AGG"
// LQD_sym = "AMEX:LQD"
// MBB_sym = "NASDAQ:MBB"
// SHY_sym = "NASDAQ:SHY"
// // Function to calculate dividend yield
// getDividendYield(symbol,sym) =>
// dividendPerShare = request.dividends(symbol)
// dividendYield = (dividendPerShare / sym) * 100
// dividendYield
// CWB_roc = getDividendYield(CWB_sym, CWB)
// BKLN_roc = getDividendYield(BKLN_sym, BKLN)
// HYG_roc = getDividendYield(HYG_sym, HYG)
// PFF_roc = getDividendYield(PFF_sym, PFF)
// EMB_roc = getDividendYield(EMB_sym, EMB)
// TLT_roc = getDividendYield(TLT_sym, TLT)
// IEF_roc = getDividendYield(IEF_sym, IEF)
// TIP_roc = getDividendYield(TIP_sym, TIP)
// STIP_roc = getDividendYield(STIP_sym, STIP)
// EMLC_roc = getDividendYield(EMLC_sym, EMLC)
// BIZD_roc = getDividendYield(BIZD_sym, BIZD) - 2
// AGG_roc = getDividendYield(AGG_sym, AGG)
// LQD_roc = getDividendYield(LQD_sym, LQD)
// MBB_roc = getDividendYield(MBB_sym, MBB)
// SHY_roc = getDividendYield(SHY_sym, SHY)
////////////////////////////////////***********************************************************************
// <<<Now this is gonna be on how to compare them against each other...>>>
// Multiple options:
// 1. Avg of all yields -> see which perform better and worse
// 2. Avg of only the regime Yields -> perfomance values
// 3. Avg of all top vs all bottom perfomers -> relative rate of change
// 4. sum of Top to Bot... then compare for highest/lowest
/////////////////*****************Fixed Income FACTORS*************//////////////////
//sharpe ratio calculation function -> BY QuantiLuxe / ELiCobra
f_sharpe(src, lookback) =>
float daily_return = src / src[1] - 1
returns_array = array.new_float(0)
for i = 0 to lookback
array.push(returns_array, daily_return[i])
standard_deviation = array.stdev(returns_array)
mean = array.avg(returns_array)
math.round(mean / standard_deviation * math.sqrt(lookback), 2)
//sortino ratio calculation function -> BY QuantiLuxe / ELiCobra
f_sortino(src, lookback) =>
float daily_return = src / src[1] - 1
returns_array = array.new_float(0)
negative_returns_array = array.new_float(0)
for i = 0 to lookback
array.push(returns_array, daily_return[i])
if daily_return[i] <= 0.0
array.push(negative_returns_array, daily_return[i])
else
array.push(negative_returns_array, 0.0)
negative_returns_standard_deviation = array.stdev(negative_returns_array)
mean = array.avg(returns_array)
math.round(mean / negative_returns_standard_deviation * math.sqrt(lookback), 2)
//omega ratio calculation function -> BY QuantiLuxe / ELiCobra
f_omega(src, lookback) =>
float daily_return = src / src[1] - 1
negative_returns_array = array.new_float(0)
positive_returns_array = array.new_float(0)
for i = 0 to lookback
if daily_return[i] <= 0.0
array.push(negative_returns_array, daily_return[i])
array.push(positive_returns_array, 0.0)
else
array.push(positive_returns_array, daily_return[i])
array.push(negative_returns_array, 0.0)
postive_area = array.sum(positive_returns_array)
negative_area = array.sum(negative_returns_array) * (-1)
math.round(postive_area / negative_area, 2)
//normalization calculation function
f_normalization(src, lookback) =>
lowest = ta.lowest (src, lookback)
highest = ta.highest(src, lookback)
normalized = (src - lowest) / (highest - lowest) - 0.5
//calculate the average Fixed Income RoC
avgROCFI = math.avg(
nz(ta.roc(CWB, rocPeriod)),
nz(ta.roc(BKLN, rocPeriod)),
nz(ta.roc(HYG, rocPeriod)),
nz(ta.roc(PFF, rocPeriod)),
nz(ta.roc(EMB, rocPeriod)),
nz(ta.roc(TLT, rocPeriod)),
nz(ta.roc(IEF, rocPeriod)),
nz(ta.roc(TIP, rocPeriod)),
nz(ta.roc(STIP, rocPeriod)),
nz(ta.roc(EMLC, rocPeriod)),
nz(ta.roc(BIZD, rocPeriod)),
nz(ta.roc(AGG, rocPeriod)),
nz(ta.roc(LQD, rocPeriod)),
nz(ta.roc(MBB, rocPeriod)),
nz(ta.roc(SHY, rocPeriod)))
//calculate the average Fixed Income Sharpe value
avgRoCFISH = math.avg(
nz(f_sharpe(CWB, rocPeriod)),
nz(f_sharpe(BKLN, rocPeriod)),
nz(f_sharpe(HYG, rocPeriod)),
nz(f_sharpe(PFF, rocPeriod)),
nz(f_sharpe(EMB, rocPeriod)),
nz(f_sharpe(TLT, rocPeriod)),
nz(f_sharpe(IEF, rocPeriod)),
nz(f_sharpe(TIP, rocPeriod)),
nz(f_sharpe(STIP, rocPeriod)),
nz(f_sharpe(EMLC, rocPeriod)),
nz(f_sharpe(BIZD, rocPeriod)),
nz(f_sharpe(AGG, rocPeriod)),
nz(f_sharpe(LQD, rocPeriod)),
nz(f_sharpe(MBB, rocPeriod)),
nz(f_sharpe(SHY, rocPeriod)))
//calculate the average Fixed Income Sortino value
avgRoCFISO = math.avg(
nz(f_sortino(CWB, rocPeriod)),
nz(f_sortino(BKLN, rocPeriod)),
nz(f_sortino(HYG, rocPeriod)),
nz(f_sortino(PFF, rocPeriod)),
nz(f_sortino(EMB, rocPeriod)),
nz(f_sortino(TLT, rocPeriod)),
nz(f_sortino(IEF, rocPeriod)),
nz(f_sortino(TIP, rocPeriod)),
nz(f_sortino(STIP, rocPeriod)),
nz(f_sortino(EMLC, rocPeriod)),
nz(f_sortino(BIZD, rocPeriod)),
nz(f_sortino(AGG, rocPeriod)),
nz(f_sortino(LQD, rocPeriod)),
nz(f_sortino(MBB, rocPeriod)),
nz(f_sortino(SHY, rocPeriod)))
//calculate the average Fixed Income Omega value
avgRoCFIO = math.avg(
nz(f_omega(CWB, rocPeriod)),
nz(f_omega(BKLN, rocPeriod)),
nz(f_omega(HYG, rocPeriod)),
nz(f_omega(PFF, rocPeriod)),
nz(f_omega(EMB, rocPeriod)),
nz(f_omega(TLT, rocPeriod)),
nz(f_omega(IEF, rocPeriod)),
nz(f_omega(TIP, rocPeriod)),
nz(f_omega(STIP, rocPeriod)),
nz(f_omega(EMLC, rocPeriod)),
nz(f_omega(BIZD, rocPeriod)),
nz(f_omega(AGG, rocPeriod)),
nz(f_omega(LQD, rocPeriod)),
nz(f_omega(MBB, rocPeriod)),
nz(f_omega(SHY, rocPeriod)))
//calculate the average Fixed Income Normalized value
avgRoCFINO = math.avg(
nz(f_normalization(CWB, rocPeriod)),
nz(f_normalization(BKLN, rocPeriod)),
nz(f_normalization(HYG, rocPeriod)),
nz(f_normalization(PFF, rocPeriod)),
nz(f_normalization(EMB, rocPeriod)),
nz(f_normalization(TLT, rocPeriod)),
nz(f_normalization(IEF, rocPeriod)),
nz(f_normalization(TIP, rocPeriod)),
nz(f_normalization(STIP, rocPeriod)),
nz(f_normalization(EMLC, rocPeriod)),
nz(f_normalization(BIZD, rocPeriod)),
nz(f_normalization(AGG, rocPeriod)),
nz(f_normalization(LQD, rocPeriod)),
nz(f_normalization(MBB, rocPeriod)),
nz(f_normalization(SHY, rocPeriod)))
var float CWB_roc = na
var float BKLN_roc = na
var float HYG_roc = na
var float PFF_roc = na
var float EMB_roc = na
var float TLT_roc = na
var float IEF_roc = na
var float TIP_roc = na
var float STIP_roc = na
var float EMLC_roc = na
var float BIZD_roc = na
var float AGG_roc = na
var float LQD_roc = na
var float MBB_roc = na
var float SHY_roc = na
/////////////////// -> potentially make a single function that then uses switch statements to decide the CalcType
if CalcType == "Rate of Change"
// Calculate the relative RoC for each asset - Standard
CWB_roc := ta.roc(CWB , rocPeriod) - (useRelative? avgROCFI : 0)
BKLN_roc := ta.roc(BKLN, rocPeriod) - (useRelative? avgROCFI : 0)
HYG_roc := ta.roc(HYG, rocPeriod) - (useRelative? avgROCFI : 0)
PFF_roc := ta.roc(PFF, rocPeriod) - (useRelative? avgROCFI : 0)
EMB_roc := ta.roc(EMB, rocPeriod) - (useRelative? avgROCFI : 0)
TLT_roc := ta.roc(TLT, rocPeriod) - (useRelative? avgROCFI : 0)
IEF_roc := ta.roc(IEF, rocPeriod) - (useRelative? avgROCFI : 0)
TIP_roc := ta.roc(TIP, rocPeriod) - (useRelative? avgROCFI : 0)
STIP_roc := ta.roc(STIP, rocPeriod) - (useRelative? avgROCFI : 0)
EMLC_roc := ta.roc(EMLC, rocPeriod) - (useRelative? avgROCFI : 0)
BIZD_roc := ta.roc(BIZD, rocPeriod) - (useRelative? avgROCFI : 0)
AGG_roc := ta.roc(AGG, rocPeriod) - (useRelative? avgROCFI : 0)
LQD_roc := ta.roc(LQD, rocPeriod) - (useRelative? avgROCFI : 0)
SHY_roc := ta.roc(SHY, rocPeriod) - (useRelative? avgROCFI : 0)
MBB_roc := ta.roc(MBB, rocPeriod) - (useRelative? avgROCFI : 0)
else if CalcType == "Sharpe Ratio"
// Calculate the Sharpe ratio for each asset - optional
CWB_roc := f_sharpe(CWB , rocPeriod) - (useRelative? avgRoCFISH : 0)
BKLN_roc := f_sharpe(BKLN, rocPeriod) - (useRelative? avgRoCFISH : 0)
HYG_roc := f_sharpe(HYG, rocPeriod) - (useRelative? avgRoCFISH : 0)
PFF_roc := f_sharpe(PFF, rocPeriod) - (useRelative? avgRoCFISH : 0)
EMB_roc := f_sharpe(EMB, rocPeriod) - (useRelative? avgRoCFISH : 0)
TLT_roc := f_sharpe(TLT, rocPeriod) - (useRelative? avgRoCFISH : 0)
IEF_roc := f_sharpe(IEF, rocPeriod) - (useRelative? avgRoCFISH : 0)
TIP_roc := f_sharpe(TIP, rocPeriod) - (useRelative? avgRoCFISH : 0)
STIP_roc := f_sharpe(STIP, rocPeriod) - (useRelative? avgRoCFISH : 0)
EMLC_roc := f_sharpe(EMLC, rocPeriod) - (useRelative? avgRoCFISH : 0)
BIZD_roc := f_sharpe(BIZD, rocPeriod) - (useRelative? avgRoCFISH : 0)
AGG_roc := f_sharpe(AGG, rocPeriod) - (useRelative? avgRoCFISH : 0)
LQD_roc := f_sharpe(LQD, rocPeriod) - (useRelative? avgRoCFISH : 0)
SHY_roc := f_sharpe(SHY, rocPeriod) - (useRelative? avgRoCFISH : 0)
MBB_roc := f_sharpe(MBB, rocPeriod) - (useRelative? avgRoCFISH : 0)
else if CalcType == "Sortino Ratio"
// Calculate the Sortino ratio for each asset - optional
CWB_roc := f_sortino(CWB , rocPeriod) - (useRelative? avgRoCFISO : 0)
BKLN_roc := f_sortino(BKLN, rocPeriod) - (useRelative? avgRoCFISO : 0)
HYG_roc := f_sortino(HYG, rocPeriod) - (useRelative? avgRoCFISO : 0)
PFF_roc := f_sortino(PFF, rocPeriod) - (useRelative? avgRoCFISO : 0)
EMB_roc := f_sortino(EMB, rocPeriod) - (useRelative? avgRoCFISO : 0)
TLT_roc := f_sortino(TLT, rocPeriod) - (useRelative? avgRoCFISO : 0)
IEF_roc := f_sortino(IEF, rocPeriod) - (useRelative? avgRoCFISO : 0)
TIP_roc := f_sortino(TIP, rocPeriod) - (useRelative? avgRoCFISO : 0)
STIP_roc := f_sortino(STIP, rocPeriod) - (useRelative? avgRoCFISO : 0)
EMLC_roc := f_sortino(EMLC, rocPeriod) - (useRelative? avgRoCFISO : 0)
BIZD_roc := f_sortino(BIZD, rocPeriod) - (useRelative? avgRoCFISO : 0)
AGG_roc := f_sortino(AGG, rocPeriod) - (useRelative? avgRoCFISO : 0)
LQD_roc := f_sortino(LQD, rocPeriod) - (useRelative? avgRoCFISO : 0)
SHY_roc := f_sortino(SHY, rocPeriod) - (useRelative? avgRoCFISO : 0)
MBB_roc := f_sortino(MBB, rocPeriod) - (useRelative? avgRoCFISO : 0)
else if CalcType == "Omega Ratio"
// Calculate the Omega ratio for each asset - optional
CWB_roc := f_omega(CWB , rocPeriod) - (useRelative? avgRoCFIO : 0)
BKLN_roc := f_omega(BKLN, rocPeriod) - (useRelative? avgRoCFIO : 0)
HYG_roc := f_omega(HYG, rocPeriod) - (useRelative? avgRoCFIO : 0)
PFF_roc := f_omega(PFF, rocPeriod) - (useRelative? avgRoCFIO : 0)
EMB_roc := f_omega(EMB, rocPeriod) - (useRelative? avgRoCFIO : 0)
TLT_roc := f_omega(TLT, rocPeriod) - (useRelative? avgRoCFIO : 0)
IEF_roc := f_omega(IEF, rocPeriod) - (useRelative? avgRoCFIO : 0)
TIP_roc := f_omega(TIP, rocPeriod) - (useRelative? avgRoCFIO : 0)
STIP_roc := f_omega(STIP, rocPeriod) - (useRelative? avgRoCFIO : 0)
EMLC_roc := f_omega(EMLC, rocPeriod) - (useRelative? avgRoCFIO : 0)
BIZD_roc := f_omega(BIZD, rocPeriod) - (useRelative? avgRoCFIO : 0)
AGG_roc := f_omega(AGG, rocPeriod) - (useRelative? avgRoCFIO : 0)
LQD_roc := f_omega(LQD, rocPeriod) - (useRelative? avgRoCFIO : 0)
SHY_roc := f_omega(SHY, rocPeriod) - (useRelative? avgRoCFIO : 0)
MBB_roc := f_omega(MBB, rocPeriod) - (useRelative? avgRoCFIO : 0)
else if CalcType == "Normalization"
// Calculate the Normalization for each asset - optional
CWB_roc := f_normalization(CWB , rocPeriod) - (useRelative? avgRoCFINO : 0)
BKLN_roc := f_normalization(BKLN, rocPeriod) - (useRelative? avgRoCFINO : 0)
HYG_roc := f_normalization(HYG, rocPeriod) - (useRelative? avgRoCFINO : 0)
PFF_roc := f_normalization(PFF, rocPeriod) - (useRelative? avgRoCFINO : 0)
EMB_roc := f_normalization(EMB, rocPeriod) - (useRelative? avgRoCFINO : 0)
TLT_roc := f_normalization(TLT, rocPeriod) - (useRelative? avgRoCFINO : 0)
IEF_roc := f_normalization(IEF, rocPeriod) - (useRelative? avgRoCFINO : 0)
TIP_roc := f_normalization(TIP, rocPeriod) - (useRelative? avgRoCFINO : 0)
STIP_roc := f_normalization(STIP, rocPeriod) - (useRelative? avgRoCFINO : 0)
EMLC_roc := f_normalization(EMLC, rocPeriod) - (useRelative? avgRoCFINO : 0)
BIZD_roc := f_normalization(BIZD, rocPeriod) - (useRelative? avgRoCFINO : 0)
AGG_roc := f_normalization(AGG, rocPeriod) - (useRelative? avgRoCFINO : 0)
LQD_roc := f_normalization(LQD, rocPeriod) - (useRelative? avgRoCFINO : 0)
SHY_roc := f_normalization(SHY, rocPeriod) - (useRelative? avgRoCFINO : 0)
MBB_roc := f_normalization(MBB, rocPeriod) - (useRelative? avgRoCFINO : 0)
// Calculate the probabilities for Fixed Income
GoldilocksY = (CWB_roc >0?+1:0) + (BKLN_roc>0?+1:0) + (HYG_roc>0?+1:0) + (PFF_roc >0?+1:0) + (EMB_roc >0?+1:0) + (TLT_roc<0?+1:0) + (IEF_roc <0?+1:0) + (TIP_roc <0?+1:0) + (STIP_roc<0?+1:0) + (EMLC_roc<0?+1:0)
ReflationY = (BKLN_roc>0?+1:0) + (CWB_roc >0?+1:0) + (HYG_roc>0?+1:0) + (STIP_roc >0?+1:0) + (BIZD_roc>0?+1:0) + (TLT_roc<0?+1:0) + (IEF_roc <0?+1:0) + (AGG_roc <0?+1:0) + (LQD_roc <0?+1:0) + (MBB_roc <0?+1:0)
InflationY = (SHY_roc >0?+1:0) + (STIP_roc>0?+1:0) + (IEF_roc>0?+1:0) + (TIP_roc >0?+1:0) + (TLT_roc >0?+1:0) + (CWB_roc<0?+1:0) + (BIZD_roc<0?+1:0) + (EMLC_roc<0?+1:0) + (PFF_roc <0?+1:0) + (LQD_roc <0?+1:0)
DeflationY = (SHY_roc >0?+1:0) + (IEF_roc >0?+1:0) + (AGG_roc>0?+1:0) + (MBB_roc >0?+1:0) + (LQD_roc >0?+1:0) + (PFF_roc<0?+1:0) + (BIZD_roc<0?+1:0) + (EMLC_roc<0?+1:0) + (HYG_roc <0?+1:0) + (BKLN_roc<0?+1:0)
DenumeratorY = GoldilocksY + ReflationY + InflationY + DeflationY
/////////////////*****************MACRO FACTORS*************//////////////////
//calculate the average Macro RoC
avgROC = math.avg(
nz(ta.roc(BITO, rocPeriod)),
nz(ta.roc(DBB, rocPeriod)),
nz(ta.roc(DBC, rocPeriod)),
nz(ta.roc(UDN, rocPeriod)),
nz(ta.roc(GLD, rocPeriod)),
nz(ta.roc(VIXM, rocPeriod)),
nz(ta.roc(UUP, rocPeriod)),
nz(ta.roc(PFIX, rocPeriod)),
nz(ta.roc(USO, rocPeriod)),
nz(ta.roc(DBP, rocPeriod)),
nz(ta.roc(DBA, rocPeriod)))
//calculate the average Macro Sharpe value
avgRoCMSH = math.avg(
nz(f_sharpe(BITO, rocPeriod)),
nz(f_sharpe(DBB, rocPeriod)),
nz(f_sharpe(DBC, rocPeriod)),
nz(f_sharpe(UDN, rocPeriod)),
nz(f_sharpe(GLD, rocPeriod)),
nz(f_sharpe(VIXM, rocPeriod)),
nz(f_sharpe(UUP, rocPeriod)),
nz(f_sharpe(PFIX, rocPeriod)),
nz(f_sharpe(USO, rocPeriod)),
nz(f_sharpe(DBP, rocPeriod)),
nz(f_sharpe(DBA, rocPeriod)))
//calculate the average Macro Sortino value
avgRoCMSO = math.avg(
nz(f_sortino(BITO, rocPeriod)),
nz(f_sortino(DBB, rocPeriod)),
nz(f_sortino(DBC, rocPeriod)),
nz(f_sortino(UDN, rocPeriod)),
nz(f_sortino(GLD, rocPeriod)),
nz(f_sortino(VIXM, rocPeriod)),
nz(f_sortino(UUP, rocPeriod)),
nz(f_sortino(PFIX, rocPeriod)),
nz(f_sortino(USO, rocPeriod)),
nz(f_sortino(DBP, rocPeriod)),
nz(f_sortino(DBA, rocPeriod)))
//calculate the average Macro Omega value
avgRoCMO = math.avg(
nz(f_omega(BITO, rocPeriod)),
nz(f_omega(DBB, rocPeriod)),
nz(f_omega(DBC, rocPeriod)),
nz(f_omega(UDN, rocPeriod)),
nz(f_omega(GLD, rocPeriod)),
nz(f_omega(VIXM, rocPeriod)),
nz(f_omega(UUP, rocPeriod)),
nz(f_omega(PFIX, rocPeriod)),
nz(f_omega(USO, rocPeriod)),
nz(f_omega(DBP, rocPeriod)),
nz(f_omega(DBA, rocPeriod)))
//calculate the average Macro Normalized value
avgRoCMNO = math.avg(
nz(f_normalization(BITO, rocPeriod)),
nz(f_normalization(DBB, rocPeriod)),
nz(f_normalization(DBC, rocPeriod)),
nz(f_normalization(UDN, rocPeriod)),
nz(f_normalization(GLD, rocPeriod)),
nz(f_normalization(VIXM, rocPeriod)),
nz(f_normalization(UUP, rocPeriod)),
nz(f_normalization(PFIX, rocPeriod)),
nz(f_normalization(USO, rocPeriod)),
nz(f_normalization(DBP, rocPeriod)),
nz(f_normalization(DBA, rocPeriod)))
var float rocBITO = na
var float rocDBB = na
var float rocDBC = na
var float rocUDN = na
var float rocGLD = na
var float rocVIXM = na
var float rocUUP = na
var float rocPFIX = na
var float rocUSO = na
var float rocDBP = na
var float rocDBA = na
if CalcType == "Rate of Change"
// Calculate the relative RoC for each asset - Standard
rocBITO := ta.roc(BITO, rocPeriod) - (useRelative? avgROC : 0)
rocDBB := ta.roc(DBB, rocPeriod) - (useRelative? avgROC : 0)
rocDBC := ta.roc(DBC, rocPeriod) - (useRelative? avgROC : 0)
rocUDN := ta.roc(UDN, rocPeriod) - (useRelative? avgROC : 0)
rocGLD := ta.roc(GLD, rocPeriod) - (useRelative? avgROC : 0)
rocVIXM := ta.roc(VIXM, rocPeriod) - (useRelative? avgROC : 0)
rocUUP := ta.roc(UUP, rocPeriod) - (useRelative? avgROC : 0)
rocPFIX := ta.roc(PFIX, rocPeriod) - (useRelative? avgROC : 0)
rocUSO := ta.roc(USO, rocPeriod) - (useRelative? avgROC : 0)
rocDBP := ta.roc(DBP, rocPeriod) - (useRelative? avgROC : 0)
rocDBA := ta.roc(DBA, rocPeriod) - (useRelative? avgROC : 0)
else if CalcType == "Sharpe Ratio"
// Calculate the Sharpe ratio for each asset - optional
rocBITO := f_sharpe(BITO, rocPeriod) - (useRelative? avgRoCMSH : 0)
rocDBB := f_sharpe(DBB, rocPeriod) - (useRelative? avgRoCMSH : 0)
rocDBC := f_sharpe(DBC, rocPeriod) - (useRelative? avgRoCMSH : 0)
rocUDN := f_sharpe(UDN, rocPeriod) - (useRelative? avgRoCMSH : 0)
rocGLD := f_sharpe(GLD, rocPeriod) - (useRelative? avgRoCMSH : 0)
rocVIXM := f_sharpe(VIXM, rocPeriod) - (useRelative? avgRoCMSH : 0)
rocUUP := f_sharpe(UUP, rocPeriod) - (useRelative? avgRoCMSH : 0)
rocPFIX := f_sharpe(PFIX, rocPeriod) - (useRelative? avgRoCMSH : 0)
rocUSO := f_sharpe(USO, rocPeriod) - (useRelative? avgRoCMSH : 0)
rocDBP := f_sharpe(DBP, rocPeriod) - (useRelative? avgRoCMSH : 0)
rocDBA := f_sharpe(DBA, rocPeriod) - (useRelative? avgRoCMSH : 0)
else if CalcType == "Sortino Ratio"
// Calculate the Sortino ratio for each asset - optional
rocBITO := f_sortino(BITO, rocPeriod) - (useRelative? avgRoCMSO : 0)
rocDBB := f_sortino(DBB, rocPeriod) - (useRelative? avgRoCMSO : 0)
rocDBC := f_sortino(DBC, rocPeriod) - (useRelative? avgRoCMSO : 0)
rocUDN := f_sortino(UDN, rocPeriod) - (useRelative? avgRoCMSO : 0)
rocGLD := f_sortino(GLD, rocPeriod) - (useRelative? avgRoCMSO : 0)
rocVIXM := f_sortino(VIXM, rocPeriod) - (useRelative? avgRoCMSO : 0)
rocUUP := f_sortino(UUP, rocPeriod) - (useRelative? avgRoCMSO : 0)
rocPFIX := f_sortino(PFIX, rocPeriod) - (useRelative? avgRoCMSO : 0)
rocUSO := f_sortino(USO, rocPeriod) - (useRelative? avgRoCMSO : 0)
rocDBP := f_sortino(DBP, rocPeriod) - (useRelative? avgRoCMSO : 0)
rocDBA := f_sortino(DBA, rocPeriod) - (useRelative? avgRoCMSO : 0)
else if CalcType == "Omega Ratio"
// Calculate the Omega ratio for each asset - optional
rocBITO := f_omega(BITO, rocPeriod) - (useRelative? avgRoCMO : 0)
rocDBB := f_omega(DBB, rocPeriod) - (useRelative? avgRoCMO : 0)
rocDBC := f_omega(DBC, rocPeriod) - (useRelative? avgRoCMO : 0)
rocUDN := f_omega(UDN, rocPeriod) - (useRelative? avgRoCMO : 0)
rocGLD := f_omega(GLD, rocPeriod) - (useRelative? avgRoCMO : 0)
rocVIXM := f_omega(VIXM, rocPeriod) - (useRelative? avgRoCMO : 0)
rocUUP := f_omega(UUP, rocPeriod) - (useRelative? avgRoCMO : 0)
rocPFIX := f_omega(PFIX, rocPeriod) - (useRelative? avgRoCMO : 0)
rocUSO := f_omega(USO, rocPeriod) - (useRelative? avgRoCMO : 0)
rocDBP := f_omega(DBP, rocPeriod) - (useRelative? avgRoCMO : 0)
rocDBA := f_omega(DBA, rocPeriod) - (useRelative? avgRoCMO : 0)
else if CalcType == "Normalization"
// Calculate the Normalization for each asset - optional
rocBITO := f_normalization(BITO, rocPeriod) - (useRelative? avgRoCMNO : 0)
rocDBB := f_normalization(DBB, rocPeriod) - (useRelative? avgRoCMNO : 0)
rocDBC := f_normalization(DBC, rocPeriod) - (useRelative? avgRoCMNO : 0)
rocUDN := f_normalization(UDN, rocPeriod) - (useRelative? avgRoCMNO : 0)
rocGLD := f_normalization(GLD, rocPeriod) - (useRelative? avgRoCMNO : 0)
rocVIXM := f_normalization(VIXM, rocPeriod) - (useRelative? avgRoCMNO : 0)
rocUUP := f_normalization(UUP, rocPeriod) - (useRelative? avgRoCMNO : 0)
rocPFIX := f_normalization(PFIX, rocPeriod) - (useRelative? avgRoCMNO : 0)
rocUSO := f_normalization(USO, rocPeriod) - (useRelative? avgRoCMNO : 0)
rocDBP := f_normalization(DBP, rocPeriod) - (useRelative? avgRoCMNO : 0)
rocDBA := f_normalization(DBA, rocPeriod) - (useRelative? avgRoCMNO : 0)
// Calculate the probabilities
Goldilocks = (rocBITO>0?+1:0) + (rocDBB>0?+1:0) + (rocDBC>0?+1:0) + (rocUDN>0?+1:0) +(rocGLD>0?+1:0) + (rocVIXM<0?+1:0) + (rocUUP<0?+1:0) + (rocPFIX<0?+1:0) + (rocUSO<0?+1:0) + (rocDBP<0?+1:0)
Reflation = (rocBITO>0?+1:0) + (rocDBC>0?+1:0) + (rocUSO>0?+1:0) + (rocDBB>0?+1:0) +(rocGLD>0?+1:0) + (rocUUP<0?+1:0) + (rocDBA<0?+1:0) + (rocUDN<0?+1:0) + (rocDBP<0?+1:0) + (rocVIXM<0?+1:0)
Inflation = (rocBITO>0?+1:0) + (rocGLD>0?+1:0) + (rocVIXM>0?+1:0) + (rocUUP>0?+1:0) +(rocPFIX>0?+1:0) + (rocDBB<0?+1:0) + (rocUDN<0?+1:0) + (rocDBC<0?+1:0) + (rocUSO<0?+1:0) + (rocDBP<0?+1:0)
Deflation = (rocUUP>0?+1:0) + (rocGLD>0?+1:0) + (rocVIXM>0?+1:0) + (rocDBP>0?+1:0) +(rocPFIX>0?+1:0) + (rocBITO<0?+1:0) + (rocUDN<0?+1:0) + (rocDBC<0?+1:0) + (rocUSO<0?+1:0) + (rocDBB<0?+1:0)
Denumerator = Goldilocks + Reflation + Inflation + Deflation
Goldilocksx = Goldilocks + GoldilocksY
Reflationx = Reflation + ReflationY
Inflationx = Inflation + InflationY
Deflationx = Deflation + DeflationY
DenumeratorX = Goldilocksx + Reflationx + Inflationx + Deflationx
// Find the greatest value among the scenarios
maxValueX = math.max(Goldilocksx, Reflationx, Inflationx, Deflationx)
// Determine the market scenario based on the greatest value
Riskx = ""
if maxValueX == Goldilocksx or maxValueX == Reflationx
Riskx := "RISK ON"
else
Riskx := "RISK OFF"
color regCol = na
if maxValueX == Goldilocksx
regCol := color.new(color.green, 50)
else if maxValueX == Reflationx
regCol := color.new(color.lime, 50)
else if maxValueX == Inflationx
regCol := color.new(color.red, 50)
else if maxValueX == Deflationx
regCol := color.new(color.blue, 50)
plot(colx? Riskx == "RISK ON"? 1 : -1 : na )
bgcolor(colx? Riskx == "RISK ON"? color.new(color.green, 60) : color.new(color.red, 60):na)
RiskColX = (Riskx == "RISK ON"? color.green : color.red)
RiskBgx = (Riskx == "RISK ON"? color.new(color.green, 40) : color.new(color.red, 40))
bgcolor(reg? regCol: na)
var string G2 = "🌌 Table Settings Performance 🌌"
string table_y_pos = input.string(defval = "bottom", title = "Table Position", options = ["top", "middle", "bottom"], group = G2, inline = "1")
string table_x_pos = input.string(defval = "right", title = "", options = ["left", "center", "right"], group = G2, inline = "1")
string i_text_size = input.string(defval=size.tiny, title='Text Size:', options = [size.tiny, size.small, size.normal, size.large, size.huge, size.auto], group = G2)
color positive_color_input = color(color.new(color.green, 0))
color negative_color_input = color(color.new(color.red, 0))
var table table = table.new(
table_y_pos + "_" + table_x_pos,
columns = 10,
rows = 34,
frame_color = color.white,
frame_width = 1,
border_color = color.white,
border_width = 1)
if showPerfTab
table.merge_cells(table, 0, 0, 7, 0)
table.merge_cells(table, 0, 1, 1, 1)
table.merge_cells(table, 2, 1, 3, 1)
table.merge_cells(table, 4, 1, 5, 1)
table.merge_cells(table, 6, 1, 7, 1)
table.merge_cells(table, 0, 2, 7, 2)
table.merge_cells(table, 0, 8, 7, 8)
table.merge_cells(table, 0, 16, 7, 16)
table.merge_cells(table, 0, 23, 7, 23)
table.merge_cells(table, 0, 29, 7, 29)
table.merge_cells(table, 0, 33, 7, 33)
// Definitions
if showPerfTab and barstate.islast
table.cell(table, 0, 0, text = "🌌 CE - Fixed Income and Macro "+str.tostring(rocPeriod)+"D 🌌", text_size = i_text_size, text_color = color.purple)
table.cell(table, 0, 2, text = "Top 5 Fixed Income Factors ", text_size = i_text_size, text_color = color.green)
table.cell(table, 0, 8, text = "Bottom 5 Fixed Income Factors ", text_size = i_text_size, text_color = color.red)
table.cell(table, 0, 16, text = "Top 5 Macro Factors", text_size = i_text_size, text_color = color.green)
table.cell(table, 0, 23, text = "Bottom 5 Macro Factors", text_size = i_text_size, text_color = color.red)
table.cell(table, 0, 29, text = "Risk Period: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 0, 33, text = Riskx, text_size = i_text_size, text_color = color.white , bgcolor = RiskBgx, text_font_family = font.family_monospace)
table.cell(table, 0, 1,"GOLDILOCKS", text_size = i_text_size, text_color = color.green)
table.cell(table, 2, 1,"REFLATION", text_size = i_text_size, text_color = color.lime)
table.cell(table, 4, 1,"INFLATION", text_size = i_text_size, text_color = color.red)
table.cell(table, 6, 1,"DEFLATION", text_size = i_text_size, text_color = color.blue)
// GOLDILOCKS *** Top 5 Fixed Income Factors
table.cell(table, 0, 3,"Convertibles (CWB)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 3,str.tostring(math.round(CWB_roc,2)), text_size = i_text_size, text_color = CWB_roc > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 4,"Leveraged Loans (BKLN)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 4,str.tostring(math.round(BKLN_roc,2)), text_size = i_text_size, text_color = BKLN_roc > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 5,"High Yield Credit (HYG)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 5,str.tostring(math.round(HYG_roc,2)), text_size = i_text_size, text_color = HYG_roc > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 6,"Preferreds (PFF)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 6,str.tostring(math.round(PFF_roc,2)), text_size = i_text_size, text_color = PFF_roc > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 7,"Emerging Market US$ Bonds (EMB)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 7,str.tostring(math.round(EMB_roc,2)), text_size = i_text_size, text_color = EMB_roc > 0 ? positive_color_input : negative_color_input)
// GOLDILOCKS *** Bottom 5 Fixed Income Factors
table.cell(table, 0, 9, "Long Bond (TLT)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 9,str.tostring(math.round(TLT_roc,2)), text_size = i_text_size, text_color = TLT_roc > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 10,"5-10yr Treasurys (IEF)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 10,str.tostring(math.round(IEF_roc,2)), text_size = i_text_size, text_color = IEF_roc > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 11,"5-10yr TIPS (TIP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 11,str.tostring(math.round(TIP_roc,2)), text_size = i_text_size, text_color = TIP_roc > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 12,"0-5yr TIPS (STIP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 12,str.tostring(math.round(STIP_roc,2)),text_size = i_text_size, text_color = STIP_roc > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 13,"EM Local Currency Bonds (EMLC)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 13,str.tostring(math.round(EMLC_roc,2)),text_size = i_text_size, text_color = EMLC_roc > 0 ? positive_color_input : negative_color_input)
// REFLATION *** Top 5 Fixed Income Factors
table.cell(table, 2, 3,"Leveraged Loans (BKLN)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 3,str.tostring(math.round(BKLN_roc,2)), text_size = i_text_size, text_color = BKLN_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 2, 4,"Convertibles (CWB)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 4,str.tostring(math.round(CWB_roc,2)), text_size = i_text_size, text_color = CWB_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 2, 5,"High Yield Credit (HYG)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 5,str.tostring(math.round(HYG_roc,2)), text_size = i_text_size, text_color = HYG_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 2, 6,"0-5yr TIPS (STIP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 6,str.tostring(math.round(STIP_roc,2)), text_size = i_text_size, text_color = STIP_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 2, 7,"BDCs (BIZD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 7,str.tostring(math.round(BIZD_roc,2)), text_size = i_text_size, text_color = BIZD_roc > 0? positive_color_input : negative_color_input)
// REFLATION *** Bottom 5 Fixed Income Factors
table.cell(table, 2, 9, "Long Bond (TLT)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 9,str.tostring(math.round(TLT_roc,2)), text_size = i_text_size, text_color = TLT_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 2, 10,"5-10yr Treasurys (IEF)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 10,str.tostring(math.round(IEF_roc,2)), text_size = i_text_size, text_color = IEF_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 2, 11,"Barclays Agg (AGG)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 11,str.tostring(math.round(AGG_roc,2)), text_size = i_text_size, text_color = AGG_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 2, 12,"Investment Grade Credit (LQD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 12,str.tostring(math.round(LQD_roc,2)), text_size = i_text_size, text_color = LQD_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 2, 13,"MBS (MBB)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 13,str.tostring(math.round(MBB_roc,2)), text_size = i_text_size, text_color = MBB_roc > 0? positive_color_input : negative_color_input)
// INFLATION *** Top 5 Fixed Income Factors
table.cell(table, 4, 3,"1-3yr Treasurys (SHY)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 3,str.tostring(math.round(SHY_roc,2)), text_size = i_text_size, text_color = SHY_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 4, 4,"0-5yr TIPS (STIP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 4,str.tostring(math.round(STIP_roc,2)), text_size = i_text_size, text_color = STIP_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 4, 5,"5-10yr Treasurys (IEF)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 5,str.tostring(math.round(IEF_roc,2)), text_size = i_text_size, text_color = IEF_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 4, 6,"5-10yr TIPS (TIP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 6,str.tostring(math.round(TIP_roc,2)), text_size = i_text_size, text_color = TIP_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 4, 7,"Long Bond (TLT)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 7,str.tostring(math.round(TLT_roc,2)), text_size = i_text_size, text_color = TLT_roc > 0? positive_color_input : negative_color_input)
// INFLATION *** Bottom 5 Fixed Income Factors
table.cell(table, 4, 9, "Convertibles (CWB)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 9,str.tostring(math.round(CWB_roc,2)), text_size = i_text_size, text_color = CWB_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 4, 10,"BDCs (BIZD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 10,str.tostring(math.round(BIZD_roc,2)),text_size = i_text_size, text_color = BIZD_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 4, 11,"EM Local Currency Bonds (EMLC)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 11,str.tostring(math.round(EMLC_roc,2)),text_size = i_text_size, text_color = EMLC_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 4, 12,"Preferreds (PFF)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 12,str.tostring(math.round(PFF_roc,2)), text_size = i_text_size, text_color = PFF_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 4, 13,"Investment Grade Credit (LQD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 13,str.tostring(math.round(LQD_roc,2)), text_size = i_text_size, text_color = LQD_roc > 0? positive_color_input : negative_color_input)
// DEFLATION *** Top 5 Fixed Income Factors
table.cell(table, 6, 3,"1-3yr Treasurys (SHY)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 3,str.tostring(math.round(SHY_roc,2)), text_size = i_text_size, text_color = SHY_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 6, 4,"5-10yr Treasurys (IEF)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 4,str.tostring(math.round(IEF_roc,2)), text_size = i_text_size, text_color = IEF_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 6, 5,"Barclays Agg (AGG)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 5,str.tostring(math.round(AGG_roc,2)), text_size = i_text_size, text_color = AGG_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 6, 6,"MBS (MBB)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 6,str.tostring(math.round(MBB_roc,2)), text_size = i_text_size, text_color = MBB_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 6, 7,"Investment Grade Credit (LQD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 7,str.tostring(math.round(LQD_roc,2)), text_size = i_text_size, text_color = LQD_roc > 0? positive_color_input : negative_color_input)
// DEFLATION *** Bottom 5 Fixed Income Factors
table.cell(table, 6, 9, "Preferreds (PFF)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 9,str.tostring(math.round(PFF_roc,2)), text_size = i_text_size, text_color = PFF_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 6, 10,"BDCs (BIZD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 10,str.tostring(math.round(BIZD_roc,2)),text_size = i_text_size, text_color = BIZD_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 6, 11,"EM Local Currency Bonds (EMLC)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 11,str.tostring(math.round(EMLC_roc,2)),text_size = i_text_size, text_color = EMLC_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 6, 12,"High Yield Credit (HYG)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 12,str.tostring(math.round(HYG_roc,2)), text_size = i_text_size, text_color = HYG_roc > 0? positive_color_input : negative_color_input)
table.cell(table, 6, 13,"Leveraged Loans (BKLN)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 13,str.tostring(math.round(BKLN_roc,2)),text_size = i_text_size, text_color = BKLN_roc > 0? positive_color_input : negative_color_input)
// //// MACRO FACTORS
// GOLDILOCKS *** Top 5 MACRO FACTORS
table.cell(table, 0, 17,"Bitcoin (BITO)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 17,str.tostring(math.round(rocBITO,2)), text_size = i_text_size, text_color = rocBITO > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 18,"Industrial Metals (DBB)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 18,str.tostring(math.round(rocDBB,2)), text_size = i_text_size, text_color = rocDBB > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 19,"Commodities (DBC)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 19,str.tostring(math.round(rocDBC,2)), text_size = i_text_size, text_color = rocDBC > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 21,"Inverse US Dollar (UDN)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 21,str.tostring(math.round(rocUDN,2)), text_size = i_text_size, text_color = rocUDN > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 22,"Gold (GLD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 22,str.tostring(math.round(rocGLD,2)), text_size = i_text_size, text_color = rocGLD > 0 ? positive_color_input : negative_color_input)
// GOLDILOCKS *** Bottom 5 MACRO FACTORS
table.cell(table, 0, 24, "Equity Volatility (VIXM)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 24,str.tostring(math.round(rocVIXM,2)), text_size = i_text_size, text_color = rocVIXM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 25,"US Dollar (UUP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 25,str.tostring(math.round(rocUUP,2)), text_size = i_text_size, text_color = rocUUP > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 26,"Interest Rate Volatility (PFIX)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 26,str.tostring(math.round(rocPFIX,2)), text_size = i_text_size, text_color = rocPFIX > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 27,"Energy (USO)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 27,str.tostring(math.round(rocUSO,2)), text_size = i_text_size, text_color = rocUSO > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 28,"Precious Metals (DBP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 28,str.tostring(math.round(rocDBP,2)), text_size = i_text_size, text_color = rocDBP > 0 ? positive_color_input : negative_color_input)
// REFLATION *** Top 5 MACRO FACTORS
table.cell(table, 2, 17,"Bitcoin (BITO)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 17,str.tostring(math.round(rocBITO,2)), text_size = i_text_size, text_color = rocBITO > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 18,"Commodities (DBC)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 18,str.tostring(math.round(rocDBC,2)), text_size = i_text_size, text_color = rocDBC > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 19,"Energy (USO)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 19,str.tostring(math.round(rocUSO,2)), text_size = i_text_size, text_color = rocUSO > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 21,"Industrial Metals (DBB)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 21,str.tostring(math.round(rocDBB,2)), text_size = i_text_size, text_color = rocDBB > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 22,"Gold (GLD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 22,str.tostring(math.round(rocGLD,2)), text_size = i_text_size, text_color = rocGLD > 0 ? positive_color_input : negative_color_input)
// REFLATION *** Bottom 5 MACRO FACTORS
table.cell(table, 2, 24,"US Dollar (UUP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 24,str.tostring(math.round(rocUUP,2)), text_size = i_text_size, text_color = rocUUP > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 25,"Agriculture (DBA)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 25,str.tostring(math.round(rocDBA,2)), text_size = i_text_size, text_color = rocDBA > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 26,"Inverse US Dollar (UDN)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 26,str.tostring(math.round(rocUDN,2)), text_size = i_text_size, text_color = rocUDN > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 27,"Precious Metals (DBP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 27,str.tostring(math.round(rocDBP,2)), text_size = i_text_size, text_color = rocDBP > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 28,"Equity Volatility (VIXM)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 28,str.tostring(math.round(rocVIXM,2)), text_size = i_text_size, text_color = rocVIXM > 0 ? positive_color_input : negative_color_input)
// INFLATION *** Top 5 MACRO FACTORS
table.cell(table, 4, 17,"Bitcoin (BITO)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 17,str.tostring(math.round(rocBITO,2)), text_size = i_text_size, text_color = rocBITO > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 18,"Gold (GLD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 18,str.tostring(math.round(rocGLD,2)), text_size = i_text_size, text_color = rocGLD > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 19,"Equity Volatility (VIXM)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 19,str.tostring(math.round(rocVIXM,2)), text_size = i_text_size, text_color = rocVIXM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 21,"US Dollar (UUP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 21,str.tostring(math.round(rocUUP,2)), text_size = i_text_size, text_color = rocUUP > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 22,"Interest Rate Volatility (PFIX)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 22,str.tostring(math.round(rocPFIX,2)), text_size = i_text_size, text_color = rocPFIX > 0 ? positive_color_input : negative_color_input)
// INFLATION *** Bottom 5 MACRO FACTORS
table.cell(table, 4, 24, "Industrial Metals (DBB)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 24,str.tostring(math.round(rocDBB,2)), text_size = i_text_size, text_color = rocDBB > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 25,"Inverse US Dollar (UDN)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 25,str.tostring(math.round(rocUDN,2)), text_size = i_text_size, text_color = rocUDN > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 26,"Commodities (DBC)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 26,str.tostring(math.round(rocDBC,2)), text_size = i_text_size, text_color = rocDBC > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 27,"Energy (USO)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 27,str.tostring(math.round(rocUSO,2)), text_size = i_text_size, text_color = rocUSO > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 28,"Precious Metals (DBP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 28,str.tostring(math.round(rocDBP,2)), text_size = i_text_size, text_color = rocDBP > 0 ? positive_color_input : negative_color_input)
// DEFLATION *** Top 5 MACRO FACTORS
table.cell(table, 6, 17,"US Dollar (UUP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 17,str.tostring(math.round(rocUUP,2)), text_size = i_text_size, text_color = rocUUP > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 18,"Gold (GLD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 18,str.tostring(math.round(rocGLD,2)), text_size = i_text_size, text_color = rocGLD > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 19,"Equity Volatility (VIXM)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 19,str.tostring(math.round(rocVIXM,2)), text_size = i_text_size, text_color = rocVIXM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 21,"Precious Metals (DBP)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 21,str.tostring(math.round(rocDBP,2)), text_size = i_text_size, text_color = rocDBP > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 22,"Interest Rate Volatility (PFIX)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 22,str.tostring(math.round(rocPFIX,2)), text_size = i_text_size, text_color = rocPFIX > 0 ? positive_color_input : negative_color_input)
// DEFLATION *** Bottom 5 MACRO FACTORS
table.cell(table, 6, 24, "Bitcoin (BITO)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 24,str.tostring(math.round(rocBITO,2)), text_size = i_text_size, text_color = rocBITO > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 25,"Inverse US Dollar (UDN)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 25,str.tostring(math.round(rocUDN,2)), text_size = i_text_size, text_color = rocUDN > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 26,"Commodities (DBC)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 26,str.tostring(math.round(rocDBC,2)), text_size = i_text_size, text_color = rocDBC > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 27,"Energy (USO)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 27,str.tostring(math.round(rocUSO,2)), text_size = i_text_size, text_color = rocUSO > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 28,"Industrial Metals (DBB)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 28,str.tostring(math.round(rocDBB,2)), text_size = i_text_size, text_color = rocDBB > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 32, text = "Goldilocksx Probability: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 32,str.tostring(math.round(Goldilocksx/DenumeratorX*100, 2))+"% | "+str.tostring(Goldilocksx)+ " / 20",text_size = i_text_size, text_color = RiskColX)
table.cell(table, 2, 32, text = "Reflation Probability: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 32,str.tostring(math.round(Reflationx/DenumeratorX*100, 2))+"% | "+str.tostring(Reflationx)+ " / 20", text_size = i_text_size, text_color = RiskColX)
table.cell(table, 4, 32, text = "Inflation Probability: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 32,str.tostring(math.round(Inflationx/DenumeratorX*100, 2))+"% | "+str.tostring(Inflationx)+ " / 20", text_size = i_text_size, text_color = RiskColX)
table.cell(table, 6, 32, text = "Deflation Probability: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 32,str.tostring(math.round(Deflationx/DenumeratorX*100, 2))+"% | "+str.tostring(Deflationx)+ " / 20", text_size = i_text_size, text_color = RiskColX)
// SOME FUN SHIT DOWN HERE
RiskULTIMATE = ""
color regColULTIMATE = na
if ultimateGRID or ultimateRISK
// Calculate the relative RoC for each asset -
CWB_RoC = ta.roc(CWB , rocPeriod) - (useRelative? avgROCFI : 0)
BKLN_RoC = ta.roc(BKLN, rocPeriod) - (useRelative? avgROCFI : 0)
HYG_RoC = ta.roc(HYG, rocPeriod) - (useRelative? avgROCFI : 0)
PFF_RoC = ta.roc(PFF, rocPeriod) - (useRelative? avgROCFI : 0)
EMB_RoC = ta.roc(EMB, rocPeriod) - (useRelative? avgROCFI : 0)
TLT_RoC = ta.roc(TLT, rocPeriod) - (useRelative? avgROCFI : 0)
IEF_RoC = ta.roc(IEF, rocPeriod) - (useRelative? avgROCFI : 0)
TIP_RoC = ta.roc(TIP, rocPeriod) - (useRelative? avgROCFI : 0)
STIP_RoC = ta.roc(STIP, rocPeriod) - (useRelative? avgROCFI : 0)
EMLC_RoC = ta.roc(EMLC, rocPeriod) - (useRelative? avgROCFI : 0)
BIZD_RoC = ta.roc(BIZD, rocPeriod) - (useRelative? avgROCFI : 0)
AGG_RoC = ta.roc(AGG, rocPeriod) - (useRelative? avgROCFI : 0)
LQD_RoC = ta.roc(LQD, rocPeriod) - (useRelative? avgROCFI : 0)
SHY_RoC = ta.roc(SHY, rocPeriod) - (useRelative? avgROCFI : 0)
MBB_RoC = ta.roc(MBB, rocPeriod) - (useRelative? avgROCFI : 0)
// Calculate the Sharpe ratio for each asset -
CWB_Sharpe = f_sharpe(CWB , rocPeriod) - (useRelative? avgRoCFISH : 0)
BKLN_Sharpe = f_sharpe(BKLN, rocPeriod) - (useRelative? avgRoCFISH : 0)
HYG_Sharpe = f_sharpe(HYG, rocPeriod) - (useRelative? avgRoCFISH : 0)
PFF_Sharpe = f_sharpe(PFF, rocPeriod) - (useRelative? avgRoCFISH : 0)
EMB_Sharpe = f_sharpe(EMB, rocPeriod) - (useRelative? avgRoCFISH : 0)
TLT_Sharpe = f_sharpe(TLT, rocPeriod) - (useRelative? avgRoCFISH : 0)
IEF_Sharpe = f_sharpe(IEF, rocPeriod) - (useRelative? avgRoCFISH : 0)
TIP_Sharpe = f_sharpe(TIP, rocPeriod) - (useRelative? avgRoCFISH : 0)
STIP_Sharpe = f_sharpe(STIP, rocPeriod) - (useRelative? avgRoCFISH : 0)
EMLC_Sharpe = f_sharpe(EMLC, rocPeriod) - (useRelative? avgRoCFISH : 0)
BIZD_Sharpe = f_sharpe(BIZD, rocPeriod) - (useRelative? avgRoCFISH : 0)
AGG_Sharpe = f_sharpe(AGG, rocPeriod) - (useRelative? avgRoCFISH : 0)
LQD_Sharpe = f_sharpe(LQD, rocPeriod) - (useRelative? avgRoCFISH : 0)
SHY_Sharpe = f_sharpe(SHY, rocPeriod) - (useRelative? avgRoCFISH : 0)
MBB_Sharpe = f_sharpe(MBB, rocPeriod) - (useRelative? avgRoCFISH : 0)
// Calculate the Sortino ratio for each asset -
CWB_Sortino = f_sortino(CWB , rocPeriod) - (useRelative? avgRoCFISO : 0)
BKLN_Sortino = f_sortino(BKLN, rocPeriod) - (useRelative? avgRoCFISO : 0)
HYG_Sortino = f_sortino(HYG, rocPeriod) - (useRelative? avgRoCFISO : 0)
PFF_Sortino = f_sortino(PFF, rocPeriod) - (useRelative? avgRoCFISO : 0)
EMB_Sortino = f_sortino(EMB, rocPeriod) - (useRelative? avgRoCFISO : 0)
TLT_Sortino = f_sortino(TLT, rocPeriod) - (useRelative? avgRoCFISO : 0)
IEF_Sortino = f_sortino(IEF, rocPeriod) - (useRelative? avgRoCFISO : 0)
TIP_Sortino = f_sortino(TIP, rocPeriod) - (useRelative? avgRoCFISO : 0)
STIP_Sortino = f_sortino(STIP, rocPeriod) - (useRelative? avgRoCFISO : 0)
EMLC_Sortino = f_sortino(EMLC, rocPeriod) - (useRelative? avgRoCFISO : 0)
BIZD_Sortino = f_sortino(BIZD, rocPeriod) - (useRelative? avgRoCFISO : 0)
AGG_Sortino = f_sortino(AGG, rocPeriod) - (useRelative? avgRoCFISO : 0)
LQD_Sortino = f_sortino(LQD, rocPeriod) - (useRelative? avgRoCFISO : 0)
SHY_Sortino = f_sortino(SHY, rocPeriod) - (useRelative? avgRoCFISO : 0)
MBB_Sortino = f_sortino(MBB, rocPeriod) - (useRelative? avgRoCFISO : 0)
// Calculate the Omega ratio for each asset -
CWB_Omega = f_omega(CWB , rocPeriod) - (useRelative? avgRoCFIO : 0)
BKLN_Omega = f_omega(BKLN, rocPeriod) - (useRelative? avgRoCFIO : 0)
HYG_Omega = f_omega(HYG, rocPeriod) - (useRelative? avgRoCFIO : 0)
PFF_Omega = f_omega(PFF, rocPeriod) - (useRelative? avgRoCFIO : 0)
EMB_Omega = f_omega(EMB, rocPeriod) - (useRelative? avgRoCFIO : 0)
TLT_Omega = f_omega(TLT, rocPeriod) - (useRelative? avgRoCFIO : 0)
IEF_Omega = f_omega(IEF, rocPeriod) - (useRelative? avgRoCFIO : 0)
TIP_Omega = f_omega(TIP, rocPeriod) - (useRelative? avgRoCFIO : 0)
STIP_Omega = f_omega(STIP, rocPeriod) - (useRelative? avgRoCFIO : 0)
EMLC_Omega = f_omega(EMLC, rocPeriod) - (useRelative? avgRoCFIO : 0)
BIZD_Omega = f_omega(BIZD, rocPeriod) - (useRelative? avgRoCFIO : 0)
AGG_Omega = f_omega(AGG, rocPeriod) - (useRelative? avgRoCFIO : 0)
LQD_Omega = f_omega(LQD, rocPeriod) - (useRelative? avgRoCFIO : 0)
SHY_Omega = f_omega(SHY, rocPeriod) - (useRelative? avgRoCFIO : 0)
MBB_Omega = f_omega(MBB, rocPeriod) - (useRelative? avgRoCFIO : 0)
// Calculate the Normalization for each asset -
CWB_Normal = f_normalization(CWB , rocPeriod) - (useRelative? avgRoCFINO : 0)
BKLN_Normal = f_normalization(BKLN, rocPeriod) - (useRelative? avgRoCFINO : 0)
HYG_Normal = f_normalization(HYG, rocPeriod) - (useRelative? avgRoCFINO : 0)
PFF_Normal = f_normalization(PFF, rocPeriod) - (useRelative? avgRoCFINO : 0)
EMB_Normal = f_normalization(EMB, rocPeriod) - (useRelative? avgRoCFINO : 0)
TLT_Normal = f_normalization(TLT, rocPeriod) - (useRelative? avgRoCFINO : 0)
IEF_Normal = f_normalization(IEF, rocPeriod) - (useRelative? avgRoCFINO : 0)
TIP_Normal = f_normalization(TIP, rocPeriod) - (useRelative? avgRoCFINO : 0)
STIP_Normal = f_normalization(STIP, rocPeriod) - (useRelative? avgRoCFINO : 0)
EMLC_Normal = f_normalization(EMLC, rocPeriod) - (useRelative? avgRoCFINO : 0)
BIZD_Normal = f_normalization(BIZD, rocPeriod) - (useRelative? avgRoCFINO : 0)
AGG_Normal = f_normalization(AGG, rocPeriod) - (useRelative? avgRoCFINO : 0)
LQD_Normal = f_normalization(LQD, rocPeriod) - (useRelative? avgRoCFINO : 0)
SHY_Normal = f_normalization(SHY, rocPeriod) - (useRelative? avgRoCFINO : 0)
MBB_Normal = f_normalization(MBB, rocPeriod) - (useRelative? avgRoCFINO : 0)
// Calculate the probabilities for Fixed Income RoC
GoldilocksFIroc = (CWB_RoC >0?+1:0) + (BKLN_RoC>0?+1:0) + (HYG_RoC>0?+1:0) + (PFF_RoC >0?+1:0) + (EMB_RoC >0?+1:0) + (TLT_RoC<0?+1:0) + (IEF_RoC <0?+1:0) + (TIP_RoC <0?+1:0) + (STIP_RoC<0?+1:0) + (EMLC_RoC<0?+1:0)
ReflationFIroc = (BKLN_RoC>0?+1:0) + (CWB_RoC >0?+1:0) + (HYG_RoC>0?+1:0) + (STIP_RoC >0?+1:0) + (BIZD_RoC>0?+1:0) + (TLT_RoC<0?+1:0) + (IEF_RoC <0?+1:0) + (AGG_RoC <0?+1:0) + (LQD_RoC <0?+1:0) + (MBB_RoC <0?+1:0)
InflationFIroc = (SHY_RoC >0?+1:0) + (STIP_RoC>0?+1:0) + (IEF_RoC>0?+1:0) + (TIP_RoC >0?+1:0) + (TLT_RoC >0?+1:0) + (CWB_RoC<0?+1:0) + (BIZD_RoC<0?+1:0) + (EMLC_RoC<0?+1:0) + (PFF_RoC <0?+1:0) + (LQD_RoC <0?+1:0)
DeflationFIroc = (SHY_RoC >0?+1:0) + (IEF_RoC >0?+1:0) + (AGG_RoC>0?+1:0) + (MBB_RoC >0?+1:0) + (LQD_RoC >0?+1:0) + (PFF_RoC<0?+1:0) + (BIZD_RoC<0?+1:0) + (EMLC_RoC<0?+1:0) + (HYG_RoC <0?+1:0) + (BKLN_RoC<0?+1:0)
DenumeratorFIroc = GoldilocksFIroc + ReflationFIroc + InflationFIroc + DeflationFIroc
// Calculate the probabilities for Fixed Income Sharpe
GoldilocksFISharpe = (CWB_Sharpe >0?+1:0) + (BKLN_Sharpe>0?+1:0) + (HYG_Sharpe>0?+1:0) + (PFF_Sharpe >0?+1:0) + (EMB_Sharpe >0?+1:0) + (TLT_Sharpe<0?+1:0) + (IEF_Sharpe <0?+1:0) + (TIP_Sharpe <0?+1:0) + (STIP_Sharpe<0?+1:0) + (EMLC_Sharpe<0?+1:0)
ReflationFISharpe = (BKLN_Sharpe>0?+1:0) + (CWB_Sharpe >0?+1:0) + (HYG_Sharpe>0?+1:0) + (STIP_Sharpe >0?+1:0) + (BIZD_Sharpe>0?+1:0) + (TLT_Sharpe<0?+1:0) + (IEF_Sharpe <0?+1:0) + (AGG_Sharpe <0?+1:0) + (LQD_Sharpe <0?+1:0) + (MBB_Sharpe <0?+1:0)
InflationFISharpe = (SHY_Sharpe >0?+1:0) + (STIP_Sharpe>0?+1:0) + (IEF_Sharpe>0?+1:0) + (TIP_Sharpe >0?+1:0) + (TLT_Sharpe >0?+1:0) + (CWB_Sharpe<0?+1:0) + (BIZD_Sharpe<0?+1:0) + (EMLC_Sharpe<0?+1:0) + (PFF_Sharpe <0?+1:0) + (LQD_Sharpe <0?+1:0)
DeflationFISharpe = (SHY_Sharpe >0?+1:0) + (IEF_Sharpe >0?+1:0) + (AGG_Sharpe>0?+1:0) + (MBB_Sharpe >0?+1:0) + (LQD_Sharpe >0?+1:0) + (PFF_Sharpe<0?+1:0) + (BIZD_Sharpe<0?+1:0) + (EMLC_Sharpe<0?+1:0) + (HYG_Sharpe <0?+1:0) + (BKLN_Sharpe<0?+1:0)
DenumeratorFISharpe = GoldilocksFISharpe + ReflationFISharpe + InflationFISharpe + DeflationFISharpe
// Calculate the probabilities for Fixed Income Sortino
GoldilocksFISortino = (CWB_Sortino >0?+1:0) + (BKLN_Sortino>0?+1:0) + (HYG_Sortino>0?+1:0) + (PFF_Sortino >0?+1:0) + (EMB_Sortino >0?+1:0) + (TLT_Sortino<0?+1:0) + (IEF_Sortino <0?+1:0) + (TIP_Sortino <0?+1:0) + (STIP_Sortino<0?+1:0) + (EMLC_Sortino<0?+1:0)
ReflationFISortino = (BKLN_Sortino>0?+1:0) + (CWB_Sortino >0?+1:0) + (HYG_Sortino>0?+1:0) + (STIP_Sortino >0?+1:0) + (BIZD_Sortino>0?+1:0) + (TLT_Sortino<0?+1:0) + (IEF_Sortino <0?+1:0) + (AGG_Sortino <0?+1:0) + (LQD_Sortino <0?+1:0) + (MBB_Sortino <0?+1:0)
InflationFISortino = (SHY_Sortino >0?+1:0) + (STIP_Sortino>0?+1:0) + (IEF_Sortino>0?+1:0) + (TIP_Sortino >0?+1:0) + (TLT_Sortino >0?+1:0) + (CWB_Sortino<0?+1:0) + (BIZD_Sortino<0?+1:0) + (EMLC_Sortino<0?+1:0) + (PFF_Sortino <0?+1:0) + (LQD_Sortino <0?+1:0)
DeflationFISortino = (SHY_Sortino >0?+1:0) + (IEF_Sortino >0?+1:0) + (AGG_Sortino>0?+1:0) + (MBB_Sortino >0?+1:0) + (LQD_Sortino >0?+1:0) + (PFF_Sortino<0?+1:0) + (BIZD_Sortino<0?+1:0) + (EMLC_Sortino<0?+1:0) + (HYG_Sortino <0?+1:0) + (BKLN_Sortino<0?+1:0)
DenumeratorFISortino = GoldilocksFISortino + ReflationFISortino + InflationFISortino + DeflationFISortino
// Calculate the probabilities for Fixed Income Omega
GoldilocksFIOmega = (CWB_Omega >0?+1:0) + (BKLN_Omega>0?+1:0) + (HYG_Omega>0?+1:0) + (PFF_Omega >0?+1:0) + (EMB_Omega >0?+1:0) + (TLT_Omega<0?+1:0) + (IEF_Omega <0?+1:0) + (TIP_Omega <0?+1:0) + (STIP_Omega<0?+1:0) + (EMLC_Omega<0?+1:0)
ReflationFIOmega = (BKLN_Omega>0?+1:0) + (CWB_Omega >0?+1:0) + (HYG_Omega>0?+1:0) + (STIP_Omega >0?+1:0) + (BIZD_Omega>0?+1:0) + (TLT_Omega<0?+1:0) + (IEF_Omega <0?+1:0) + (AGG_Omega <0?+1:0) + (LQD_Omega <0?+1:0) + (MBB_Omega <0?+1:0)
InflationFIOmega = (SHY_Omega >0?+1:0) + (STIP_Omega>0?+1:0) + (IEF_Omega>0?+1:0) + (TIP_Omega >0?+1:0) + (TLT_Omega >0?+1:0) + (CWB_Omega<0?+1:0) + (BIZD_Omega<0?+1:0) + (EMLC_Omega<0?+1:0) + (PFF_Omega <0?+1:0) + (LQD_Omega <0?+1:0)
DeflationFIOmega = (SHY_Omega >0?+1:0) + (IEF_Omega >0?+1:0) + (AGG_Omega>0?+1:0) + (MBB_Omega >0?+1:0) + (LQD_Omega >0?+1:0) + (PFF_Omega<0?+1:0) + (BIZD_Omega<0?+1:0) + (EMLC_Omega<0?+1:0) + (HYG_Omega <0?+1:0) + (BKLN_Omega<0?+1:0)
DenumeratorFIOmega = GoldilocksFIOmega + ReflationFIOmega + InflationFIOmega + DeflationFIOmega
// Calculate the probabilities for Fixed Income Normalization
GoldilocksFINormal = (CWB_Normal >0?+1:0) + (BKLN_Normal>0?+1:0) + (HYG_Normal>0?+1:0) + (PFF_Normal >0?+1:0) + (EMB_Normal >0?+1:0) + (TLT_Normal<0?+1:0) + (IEF_Normal <0?+1:0) + (TIP_Normal <0?+1:0) + (STIP_Normal<0?+1:0) + (EMLC_Normal<0?+1:0)
ReflationFINormal = (BKLN_Normal>0?+1:0) + (CWB_Normal >0?+1:0) + (HYG_Normal>0?+1:0) + (STIP_Normal >0?+1:0) + (BIZD_Normal>0?+1:0) + (TLT_Normal<0?+1:0) + (IEF_Normal <0?+1:0) + (AGG_Normal <0?+1:0) + (LQD_Normal <0?+1:0) + (MBB_Normal <0?+1:0)
InflationFINormal = (SHY_Normal >0?+1:0) + (STIP_Normal>0?+1:0) + (IEF_Normal>0?+1:0) + (TIP_Normal >0?+1:0) + (TLT_Normal >0?+1:0) + (CWB_Normal<0?+1:0) + (BIZD_Normal<0?+1:0) + (EMLC_Normal<0?+1:0) + (PFF_Normal <0?+1:0) + (LQD_Normal <0?+1:0)
DeflationFINormal = (SHY_Normal >0?+1:0) + (IEF_Normal >0?+1:0) + (AGG_Normal>0?+1:0) + (MBB_Normal >0?+1:0) + (LQD_Normal >0?+1:0) + (PFF_Normal<0?+1:0) + (BIZD_Normal<0?+1:0) + (EMLC_Normal<0?+1:0) + (HYG_Normal <0?+1:0) + (BKLN_Normal<0?+1:0)
DenumeratorFINormal = GoldilocksFINormal + ReflationFINormal + InflationFINormal + DeflationFINormal
// Calculate the relative RoC for each asset -
RoCBITO = ta.roc(BITO, rocPeriod) - (useRelative? avgROC : 0)
RoCDBB = ta.roc(DBB, rocPeriod) - (useRelative? avgROC : 0)
RoCDBC = ta.roc(DBC, rocPeriod) - (useRelative? avgROC : 0)
RoCUDN = ta.roc(UDN, rocPeriod) - (useRelative? avgROC : 0)
RoCGLD = ta.roc(GLD, rocPeriod) - (useRelative? avgROC : 0)
RoCVIXM = ta.roc(VIXM, rocPeriod) - (useRelative? avgROC : 0)
RoCUUP = ta.roc(UUP, rocPeriod) - (useRelative? avgROC : 0)
RoCPFIX = ta.roc(PFIX, rocPeriod) - (useRelative? avgROC : 0)
RoCUSO = ta.roc(USO, rocPeriod) - (useRelative? avgROC : 0)
RoCDBP = ta.roc(DBP, rocPeriod) - (useRelative? avgROC : 0)
RoCDBA = ta.roc(DBA, rocPeriod) - (useRelative? avgROC : 0)
// Calculate the Sharpe ratio for each asset -
SharpeBITO = f_sharpe(BITO, rocPeriod) - (useRelative? avgRoCMSH : 0)
SharpeDBB = f_sharpe(DBB, rocPeriod) - (useRelative? avgRoCMSH : 0)
SharpeDBC = f_sharpe(DBC, rocPeriod) - (useRelative? avgRoCMSH : 0)
SharpeUDN = f_sharpe(UDN, rocPeriod) - (useRelative? avgRoCMSH : 0)
SharpeGLD = f_sharpe(GLD, rocPeriod) - (useRelative? avgRoCMSH : 0)
SharpeVIXM = f_sharpe(VIXM, rocPeriod) - (useRelative? avgRoCMSH : 0)
SharpeUUP = f_sharpe(UUP, rocPeriod) - (useRelative? avgRoCMSH : 0)
SharpePFIX = f_sharpe(PFIX, rocPeriod) - (useRelative? avgRoCMSH : 0)
SharpeUSO = f_sharpe(USO, rocPeriod) - (useRelative? avgRoCMSH : 0)
SharpeDBP = f_sharpe(DBP, rocPeriod) - (useRelative? avgRoCMSH : 0)
SharpeDBA = f_sharpe(DBA, rocPeriod) - (useRelative? avgRoCMSH : 0)
// Calculate the Sortino ratio for each asset -
SortinoBITO = f_sortino(BITO, rocPeriod) - (useRelative? avgRoCMSO : 0)
SortinoDBB = f_sortino(DBB, rocPeriod) - (useRelative? avgRoCMSO : 0)
SortinoDBC = f_sortino(DBC, rocPeriod) - (useRelative? avgRoCMSO : 0)
SortinoUDN = f_sortino(UDN, rocPeriod) - (useRelative? avgRoCMSO : 0)
SortinoGLD = f_sortino(GLD, rocPeriod) - (useRelative? avgRoCMSO : 0)
SortinoVIXM = f_sortino(VIXM, rocPeriod) - (useRelative? avgRoCMSO : 0)
SortinoUUP = f_sortino(UUP, rocPeriod) - (useRelative? avgRoCMSO : 0)
SortinoPFIX = f_sortino(PFIX, rocPeriod) - (useRelative? avgRoCMSO : 0)
SortinoUSO = f_sortino(USO, rocPeriod) - (useRelative? avgRoCMSO : 0)
SortinoDBP = f_sortino(DBP, rocPeriod) - (useRelative? avgRoCMSO : 0)
SortinoDBA = f_sortino(DBA, rocPeriod) - (useRelative? avgRoCMSO : 0)
// Calculate the Omega ratio for each asset - optional
OmegaBITO = f_omega(BITO, rocPeriod) - (useRelative? avgRoCMO : 0)
OmegaDBB = f_omega(DBB, rocPeriod) - (useRelative? avgRoCMO : 0)
OmegaDBC = f_omega(DBC, rocPeriod) - (useRelative? avgRoCMO : 0)
OmegaUDN = f_omega(UDN, rocPeriod) - (useRelative? avgRoCMO : 0)
OmegaGLD = f_omega(GLD, rocPeriod) - (useRelative? avgRoCMO : 0)
OmegaVIXM = f_omega(VIXM, rocPeriod) - (useRelative? avgRoCMO : 0)
OmegaUUP = f_omega(UUP, rocPeriod) - (useRelative? avgRoCMO : 0)
OmegaPFIX = f_omega(PFIX, rocPeriod) - (useRelative? avgRoCMO : 0)
OmegaUSO = f_omega(USO, rocPeriod) - (useRelative? avgRoCMO : 0)
OmegaDBP = f_omega(DBP, rocPeriod) - (useRelative? avgRoCMO : 0)
OmegaDBA = f_omega(DBA, rocPeriod) - (useRelative? avgRoCMO : 0)
// Calculate the Normalization for each asset - optional
NormalBITO = f_normalization(BITO, rocPeriod) - (useRelative? avgRoCMNO : 0)
NormalDBB = f_normalization(DBB, rocPeriod) - (useRelative? avgRoCMNO : 0)
NormalDBC = f_normalization(DBC, rocPeriod) - (useRelative? avgRoCMNO : 0)
NormalUDN = f_normalization(UDN, rocPeriod) - (useRelative? avgRoCMNO : 0)
NormalGLD = f_normalization(GLD, rocPeriod) - (useRelative? avgRoCMNO : 0)
NormalVIXM = f_normalization(VIXM, rocPeriod) - (useRelative? avgRoCMNO : 0)
NormalUUP = f_normalization(UUP, rocPeriod) - (useRelative? avgRoCMNO : 0)
NormalPFIX = f_normalization(PFIX, rocPeriod) - (useRelative? avgRoCMNO : 0)
NormalUSO = f_normalization(USO, rocPeriod) - (useRelative? avgRoCMNO : 0)
NormalDBP = f_normalization(DBP, rocPeriod) - (useRelative? avgRoCMNO : 0)
NormalDBA = f_normalization(DBA, rocPeriod) - (useRelative? avgRoCMNO : 0)
// Calculate the probabilities Macro RoC
GoldilocksMroc = (RoCBITO>0?+1:0) + (RoCDBB>0?+1:0) + (RoCDBC>0?+1:0) + (RoCUDN>0?+1:0) +(RoCGLD>0?+1:0) + (RoCVIXM<0?+1:0) + (RoCUUP<0?+1:0) + (RoCPFIX<0?+1:0) + (RoCUSO<0?+1:0) + (RoCDBP<0?+1:0)
ReflationMroc = (RoCBITO>0?+1:0) + (RoCDBC>0?+1:0) + (RoCUSO>0?+1:0) + (RoCDBB>0?+1:0) +(RoCGLD>0?+1:0) + (RoCUUP<0?+1:0) + (RoCDBA<0?+1:0) + (RoCUDN<0?+1:0) + (RoCDBP<0?+1:0) + (RoCVIXM<0?+1:0)
InflationMroc = (RoCBITO>0?+1:0) + (RoCGLD>0?+1:0) + (RoCVIXM>0?+1:0) + (RoCUUP>0?+1:0) +(RoCPFIX>0?+1:0) + (RoCDBB<0?+1:0) + (RoCUDN<0?+1:0) + (RoCDBC<0?+1:0) + (RoCUSO<0?+1:0) + (RoCDBP<0?+1:0)
DeflationMroc = (RoCUUP>0?+1:0) + (RoCGLD>0?+1:0) + (RoCVIXM>0?+1:0) + (RoCDBP>0?+1:0) +(RoCPFIX>0?+1:0) + (RoCBITO<0?+1:0) + (RoCUDN<0?+1:0) + (RoCDBC<0?+1:0) + (RoCUSO<0?+1:0) + (RoCDBB<0?+1:0)
DenumeratorMroc = GoldilocksMroc + ReflationMroc + InflationMroc + DeflationMroc
// Calculate the probabilities Macro Sharpe
GoldilocksMSharpe = (SharpeBITO>0?+1:0) + (SharpeDBB>0?+1:0) + (SharpeDBC>0?+1:0) + (SharpeUDN>0?+1:0) +(SharpeGLD>0?+1:0) + (SharpeVIXM<0?+1:0) + (SharpeUUP<0?+1:0) + (SharpePFIX<0?+1:0) + (SharpeUSO<0?+1:0) + (SharpeDBP<0?+1:0)
ReflationMSharpe = (SharpeBITO>0?+1:0) + (SharpeDBC>0?+1:0) + (SharpeUSO>0?+1:0) + (SharpeDBB>0?+1:0) +(SharpeGLD>0?+1:0) + (SharpeUUP<0?+1:0) + (SharpeDBA<0?+1:0) + (SharpeUDN<0?+1:0) + (SharpeDBP<0?+1:0) + (SharpeVIXM<0?+1:0)
InflationMSharpe = (SharpeBITO>0?+1:0) + (SharpeGLD>0?+1:0) + (SharpeVIXM>0?+1:0) + (SharpeUUP>0?+1:0) +(SharpePFIX>0?+1:0) + (SharpeDBB<0?+1:0) + (SharpeUDN<0?+1:0) + (SharpeDBC<0?+1:0) + (SharpeUSO<0?+1:0) + (SharpeDBP<0?+1:0)
DeflationMSharpe = (SharpeUUP>0?+1:0) + (SharpeGLD>0?+1:0) + (SharpeVIXM>0?+1:0) + (SharpeDBP>0?+1:0) +(SharpePFIX>0?+1:0) + (SharpeBITO<0?+1:0) + (SharpeUDN<0?+1:0) + (SharpeDBC<0?+1:0) + (SharpeUSO<0?+1:0) + (SharpeDBB<0?+1:0)
DenumeratorMSharpe = GoldilocksMSharpe + ReflationMSharpe + InflationMSharpe + DeflationMSharpe
// Calculate the probabilities Macro Sortino
GoldilocksMSortino = (SortinoBITO>0?+1:0) + (SortinoDBB>0?+1:0) + (SortinoDBC>0?+1:0) + (SortinoUDN>0?+1:0) +(SortinoGLD>0?+1:0) + (SortinoVIXM<0?+1:0) + (SortinoUUP<0?+1:0) + (SortinoPFIX<0?+1:0) + (SortinoUSO<0?+1:0) + (SortinoDBP<0?+1:0)
ReflationMSortino = (SortinoBITO>0?+1:0) + (SortinoDBC>0?+1:0) + (SortinoUSO>0?+1:0) + (SortinoDBB>0?+1:0) +(SortinoGLD>0?+1:0) + (SortinoUUP<0?+1:0) + (SortinoDBA<0?+1:0) + (SortinoUDN<0?+1:0) + (SortinoDBP<0?+1:0) + (SortinoVIXM<0?+1:0)
InflationMSortino = (SortinoBITO>0?+1:0) + (SortinoGLD>0?+1:0) + (SortinoVIXM>0?+1:0) + (SortinoUUP>0?+1:0) +(SortinoPFIX>0?+1:0) + (SortinoDBB<0?+1:0) + (SortinoUDN<0?+1:0) + (SortinoDBC<0?+1:0) + (SortinoUSO<0?+1:0) + (SortinoDBP<0?+1:0)
DeflationMSortino = (SortinoUUP>0?+1:0) + (SortinoGLD>0?+1:0) + (SortinoVIXM>0?+1:0) + (SortinoDBP>0?+1:0) +(SortinoPFIX>0?+1:0) + (SortinoBITO<0?+1:0) + (SortinoUDN<0?+1:0) + (SortinoDBC<0?+1:0) + (SortinoUSO<0?+1:0) + (SortinoDBB<0?+1:0)
DenumeratorMSortino = GoldilocksMSortino + ReflationMSortino + InflationMSortino + DeflationMSortino
// Calculate the probabilities Macro Omega
GoldilocksMOmega = (OmegaBITO>0?+1:0) + (OmegaDBB>0?+1:0) + (OmegaDBC>0?+1:0) + (OmegaUDN>0?+1:0) +(OmegaGLD>0?+1:0) + (OmegaVIXM<0?+1:0) + (OmegaUUP<0?+1:0) + (OmegaPFIX<0?+1:0) + (OmegaUSO<0?+1:0) + (OmegaDBP<0?+1:0)
ReflationMOmega = (OmegaBITO>0?+1:0) + (OmegaDBC>0?+1:0) + (OmegaUSO>0?+1:0) + (OmegaDBB>0?+1:0) +(OmegaGLD>0?+1:0) + (OmegaUUP<0?+1:0) + (OmegaDBA<0?+1:0) + (OmegaUDN<0?+1:0) + (OmegaDBP<0?+1:0) + (OmegaVIXM<0?+1:0)
InflationMOmega = (OmegaBITO>0?+1:0) + (OmegaGLD>0?+1:0) + (OmegaVIXM>0?+1:0) + (OmegaUUP>0?+1:0) +(OmegaPFIX>0?+1:0) + (OmegaDBB<0?+1:0) + (OmegaUDN<0?+1:0) + (OmegaDBC<0?+1:0) + (OmegaUSO<0?+1:0) + (OmegaDBP<0?+1:0)
DeflationMOmega = (OmegaUUP>0?+1:0) + (OmegaGLD>0?+1:0) + (OmegaVIXM>0?+1:0) + (OmegaDBP>0?+1:0) +(OmegaPFIX>0?+1:0) + (OmegaBITO<0?+1:0) + (OmegaUDN<0?+1:0) + (OmegaDBC<0?+1:0) + (OmegaUSO<0?+1:0) + (OmegaDBB<0?+1:0)
DenumeratorMOmega = GoldilocksMOmega + ReflationMOmega + InflationMOmega + DeflationMOmega
// Calculate the probabilities Macro Normalization
GoldilocksMNormal = (NormalBITO>0?+1:0) + (NormalDBB>0?+1:0) + (NormalDBC>0?+1:0) + (NormalUDN>0?+1:0) +(NormalGLD>0?+1:0) + (NormalVIXM<0?+1:0) + (NormalUUP<0?+1:0) + (NormalPFIX<0?+1:0) + (NormalUSO<0?+1:0) + (NormalDBP<0?+1:0)
ReflationMNormal = (NormalBITO>0?+1:0) + (NormalDBC>0?+1:0) + (NormalUSO>0?+1:0) + (NormalDBB>0?+1:0) +(NormalGLD>0?+1:0) + (NormalUUP<0?+1:0) + (NormalDBA<0?+1:0) + (NormalUDN<0?+1:0) + (NormalDBP<0?+1:0) + (NormalVIXM<0?+1:0)
InflationMNormal = (NormalBITO>0?+1:0) + (NormalGLD>0?+1:0) + (NormalVIXM>0?+1:0) + (NormalUUP>0?+1:0) +(NormalPFIX>0?+1:0) + (NormalDBB<0?+1:0) + (NormalUDN<0?+1:0) + (NormalDBC<0?+1:0) + (NormalUSO<0?+1:0) + (NormalDBP<0?+1:0)
DeflationMNormal = (NormalUUP>0?+1:0) + (NormalGLD>0?+1:0) + (NormalVIXM>0?+1:0) + (NormalDBP>0?+1:0) +(NormalPFIX>0?+1:0) + (NormalBITO<0?+1:0) + (NormalUDN<0?+1:0) + (NormalDBC<0?+1:0) + (NormalUSO<0?+1:0) + (NormalDBB<0?+1:0)
DenumeratorMNormal = GoldilocksMNormal + ReflationMNormal + InflationMNormal + DeflationMNormal
////// ROC
GoldilocksTotRoC = GoldilocksFIroc + GoldilocksMroc
ReflationTotRoC = ReflationFIroc + ReflationMroc
InflationTotRoC = InflationFIroc + InflationMroc
DeflationTotRoC = DeflationFIroc + DeflationMroc
////////SHARPE
GoldilocksTotSharpe = GoldilocksFISharpe + GoldilocksMSharpe
ReflationTotSharpe = ReflationFISharpe + ReflationMSharpe
InflationTotSharpe = InflationFISharpe + InflationMSharpe
DeflationTotSharpe = DeflationFISharpe + DeflationMSharpe
///////SORTINO
GoldilocksTotSortino = GoldilocksFISortino + GoldilocksMSortino
ReflationTotSortino = ReflationFISortino + ReflationMSortino
InflationTotSortino = InflationFISortino + InflationMSortino
DeflationTotSortino = DeflationFISortino + DeflationMSortino
/////////OMEGA
GoldilocksTotOmega = GoldilocksFIOmega + GoldilocksMOmega
ReflationTotOmega = ReflationFIOmega + ReflationMOmega
InflationTotOmega = InflationFIOmega + InflationMOmega
DeflationTotOmega = DeflationFIOmega + DeflationMOmega
/////////NORMALIZATION
GoldilocksTotNormal = GoldilocksFINormal + GoldilocksMNormal
ReflationTotNormal = ReflationFINormal + ReflationMNormal
InflationTotNormal = InflationFINormal + InflationMNormal
DeflationTotNormal = DeflationFINormal + DeflationMNormal
// Calculate the individual cross regimes
GoldilocksULTIMATE = GoldilocksTotRoC+ GoldilocksTotSharpe + GoldilocksTotSortino + GoldilocksTotOmega + GoldilocksTotNormal
ReflationULTIMATE = ReflationTotRoC + ReflationTotSharpe + ReflationTotSortino + ReflationTotOmega + ReflationTotNormal
InflationULTIMATE = InflationTotRoC + InflationTotSharpe + InflationTotSortino + InflationTotOmega + InflationTotNormal
DeflationULTIMATE = DeflationTotRoC + DeflationTotSharpe + DeflationTotSortino + DeflationTotOmega + DeflationTotNormal
DenumeratorULTIMATE = GoldilocksULTIMATE + ReflationULTIMATE + InflationULTIMATE + DeflationULTIMATE
// Find the greatest value among the scenarios
maxValueULTIMATE = math.max(GoldilocksULTIMATE, ReflationULTIMATE, InflationULTIMATE, DeflationULTIMATE)
// Determine the market scenario based on the greatest value
if maxValueULTIMATE == GoldilocksULTIMATE or maxValueULTIMATE == ReflationULTIMATE
RiskULTIMATE := "RISK ON"
else
RiskULTIMATE := "RISK OFF"
if maxValueULTIMATE == GoldilocksULTIMATE
regColULTIMATE := color.new(color.green, 50)
else if maxValueULTIMATE == ReflationULTIMATE
regColULTIMATE := color.new(color.lime, 50)
else if maxValueULTIMATE == InflationULTIMATE
regColULTIMATE := color.new(color.red, 50)
else if maxValueULTIMATE == DeflationULTIMATE
regColULTIMATE := color.new(color.blue, 50)
// var table debug = table.new(
// table_y_pos + "_" + table_x_pos,
// columns = 2,
// rows = 7,
// frame_color = color.white,
// frame_width = 1,
// border_color = color.white,
// border_width = 1)
// if barstate.islast
// table.cell(debug, 0, 0,"GoldilocksULTIMATE", text_size = i_text_size, text_color = color.white)
// table.cell(debug, 1, 0,str.tostring(GoldilocksULTIMATE),text_size = i_text_size, text_color = color.white)
// table.cell(debug, 0, 1,"ReflationULTIMATE", text_size = i_text_size, text_color = color.white)
// table.cell(debug, 1, 1,str.tostring(ReflationULTIMATE), text_size = i_text_size, text_color = color.white)
// table.cell(debug, 0, 2,"InflationULTIMATE", text_size = i_text_size, text_color = color.white)
// table.cell(debug, 1, 2,str.tostring(InflationULTIMATE), text_size = i_text_size, text_color = color.white)
// table.cell(debug, 0, 3,"DeflationULTIMATE", text_size = i_text_size, text_color = color.white)
// table.cell(debug, 1, 3,str.tostring(DeflationULTIMATE), text_size = i_text_size, text_color = color.white)
// table.cell(debug, 0, 4,"maxValueULTIMATE", text_size = i_text_size, text_color = color.white)
// table.cell(debug, 1, 4,str.tostring(maxValueULTIMATE), text_size = i_text_size, text_color = color.white)
plot( ultimateRISK? RiskULTIMATE == "RISK ON"? 1 : -1 : na )
bgcolor(ultimateRISK? RiskULTIMATE == "RISK ON"? color.new(color.green, 60) : color.new(color.red, 60):na)
bgcolor(ultimateGRID? regColULTIMATE: na)
barcolor(barcRisk? colx? RiskBgx : ultimateRISK? RiskULTIMATE == "RISK ON"? color.green : color.red: na :na)
barcolor(barcGRID? reg? regCol : ultimateGRID? regColULTIMATE :na:na) |
POA | https://www.tradingview.com/script/bKxv6R8N/ | dokang | https://www.tradingview.com/u/dokang/ | 40 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dokang
//@version=5
// @description This library is a client script for making a webhook signal formatted string to PoABOT server.
library("POA", overlay = true)
is_stock() =>
var stocks = array.from("KRX", "NASDAQ", "ARCA", "AMEX", "NYSE")
array.includes(stocks, syminfo.prefix)
is_korea_stock() =>
syminfo.prefix == "KRX"
is_us_stock() =>
var stocks = array.from("NASDAQ", "ARCA", "AMEX", "NYSE")
array.includes(stocks, syminfo.prefix)
is_crypto() =>
(syminfo.type == "crypto")
is_futures() =>
code = switch syminfo.prefix
"BINANCE" => ".P"
"BYBIT" => ".P"
"BITGET" => ".P"
"UPBIT" => "PERP"
"OKX" => ".P"
=>".P"
is_crypto() and str.endswith(syminfo.ticker, code)
is_spot() =>
is_crypto() and (not is_futures())
get_exchange_and_base_and_quote() =>
is_stock = is_stock()
base = is_stock ? syminfo.ticker : syminfo.basecurrency
quote = is_stock ? syminfo.currency : str.replace(syminfo.ticker, syminfo.basecurrency, "", 0)
[syminfo.prefix, base, quote]
get_side_and_qty_and_price_and_orderName() =>
["{{strategy.order.action}}", "{{strategy.order.contracts}}", "{{strategy.order.price}}", "{{strategy.order.comment}}"]
// @function Create a buy order message for POABOT
// @param password (string) [Required] The password of your bot.
// @param percent (float) [Optional] The percent for buy based on your wallet balance.
// @param kis_number (int) [Optional] The number of koreainvestment account.
// @returns (string) A string containing the formatted webhook message.
buy_order(string password, float percent=na, int kis_number = 1) =>
[exchange, str_base, str_quote] = get_exchange_and_base_and_quote()
[str_side, str_qty, str_price, order_name] = get_side_and_qty_and_price_and_orderName()
order_qty = str.tonumber(str_qty)
if not na(percent)
str_qty := na
json = '{'
+ str.format(
'
"password":"{0}",
"exchange":"{1}",
"base":"{2}",
"quote":"{3}",
"side":"{4}",
"amount":"{5}",
"price":"{6}",
"percent":"{7}",
"order_name":"{8}",
"kis_number": "{9}"
', password, exchange, str_base, str_quote, str_side, str_qty, str_price, percent, order_name, kis_number)
+'}'
json
// @function Create a sell order message for POABOT
// @param password (string) [Required] The password of your bot.
// @param percent (float) [Optional] The percent for sell based on your wallet balance.
// @param kis_number (int) [Optional] The number of koreainvestment account. Default 1
// @returns (string) A string containing the formatted webhook message.
sell_order(string password, float percent = na, int kis_number = 1) =>
[exchange, str_base, str_quote] = get_exchange_and_base_and_quote()
[str_side, str_qty, str_price, order_name] = get_side_and_qty_and_price_and_orderName()
if not na(percent)
str_qty := na
json = '{'
+ str.format(
'
"password":"{0}",
"exchange":"{1}",
"base":"{2}",
"quote":"{3}",
"side":"{4}",
"price":"{5}",
"amount":"{6}",
"percent": "{7}",
"order_name":"{8}",
"kis_number":"{9}"
', password, exchange, str_base, str_quote, str_side, str_price, str_qty, percent, order_name, kis_number)
+'}'
json
// @function Create a entry order message for POABOT
// @param password (string) [Required] The password of your bot.
// @param percent (float) [Optional] The percent for entry based on your wallet balance.
// @param leverage (int) [Optional] The leverage of entry. If not set, your levereage doesn't change.
// @param margin_mode (string) [Optional] The margin mode for trade(only for OKX). "cross" or "isolated"
// @returns (string) A json formatted string for webhook message.
entry_order(string password, float percent = na, int leverage = na, string margin_mode = na) =>
[exchange, base, quote] = get_exchange_and_base_and_quote()
[side, str_qty, str_price, order_name] = get_side_and_qty_and_price_and_orderName()
str_leverage = str.tostring(leverage)
if not na(percent)
str_qty := na
json = '{'
+ str.format(
'
"password":"{0}",
"exchange":"{1}",
"base":"{2}",
"quote":"{3}",
"side":"{4}",
"amount":"{5}",
"price":"{6}",
"percent":"{7}",
"leverage": "{8}",
"margin_mode": "{9}",
"order_name":"{10}"
', password, exchange, base, quote, "entry/"+side, str_qty, str_price, percent, str_leverage, margin_mode, order_name)
+'}'
json
// @function Create a close order message for POABOT
// @param password (string) [Required] The password of your bot.
// @param percent (float) [Optional] The percent for close based on your wallet balance.
// @param margin_mode (string) [Optional] The margin mode for trade(only for OKX). "cross" or "isolated"
// @returns (string) A json formatted string for webhook message.
close_order(string password, float percent = na, string margin_mode = na) =>
[exchange, base, quote] = get_exchange_and_base_and_quote()
[side, str_qty, str_price, order_name] = get_side_and_qty_and_price_and_orderName()
if not na(percent)
str_qty := na
json = '{'
+ str.format(
'
"password":"{0}",
"exchange":"{1}",
"base":"{2}",
"quote":"{3}",
"side":"{4}",
"price":"{5}",
"amount":"{6}",
"percent":"{7}",
"margin_mode":"{8}",
"order_name":"{9}"
', password, exchange, base, quote, "close/"+side, str_price, str_qty, percent, margin_mode,order_name)
+'}'
json
///////////////////////// EXPORT //////////////////////////////////////
// @function Create a entry message for POABOT
// @param password (string) [Required] The password of your bot.
// @param percent (float) [Optional] The percent for entry based on your wallet balance.
// @param leverage (int) [Optional] The leverage of entry. If not set, your levereage doesn't change.
// @param margin_mode (string) [Optional] The margin mode for trade(only for OKX). "cross" or "isolated"
// @param kis_number (int) [Optional] The number of koreainvestment account. Default 1
// @returns (string) A json formatted string for webhook message.
export entry_message(string password, float percent = na, int leverage = na, string margin_mode = na, int kis_number=1) =>
is_buy = is_stock() or is_spot()
is_buy ? buy_order(password, percent, kis_number) : entry_order(password, percent, leverage, margin_mode)
// @function Create a order message for POABOT
// @param password (string) [Required] The password of your bot.
// @param percent (float) [Optional] The percent for entry based on your wallet balance.
// @param leverage (int) [Optional] The leverage of entry. If not set, your levereage doesn't change.
// @param margin_mode (string) [Optional] The margin mode for trade(only for OKX). "cross" or "isolated"
// @param kis_number (int) [Optional] The number of koreainvestment account. Default 1
// @returns (string) A json formatted string for webhook message.
export order_message(string password, float percent = na, int leverage = na, string margin_mode = na, int kis_number=1) =>
is_buy = is_stock() or is_spot()
is_buy ? buy_order(password, percent, kis_number) : entry_order(password, percent, leverage, margin_mode)
// @function Create a close message for POABOT
// @param password (string) [Required] The password of your bot.
// @param percent (float) [Optional] The percent for close based on your wallet balance.
// @param margin_mode (string) [Optional] The margin mode for trade(only for OKX). "cross" or "isolated"
// @param kis_number (int) [Optional] The number of koreainvestment account. Default 1
// @returns (string) A json formatted string for webhook message.
export close_message(string password, float percent = na, string margin_mode = na, int kis_number=1) =>
is_sell = is_stock() or is_spot()
is_sell ? sell_order(password, percent, kis_number) : close_order(password, percent, margin_mode)
// @function Create a exit message for POABOT
// @param password (string) [Required] The password of your bot.
// @param percent (float) [Optional] The percent for exit based on your wallet balance.
// @param margin_mode (string) [Optional] The margin mode for trade(only for OKX). "cross" or "isolated"
// @param kis_number (int) [Optional] The number of koreainvestment account. Default 1
// @returns (string) A json formatted string for webhook message.
export exit_message(string password, float percent = na, string margin_mode = na, int kis_number=1) =>
close_message(password, percent, margin_mode, kis_number)
// @function Create a manual message for POABOT
// @param password (string) [Required] The password of your bot.
// @param exchange (string) [Required] The exchange
// @param base (string) [Required] The base
// @param quote (string) [Required] The quote of order message
// @param side (string) [Required] The side of order messsage
// @param qty (float) [Optional] The qty of order message
// @param price (float) [Optional] The price of order message
// @param percent (float) [Optional] The percent for order based on your wallet balance.
// @param leverage (int) [Optional] The leverage of entry. If not set, your levereage doesn't change.
// @param margin_mode (string) [Optional] The margin mode for trade(only for OKX). "cross" or "isolated"
// @param kis_number (int) [Optional] The number of koreainvestment account.
// @param order_name (string) [Optional] The name of order message
// @returns (string) A json formatted string for webhook message.
export manual_message( string password,
string exchange,
string base,
string quote,
string side,
float qty = na,
float price = na,
float percent = na,
int leverage = na,
string margin_mode = na,
int kis_number=1,
string order_name="Order") =>
str_leverage = na(leverage) ? na : str.tostring(leverage)
str_qty = str.tostring(qty)
str_price = str.tostring(price)
if not na(percent)
str_qty := na
json = '{'
+ str.format(
'
"password":"{0}",
"exchange":"{1}",
"base":"{2}",
"quote":"{3}",
"side":"{4}",
"amount":"{5}",
"price":"{6}",
"percent":"{7}",
"leverage": "{8}",
"margin_mode": "{9}",
"order_name":"{10}",
"kis_number": "{11}"
', password, exchange, base, quote, side, str_qty, str_price, percent, str_leverage, margin_mode, order_name, kis_number)
+'}'
json
// @function Create a trade start line
// @param start_time (int) [Required] The start of time.
// @param end_time (int) [Required] The end of time.
// @param hide_trade_line (bool) [Optional] if true, hide trade line. Default false.
// @returns (bool) Get bool for trade based on time range.
export in_trade(int start_time, int end_time, bool hide_trade_line = false) =>
allowedToTrade = (time>=start_time) and (time<=end_time)
if barstate.islastconfirmedhistory and not hide_trade_line
var myLine = line(na)
line.delete(myLine)
myLine := line.new(start_time, low, start_time, high, xloc=xloc.bar_time, color = color.rgb(255, 153, 0, 50), width = 3, extend = extend.both, style = line.style_dashed)
allowedToTrade
// @function Get exchange specific real qty
// @param qty (float) [Optional] qty
// @param precision (float) [Optional] precision
// @param leverage (int) [Optional] leverage
// @param contract_size (float) [Optional] contract_size
// @returns (float) exchange specific qty.
export real_qty(float qty = na, float precision = na, int leverage = na, float contract_size = na, string default_qty_type = na, float default_qty_value = na) =>
_initial_qty = float(na)
if na(qty)
if default_qty_type == strategy.percent_of_equity
_initial_qty := strategy.equity/close * default_qty_value * 0.01
else if default_qty_type == strategy.cash
_initial_qty := default_qty_value * 1.0 / close
else if default_qty_type == strategy.fixed
_initial_qty := default_qty_value
else
_initial_qty := strategy.equity/close
else
_initial_qty := qty
// _initial_qty = na(qty) ? strategy.equity/close : qty
initial_qty = float(na)
if not is_futures()
initial_qty := _initial_qty
else
initial_qty := na(leverage) ? _initial_qty : leverage * _initial_qty
exchange = syminfo.prefix
_precision = float(na)
if na(precision)
_precision := if exchange == "BINANCE"
switch syminfo.basecurrency
"BTC" => 0.001
"ETH" => 0.001
"BNB" => 0.01
"XRP" => 0.1
"DOT" => 0.1
"LTC" => 0.001
"LINK" => 0.01
"ATOM" => 0.01
"XMR" => 0.001
"ETC" => 0.01
"BCH" => 0.001
"TRB" => 0.1
=> close >= 10000 ? 0.001 : close >= 1000 ? 0.01 : close >= 30 ? 0.1 : 1
else if exchange == "BYBIT"
switch syminfo.basecurrency
"BTC" => 0.001
"ETH" => 0.01
"BNB" => 0.01
"SOL" => 0.1
"DOT" => 0.1
"LTC" => 0.1
"SHIB" => 10
"AVAX" => 0.1
"LINK" => 0.1
"ATOM" => 0.1
"UNI" => 0.1
"XMR" => 0.01
"ETC" => 0.1
"ICP" => 0.1
"BCH" => 0.01
=> close >= 10000 ? 0.001 : close >= 1000 ? 0.01 : close >= 30 ? 0.1 : 1
else if exchange == "BITGET"
switch syminfo.basecurrency
"BTC" => 0.001
"ETH" => 0.01
"BNB" => 0.01
"LTC" => 0.1
"SHIB" => 10000
"AVAX" => 0.1
"XMR" => 0.01
"ICP" => 0.01
"BCH" => 0.01
=> close >= 10000 ? 0.001 : close >= 1000 ? 0.01 : close >= 30 ? 0.1 : 1
else if exchange == "OKX"
na
else if exchange == "UPBIT"
1e-08
else
if syminfo.type == "crypto" and syminfo.currency != "KRW"
close >= 10000 ? 0.001 : close >= 1000 ? 0.01 : close >= 100 ? 0.1 : 1
else
_precision := precision <= 0 ? 1 : math.pow(10, -precision)
_contract_size = na(contract_size) ? float(na) : contract_size
if na(_contract_size)
_contract_size := if exchange == "OKX"
switch syminfo.basecurrency
"BTC" => 0.01
"ETH" => 0.1
"LTC" => 1
"XRP" => 100
"BCH" => 0.1
"SOL" => 1
"FIL" => 0.1
"PEPE" => 25
"DOGE" => 1000
"APT" => 1
initial_qty := if na(_contract_size)
initial_qty
else
math.floor(initial_qty / _contract_size) * _contract_size
if na(_precision)
initial_qty
else
decimal = math.abs(math.round(math.log10(_precision)))
factor = math.pow(10, decimal)
result = int(initial_qty * factor) / factor
result == 0 ? initial_qty : result
export type bot
string password
int start_time
int end_time
int leverage = 1
float initial_capital = na
string default_qty_type = strategy.percent_of_equity
float default_qty_value = 100
string margin_mode
float contract_size
int kis_number
float entry_percent
float close_percent
float exit_percent
table log_table
float fixed_qty = na
float fixed_cash = na
bool real = true
bool auto_alert_message = true
bool hide_trade_line = false
// @function Set bot object.
// @param password (string) [Optional] password for poabot.
// @param start_time (int) [Optional] start_time timestamp.
// @param end_time (int) [Optional] end_time timestamp.
// @param leverage (int) [Optional] leverage.
// @param margin_mode (string) [Optional] The margin mode for trade(only for OKX). "cross" or "isolated"
// @param kis_number (int) [Optional] kis_number for poabot.
// @param entry_percent (float) [Optional] entry_percent for poabot.
// @param close_percent (float) [Optional] close_percent for poabot.
// @param exit_percent (float) [Optional] exit_percent for poabot.
// @param fixed_qty (float) [Optional] fixed qty.
// @param fixed_cash (float) [Optional] fixed cash.
// @param real (bool) [Optional] convert qty for exchange specific.
// @param auto_alert_message (bool) [Optional] convert alert_message for exchange specific.
// @param hide_trade_line (bool) [Optional] if true, Hide trade line. Default false.
// @returns (void)
export method set(bot this, string password = na, int start_time = na, int end_time = na, int leverage = na, float initial_capital = na,string default_qty_type = na, float default_qty_value = na , string margin_mode = na, float contract_size = na, int kis_number = na, float entry_percent = na, float close_percent = na, float exit_percent = na, float fixed_qty = na, float fixed_cash = na,bool real = na, bool auto_alert_message = na, bool hide_trade_line = false) =>
if not na(password)
this.password := password
if not na(start_time)
this.start_time := start_time
if not na(end_time)
this.end_time := end_time
if not na(leverage)
this.leverage := leverage
if not na(initial_capital)
this.initial_capital := initial_capital
if not na(default_qty_type)
this.default_qty_type := default_qty_type
if not na(default_qty_value)
this.default_qty_value := default_qty_value
if not na(margin_mode)
this.margin_mode := margin_mode
if not na(contract_size)
this.contract_size := contract_size
if not na(kis_number)
this.kis_number := kis_number
if not na(entry_percent)
this.entry_percent := entry_percent
if not na(close_percent)
this.close_percent := close_percent
if not na(exit_percent)
this.exit_percent := exit_percent
if not na(fixed_qty)
this.fixed_qty := fixed_qty
if not na(fixed_cash)
this.fixed_cash := fixed_cash
if not na(real)
this.real := real
if not na(auto_alert_message)
this.auto_alert_message := auto_alert_message
if not na(hide_trade_line)
this.hide_trade_line := hide_trade_line
var cell_text_color = color.white
// @function Print message using log table.
// @param password (string) [Required] message.
// @returns (void)
export method print(bot this, string message) =>
if na(this.log_table)
this.log_table := table.new(position.bottom_center, 2, 2, color.red)
table.cell(this.log_table, 0, 0, "", text_color = cell_text_color)
table.cell_set_text(this.log_table, 0, 0, message)
// @function start trade using start_time and end_time
// @returns (void)
export method start_trade(bot this) =>
if na(this.start_time)
this.print("start_time has not been set.")
in_trade(this.start_time, this.end_time, this.hide_trade_line)
// @function It is a command to enter market position. If an order with the same ID is already pending, it is possible to modify the order. If there is no order with the specified ID, a new order is placed. To deactivate an entry order, the command strategy.cancel or strategy.cancel_all should be used. In comparison to the function strategy.order, the function strategy.entry is affected by pyramiding and it can reverse market position correctly. If both 'limit' and 'stop' parameters are 'NaN', the order type is market order.
// @param id (string) [Required] A required parameter. The order identifier. It is possible to cancel or modify an order by referencing its identifier.
// @param direction (string) [Required] A required parameter. Market position direction: 'strategy.long' is for long, 'strategy.short' is for short.
// @param qty (float) [Optional] An optional parameter. Number of contracts/shares/lots/units to trade. The default value is 'NaN'.
// @param limit (float) [Optional] An optional parameter. Limit price of the order. If it is specified, the order type is either 'limit', or 'stop-limit'. 'NaN' should be specified for any other order type.
// @param stop (float) [Optional] An optional parameter. Stop price of the order. If it is specified, the order type is either 'stop', or 'stop-limit'. 'NaN' should be specified for any other order type.
// @param oca_name (string) [Optional] An optional parameter. Name of the OCA group the order belongs to. If the order should not belong to any particular OCA group, there should be an empty string.
// @param oca_type (string) [Optional] An optional parameter. Type of the OCA group. The allowed values are: "strategy.oca.none" - the order should not belong to any particular OCA group; "strategy.oca.cancel" - the order should belong to an OCA group, where as soon as an order is filled, all other orders of the same group are cancelled; "strategy.oca.reduce" - the order should belong to an OCA group, where if X number of contracts of an order is filled, number of contracts for each other order of the same OCA group is decreased by X.
// @param comment (string) [Optional] An optional parameter. Additional notes on the order.
// @param alert_message (string) [Optional] An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
// @param when (bool) [Optional] An optional parmeter. Condition, deprecated.
// @returns (void)
export method entry(
bot this,
string id,
string direction,
float qty = na,
float limit = na,
float stop = na,
string oca_name = na,
string oca_type = na,
string comment = na,
string alert_message = na,
bool when = na
) =>
if na(this.start_time)
this.print("start_time has not been set.")
if not na(when)
this.print("'when' will be deprecated. We recommend using `if` or `switch` conditional blocks instead.")
if in_trade(this.start_time, this.end_time, this.hide_trade_line) and (when or na(when))
var directions = array.from("strategy.long", "strategy.short")
if not array.includes(directions, str.lower(direction))
this.print('Only "strategy.long" and "strategy.short" directions are permitted.')
else if this.real and strategy.equity < 0
this.print('Equity is lower than 0')
else
_direction = direction == "strategy.long" ? strategy.long : direction == "strategy.short" ? strategy.short : na
final_qty = float(na)
initial_qty = if not na(this.fixed_cash)
this.fixed_cash / close
else if not na(this.fixed_qty)
this.fixed_qty
else
qty
final_qty := this.real ? real_qty(initial_qty, leverage = this.leverage, contract_size = this.contract_size, default_qty_type = this.default_qty_type, default_qty_value = this.default_qty_value) : initial_qty
if this.real and final_qty <= 0
this.print(str.format("Insufficient capital for entry : {0}", strategy.equity))
if na(oca_type)
strategy.entry(id=id, direction=_direction, qty=final_qty, limit=limit, stop=stop, oca_name=oca_name, comment = comment, alert_message = this.auto_alert_message ? entry_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : na(alert_message) ? entry_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : alert_message)
else if oca_type == "strategy.oca.none"
strategy.entry(id=id, direction=_direction, qty=final_qty, limit=limit, stop=stop, oca_name=oca_name, oca_type = strategy.oca.none, comment = comment, alert_message = this.auto_alert_message ? entry_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : na(alert_message) ? entry_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : alert_message)
else if oca_type == "strategy.oca.cancel"
strategy.entry(id=id, direction=_direction, qty=final_qty, limit=limit, stop=stop, oca_name=oca_name, oca_type = strategy.oca.cancel, comment = comment, alert_message = this.auto_alert_message ? entry_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : na(alert_message) ? entry_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : alert_message)
else if oca_type == "strategy.oca.reduce"
strategy.entry(id=id, direction=_direction, qty=final_qty, limit=limit, stop=stop, oca_name=oca_name, oca_type = strategy.oca.reduce, comment = comment, alert_message = this.auto_alert_message ? entry_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : na(alert_message) ? entry_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : alert_message)
// @function It is a command to place order. If an order with the same ID is already pending, it is possible to modify the order. If there is no order with the specified ID, a new order is placed. To deactivate order, the command strategy.cancel or strategy.cancel_all should be used. In comparison to the function strategy.entry, the function strategy.order is not affected by pyramiding. If both 'limit' and 'stop' parameters are 'NaN', the order type is market order.
// @param id (string) [Required] A required parameter. The order identifier. It is possible to cancel or modify an order by referencing its identifier.
// @param direction (string) [Required] A required parameter. Market position direction: 'strategy.long' is for long, 'strategy.short' is for short.
// @param qty (float) [Optional] An optional parameter. Number of contracts/shares/lots/units to trade. The default value is 'NaN'.
// @param limit (float) [Optional] An optional parameter. Limit price of the order. If it is specified, the order type is either 'limit', or 'stop-limit'. 'NaN' should be specified for any other order type.
// @param stop (float) [Optional] An optional parameter. Stop price of the order. If it is specified, the order type is either 'stop', or 'stop-limit'. 'NaN' should be specified for any other order type.
// @param oca_name (string) [Optional] An optional parameter. Name of the OCA group the order belongs to. If the order should not belong to any particular OCA group, there should be an empty string.
// @param oca_type (string) [Optional] An optional parameter. Type of the OCA group. The allowed values are: "strategy.oca.none" - the order should not belong to any particular OCA group; "strategy.oca.cancel" - the order should belong to an OCA group, where as soon as an order is filled, all other orders of the same group are cancelled; "strategy.oca.reduce" - the order should belong to an OCA group, where if X number of contracts of an order is filled, number of contracts for each other order of the same OCA group is decreased by X.
// @param comment (string) [Optional] An optional parameter. Additional notes on the order.
// @param alert_message (string) [Optional] An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
// @param when (bool) [Optional] An optional parmeter. Condition, deprecated.
// @returns (void)
export method order( bot this,
string id,
string direction,
float qty = na,
float limit = na,
float stop = na,
string oca_name = na,
string oca_type = na,
string comment = na,
string alert_message = na,
bool when = na
) =>
if na(this.start_time)
this.print("start_time has not been set.")
if not na(when)
this.print("'when' will be deprecated. We recommend using `if` or `switch` conditional blocks instead.")
if in_trade(this.start_time, this.end_time, this.hide_trade_line) and (when or na(when))
var directions = array.from("strategy.long", "strategy.short")
if not array.includes(directions, str.lower(direction))
this.print('Only "strategy.long" and "strategy.short" directions are permitted.')
else if this.real and strategy.equity < 0
this.print('Equity is lower than 0')
else
_direction = direction == "strategy.long" ? strategy.long : direction == "strategy.short" ? strategy.short : na
final_qty = float(na)
initial_qty = if not na(this.fixed_cash)
this.fixed_cash / close
else if not na(this.fixed_qty)
this.fixed_qty
else
qty
final_qty := this.real ? real_qty(initial_qty, leverage = this.leverage, contract_size = this.contract_size, default_qty_type = this.default_qty_type, default_qty_value = this.default_qty_value) : initial_qty
if this.real and final_qty <= 0
this.print(str.format("Insufficient capital for entry : {0}", strategy.equity))
if na(oca_type)
strategy.order(id=id, direction=_direction, qty=final_qty, limit=limit, stop=stop, oca_name=oca_name, comment = comment, alert_message = this.auto_alert_message ? order_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : na(alert_message) ? order_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : alert_message)
else if oca_type == "strategy.oca.none"
strategy.order(id=id, direction=_direction, qty=final_qty, limit=limit, stop=stop, oca_name=oca_name, oca_type = strategy.oca.none, comment = comment, alert_message = this.auto_alert_message ? order_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : na(alert_message) ? order_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : alert_message)
else if oca_type == "strategy.oca.cancel"
strategy.order(id=id, direction=_direction, qty=final_qty, limit=limit, stop=stop, oca_name=oca_name, oca_type = strategy.oca.cancel, comment = comment, alert_message = this.auto_alert_message ? order_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : na(alert_message) ? order_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : alert_message)
else if oca_type == "strategy.oca.reduce"
strategy.order(id=id, direction=_direction, qty=final_qty, limit=limit, stop=stop, oca_name=oca_name, oca_type = strategy.oca.reduce, comment = comment, alert_message = this.auto_alert_message ? order_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : na(alert_message) ? order_message(this.password, this.entry_percent, leverage = this.leverage, margin_mode = this.margin_mode, kis_number=this.kis_number) : alert_message)
// @function Exits the current market position, making it flat.
// @param comment (string) [Optional] An optional parameter. Additional notes on the order.
// @param alert_message (string) [Optional] An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
// @param immediately (bool) [Optional] An optional parameter. If true, the closing order will be executed on the tick where it has been placed, ignoring the strategy parameters that restrict the order execution to the open of the next bar. The default is false.
// @param when (bool) [Optional] An optional parmeter. Condition, deprecated.
// @returns (void)
export method close_all(bot this, string comment = na, string alert_message = na, bool immediately = false, bool when = na) =>
if na(this.start_time)
this.print("start_time has not been set.")
if not na(when)
this.print("'when' will be deprecated. We recommend using `if` or `switch` conditional blocks instead.")
if in_trade(this.start_time, this.end_time, this.hide_trade_line) and (when or na(when))
this.set()
strategy.close_all(comment, alert_message, immediately)
// @function It is a command to cancel/deactivate pending orders by referencing their names, which were generated by the functions: strategy.order, strategy.entry and strategy.exit.
// @param id (string) [Optional] A required parameter. The order identifier. It is possible to cancel an order by referencing its identifier.
// @param when (bool) [Optional] An optional parmeter. Condition, deprecated.
// @returns (void)
export method cancel(bot this, string id, bool when = na) =>
if na(this.start_time)
this.print("start_time has not been set.")
if not na(when)
this.print("'when' will be deprecated. We recommend using `if` or `switch` conditional blocks instead.")
if in_trade(this.start_time, this.end_time, this.hide_trade_line) and (when or na(when))
this.set()
strategy.cancel(id)
// @function It is a command to cancel/deactivate all pending orders, which were generated by the functions: strategy.order, strategy.entry and strategy.exit.
// @param when (bool) [Optional] An optional parmeter. Condition, deprecated.
// @returns (void)
export method cancel_all(bot this, bool when = na) =>
if na(this.start_time)
this.print("start_time has not been set.")
if not na(when)
this.print("'when' will be deprecated. We recommend using `if` or `switch` conditional blocks instead.")
if in_trade(this.start_time, this.end_time, this.hide_trade_line) and (when or na(when))
this.set()
strategy.cancel_all()
// @function It is a command to exit from the entry with the specified ID. If there were multiple entry orders with the same ID, all of them are exited at once. If there are no open entries with the specified ID by the moment the command is triggered, the command will not come into effect. The command uses market order. Every entry is closed by a separate market order.
// @param id (string) [Required] A required parameter. The order identifier. It is possible to close an order by referencing its identifier.
// @param comment (string) [Optional] An optional parameter. Additional notes on the order.
// @param qty (float) [Optional] An optional parameter. Number of contracts/shares/lots/units to exit a trade with. The default value is 'NaN'.
// @param qty_percent (float) [Optional] Defines the percentage (0-100) of the position to close. Its priority is lower than that of the 'qty' parameter. Optional. The default is 100.
// @param alert_message (string) [Optional] An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
// @param immediately (bool) [Optional] An optional parameter. If true, the closing order will be executed on the tick where it has been placed, ignoring the strategy parameters that restrict the order execution to the open of the next bar. The default is false.
// @param when (bool) [Optional] An optional parmeter. Condition, deprecated.
// @returns (void)
export method close(
bot this,
string id,
string comment=na,
float qty=na,
float qty_percent=100,
string alert_message = na,
bool immediately = false,
bool when = na
) =>
if na(this.start_time)
this.print("start_time has not been set.")
if not na(when)
this.print("'when' will be deprecated. We recommend using `if` or `switch` conditional blocks instead.")
if in_trade(this.start_time, this.end_time, this.hide_trade_line) and (when or na(when))
strategy.close(id=id, comment=comment, qty=qty, qty_percent = qty_percent, alert_message = this.auto_alert_message ? close_message(this.password, this.close_percent, this.margin_mode, this.kis_number) : na(alert_message) ? close_message(this.password, this.close_percent, this.margin_mode, this.kis_number) : alert_message, immediately = immediately)
// @function Converts ticks to a price offset from the supplied price or the average entry price.
// @param ticks (float) Ticks to convert to a price.
// @param from (float) A price that can be used to calculate from. Optional. The default value is `strategy.position_avg_price`.
// @returns (float) A price level that has a distance from the entry price equal to the specified number of ticks.
export ticks_to_price(series float ticks, series float from = strategy.position_avg_price) =>
float offset = ticks * syminfo.mintick
strategy.position_size != 0 ? from + offset : float(na)
// @function It is a command to exit either a specific entry, or whole market position. If an order with the same ID is already pending, it is possible to modify the order. If an entry order was not filled, but an exit order is generated, the exit order will wait till entry order is filled and then the exit order is placed. To deactivate an exit order, the command strategy.cancel or strategy.cancel_all should be used. If the function strategy.exit is called once, it exits a position only once. If you want to exit multiple times, the command strategy.exit should be called multiple times. If you use a stop loss and a trailing stop, their order type is 'stop', so only one of them is placed (the one that is supposed to be filled first). If all the following parameters 'profit', 'limit', 'loss', 'stop', 'trail_points', 'trail_offset' are 'NaN', the command will fail. To use market order to exit, the command strategy.close or strategy.close_all should be used.
// @param id (string) [Required] A required parameter. The order identifier. It is possible to cancel or modify an order by referencing its identifier.
// @param from_entry (string) [Optional] An optional parameter. The identifier of a specific entry order to exit from it. To exit all entries an empty string should be used. The default values is empty string.
// @param qty (float) [Optional] An optional parameter. Number of contracts/shares/lots/units to exit a trade with. The default value is 'NaN'.
// @param qty_percent (float) [Optional] Defines the percentage of (0-100) the position to close. Its priority is lower than that of the 'qty' parameter. Optional. The default is 100.
// @param profit (float) [Optional] An optional parameter. Profit target (specified in ticks). If it is specified, a limit order is placed to exit market position when the specified amount of profit (in ticks) is reached. The default value is 'NaN'.
// @param limit (float) [Optional] An optional parameter. Profit target (requires a specific price). If it is specified, a limit order is placed to exit market position at the specified price (or better). Priority of the parameter 'limit' is higher than priority of the parameter 'profit' ('limit' is used instead of 'profit', if its value is not 'NaN'). The default value is 'NaN'.
// @param loss (float) [Optional] An optional parameter. Stop loss (specified in ticks). If it is specified, a stop order is placed to exit market position when the specified amount of loss (in ticks) is reached. The default value is 'NaN'.
// @param stop (float) [Optional] An optional parameter. Stop loss (requires a specific price). If it is specified, a stop order is placed to exit market position at the specified price (or worse). Priority of the parameter 'stop' is higher than priority of the parameter 'loss' ('stop' is used instead of 'loss', if its value is not 'NaN'). The default value is 'NaN'.
// @param trail_price (float) [Optional] An optional parameter. Trailing stop activation level (requires a specific price). If it is specified, a trailing stop order will be placed when the specified price level is reached. The offset (in ticks) to determine initial price of the trailing stop order is specified in the 'trail_offset' parameter: X ticks lower than activation level to exit long position; X ticks higher than activation level to exit short position. The default value is 'NaN'.
// @param trail_points (float) [Optional] An optional parameter. Trailing stop activation level (profit specified in ticks). If it is specified, a trailing stop order will be placed when the calculated price level (specified amount of profit) is reached. The offset (in ticks) to determine initial price of the trailing stop order is specified in the 'trail_offset' parameter: X ticks lower than activation level to exit long position; X ticks higher than activation level to exit short position. The default value is 'NaN'.
// @param trail_offset (float) [Optional] An optional parameter. Trailing stop price (specified in ticks). The offset in ticks to determine initial price of the trailing stop order: X ticks lower than 'trail_price' or 'trail_points' to exit long position; X ticks higher than 'trail_price' or 'trail_points' to exit short position. The default value is 'NaN'.
// @param oca_name (string) [Optional] An optional parameter. Name of the OCA group (oca_type = strategy.oca.reduce) the profit target, the stop loss / the trailing stop orders belong to. If the name is not specified, it will be generated automatically.
// @param comment (string) [Optional] Additional notes on the order. If specified, displays near the order marker on the chart. Optional. The default is na.
// @param comment_profit (string) [Optional] Additional notes on the order if the exit was triggered by crossing `profit` or `limit` specifically. If specified, supercedes the `comment` parameter and displays near the order marker on the chart. Optional. The default is na.
// @param comment_loss (string) [Optional] Additional notes on the order if the exit was triggered by crossing `stop` or `loss` specifically. If specified, supercedes the `comment` parameter and displays near the order marker on the chart. Optional. The default is na.
// @param comment_trailing (string) [Optional] Additional notes on the order if the exit was triggered by crossing `trail_offset` specifically. If specified, supercedes the `comment` parameter and displays near the order marker on the chart. Optional. The default is na.
// @param alert_message (string) [Optional] Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create Alert" dialog. Optional. The default is na.
// @param alert_profit (string) [Optional] Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create Alert" dialog. Only replaces the text if the exit was triggered by crossing `profit` or `limit` specifically. Optional. The default is na.
// @param alert_loss (string) [Optional] Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create Alert" dialog. Only replaces the text if the exit was triggered by crossing `stop` or `loss` specifically. Optional. The default is na.
// @param alert_trailing (string) [Optional] Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create Alert" dialog. Only replaces the text if the exit was triggered by crossing `trail_offset` specifically. Optional. The default is na.
// @param when (bool) [Optional] An optional parmeter. Condition, deprecated.
// @returns (void)
export method exit( bot this,
string id,
string from_entry = na,
float qty = na,
float qty_percent = 100,
float profit = na,
float limit = na,
float loss = na,
float stop = na,
float trail_price = na,
float trail_points = na,
float trail_offset = na,
string oca_name = na,
string comment = na,
string comment_profit = na,
string comment_loss = na,
string comment_trailing = na,
string alert_message = na,
string alert_profit = na,
string alert_loss = na,
string alert_trailing = na,
bool when = na
) =>
if na(this.start_time)
this.print("start_time has not been set.")
if not na(when)
this.print("'when' will be deprecated. We recommend using `if` or `switch` conditional blocks instead.")
if in_trade(this.start_time, this.end_time, this.hide_trade_line) and (when or na(when))
strategy.exit(id,
from_entry,
qty,
qty_percent,
profit,
limit,
loss,
stop,
trail_price,
trail_points,
trail_offset,
oca_name,
comment,
comment_profit,
comment_loss,
comment_trailing,
this.auto_alert_message ? exit_message(this.password, this.exit_percent, this.margin_mode, this.kis_number) : na(alert_message) ? exit_message(this.password, this.exit_percent, this.margin_mode, this.kis_number) : alert_message,
alert_profit,
alert_loss,
alert_trailing
)
// @function Converts a percentage of the supplied price or the average entry price to ticks.
// @param percent (float) The percentage of supplied price to convert to ticks. 50 is 50% of the entry price.
// @param from (float) A price that can be used to calculate from. Optional. The default value is `strategy.position_avg_price`.
// @returns (float) A value in ticks.
export percent_to_ticks(series float percent, series float from = strategy.position_avg_price) =>
strategy.position_size != 0 ? percent / 100 * from / syminfo.mintick : percent / 100 * close / syminfo.mintick
// @function Converts a percentage of the supplied price or the average entry price to a price.
// @param percent (float) The percentage of the supplied price to convert to price. 50 is 50% of the supplied price.
// @param from (float) A price that can be used to calculate from. Optional. The default value is `strategy.position_avg_price`.
// @returns (float) A value in the symbol's quote currency (USD for BTCUSD).
export percent_to_price(series float percent, series float from = strategy.position_avg_price) =>
strategy.position_size != 0 ? (1 + percent / 100) * from : float(na) |
Grid by Volatility (Expo) | https://www.tradingview.com/script/oByzEgAT-Grid-by-Volatility-Expo/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 528 | 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/
// © Zeiierman
//@version=5
indicator("Grid by Volatility (Expo)", overlay=true)
// ~~ ToolTips {
t1 = "The length of bars to calculate the Standard Deviation. A larger value will consider more bars, making it smoother but less responsive. \n\nThe second value adjusts the Standard Deviation by multiplying it with this factor."
t2 = "The length of bars to calculate the weighted moving average for smoothing the grid lines."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Input {
volatilityType = input.string("Stdev", options=["Stdev", "Atr"], title="Volatility Type")
volatilityLength = input.int(200, title="Volatility Length", minval = 2, inline="stdev", group="Volatility")
squeezeAdjustment = input.int(6, title="", minval=1, maxval=200, inline="stdev", group="Volatility", tooltip=t1)
smoothingPeriod = input.int(2, title="Grid Confirmation Length",minval=1, maxval=200, inline="stdev", group="Confirmation", tooltip=t2)
VOLATILITY_ADJUSTMENT = 2
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Function to calculate standard deviation
calculateStdev(priceSource, period) =>
if bar_index < period - 1
0.0
else
sum = 0.0
for i = 0 to period - 1
sum := sum + priceSource[i]
mean = sum / period
sumOfSquaredDifferences = 0.0
for i = 0 to period - 1
sumOfSquaredDifferences := sumOfSquaredDifferences + math.pow(priceSource[i] - mean, 2)
stdev = math.sqrt(sumOfSquaredDifferences / period * squeezeAdjustment)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Function to determine the trend direction
calculateTrendDirection(price) =>
price - price[1] > 0 ? 1 : (price - price[1] < 0 ? -1 : 0)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Calculate Volatility-Based Grid
calculateVolatilityBasedGrid() =>
var float midLine = na
var float fullVolatility = na
Volatility = volatilityType=="Stdev"? calculateStdev(close, volatilityLength): ta.atr(volatilityLength) * squeezeAdjustment
trendDirection = calculateTrendDirection(close)
if (na(midLine))
midLine := close
// Update midLine based on trend and volatility
priceDifference = math.abs(close - midLine)
midLine := priceDifference > Volatility ? midLine + trendDirection * Volatility : midLine
// Update full volatility
fullVolatility := na(fullVolatility) ? Volatility : (midLine == midLine[1] ? fullVolatility : Volatility)
[midLine + fullVolatility, midLine + fullVolatility / VOLATILITY_ADJUSTMENT, midLine, midLine - fullVolatility / VOLATILITY_ADJUSTMENT, midLine - fullVolatility]
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Main calculations
[upperRange2Value, upperRange1Value, midLineValue, lowerRange1Value, lowerRange2Value] = calculateVolatilityBasedGrid()
upperRange2 = ta.wma(upperRange2Value, smoothingPeriod)
upperRange1 = ta.wma(upperRange1Value, smoothingPeriod)
midLineAvg = ta.wma(midLineValue, smoothingPeriod)
lowerRange1 = ta.wma(lowerRange1Value, smoothingPeriod)
lowerRange2 = ta.wma(lowerRange2Value, smoothingPeriod)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plot
OnOff = midLineAvg==midLineAvg[1]?true:false
plot(upperRange2, title="Upper Range 2", color=OnOff?#fd3232:na)
plot(upperRange1, title="Upper Range 1", color=OnOff?#fd3232:na)
plot(midLineAvg, title="Average Mid Line", color=OnOff?#1441f8:na)
plot(lowerRange1, title="Lower Range 1", color=OnOff?#2ce056:na)
plot(lowerRange2, title="Lower Range 2", color=OnOff?#2ce056:na)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
Camac | https://www.tradingview.com/script/cNMkMjey-Camac/ | culturalCardin27605 | https://www.tradingview.com/u/culturalCardin27605/ | 6 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Majid Rajabi Vardanjani
//@version=4
study("Camac", overlay=true, max_labels_count=500)
Periods2 = input(title="ATR Period 2", type=input.integer, defval=2, group="ST2")
src2 = input("hl2", title="Source 2", group="ST2", options=["open", "high", "low", "close", "hl2", "hlc3", "ohlc4"])
Multiplier2 = input(title="ATR Multiplier 2", type=input.float, step=0.1, defval=1.0, group="ST2")
changeATR2= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true, group="ST2")
Periods3 = input(title="ATR Period 3", type=input.integer, defval=3, group="ST3")
src3 = input("hlc3", title="Source 31", group="ST3", options=["open", "high", "low", "close", "hl2", "hlc3", "ohlc4"])
Multiplier3 = input(title="ATR Multiplier 3", type=input.float, step=0.1, defval=1.0, group="ST3")
changeATR3= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true, group="ST3")
length = input(title="ATR Period", type=input.integer, defval=1, group="Chandelier")
mult = input(title="ATR Multiplier", type=input.float, step=0.1, defval=1.8, group="Chandelier")
O = open
H = high
L = low
C = close
HL2 = hl2
HLC3 = hlc3
OHLC4 = ohlc4
TR = tr
ATR2 = atr(Periods2)
ATR3 = atr(Periods3)
ATRCh = atr(length)
HighestCh = highest(length)
LowestCh = lowest(length)
buyLabelColor = input(color.green, "Buy Labels Color")
sellLabelColor = input(color.red, "Sell Labels Color")
B2 = input("1", "Buy SuperTrend 2 (Alert & Label)", group="Options")
B3 = input("2", "Buy SuperTrend 3 (Alert & Label)", group="Options")
CHB = input("3", "Buy Cahandelier (Alert & Label)", group="Options")
S2 = input("1", "Sell SuperTrend 2 (Alert & Label)", group="Options")
S3 = input("2", "Sell SuperTrend 3 (Alert & Label)", group="Options")
CHS = input("3", "Sell Cahandelier (Alert & Label)", group="Options")
displayST2Labels = input(true, "Display Super-Trend 2 Signals?", group="Display")
displayST3Labels = input(true, "Display Super-Trend 3 Signals?", group="Display")
displayChandelierLabels = input(true, "Display Chandelier-Exit Signals?", group="Display")
getSource(src, O, L, H, C, HL2, HLC3, OHLC4) =>
realSrc = O
if src == "low"
realSrc := L
else if src == "high"
realSrc := H
else if src == "close"
realSrc := C
else if src == "hl2"
realSrc := HL2
else if src == "hlc3"
realSrc := HLC3
else if src == "ohlc4"
realSrc := OHLC4
realSrc
// SuperTrend2 -----------------------------------------------------------------------------------------------------
atr22 = sma(TR, Periods2)
atr2= changeATR2 ? ATR2 : atr22
up2=getSource(src3, O, L, H, C, HL2, HLC3, OHLC4)-(Multiplier2*atr2)
up21 = nz(up2[1],up2)
up2 := C[1] > up21 ? max(up2,up21) : up2
dn2=getSource(src2, O, L, H, C, HL2, HLC3, OHLC4)+(Multiplier2*atr2)
dn21 = nz(dn2[1], dn2)
dn2 := C[1] < dn21 ? min(dn2, dn21) : dn2
trend2 = 1
trend2 := nz(trend2[1], trend2)
trend2 := trend2 == -1 and C > dn21 ? 1 : trend2 == 1 and C < up2 ? -1 : trend2
buySignal2 = trend2 == 1 and trend2[1] == -1
sellSignal2 = trend2 == -1 and trend2[1] == 1
// SuperTrend3 -----------------------------------------------------------------------------------------------------
atr32 = sma(TR, Periods3)
atr3= changeATR3 ? ATR3 : atr32
up3=getSource(src3, O, L, H, C, HL2, HLC3, OHLC4)-(Multiplier3*atr3)
up31 = nz(up3[1],up3)
up3 := C[1] > up31 ? max(up3,up31) : up3
dn3=getSource(src3, O, L, H, C, HL2, HLC3, OHLC4)+(Multiplier3*atr3)
dn31 = nz(dn3[1], dn3)
dn3 := C[1] < dn31 ? min(dn3, dn31) : dn3
trend3 = 1
trend3 := nz(trend3[1], trend3)
trend3 := trend3 == -1 and C > dn31 ? 1 : trend3 == 1 and C < up3 ? -1 : trend3
buySignal3 = trend3 == 1 and trend3[1] == -1
sellSignal3 = trend3 == -1 and trend3[1] == 1
// Chandelier -----------------------------------------------------------------------------------------------------
useClose = false
atr = mult * ATRCh
longStop = HighestCh - atr
longStopPrev = nz(longStop[1], longStop)
longStop := C[1] > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = LowestCh + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := C[1] < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
var int dir = 1
dir := C > shortStopPrev ? 1 : C < longStopPrev ? -1 : dir
buySignal = dir == 1 and dir[1] == -1
sellSignal = dir == -1 and dir[1] == 1
// Signals ==============================
buyText = "\n"
sellText = "\n"
if buySignal2 and displayST2Labels
buyText := buyText + B2 + "\n"
if buySignal and displayChandelierLabels
buyText := buyText + CHB + "\n"
if buySignal3 and displayST3Labels
buyText := buyText + B3 + "\n"
if sellSignal2 and displayST2Labels
sellText := sellText + S2 + "\n"
if sellSignal and displayChandelierLabels
sellText := sellText + CHS + "\n"
if sellSignal3 and displayST3Labels
sellText := sellText + S3 + "\n"
buySignals = ((buySignal3 and displayST3Labels) or (buySignal and displayChandelierLabels) or (buySignal2 and displayST2Labels))
sellSignals = ((sellSignal3 and displayST3Labels) or (sellSignal and displayChandelierLabels) or (sellSignal2 and displayST2Labels))
if buySignals
label.new(bar_index, L, buyText, color=buyLabelColor, textcolor=color.white, style=label.style_label_up, size=size.small)
alert(buyText, alert.freq_once_per_bar_close)
if sellSignals
label.new(bar_index, H, sellText, color=sellLabelColor, textcolor=color.white, style=label.style_label_down, size=size.small)
alert(sellText, alert.freq_once_per_bar_close)
|
Dynamic Point of Control (POC) | https://www.tradingview.com/script/azqsH7MJ-Dynamic-Point-of-Control-POC/ | tkarolak | https://www.tradingview.com/u/tkarolak/ | 84 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tkarolak
//@version=5
// ====================
// ==== Background ====
// ====================
// The Dynamic POC Indicator is a potent tool designed to provide traders with real-time market insights.
// It helps identify critical price levels (POC), analyze volume distribution, and gauge market sentiment.
// Key Features:
// 1. Instant Updates: The POC recalculates with every new bar, keeping you well-informed about evolving market conditions.
// 2. Market Sentiment: Assess sentiment by examining bullish volume share. This metric indicates whether the market leans towards bullish or bearish tendencies.
// 3. Customization: Tailor inputs to align with your unique trading strategy. Adjust source, bar count, and row size for fine-tuned analysis.
// 4. Chart Visualization: Graphically view POC and related data on your price chart, enhancing your understanding of critical price levels and volume insights.
//
// How to Use:
// - POC Identification: Locate the POC price level, representing the price point with the highest trading volume in the historical range.
// It often serves as pivotal support or resistance.
// - Volume Analysis: Study volume distribution across different price segments to pinpoint potential trade entry and exit zones.
// - Sentiment Assessment: Gauge market sentiment via the "Bias of Volume Share at POC." - insight available in Data Window
// A bullish bias suggests a positive sentiment, while a bearish bias indicates negativity.
//
// The Dynamic POC Indicator equips traders with a dynamic, adaptable tool, enhancing their ability to navigate markets effectively.
// To maximize effectiveness, combine Dynamic POC insights with other technical tools and sound risk management strategies for comprehensive trading decisions.
indicator("Dynamic Point of Control (POC)", shorttitle = "Dynamic POC", overlay=true, format = format.price)
// Custom types
type SettingsPoc
float source
int bars
int slots
// Tooltips for parameter explanations
gPoc = "Dynamic Point of Control"
ttSourcePoc = "Select the price source Dynami POC calculations"
ttBarsPoc = "Define the number of historical bars to include in the analysis. A larger value encompasses more historical data, while a smaller value focuses on recent price action."
ttSlotsPoc = "Specify the number of rows or price segments within the selected historical range. A smaller row size provides a more detailed analysis, while a larger row size simplifies the view."
// Input parameters
SettingsPoc settingsPoc =
SettingsPoc.new(
input.source (close, "Source", group = gPoc, tooltip = ttSourcePoc),
input.int (150, "Number of Bars / MA length", group = gPoc, minval = 1, maxval = 2000, tooltip = ttBarsPoc),
input.int (10, "Row Size", group = gPoc, minval = 5, maxval = 100, tooltip = ttSlotsPoc)
)
// Runtime error indicating the absence of volume data from the data vendor
if barstate.islast and ta.cum(volume) == 0
runtime.error("No volume is provided by the data vendor.")
// Confirmation condition
bool confirmed = barstate.isconfirmed
// Calculate the highest and lowest price within the specified number of bars
float top = ta.highest(settingsPoc.bars)
float bot = ta.lowest(settingsPoc.bars)
// Calculate the price step for each row/slot
float step = (top - bot) / settingsPoc.slots
// Calculate & keep rows/slots middle price levels
levels = array.new_float(settingsPoc.slots)
for x = 0 to settingsPoc.slots - 1 by 1
array.set(levels, x, bot + step * x + step/2)
// Initialize arrays to store volumes
volumes = array.new_float(settingsPoc.slots, 0.0)
volumesBull = array.new_float(settingsPoc.slots, 0.0)
int index = na
// Loop through historical bars
for bars = 0 to settingsPoc.bars - 1 by 1
if confirmed and bar_index >= settingsPoc.bars
// Calculate the index of the row for the current bar
index := int((settingsPoc.source[bars] - bot) / step)
index := index == settingsPoc.slots ? settingsPoc.slots - 1 : index
// Accumulate volume within the row/slot
float currentVol = array.get(volumes, index)
float currentVolBull = array.get(volumesBull, index)
array.set(volumes, index, currentVol + volume[bars])
// Check if the current bar is bullish and accumulate volume within the row/slot
array.set(volumesBull, index, close[bars] >= open[bars] ? currentVolBull + volume[bars] : currentVolBull)
// Find the index of the Point of Control (POC) based on the maximum volume
int pocIndex = array.indexof(volumes, array.max(volumes))
// Calculate the percentage of bullish volume share at POC
float bullishShare = array.get(volumesBull, pocIndex) / array.get(volumes, pocIndex) * 100
// Calculate Volume Weighted Moving Average (VWMA)
ma = ta.vwma(settingsPoc.source, settingsPoc.bars)
// Get calculated Point of Control (POC) level
poc_level = array.get(levels, pocIndex)
////////////////////////////////////////////////////////////////////////////////
// ====== DRAWING and PLOTTING ====== //
////////////////////////////////////////////////////////////////////////////////
// Determine the color of the line based on bullish sentiment
colorLine = bullishShare >= 50 ? color.green : color.red
// Plot POC and other data on the chart
plot(poc_level, "POC", color=colorLine, linewidth=2)
plot(bullishShare, "Bias of Volume Share at POC", display=display.data_window) |
Bias of Volume Share inside Std Deviation Channel | https://www.tradingview.com/script/CxVru5aS-Bias-of-Volume-Share-inside-Std-Deviation-Channel/ | tkarolak | https://www.tradingview.com/u/tkarolak/ | 58 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tkarolak
//@version=5
// ====================
// ==== Background ====
// ====================
// This indicator assesses bullish or bearish bias based on the share of bullish candles
// within a standard deviation channel using historical price and volume data. Bias is
// calculated by evaluating the share of bullish candles in the total share over a
// specified lookback period. If the share of bullish candles exceeds 50%, it signals a
// bullish bias, while below 50% indicates a bearish bias. Traders use this calculation
// to gauge market sentiment for trading decisions.
// Hypothesis:
// - Bullish Bias: A high share of bullish candles within the channel suggests a bullish bias.
// - Bearish Bias: A high share of bullish candles within the channel suggests a bearish bias.
// Usage:
// 1. Customize settings to match your trading strategy.
// 2. Set upper and lower lines to define the share range of interest.
// 3. Interpret the indicator:
// - Bullish Bias: Indicator > 50
// - Overbought Territory: Above the upper share boundary.
// - Bearish Bias: Indicator < 50
// - Oversold Territory: Below the lower share boundary.
// 4. Confirm sufficient volume data.
// 5. Use the share of bullish candles' bias information in conjunction with other indicators for trading decisions.
indicator("Bias of Volume Share inside Std Deviation Channel", shorttitle="Bias of Volume Share", max_bars_back = 2000, overlay=false, format = format.price)
// Custom types
type SettingsBias
float source
int lookback
float sigma
int smoothing
// Settings Group & Tooltips
string gBiasVolume = "Bias of Volume Setting"
string ttLookbackBias = "Specifies the number of historical bars to analyze."
string ttChannelBias = "Set upper and lower lines to detect bullish/bearish zones."
string ttSmoothingBias = "Determines the length of smoothing for the calculated volume share."
string ttSigmaBias = "This parameter allows you to specify the width of the Standard Deviation Range around the average price by defining the number of standard deviations to include in calculations. A higher value results in a wider channel, encompassing a larger price range, while a lower value narrows the channel, focusing on a smaller price range for analysis."
// Initialize the settings for Bias of Volume Share Indicator
SettingsBias settingsBias =
SettingsBias.new(
input.source (close, "Source", group = gBiasVolume),
input.int (500, "Number of Bars", group = gBiasVolume, minval=1, maxval=2000, tooltip = ttLookbackBias),
input.float (3.0, "Standard Deviation Channel Width (Sigma)", group = gBiasVolume, minval = 1, maxval = 4, tooltip = ttSigmaBias),
input.int (3, "Share Smoothing Length", group = gBiasVolume, tooltip = ttSmoothingBias)
)
settingsBiasUpper = input.float(55, "Upper Line", group = gBiasVolume, minval = 50, maxval = 100, tooltip = ttChannelBias)
settingsBiasLower = input.float(45, "Lower Line", group = gBiasVolume, minval = 0, maxval = 50, tooltip = ttChannelBias)
bool confirmed = barstate.isconfirmed
if barstate.islast and ta.cum(volume) == 0
runtime.error("No volume is provided by the data vendor.")
float priceDev = ta.stdev(settingsBias.source,settingsBias.lookback)
float averagePrice = ta.sma(settingsBias.source,settingsBias.lookback)
float stdDevChannelVolumeBull = 0.0
float stdDevChannelVolumeBear = 0.0
for bars = 0 to settingsBias.lookback - 1 by 1
if confirmed and bar_index >= settingsBias.lookback
stdDevChannelVolumeBull := close[bars] > open[bars] and settingsBias.source[bars] > averagePrice - settingsBias.sigma * priceDev and settingsBias.source[bars] < averagePrice + settingsBias.sigma * priceDev ? stdDevChannelVolumeBull + volume[bars] : stdDevChannelVolumeBull
stdDevChannelVolumeBear := close[bars] < open[bars] and settingsBias.source[bars] > averagePrice - settingsBias.sigma * priceDev and settingsBias.source[bars] < averagePrice + settingsBias.sigma * priceDev ? stdDevChannelVolumeBear + volume[bars] : stdDevChannelVolumeBear
float bullishSharestdDevChannelVolumeBull = ta.sma(stdDevChannelVolumeBull / (stdDevChannelVolumeBear+stdDevChannelVolumeBull) * 100,settingsBias.smoothing)
color colorLine = bullishSharestdDevChannelVolumeBull >= 50 ? color.green : color.red
////////////////////////////////////////////////////////////////////////////////
// ====== DRAWING and PLOTTING ====== //
////////////////////////////////////////////////////////////////////////////////
// Zero hline and channel
upperx = hline(settingsBiasUpper, 'Upper Line', color.new(color.silver, 60))
median = hline(50, 'Median', color.orange, hline.style_dotted)
lowerx = hline(settingsBiasLower, 'Lower Line', color.new(color.silver, 60))
plot(bullishSharestdDevChannelVolumeBull,"Bullish Volume Share at STD Channel",color=colorLine)
color bgcolor = bullishSharestdDevChannelVolumeBull > settingsBiasUpper ? color.new(color.green,85) : (bullishSharestdDevChannelVolumeBull < settingsBiasLower ? color.new(color.red,85) : na)
bgcolor(bgcolor)
|
Traders Trend Dashboard | https://www.tradingview.com/script/L8KmH4YK-Traders-Trend-Dashboard/ | AlexFuch | https://www.tradingview.com/u/AlexFuch/ | 110 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AlexFuch
//@version=5
indicator("Traders Trend Dashboard", shorttitle = "TTD", overlay = true, scale = scale.none, max_lines_count = 500)
dashboard_position = input.session("Middle Right", "Posision", ["Top Right", "Bottom Right", "Top Left", "Bottom Left", "Top Center", "Bottom Center", "Middle Right"], group = 'Table Settings')
text_size = input.session('Normal', "Size", options = ["Tiny", "Small", "Normal", "Large"], group = 'Table Settings')
text_color = input(#d1d4dc, title = "Text Color", group = 'Table Settings')
table_color = input(color.gray, title = "Border Color", group = 'Table Settings')
uptrend_indicator = input("🟢", title = "Uptrend Indicator", group = 'Table Settings')
downtrend_indicator = input("🔴", title = "Downtrend Indicator", group = 'Table Settings')
neutraltrend_indicator = input("⚫️", title = "Neutral trend Indicator", group = 'Table Settings')
ema_length = input.int(title = "Length", defval = 50, minval = 1, maxval = 800, group = 'EMA Settings')
ema_src = input(close, title="Source", group = 'EMA Settings')
max_table_size = 200
min_table_size = 10
show_1m = input(true, title = 'Show 1m', group = 'Timeframe Settings')
show_3m = input(true, title = 'Show 3m ', group = 'Timeframe Settings')
show_5m = input(true, title = 'Show 5m', group = 'Timeframe Settings')
show_8m = input(false, title = 'Show 8m', group = 'Timeframe Settings')
show_12m = input(false, title = 'Show 12m', group = 'Timeframe Settings')
show_15m = input(true, title = 'Show 15m', group = 'Timeframe Settings')
show_20m = input(false, title = 'Show 20m', group = 'Timeframe Settings')
show_30m = input(false, title = 'Show 30m', group = 'Timeframe Settings')
show_45m = input(false, title = 'Show 45m', group = 'Timeframe Settings')
show_1h = input(true, title = 'Show 1h', group = 'Timeframe Settings')
show_2h = input(false, title = 'Show 2h', group = 'Timeframe Settings')
show_3h = input(false, title = 'Show 3h', group = 'Timeframe Settings')
show_4h = input(true, title = 'Show 4h', group = 'Timeframe Settings')
show_D = input(false, title = 'Show D', group = 'Timeframe Settings')
show_W = input(false, title = 'Show W', group = 'Timeframe Settings')
show_M = input(false, title = 'Show M', group = 'Timeframe Settings')
var table_position = dashboard_position == 'Top Right' ? position.top_right :
dashboard_position == 'Top Left' ? position.top_left :
dashboard_position == 'Top Center' ? position.top_center :
dashboard_position == 'Bottom Right' ? position.bottom_right :
dashboard_position == 'Bottom Left' ? position.bottom_left :
dashboard_position == 'Bottom Center' ? position.bottom_center :
dashboard_position == 'Middle Right' ? position.middle_right :
dashboard_position == 'Middle Left' ? position.middle_left : position.middle_right
var table_text_size = text_size == 'Normal' ? size.normal :
text_size == 'Large' ? size.large :
text_size == 'Tiny' ? size.tiny :
text_size == 'Small' ? size.small : size.normal
var t = table.new(table_position, 15, math.abs(max_table_size - min_table_size) + 2,
frame_color = table_color,
frame_width = 2,
border_color = table_color,
border_width = 2)
get_candle_values() =>
current_candle = ta.ema(ema_src, ema_length)
previous_candle = current_candle[1]
[current_candle, previous_candle]
get_trend_indicator(current_candle, previous_candle) =>
current_candle > previous_candle ? uptrend_indicator : current_candle < previous_candle ? downtrend_indicator : neutraltrend_indicator
[current_1m, previous_1m] = request.security(syminfo.tickerid, "1", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_3m, previous_3m] = request.security(syminfo.tickerid, "3", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_5m, previous_5m] = request.security(syminfo.tickerid, "5", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_8m, previous_8m] = request.security(syminfo.tickerid, "8", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_12m, previous_12m] = request.security(syminfo.tickerid, "12", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_15m, previous_15m] = request.security(syminfo.tickerid, "15", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_20m, previous_20m] = request.security(syminfo.tickerid, "20", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_30m, previous_30m] = request.security(syminfo.tickerid, "30", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_45m, previous_45m] = request.security(syminfo.tickerid, "45", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_1h, previous_1h] = request.security(syminfo.tickerid, "60", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_2h, previous_2h] = request.security(syminfo.tickerid, "120", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_3h, previous_3h] = request.security(syminfo.tickerid, "180", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_4h, previous_4h] = request.security(syminfo.tickerid, "240", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_D, previous_D] = request.security(syminfo.tickerid, "D", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_W, previous_W] = request.security(syminfo.tickerid, "W", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_M, previous_M] = request.security(syminfo.tickerid, "M", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_3M, previous_3M] = request.security(syminfo.tickerid, "3M", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_6M, previous_6M] = request.security(syminfo.tickerid, "6M", get_candle_values(), lookahead = barmerge.lookahead_on)
[current_12M, previous_12M] = request.security(syminfo.tickerid, "12M", get_candle_values(), lookahead = barmerge.lookahead_on)
if (barstate.islast)
if (show_1m)
table.cell(t, 1, 2, "1m", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 2, get_trend_indicator(current_1m, previous_1m), text_color = text_color, text_size = table_text_size)
if (show_3m)
table.cell(t, 1, 3, "3m", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 3, get_trend_indicator(current_3m, previous_3m), text_color = text_color, text_size = table_text_size)
if (show_5m)
table.cell(t, 1, 4, "5m", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 4, get_trend_indicator(current_5m, previous_5m), text_color = text_color, text_size = table_text_size)
if (show_8m)
table.cell(t, 1, 5, "8m", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 5, get_trend_indicator(current_8m, previous_8m), text_color = text_color, text_size = table_text_size)
if (show_12m)
table.cell(t, 1, 6, "12m", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 6, get_trend_indicator(current_12m, previous_12m), text_color = text_color, text_size = table_text_size)
if (show_15m)
table.cell(t, 1, 7, "15m", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 7, get_trend_indicator(current_15m, previous_15m), text_color = text_color, text_size = table_text_size)
if (show_20m)
table.cell(t, 1, 8, "20m", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 8, get_trend_indicator(current_20m, previous_20m), text_color = text_color, text_size = table_text_size)
if (show_30m)
table.cell(t, 1, 9, "30m", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 9, get_trend_indicator(current_30m, previous_30m), text_color = text_color, text_size = table_text_size)
if (show_45m)
table.cell(t, 1, 10, "45m", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 10, get_trend_indicator(current_45m, previous_45m), text_color = text_color, text_size = table_text_size)
if (show_1h)
table.cell(t, 1, 11, "1h", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 11, get_trend_indicator(current_1h, previous_1h), text_color = text_color, text_size = table_text_size)
if (show_2h)
table.cell(t, 1, 12, "2h", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 12, get_trend_indicator(current_2h, previous_2h), text_color = text_color, text_size = table_text_size)
if (show_3h)
table.cell(t, 1, 13, "3h", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 13, get_trend_indicator(current_3h, previous_3h), text_color = text_color, text_size = table_text_size)
if (show_4h)
table.cell(t, 1, 14, "4h", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 14, get_trend_indicator(current_4h, previous_4h), text_color = text_color, text_size = table_text_size)
if (show_D)
table.cell(t, 1, 15, "D", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 15, get_trend_indicator(current_D, previous_D), text_color = text_color, text_size = table_text_size)
if (show_W)
table.cell(t, 1, 16, "W", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 16, get_trend_indicator(current_W, previous_W), text_color = text_color, text_size = table_text_size)
if (show_M)
table.cell(t, 1, 17, "M", text_color = text_color, text_size = table_text_size)
table.cell(t, 5, 17, get_trend_indicator(current_M, previous_M), text_color = text_color, text_size = table_text_size)
|
ReduceSecurityCalls | https://www.tradingview.com/script/MZcJO4BX-ReduceSecurityCalls/ | f4r33x | https://www.tradingview.com/u/f4r33x/ | 2 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © f4r33x0
//@version=5
import PineCoders/LibraryStopwatch/1 as sw
// @description This library allows you to reduce the number of request.security calls to 1 per symbol per timeframe.
library("ReduceSecurityCalls")
nonRepaintingSecurity(sym, tf, expr) => request.security(sym, tf, expr[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]
ifSecurity(sym, tf, expr) => request.security(sym, tf, expr)
// @function Parsedata function, should be used inside request.security call. Optimise your calls using timeframe.change when htf data parsing! Supports up to 5 expressions (results of expressions must be float or int)
// @param mat_outs Matrix to be used as outputs, first value is newest
// @param o Please use parametres in the order they specified (o should be 1st, h should be 2nd etc..)
// @returns outs array, due to weird limitations do not try to matrix_out = matrix.copy(ParseSource)
export ParseSource(series float o = na, series float h = na, series float l = na, series float c = na, series float custom = na, int length) =>//, matrix<float> mat_outs) =>
mat_outs = matrix.new<float>()
int count = 0
if length < 1
runtime.error('length to parse should be >= 1 (current candle counts as 1)')
//if barstate.isfirst
while matrix.columns(mat_outs)<length
matrix.add_col(mat_outs,0)
while matrix.rows(mat_outs)<5
matrix.add_row(mat_outs,0)
count += na(o) ? 0 : 1
count += na(h) ? 0 : 1
count += na(l) ? 0 : 1
count += na(c) ? 0 : 1
count += na(custom) ? 0 : 1
for i=0 to length-1
if count >= 1
matrix.set(mat_outs, 0, i, o[i])
if count >= 2
matrix.set(mat_outs, 1, i, h[i])
if count >= 3
matrix.set(mat_outs, 2, i, l[i])
if count >= 4
matrix.set(mat_outs, 3, i, c[i])
if count == 5
matrix.set(mat_outs, 4, i, custom[i])
mat_outs
inp_l = input.int(defval = 5, title = 'length')
inp_tf =input.timeframe(defval = '1D', title = 'TF')
inp_sym =input.symbol(defval = 'BYBIT:BTCUSDT.P',title = 'symbol')
var mat_parsed = matrix.new<float>(5, inp_l, 0)
if barstate.isfirst or timeframe.change(inp_tf)
mat_parsed :=ifSecurity(syminfo.tickerid, inp_tf, ParseSource(o=open, h= high, l=low, c=close, custom =ta.tr(true), length =inp_l))//, mat_outs = mat_parsed))
[timePerBarInMs, totalTimeInMs, barsTimed, barsNotTimed] = sw.stopwatchStats()
msElapsed = sw.stopwatch()
res = array.size(matrix.row(mat_parsed, int(math.random(0,5))))
if barstate.islast
var table t = table.new(position.middle_right, 1, 1)
var txt = str.tostring(timePerBarInMs, "ms/bar: #.######\n") +
str.tostring(totalTimeInMs, "Total time (ms): #,###.######\n") +
str.tostring(barsTimed + barsNotTimed, "Bars analyzed: #\n") +
str.tostring(mat_parsed)+'\n Symbol: ' +
inp_sym + '\n TF: ' +
inp_tf +'\n data length: ' +
str.tostring(res)
//res2
table.cell(t, 0, 0, txt, bgcolor = color.yellow, text_halign = text.align_right)
|
fast_utils | https://www.tradingview.com/script/rZqOUF2A-fast-utils/ | f4r33x | https://www.tradingview.com/u/f4r33x/ | 0 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © f4r33x
//@version=5
// @description This library contains my favourite functions. Will be updated frequently
library("fast_utils")
// @function : Count int digits in number
// @returns : number of int digits in number
export count_int_digits(float a) =>
b = (int(a))
counter = int(math.log10(b))+1
// @function : Count float digits in number
// @returns : number of float digits in number
export count_float_digits(float a) =>
b = (a%1)*math.pow(10, 16)
counter = int(math.log10(b))+1
// @function : convert values in array or matrix into string values
// @returns : array or matrix of string values
export stringify(float[] arr) =>
string res = na
for val in arr
res += str.tostring(val) + ';'
arr_res = str.split(res, ';')
array.pop(arr_res)
arr_res
export stringify(int[] arr) =>
string res = na
for val in arr
res += str.tostring(val) + ';'
arr_res = str.split(res, ';')
array.pop(arr_res)
arr_res
export stringify(bool[] arr) =>
string res = na
for val in arr
res += str.tostring(val) + ';'
arr_res = str.split(res, ';')
array.pop(arr_res)
arr_res
export stringify(matrix<float> mat) =>
result =matrix.new<string>()
string res = na
for i= 0 to matrix.rows(mat)-1
arr = matrix.row(mat, i)
for val in arr
res += str.tostring(val) + ';'
matrix.add_row(result, i, str.split(res, ';'))
result
export stringify(matrix<bool> mat) =>
result =matrix.new<string>()
string res = na
for i= 0 to matrix.rows(mat)-1
arr = matrix.row(mat, i)
for val in arr
res += str.tostring(val) + ';'
arr_res = str.split(res, ';')
array.pop(arr_res)
matrix.add_row(result, i, arr_res)
result
export stringify(matrix<int> mat) =>
result =matrix.new<string>()
string res = na
for i= 0 to matrix.rows(mat)-1
arr = matrix.row(mat, i)
for val in arr
res += str.tostring(val) + ';'
arr_res = str.split(res, ';')
array.pop(arr_res)
matrix.add_row(result, i, arr_res)
result
// @function : compare values in arrays
// @returns : bool value
export arrcompare(float[] arr_a, float[] arr_b) =>
bool res = true
if array.size(arr_a)>0
for [index, value] in arr_a
if value != array.get(arr_b, index)
res := false
break
else
res := false
res
export arrcompare(int[] arr_a, int[] arr_b) =>
bool res = true
if array.size(arr_a)>0
for [index, value] in arr_a
if value != array.get(arr_b, index)
res := false
break
else
res := false
res
export arrcompare(bool[] arr_a, bool[] arr_b) =>
bool res = true
if array.size(arr_a)>0
for [index, value] in arr_a
if value != array.get(arr_b, index)
res := false
break
else
res := false
res
export arrcompare(string[] arr_a, string[] arr_b) =>
bool res = true
if array.size(arr_a)>0
for [index, value] in arr_a
if value != array.get(arr_b, index)
res := false
break
else
res := false
res
export arrcompare(line[] arr_a, line[] arr_b) =>
bool res = true
if array.size(arr_a)>0
for [index, value] in arr_a
if value != array.get(arr_b, index)
res := false
break
else
res := false
res
export arrcompare(label[] arr_a, label[] arr_b) =>
bool res = true
if array.size(arr_a)>0
for [index, value] in arr_a
if value != array.get(arr_b, index)
res := false
break
else
res := false
res
// @function : remove duplicate values in array
// @returns : array without duplicates
export arrdedup(int[] arr) =>
int _size = array.size(arr)
if _size > 0
_dict = array.from(array.get(arr, 0))
for _i = 1 to _size-1
_value = array.get(arr, _i)
if array.indexof(_dict, _value) < 0
array.push(_dict, _value)
_dict
else
//runtime.error('array must have atleast one element.')
array.copy(arr)
export arrdedup(float[] arr) =>
int _size = array.size(arr)
if _size > 0
_dict = array.from(array.get(arr, 0))
for _i = 1 to _size-1
_value = array.get(arr, _i)
if array.indexof(_dict, _value) < 0
array.push(_dict, _value)
_dict
else
//runtime.error('array must have atleast one element.')
array.copy(arr)
export arrdedup(bool[] arr) =>
int _size = array.size(arr)
if _size > 0
_dict = array.from(array.get(arr, 0))
for _i = 1 to _size-1
_value = array.get(arr, _i)
if array.indexof(_dict, _value) < 0
array.push(_dict, _value)
_dict
else
//runtime.error('array must have atleast one element.')
array.copy(arr)
export arrdedup(string[] arr) =>
int _size = array.size(arr)
if _size > 0
_dict = array.from(array.get(arr, 0))
for _i = 1 to _size-1
_value = array.get(arr, _i)
if array.indexof(_dict, _value) < 0
array.push(_dict, _value)
_dict
else
//runtime.error('array must have atleast one element.')
array.copy(arr)
export arrdedup(box[] arr) =>
int _size = array.size(arr)
if _size > 0
_dict = array.from(array.get(arr, 0))
for _i = 1 to _size-1
_value = array.get(arr, _i)
if array.indexof(_dict, _value) < 0
array.push(_dict, _value)
_dict
else
//runtime.error('array must have atleast one element.')
array.copy(arr)
export arrdedup(line[] arr) =>
int _size = array.size(arr)
if _size > 0
_dict = array.from(array.get(arr, 0))
for _i = 1 to _size-1
_value = array.get(arr, _i)
if array.indexof(_dict, _value) < 0
array.push(_dict, _value)
_dict
else
//runtime.error('array must have atleast one element.')
array.copy(arr)
export arrdedup(linefill[] arr) =>
int _size = array.size(arr)
if _size > 0
_dict = array.from(array.get(arr, 0))
for _i = 1 to _size-1
_value = array.get(arr, _i)
if array.indexof(_dict, _value) < 0
array.push(_dict, _value)
_dict
else
//runtime.error('array must have atleast one element.')
array.copy(arr)
export arrdedup(label[] arr) =>
int _size = array.size(arr)
if _size > 0
_dict = array.from(array.get(arr, 0))
for _i = 1 to _size-1
_value = array.get(arr, _i)
if array.indexof(_dict, _value) < 0
array.push(_dict, _value)
_dict
else
//runtime.error('array must have atleast one element.')
array.copy(arr)
export arrdedup(table[] arr) =>
int _size = array.size(arr)
if _size > 0
_dict = array.from(array.get(arr, 0))
for _i = 1 to _size-1
_value = array.get(arr, _i)
if array.indexof(_dict, _value) < 0
array.push(_dict, _value)
_dict
else
//runtime.error('array must have atleast one element.')
array.copy(arr)
export resource(string string_a, int h = 0) =>
float offset_src = switch string_a
'close' => close[h]
'open' => open[h]
'high' => high[h]
'low' => low[h]
'hl2' => hl2[h]
'hlc3' => hlc3[h]
'hlcc4' => hlcc4[h]
'ohlc4' => ohlc4[h]
'tr' => ta.tr(true)[h]
// @function : converts current resolution in minutes
// @returns : return float number of minuted
export ResInMins() =>
_resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1. / 60. :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 1440. :
timeframe.isweekly ? 10080. :
timeframe.ismonthly ? 43800. : na)
// @function : Convert current float TF in minutes to target string TF in "timeframe.period" format.
// @param res : current resolution in minutes
// @param mult : Multiple of current TF to be calculated.
// @returns : timeframe format string
export MultOfRes(float resolution, float mult) =>
res = resolution * math.max(mult, 1)
res <= 0.083 ? "5S" :
res <= 0.251 ? "15S" :
res <= 0.501 ? "30S" :
res <= 1440 ? str.tostring(math.round(res)) :
res <= 43800 ? str.tostring(math.round(math.min(res / 1440, 365))) + "D" :
str.tostring(math.round(math.min(res / 43800, 12))) + "M" |
String_Encoder_Decoder | https://www.tradingview.com/script/54blu33h-String-Encoder-Decoder/ | f4r33x | https://www.tradingview.com/u/f4r33x/ | 0 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © f4r33x
//@version=5
// @description String encoder and decoder to use in internal data tranfer in script calculations. In example script encode 125 values once and then decode them every candle.
library("String_Encoder_Decoder")
import PineCoders/LibraryStopwatch/1 as sw
import f4r33x/fast_utils/2 as fu
// @function encode: encode some values into string
// @param array of values or values1, value2. etc: values to encode, must be stringified
// @returns encoded value
export encode(string[] arr_val) =>
string res = na
for val in arr_val
if not na(val)
res += val +';'
res
export encode(string val1, string val2, string val3=na, string val4=na, string val5=na, string val6=na) =>
arr_temp= array.from(val1, val2, val3, val4, val5, val6)
string res = na
for val in arr_temp
if not na(val)
res += val + ';'
res
// @function decode: decode into string
// @param val value to decode, must be stringified
// @returns decoded array of stringified values
export decode(string val) =>
res = str.split(val, ';')
array.pop(res)
res
// PROOF OF CONCEPT
int_values_to_encode=array.from(15, 200, 99999, -100000, 0123456789)
float_values_to_encode=array.from(15.200, 200.99999, 99999.1, -100000, 0123456789.987654)
string_values_to_encode=array.from('tr', 'close', 'high', 'low', 'custom')
var arr_encoded = array.new_string(0)
mat_decoded = matrix.new<string>()
inp_number = input.int(defval= 0, title = 'number of values to decode every candle')
inp_refresh= input.int(defval= 0, title = 'refresh me')
// ENCODE ONCE DECODE EVERY CANDLE
if barstate.isfirst
string val1 =na
string val2 =na
string val3 =na
str_int_values_to_encode =fu.stringify(int_values_to_encode)
str_float_values_to_encode =fu.stringify(float_values_to_encode)
for i=0 to array.size(string_values_to_encode)-1
val1 := array.get(string_values_to_encode, i)
for i=0 to array.size(str_int_values_to_encode)-1
val2 := array.get(str_int_values_to_encode, i)
for i=0 to array.size(str_float_values_to_encode)-1
val3 := array.get(str_float_values_to_encode, i)
array.push(arr_encoded, encode(val1,val2,val3))
for i = 0 to inp_number-1
matrix.add_row(mat_decoded, i, decode(array.get(arr_encoded,i)))
res = array.size(arr_encoded)
str_res = str.tostring(matrix.row(mat_decoded, int(math.random(0,inp_number-1))))
[timePerBarInMs, totalTimeInMs, barsTimed, barsNotTimed] = sw.stopwatchStats()
msElapsed = sw.stopwatch()
if barstate.islast
var table t = table.new(position.middle_right, 1, 1)
var txt = str.tostring(timePerBarInMs, "ms/bar: #.######\n") +
str.tostring(totalTimeInMs, "Total time (ms): #,###.######\n") +
str.tostring(barsTimed + barsNotTimed, "Bars analyzed: #\n") +
str.tostring(res, "Number of encoded values : #.################\n")+
str_res
//str.tostring(matrix.row(mat_inouts,0))+ '\n' +
//str.tostring(matrix.row(mat_inouts,1))
table.cell(t, 0, 0, txt, bgcolor = color.yellow, text_halign = text.align_right) |
Liquidity Heatmap [StratifyTrade] | https://www.tradingview.com/script/6NDgpGap/ | StratifyTrade | https://www.tradingview.com/u/StratifyTrade/ | 574 | 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/
// © HunterAlgos
//@version=5
indicator("Liquidity Heatmap [HunterAlgos]", shorttitle = "Liquidity Heatmap [1.0.0]", overlay = true, max_lines_count = 500, max_bars_back = 500, max_labels_count = 500)
long_css = input.color(#26c6da, "Long liquidity color" , group = "COLORS")
short_css = input.color(#ff0000, "Short liquidity color", group = "COLORS")
sensibility = input.int (10000, "Opacity value" , tooltip = "Adjust the opacity of the liquidity level manually - (Autopilot off)", group = "SETTINGS")
l_sens = input.int (500 , "Opacity Average", tooltip = "Set the average value of the opacity - Example : 500 set will take the average of 500 bar and 250 bar to determine the average of the liquidity levels", group = "SETTINGS")
leverage = input.float(0.5 , "Leverage" , tooltip = "Example : 0.5 = 100x leverage - 4.5 = 20x leverage", group = "SETTINGS", step = 0.5)
width = input.int (10 , "Width" , group = "SETTINGS")
leverage /= 100
auto = input.bool(true, "Autopilot", tooltip = "Determine automatically a decent opacity value" , group = "GENERAL")
show_long = input.bool(true, "Enable long liquidity" , group = "GENERAL")
show_short = input.bool(true, "Enable short liquidity" , group = "GENERAL")
filter = input.bool(true, "Filtering", tooltip = "Long liquidity = only green candle, short liquidity = only down candle", group = "GENERAL")
data = input.string("nzVolume", options=["nzOI", "OI", "nzVolume", "Volume"], group = "DATA")
type bin
float[] v
line [] u
line [] d
var z = bin.new(
array.new< float >(1)
, array.new< line >(1)
, array.new< line >(1)
)
main = data == "nzOI" ? request.security(str.tostring(syminfo.basecurrency) + "USDT.P_OI","", close - nz(close[1])) : data == "nzVolume" ? volume - nz(volume[1]) : data == "Volume" ? volume : data == "OI" ? math.abs(open - close) : na
calc() =>
if z.v.size() > 50000
z.v.shift()
z.v.push(main)
size = l_sens
avg = math.avg(ta.highest(main, size), ta.highest(main, size / 2))
round_to = 100
ceil = math.ceil (avg / round_to) * round_to
floor = math.floor(avg / round_to) * round_to
result = math.abs (avg - ceil ) < math.abs(avg - floor) ? ceil : floor
_math = auto ? result : sensibility
_math
method gradient(array<float> y, color css) =>
var color id = na
id := color.from_gradient(y.last(), 0, calc(), color.new(color.white, 100), css)
id
drawLine(x, y, _x, css) =>
var line id = na
id := line.new(x1 = x, y1 = y, x2 = _x, y2 = y, xloc = xloc.bar_index, color = css, width = width)
id
method puts(bool mode, array<line> a, line l) =>
if mode == true
if a.size() == 500
line.delete(a.shift())
a.push(l)
if mode == false
for j = a.size() - 1 to 0 by 1
x = line.get_x2(a.get(j))
y = line.get_y1(a.get(j))
if bar_index - 1 == x - 1 and not (high > y and low < y)
line.set_x2(a.get(j), bar_index + 1)
filt(bool bull) =>
bool out = false
if bull == true and filter == true
out := close > open ? true : false
if bull == false and filter == true
out := close < open ? true : false
if filter == false
out := true
out
draw() =>
bool up_dot = false
bool dn_dot = false
if show_long and filt(true) == true
line l = na
l := drawLine(bar_index, low * (1 - leverage), bar_index, z.v.gradient(long_css))
true.puts (z.u , l )
up_dot := true
if show_short and filt(false) == true
line l = na
l := drawLine(bar_index, high * (1 + leverage), bar_index, z.v.gradient(short_css))
true.puts(z.d, l)
dn_dot := true
[up_dot, dn_dot]
[up_dot, dn_dot] = draw()
false.puts(z.u, na)
false.puts(z.d, na)
|
Multiple Percentile Ranks (up to 5 sources at a time) | https://www.tradingview.com/script/9EOiQX9y-Multiple-Percentile-Ranks-up-to-5-sources-at-a-time/ | Dean_Crypto | https://www.tradingview.com/u/Dean_Crypto/ | 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/
// © Dean_Crypto
//@version=5
indicator("Multiple Percentile Ranks", shorttitle = "MPR", max_labels_count = 500)
inline1 = "i1"
inline2 = "i2"
inline3 = "i3"
inline4 = "i4"
inline5 = "i5"
groupOptions = "options"
group1 = "source 1"
group2 = "source 2"
group3 = "source 3"
group4 = "source 4"
group5 = "source 5"
sources = input.float(defval = 5, minval = 1, maxval = 5, step = 1, group = groupOptions)
sourceLabelPctLocation = input.int(defval = 2, group = groupOptions, title = "label % position")
sourceLabelLocation = input.int(defval = 6, group = groupOptions, title = "label position")
textSizeOption = input.string(title = "label text size", defval = "large", options = ["auto", "huge", "large", "normal", "small", "tiny"], group = groupOptions)
displayCurrentPct = input.bool(defval = true, title = "display current % label")
hlSourceOpt1 = input.string(defval = "volume", title = "source 1", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], inline = inline1, group = group1)
hlSourceOpt2 = input.string(defval = "volume (MA)", title = "source 2", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], inline = inline1, group = group2)
hlSourceOpt3 = input.string(defval = "range (MA)", title = "source 3", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], inline = inline1, group = group3)
hlSourceOpt4 = input.string(defval = "mfi (MA)", title = "source 4", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], inline = inline1, group = group4)
hlSourceOpt5 = input.string(defval = "eom", title = "source 5", options = ["atr (MA)", "cci (MA)", "cog (MA)", "close", "close percent", "dollar value", "eom", "gaps", "high", "low", "mfi (MA)", "obv", "open", "range (MA)", "rsi (MA)", "rvi (MA)", "timeClose (MA)", "volume", "volume (MA)"], inline = inline1, group = group5)
// len only applies if a source with (MA) has been selected
sDataLen1 = input.int(defval = 20 , minval = 1, title = "ma length", inline = inline1, group = group1)
sDataLen2 = input.int(defval = 20 , minval = 1, title = "ma length", inline = inline1, group = group2)
sDataLen3 = input.int(defval = 20 , minval = 1, title = "ma length", inline = inline1, group = group3)
sDataLen4 = input.int(defval = 20 , minval = 1, title = "ma length", inline = inline1, group = group4)
sDataLen5 = input.int(defval = 20 , minval = 1, title = "ma length", inline = inline1, group = group5)
aget(id, i) => array.get(id, i)
aget0(id) => array.get(id, 0)
aset(id, i, v) => array.set(id, i, v)
asize(id) => array.size(id)
apush(id, v) => array.push(id, v)
apop(id) => array.pop(id)
ashift(id) => array.shift(id)
unshift(id, v) => array.unshift(id, v)
bi = bar_index
lbi = last_bar_index
closePercentChange() => (nz(close[1], low) < close ? 1 : -1) * (high - low) / low * 100
closePercent = closePercentChange()
// switch function for source choices
sources(optionName, len) =>
switch optionName
"atr (MA)" => ta.atr(len)
"cci (MA)" => ta.cci(close, len)
"close percent" => closePercent
"close" => close
"cog (MA)" => ta.cog(close, len)
"dollar value" => volume * hlc3
"eom" => volume / closePercent
"gaps" => open - close[1]
"high" => high
"low" => low
"mfi (MA)" => ta.mfi(hlc3, len)
"obv" => ta.obv
"open" => open
"range (MA)" => math.round(((ta.highest(high, len) - ta.lowest(low, len)) / ta.highest(high, len) * 100), 1)
"rsi (MA)" => ta.rsi(close, len)
"rvi (MA)" => ta.ema((close - open) / (high - low) * volume, len)
"timeClose (MA)" => ta.sma(time_close, 10)
"volume (MA)" => ta.ema(volume, len)
"volume" => volume
size(sizeName) =>
switch sizeName
"auto" => size.auto
"huge" => size.huge
"large" => size.large
"normal" => size.normal
"small" => size.small
"tiny" => size.tiny
labelTextSize = size(textSizeOption)
//assigning each source to a switch option
source1 = sources(hlSourceOpt1, sDataLen1)
source2 = sources(hlSourceOpt2, sDataLen2)
source3 = sources(hlSourceOpt3, sDataLen3)
source4 = sources(hlSourceOpt4, sDataLen4)
source5 = sources(hlSourceOpt5, sDataLen5)
lowestPercentileRankInput1 = input.int(defval = 5, step = 1, minval = 0, maxval = 100, title = "bottom %", inline = inline2, group = group1)
highestPercentileRankInput1 = input.int(defval = 5, step = 1, minval = 0, maxval = 100, title = "top %", inline = inline2, group = group1)
highestPercentileRank1 = 100 - highestPercentileRankInput1
lowestPercentileRankInput2 = input.int(defval = 5, step = 1, minval = 0, maxval = 100, title = "bottom %", inline = inline2 , group = group2)
highestPercentileRankInput2 = input.int(defval = 5, step = 1, minval = 0, maxval = 100, title = "top %", inline = inline2, group = group2)
highestPercentileRank2 = 100 - highestPercentileRankInput2
lowestPercentileRankInput3 = input.int(defval = 5, step = 1, minval = 0, maxval = 100, title = "bottom %", inline = inline2 , group = group3)
highestPercentileRankInput3 = input.int(defval = 5, step = 1, minval = 0, maxval = 100, title = "top %", inline = inline2, group = group3)
highestPercentileRank3 = 100 - highestPercentileRankInput3
lowestPercentileRankInput4 = input.int(defval = 5, step = 1, minval = 0, maxval = 100, title = "bottom %", inline = inline2 , group = group4)
highestPercentileRankInput4 = input.int(defval = 5, step = 1, minval = 0, maxval = 100, title = "top %", inline = inline2, group = group4)
highestPercentileRank4 = 100 - highestPercentileRankInput4
lowestPercentileRankInput5 = input.int(defval = 5, step = 1, minval = 0, maxval = 100, title = "bottom %", inline = inline2 , group = group5)
highestPercentileRankInput5 = input.int(defval = 5, step = 1, minval = 0, maxval = 100, title = "top %", inline = inline2, group = group5)
highestPercentileRank5 = 100 - highestPercentileRankInput5
var sourceBars1 = array.new_float()
var sourceBars2 = array.new_float()
var sourceBars3 = array.new_float()
var sourceBars4 = array.new_float()
var sourceBars5 = array.new_float()
array.push(sourceBars1, source1)
if sources > 1
array.push(sourceBars2, source2)
if sources > 2
array.push(sourceBars3, source3)
if sources > 3
array.push(sourceBars4, source4)
if sources > 4
array.push(sourceBars5, source5)
pRank1 = array.percentrank(sourceBars1, bar_index)
pRank2 = array.percentrank(sourceBars2, bar_index)
pRank3 = array.percentrank(sourceBars3, bar_index)
pRank4 = array.percentrank(sourceBars4, bar_index)
pRank5 = array.percentrank(sourceBars5, bar_index)
plotColorCondition(sourceValue, lowestFilter, highestFilter) =>
sourceValue <= lowestFilter ? color.red : sourceValue >= highestFilter ? color.green : color.blue
hline(0)
hline(sources > 0 ? 1 : na)
hline(sources > 1 ? 2 : na)
hline(sources > 2 ? 3 : na)
hline(sources > 3 ? 4 : na)
hline(sources > 4 ? 5 : na)
sourceLabelCondition2 = sources > 1 ? bar_index + sourceLabelLocation : na
sourceLabelCondition3 = sources > 2 ? bar_index + sourceLabelLocation : na
sourceLabelCondition4 = sources > 3 ? bar_index + sourceLabelLocation : na
sourceLabelCondition5 = sources > 4 ? bar_index + sourceLabelLocation : na
pRankCondition1 = sources > 0 ? (pRank1 / 100) : na
pRankCondition2 = sources > 1 ? (pRank2 / 100) + 1 : na
pRankCondition3 = sources > 2 ? (pRank3 / 100) + 2 : na
pRankCondition4 = sources > 3 ? (pRank4 / 100) + 3 : na
pRankCondition5 = sources > 4 ? (pRank5 / 100) + 4 : na
plot(pRankCondition1, color = plotColorCondition(pRank1, lowestPercentileRankInput1,
highestPercentileRank1), style = plot.style_line, display = display.pane)
plot(pRankCondition2, color = plotColorCondition(pRank2, lowestPercentileRankInput2,
highestPercentileRank2), style = plot.style_line, display = display.pane)
plot(pRankCondition3, color = plotColorCondition(pRank3, lowestPercentileRankInput3,
highestPercentileRank3), style = plot.style_line, display = display.pane)
plot(pRankCondition4, color = plotColorCondition(pRank4, lowestPercentileRankInput4,
highestPercentileRank4), style = plot.style_line, display = display.pane)
plot(pRankCondition5, color = plotColorCondition(pRank5, lowestPercentileRankInput5,
highestPercentileRank5), style = plot.style_line, display = display.pane)
pctToStr(percentile, sourceNumber) => str.tostring(math.round(((percentile - sourceNumber) * 100), 1)) + "%"
sourceLabel1 = label.new(x = bar_index + sourceLabelLocation, y = 0.5, text = hlSourceOpt1, color = color.rgb(0, 0, 0),
textcolor = color.white, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabel1[1])
sourceLabelPercentile1 = label.new(x = displayCurrentPct ? bar_index + sourceLabelPctLocation : na, y = 0.5,
text = pctToStr(pRankCondition1, 0),
color = color.rgb(0, 0, 0),
textcolor = plotColorCondition(pRank1, lowestPercentileRankInput1, highestPercentileRank1),
style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelPercentile1[1])
sourceLabel2 = label.new(x = sourceLabelCondition2, y = 1.5, text = hlSourceOpt2, color = color.rgb(0, 0, 0), textcolor = color.white, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabel2[1])
sourceLabelPercentile2 = label.new(x = displayCurrentPct and (sources > 1) ? bar_index + sourceLabelPctLocation : na,
y = 1.5,
text = pctToStr(pRankCondition2, 1),
color = color.rgb(0, 0, 0),
textcolor = plotColorCondition(pRank2, lowestPercentileRankInput2, highestPercentileRank2),
style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelPercentile2[1])
sourceLabel3 = label.new(x = sourceLabelCondition3, y = 2.5, text = hlSourceOpt3, color = color.rgb(0, 0, 0), textcolor = color.white, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabel3[1])
sourceLabelPercentile3 = label.new(x = displayCurrentPct and (sources > 2) ? bar_index + sourceLabelPctLocation : na,
y = 2.5,
text = pctToStr(pRankCondition3, 2),
color = color.rgb(0, 0, 0),
textcolor = plotColorCondition(pRank3, lowestPercentileRankInput3, highestPercentileRank3),
style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelPercentile3[1])
sourceLabel4 = label.new(x = sourceLabelCondition4, y = 3.5, text = hlSourceOpt4, color = color.rgb(0, 0, 0), textcolor = color.white, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabel4[1])
sourceLabelPercentile4 = label.new(x = displayCurrentPct and (sources > 3) ? bar_index + sourceLabelPctLocation : na,
y = 3.5,
text = pctToStr(pRankCondition4, 3),
color = color.rgb(0, 0, 0),
textcolor = plotColorCondition(pRank4, lowestPercentileRankInput4, highestPercentileRank4),
style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelPercentile4[1])
sourceLabel5 = label.new(x = sourceLabelCondition5, y = 4.5, text = hlSourceOpt5, color = color.rgb(0, 0, 0), textcolor = color.white, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabel5[1])
sourceLabelPercentile5 = label.new(x = displayCurrentPct and (sources > 4) ? bar_index + sourceLabelPctLocation : na,
y = 4.5,
text = pctToStr(pRankCondition5, 4),
color = color.rgb(0, 0, 0),
textcolor = plotColorCondition(pRank5, lowestPercentileRankInput5, highestPercentileRank5),
style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelPercentile5[1])
sourceLabelHighest1 = label.new(x = bar_index + sourceLabelLocation, y = 0.75, text = "top " + str.tostring(highestPercentileRankInput1) + "%", color = color.rgb(0, 0, 0), textcolor = color.green, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelHighest1[1])
sourceLabelLowest1 = label.new(x = bar_index + sourceLabelLocation, y = 0.25, text = "bottom " + str.tostring(lowestPercentileRankInput1) + "%", color = color.rgb(0, 0, 0), textcolor = color.red, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelLowest1[1])
sourceLabelHighest2 = label.new(x = sourceLabelCondition2, y = 1.75, text = "top " + str.tostring(highestPercentileRankInput2) + "%", color = color.rgb(0, 0, 0), textcolor = color.green, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelHighest2[1])
sourceLabelLowest2 = label.new(x = sourceLabelCondition2, y = 1.25, text = "bottom " + str.tostring(lowestPercentileRankInput2) + "%", color = color.rgb(0, 0, 0), textcolor = color.red, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelLowest2[1])
sourceLabelHighest3 = label.new(x = sourceLabelCondition3, y = 2.75, text = "top " + str.tostring(highestPercentileRankInput3) + "%", color = color.rgb(0, 0, 0), textcolor = color.green, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelHighest3[1])
sourceLabelLowest3 = label.new(x = sourceLabelCondition3, y = 2.25, text = "bottom " + str.tostring(lowestPercentileRankInput3) + "%", color = color.rgb(0, 0, 0), textcolor = color.red, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelLowest3[1])
sourceLabelHighest4 = label.new(x = sourceLabelCondition4, y = 3.75, text = "top " + str.tostring(highestPercentileRankInput4) + "%", color = color.rgb(0, 0, 0), textcolor = color.green, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelHighest4[1])
sourceLabelLowest4 = label.new(x = sourceLabelCondition4, y = 3.25, text = "bottom " + str.tostring(lowestPercentileRankInput4) + "%", color = color.rgb(0, 0, 0), textcolor = color.red, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelLowest4[1])
sourceLabelHighest5 = label.new(x = sourceLabelCondition5, y = 4.75, text = "top " + str.tostring(highestPercentileRankInput5) + "%", color = color.rgb(0, 0, 0), textcolor = color.green, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelHighest5[1])
sourceLabelLowest5 = label.new(x = sourceLabelCondition5, y = 4.25, text = "bottom " + str.tostring(lowestPercentileRankInput5) + "%", color = color.rgb(0, 0, 0), textcolor = color.red, style = label.style_text_outline, size = labelTextSize)
label.delete(sourceLabelLowest5[1])
|
Coppock Curve w/ Early Turns [QuantVue] | https://www.tradingview.com/script/G4FdbLiJ-Coppock-Curve-w-Early-Turns-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 121 | study | 5 | MPL-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('Coppock Curve w/ Early Turns [QuantVue]', shorttitle='Coppock Curve w/ Early Turns', overlay=false)
//----------Inputs----------//
var g1 = 'Calculation Settings'
RateOfChangeSlowPeriod = input(14, title='Rate Of Change Slow Period', group = g1)
RateOfChangeFastPeriod = input(11, title='Rate Of Change Fast Period', group = g1)
WeightedMAPeriod = input(10, title='Weighted MA Period', group = g1)
var g2 = 'Display Settings'
above0Col = input.color(color.green, 'Above 0 Color', group = g2)
below0Col = input.color(color.red, 'Below 0 Color', group = g2)
zeroCol = input.color(color.black, 'Zero Line Color', group = g2)
var g3 = 'Early Turns'
earlyTurns = input.bool(true, 'Show Early Turns', group = g3)
etBullColor = input.color(color.blue, 'Bullish Early Turn Color ', group = g3)
etBearColor = input.color(color.maroon, 'Bearish Early Turn Color', group = g3)
//----------ROC function----------//
roc(src, length) =>
if src[length] != 0
(src / src[length] - 1) * 100
else
0.0
//----------Calculations----------//
ROC1 = roc(close, RateOfChangeSlowPeriod)
ROC2 = roc(close, RateOfChangeFastPeriod)
Coppock = ta.wma(ROC1 + ROC2, WeightedMAPeriod)
//----------Early Turns---------//
earlyTurnBull = Coppock[1] < 0 and Coppock > Coppock[1] and Coppock[1] < Coppock[2]
earlyTurnBear = Coppock[1] > 0 and Coppock < Coppock[1] and Coppock[1] > Coppock[2]
//----------Plots----------//
plot(Coppock, title='Coppock', color=Coppock > 0 ? above0Col : below0Col, linewidth=2)
plot(0, title='Zero Line', color=color.black)
plotshape(earlyTurnBull and earlyTurns ? 0 : na, style=shape.diamond, location=location.absolute, color = etBullColor, size = size.small, display = display.pane)
plotshape(earlyTurnBear and earlyTurns ? 0 : na, style=shape.diamond, location=location.absolute, color = etBearColor, size = size.small, display = display.pane)
alertcondition(earlyTurnBull or earlyTurnBear, 'Early Turn', 'Early Coppock turn for {{ticker}}') |
MTF Fair Value Gap [StratifyTrade] | https://www.tradingview.com/script/HDA8PAJ8-MTF-Fair-Value-Gap-StratifyTrade/ | StratifyTrade | https://www.tradingview.com/u/StratifyTrade/ | 294 | 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/
// © HunterAlgos
//@version=5
indicator("MTF Fair Value Gap [HunterAlgos]", shorttitle = "MTF Fair Value Gap [1.0.0]", overlay = true, max_bars_back = 500, max_boxes_count = 500, max_lines_count = 500)
auto = input.bool(true, "Auto threshold" , inline = "1", group = "FILTER")
tt = input.int (0 , "Manual threshold", inline = "2", group = "FILTER")
num = input.int (10 , "Fair value gab number" , group = "SETTINGS")
mitigation = input.string("Low/High", "Mitigation source" , options = ["Low/High", "Close"], group = "SETTINGS")
formed = input.string("Low/High", "Mitigation point" , options = ["Low/High", "Avg"] , group = "SETTINGS")
display = input.string("Current", "Displat MTF FVG", options = ["Current", "MTF", "Current + MTF"], group = "Multi timeframe")
tf = input.timeframe("" , "Current timeframe FVG", group = "Multi timeframe")
mtf = input.timeframe("", "Multi timeframe FVG", group = "Multi timeframe")
css_up = input.color(color.aqua, "Bullish FVG", group = "COLORS")
css_dn = input.color(color.red , "Bearish FVG", group = "COLORS")
mtf_up = input.color(color.blue , "MTF Bullish FVG", group = "COLORS")
mtf_dn = input.color(color.orange, "MTF Bearish FVG", group = "COLORS")
pos = input.string("right" , "Text position", options = ["right", "center", "left"] , group = "TEXT")
size = input.string("small" , "Text size" , options = ["tiny", "small", "normal", "large", "huge", "auto"], group = "TEXT")
txtcss = input.color (color.white, "Text color" , group = "TEXT")
pos() =>
out = switch pos
"center" => text.align_center
"left" => text.align_left
"right" => text.align_right
out
size() =>
out = switch size
"tiny" => size.tiny
"small" => size.small
"normal" => size.normal
"large" => size.large
"huge" => size.huge
"auto" => size.auto
out
type bar
float o
float h
float l
float c
type bb
box [] up
box [] dn
line[] lup
line[] ldn
var bx = bb.new(
array.new< box >(1)
, array.new< box >(1)
, array.new< line>(1)
, array.new< line>(1)
)
bar b = bar.new(open, high, low, close)
nacol = color.new(color.white, 100)
trigger() =>
threshold = auto ? ta.cum((b.h - b.l) / b.l) / bar_index : tt / 100
a = b.l > b.h[2] and b.c[1] > b.h[2] and (b.l - b.h[2]) / b.h[2] > threshold
b = b.h < b.l[2] and b.c[1] < b.l[2] and (b.l[2] - b.h) / b.h > threshold
[a, b]
drawBox(left, top, right, bottom, color css, string txt) =>
var box id = na
var line l = na
id := box.new(na, na, na, na, border_color = nacol, border_width = 0, xloc = xloc.bar_time, bgcolor = color.new(css, 50))
id.set_left (left )
id.set_top (top )
id.set_right (right )
id.set_bottom (bottom)
id.set_text (txt )
id.set_text_halign(pos() )
id.set_text_size (size())
id.set_text_color (txtcss)
avg = math.avg(top, bottom)
l := line.new(na, na, na, na, xloc = xloc.bar_time, color = color.white, style = line.style_solid, width = 1)
l.set_x1(left )
l.set_x2(right)
l.set_y1(avg )
l.set_y2(avg )
[id, l]
method puts(bool mode, array<box> ab, box b, line l, array<line> al, bool bull) =>
if bull == true
float src = na
float point = na
switch mitigation
"Low/High" => src := low
"Close" => src := close
=> na
if mode == true
if ab.size() >= num
box.delete (ab.shift())
line.delete(al.shift())
ab.push(b)
al.push(l)
if mode == false
for j = ab.size() - 1 to 0 by 1
x = box.get_right (ab.get(j))
z = box.get_bottom(ab.get(j))
y = box.get_top (ab.get(j))
avg = math.avg(z,y)
switch formed
"Low/High" => point := z
"Avg" => point := avg
if time - (time - time[1]) == x and not (src < point)
box.set_right(ab.get(j), time)
line.set_x2 (al.get(j), time)
if bull == false
float src = na
float point = na
switch mitigation
"Low/High" => src := high
"Close" => src := close
=> na
if mode == true
if ab.size() >= num
box.delete (ab.shift())
line.delete(al.shift())
ab.push(b)
al.push(l)
if mode == false
for j = ab.size() - 1 to 0 by 1
x = box.get_right (ab.get(j))
z = box.get_bottom(ab.get(j))
y = box.get_top (ab.get(j))
avg = math.avg(z,y)
switch formed
"Low/High" => point := z
"Avg" => point := avg
if time - (time - time[1]) == x and not (src > point)
box.set_right(ab.get(j), time)
line.set_x2 (al.get(j), time)
draw(tf, up, dn) =>
[a, b] = request.security("", tf, trigger())
if a
box b = na
line l = na
[_box, _line] = drawBox(time - (time - time[1]) * 2, low, time, high[2], up, str.tostring(tf))
b := _box
l := _line
true.puts(bx.up, b, l, bx.lup, true)
if b
box b = na
line l = na
[_box, _line] = drawBox(time - (time - time[1]) * 2, high, time, low[2], dn, str.tostring(tf))
b := _box
l := _line
true.puts(bx.dn, b, l, bx.ldn, false)
switch display
"Current" => draw(tf, css_up, css_dn)
"MTF" => draw(mtf, mtf_up, mtf_dn)
"Current + MTF" => draw(tf, css_up, css_dn), draw(mtf, mtf_up, mtf_dn)
=> na
false.puts(bx.up, na, na, bx.lup, true)
false.puts(bx.dn, na, na, bx.ldn, false) |
COT TFF Data (S&P_500_CONSOLIDATED) | https://www.tradingview.com/script/JfIbD9pU-COT-TFF-Data-S-P-500-CONSOLIDATED/ | rippydave | https://www.tradingview.com/u/rippydave/ | 7 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rippydave
//@version=5
plot(close)
indicator("COT TFF Data (S&P_500_CONSOLIDATED)", overlay=false)
float d = na
t = timestamp(year, month, dayofmonth)
d := t == timestamp(2023, 8, 15) ? -340002 : d
d := t == timestamp(2023, 8, 8) ? -333276 : d
d := t == timestamp(2023, 8, 1) ? -345468 : d
d := t == timestamp(2023, 7, 25) ? -338383 : d
d := t == timestamp(2023, 7, 18) ? -363113 : d
d := t == timestamp(2023, 7, 11) ? -327423 : d
d := t == timestamp(2023, 7, 3) ? -335338 : d
d := t == timestamp(2023, 6, 27) ? -302157 : d
d := t == timestamp(2023, 6, 20) ? -211197 : d
d := t == timestamp(2023, 6, 13) ? -303 : d
d := t == timestamp(2023, 6, 6) ? 88506 : d
d := t == timestamp(2023, 5, 30) ? 83560 : d
d := t == timestamp(2023, 5, 23) ? 61931 : d
d := t == timestamp(2023, 5, 16) ? 87917 : d
d := t == timestamp(2023, 5, 9) ? 101737 : d
d := t == timestamp(2023, 5, 2) ? 84305 : d
d := t == timestamp(2023, 4, 25) ? 12477 : d
d := t == timestamp(2023, 4, 18) ? 25913 : d
d := t == timestamp(2023, 4, 11) ? 33687 : d
d := t == timestamp(2023, 4, 4) ? 35812 : d
d := t == timestamp(2023, 3, 28) ? 39206 : d
d := t == timestamp(2023, 3, 21) ? 29822 : d
d := t == timestamp(2023, 3, 14) ? -10358 : d
d := t == timestamp(2023, 3, 7) ? -13504 : d
d := t == timestamp(2023, 2, 28) ? -19594 : d
d := t == timestamp(2023, 2, 21) ? -18310 : d
d := t == timestamp(2023, 2, 14) ? -17792 : d
d := t == timestamp(2023, 2, 7) ? -26108 : d
d := t == timestamp(2023, 1, 31) ? -27400 : d
d := t == timestamp(2023, 1, 24) ? -24271 : d
d := t == timestamp(2023, 1, 17) ? -21282 : d
d := t == timestamp(2023, 1, 10) ? -21659 : d
d := t == timestamp(2023, 1, 3) ? -21647 : d
d := t == timestamp(2022, 12, 27) ? -29714 : d
d := t == timestamp(2022, 12, 20) ? -37145 : d
d := t == timestamp(2022, 12, 13) ? -2165 : d
d := t == timestamp(2022, 12, 6) ? -4905 : d
d := t == timestamp(2022, 11, 29) ? -11488 : d
d := t == timestamp(2022, 11, 22) ? -2737 : d
d := t == timestamp(2022, 11, 15) ? 7223 : d
d := t == timestamp(2022, 11, 8) ? 13705 : d
d := t == timestamp(2022, 11, 1) ? 11306 : d
d := t == timestamp(2022, 10, 25) ? 38818 : d
d := t == timestamp(2022, 10, 18) ? 46069 : d
d := t == timestamp(2022, 10, 11) ? 42133 : d
d := t == timestamp(2022, 10, 4) ? 38746 : d
d := t == timestamp(2022, 9, 27) ? 38565 : d
d := t == timestamp(2022, 9, 20) ? 47851 : d
d := t == timestamp(2022, 9, 13) ? 77903 : d
d := t == timestamp(2022, 9, 6) ? 67031 : d
d := t == timestamp(2022, 8, 30) ? 63571 : d
d := t == timestamp(2022, 8, 23) ? 66080 : d
d := t == timestamp(2022, 8, 16) ? 72431 : d
d := t == timestamp(2022, 8, 9) ? 68038 : d
d := t == timestamp(2022, 8, 2) ? 56938 : d
d := t == timestamp(2022, 7, 26) ? 43942 : d
d := t == timestamp(2022, 7, 19) ? 48310 : d
d := t == timestamp(2022, 7, 12) ? 34119 : d
d := t == timestamp(2022, 7, 5) ? 27031 : d
d := t == timestamp(2022, 6, 28) ? 25197 : d
d := t == timestamp(2022, 6, 21) ? 15927 : d
d := t == timestamp(2022, 6, 14) ? 882 : d
d := t == timestamp(2022, 6, 7) ? -4288 : d
d := t == timestamp(2022, 5, 31) ? -16345 : d
d := t == timestamp(2022, 5, 24) ? -15720 : d
d := t == timestamp(2022, 5, 17) ? -16168 : d
d := t == timestamp(2022, 5, 10) ? -24857 : d
d := t == timestamp(2022, 5, 3) ? -20545 : d
d := t == timestamp(2022, 4, 26) ? -36167 : d
d := t == timestamp(2022, 4, 19) ? -30876 : d
d := t == timestamp(2022, 4, 12) ? -36927 : d
d := t == timestamp(2022, 4, 5) ? -21963 : d
d := t == timestamp(2022, 3, 29) ? -14822 : d
d := t == timestamp(2022, 3, 22) ? -16208 : d
d := t == timestamp(2022, 3, 15) ? -51670 : d
d := t == timestamp(2022, 3, 8) ? -60095 : d
d := t == timestamp(2022, 3, 1) ? -60268 : d
d := t == timestamp(2022, 2, 22) ? -86898 : d
d := t == timestamp(2022, 2, 15) ? -81622 : d
d := t == timestamp(2022, 2, 8) ? -92407 : d
d := t == timestamp(2022, 2, 1) ? -103072 : d
d := t == timestamp(2022, 1, 25) ? -123074 : d
d := t == timestamp(2022, 1, 18) ? -109385 : d
d := t == timestamp(2022, 1, 11) ? -97328 : d
d := t == timestamp(2022, 1, 4) ? -91213 : d
d := t == timestamp(2021, 12, 28) ? -92026 : d
d := t == timestamp(2021, 12, 21) ? -98185 : d
d := t == timestamp(2021, 12, 14) ? -92066 : d
d := t == timestamp(2021, 12, 7) ? -93042 : d
d := t == timestamp(2021, 11, 30) ? -97005 : d
d := t == timestamp(2021, 11, 23) ? -98588 : d
d := t == timestamp(2021, 11, 16) ? -96746 : d
d := t == timestamp(2021, 11, 9) ? -93924 : d
d := t == timestamp(2021, 11, 2) ? -97304 : d
d := t == timestamp(2021, 10, 26) ? -98085 : d
d := t == timestamp(2021, 10, 19) ? -92281 : d
d := t == timestamp(2021, 10, 12) ? -105846 : d
d := t == timestamp(2021, 10, 5) ? -108276 : d
d := t == timestamp(2021, 9, 28) ? -110546 : d
d := t == timestamp(2021, 9, 21) ? -112371 : d
d := t == timestamp(2021, 9, 14) ? -113316 : d
d := t == timestamp(2021, 9, 7) ? -111827 : d
d := t == timestamp(2021, 8, 31) ? -107284 : d
d := t == timestamp(2021, 8, 24) ? -103277 : d
d := t == timestamp(2021, 8, 17) ? -107575 : d
d := t == timestamp(2021, 8, 10) ? -110307 : d
d := t == timestamp(2021, 8, 3) ? -111760 : d
d := t == timestamp(2021, 7, 27) ? -114958 : d
d := t == timestamp(2021, 7, 20) ? -116968 : d
d := t == timestamp(2021, 7, 13) ? -114468 : d
d := t == timestamp(2021, 7, 6) ? -112582 : d
d := t == timestamp(2021, 6, 29) ? -115489 : d
d := t == timestamp(2021, 6, 22) ? -120406 : d
d := t == timestamp(2021, 6, 15) ? -125993 : d
d := t == timestamp(2021, 6, 8) ? -116992 : d
d := t == timestamp(2021, 6, 1) ? -114750 : d
d := t == timestamp(2021, 5, 25) ? -115858 : d
d := t == timestamp(2021, 5, 18) ? -110414 : d
d := t == timestamp(2021, 5, 11) ? -107986 : d
d := t == timestamp(2021, 5, 4) ? -100049 : d
d := t == timestamp(2021, 4, 27) ? -90087 : d
d := t == timestamp(2021, 4, 20) ? -90077 : d
d := t == timestamp(2021, 4, 13) ? -79623 : d
d := t == timestamp(2021, 4, 6) ? -74453 : d
d := t == timestamp(2021, 3, 30) ? -83363 : d
d := t == timestamp(2021, 3, 23) ? -84749 : d
d := t == timestamp(2021, 3, 16) ? -81355 : d
d := t == timestamp(2021, 3, 9) ? -90608 : d
d := t == timestamp(2021, 3, 2) ? -88080 : d
d := t == timestamp(2021, 2, 23) ? -93694 : d
d := t == timestamp(2021, 2, 16) ? -80412 : d
d := t == timestamp(2021, 2, 9) ? -78484 : d
d := t == timestamp(2021, 2, 2) ? -77466 : d
d := t == timestamp(2021, 1, 26) ? -82125 : d
d := t == timestamp(2021, 1, 19) ? -94755 : d
d := t == timestamp(2021, 1, 12) ? -90397 : d
d := t == timestamp(2021, 1, 5) ? -82061 : d
d := t == timestamp(2020, 12, 29) ? -84106 : d
d := t == timestamp(2020, 12, 21) ? -85833 : d
d := t == timestamp(2020, 12, 15) ? -85350 : d
d := t == timestamp(2020, 12, 8) ? -74818 : d
d := t == timestamp(2020, 12, 1) ? -68348 : d
d := t == timestamp(2020, 11, 24) ? -57502 : d
d := t == timestamp(2020, 11, 17) ? -62011 : d
d := t == timestamp(2020, 11, 10) ? -57325 : d
d := t == timestamp(2020, 11, 3) ? -41448 : d
d := t == timestamp(2020, 10, 27) ? -45768 : d
d := t == timestamp(2020, 10, 20) ? -39391 : d
d := t == timestamp(2020, 10, 13) ? -34043 : d
d := t == timestamp(2020, 10, 6) ? -33271 : d
d := t == timestamp(2020, 9, 29) ? -41139 : d
d := t == timestamp(2020, 9, 22) ? -46457 : d
d := t == timestamp(2020, 9, 15) ? -33255 : d
d := t == timestamp(2020, 9, 8) ? -12878 : d
d := t == timestamp(2020, 9, 1) ? -2818 : d
d := t == timestamp(2020, 8, 25) ? -1684 : d
d := t == timestamp(2020, 8, 18) ? -871 : d
d := t == timestamp(2020, 8, 11) ? 6203 : d
d := t == timestamp(2020, 8, 4) ? 11313 : d
d := t == timestamp(2020, 7, 28) ? 4479 : d
d := t == timestamp(2020, 7, 21) ? 27554 : d
d := t == timestamp(2020, 7, 14) ? 32819 : d
d := t == timestamp(2020, 7, 7) ? 39117 : d
d := t == timestamp(2020, 6, 30) ? 39601 : d
d := t == timestamp(2020, 6, 23) ? 43716 : d
d := t == timestamp(2020, 6, 16) ? 40313 : d
d := t == timestamp(2020, 6, 9) ? 35178 : d
d := t == timestamp(2020, 6, 2) ? 50894 : d
d := t == timestamp(2020, 5, 26) ? 43790 : d
d := t == timestamp(2020, 5, 19) ? 43817 : d
d := t == timestamp(2020, 5, 12) ? 37685 : d
d := t == timestamp(2020, 5, 5) ? 37198 : d
d := t == timestamp(2020, 4, 28) ? 12736 : d
d := t == timestamp(2020, 4, 21) ? 3316 : d
d := t == timestamp(2020, 4, 14) ? 4404 : d
d := t == timestamp(2020, 4, 7) ? -891 : d
d := t == timestamp(2020, 3, 31) ? -4653 : d
d := t == timestamp(2020, 3, 24) ? -58667 : d
d := t == timestamp(2020, 3, 17) ? -102440 : d
d := t == timestamp(2020, 3, 10) ? -73258 : d
d := t == timestamp(2020, 3, 3) ? -114128 : d
d := t == timestamp(2020, 2, 25) ? -143202 : d
d := t == timestamp(2020, 2, 18) ? -159140 : d
d := t == timestamp(2020, 2, 11) ? -152465 : d
d := t == timestamp(2020, 2, 4) ? -156766 : d
d := t == timestamp(2020, 1, 28) ? -151331 : d
d := t == timestamp(2020, 1, 21) ? -145088 : d
d := t == timestamp(2020, 1, 14) ? -142636 : d
d := t == timestamp(2020, 1, 7) ? -124413 : d
d := t == timestamp(2019, 12, 31) ? -129408 : d
d := t == timestamp(2019, 12, 24) ? -133301 : d
d := t == timestamp(2019, 12, 17) ? -109743 : d
d := t == timestamp(2019, 12, 10) ? -90892 : d
d := t == timestamp(2019, 12, 3) ? -87667 : d
d := t == timestamp(2019, 11, 26) ? -82427 : d
d := t == timestamp(2019, 11, 19) ? -77362 : d
d := t == timestamp(2019, 11, 12) ? -78051 : d
d := t == timestamp(2019, 11, 5) ? -71441 : d
d := t == timestamp(2019, 10, 29) ? -71117 : d
d := t == timestamp(2019, 10, 22) ? -61456 : d
d := t == timestamp(2019, 10, 15) ? -63577 : d
d := t == timestamp(2019, 10, 8) ? -64135 : d
d := t == timestamp(2019, 10, 1) ? -71342 : d
d := t == timestamp(2019, 9, 24) ? -75236 : d
d := t == timestamp(2019, 9, 17) ? -57548 : d
d := t == timestamp(2019, 9, 10) ? -49830 : d
d := t == timestamp(2019, 9, 3) ? -35867 : d
d := t == timestamp(2019, 8, 27) ? -40995 : d
d := t == timestamp(2019, 8, 20) ? -45960 : d
d := t == timestamp(2019, 8, 13) ? -52477 : d
d := t == timestamp(2019, 8, 6) ? -66822 : d
d := t == timestamp(2019, 7, 30) ? -89987 : d
d := t == timestamp(2019, 7, 23) ? -93825 : d
d := t == timestamp(2019, 7, 16) ? -91617 : d
d := t == timestamp(2019, 7, 9) ? -79456 : d
d := t == timestamp(2019, 7, 2) ? -80219 : d
d := t == timestamp(2019, 6, 25) ? -82278 : d
d := t == timestamp(2019, 6, 18) ? -75522 : d
d := t == timestamp(2019, 6, 11) ? -76852 : d
d := t == timestamp(2019, 6, 4) ? -76864 : d
d := t == timestamp(2019, 5, 28) ? -76858 : d
d := t == timestamp(2019, 5, 21) ? -73172 : d
d := t == timestamp(2019, 5, 14) ? -81177 : d
d := t == timestamp(2019, 5, 7) ? -87007 : d
d := t == timestamp(2019, 4, 30) ? -99433 : d
d := t == timestamp(2019, 4, 23) ? -95443 : d
d := t == timestamp(2019, 4, 16) ? -91528 : d
d := t == timestamp(2019, 4, 9) ? -80828 : d
d := t == timestamp(2019, 4, 2) ? -80582 : d
d := t == timestamp(2019, 3, 26) ? -84973 : d
d := t == timestamp(2019, 3, 19) ? -77599 : d
d := t == timestamp(2019, 3, 12) ? -67065 : d
d := t == timestamp(2019, 3, 5) ? -52666 : d
d := t == timestamp(2019, 2, 26) ? -53396 : d
d := t == timestamp(2019, 2, 19) ? -38421 : d
d := t == timestamp(2019, 2, 12) ? -45273 : d
d := t == timestamp(2019, 2, 5) ? -55513 : d
d := t == timestamp(2019, 1, 29) ? -92802 : d
d := t == timestamp(2019, 1, 22) ? -89809 : d
d := t == timestamp(2019, 1, 15) ? -98941 : d
d := t == timestamp(2019, 1, 8) ? -123180 : d
plot(d, "dealer", color.red, 2, plot.style_stepline)
float a = na
a := t == timestamp(2023, 8, 15) ? 774595 : a
a := t == timestamp(2023, 8, 8) ? 770733 : a
a := t == timestamp(2023, 8, 1) ? 818545 : a
a := t == timestamp(2023, 7, 25) ? 800515 : a
a := t == timestamp(2023, 7, 18) ? 802865 : a
a := t == timestamp(2023, 7, 11) ? 749857 : a
a := t == timestamp(2023, 7, 3) ? 767073 : a
a := t == timestamp(2023, 6, 27) ? 747753 : a
a := t == timestamp(2023, 6, 20) ? 793110 : a
a := t == timestamp(2023, 6, 13) ? 755193 : a
a := t == timestamp(2023, 6, 6) ? 659804 : a
a := t == timestamp(2023, 5, 30) ? 624372 : a
a := t == timestamp(2023, 5, 23) ? 623923 : a
a := t == timestamp(2023, 5, 16) ? 611230 : a
a := t == timestamp(2023, 5, 9) ? 593991 : a
a := t == timestamp(2023, 5, 2) ? 590688 : a
a := t == timestamp(2023, 4, 25) ? 115967 : a
a := t == timestamp(2023, 4, 18) ? 116670 : a
a := t == timestamp(2023, 4, 11) ? 104861 : a
a := t == timestamp(2023, 4, 4) ? 96367 : a
a := t == timestamp(2023, 3, 28) ? 84773 : a
a := t == timestamp(2023, 3, 21) ? 94133 : a
a := t == timestamp(2023, 3, 14) ? 96637 : a
a := t == timestamp(2023, 3, 7) ? 101954 : a
a := t == timestamp(2023, 2, 28) ? 97256 : a
a := t == timestamp(2023, 2, 21) ? 106622 : a
a := t == timestamp(2023, 2, 14) ? 110073 : a
a := t == timestamp(2023, 2, 7) ? 110223 : a
a := t == timestamp(2023, 1, 31) ? 113548 : a
a := t == timestamp(2023, 1, 24) ? 105528 : a
a := t == timestamp(2023, 1, 17) ? 105126 : a
a := t == timestamp(2023, 1, 10) ? 92202 : a
a := t == timestamp(2023, 1, 3) ? 86884 : a
a := t == timestamp(2022, 12, 27) ? 88753 : a
a := t == timestamp(2022, 12, 20) ? 88225 : a
a := t == timestamp(2022, 12, 13) ? 97142 : a
a := t == timestamp(2022, 12, 6) ? 91876 : a
a := t == timestamp(2022, 11, 29) ? 95526 : a
a := t == timestamp(2022, 11, 22) ? 90199 : a
a := t == timestamp(2022, 11, 15) ? 84957 : a
a := t == timestamp(2022, 11, 8) ? 64020 : a
a := t == timestamp(2022, 11, 1) ? 64108 : a
a := t == timestamp(2022, 10, 25) ? 55898 : a
a := t == timestamp(2022, 10, 18) ? 44945 : a
a := t == timestamp(2022, 10, 11) ? 35888 : a
a := t == timestamp(2022, 10, 4) ? 39751 : a
a := t == timestamp(2022, 9, 27) ? 42667 : a
a := t == timestamp(2022, 9, 20) ? 56510 : a
a := t == timestamp(2022, 9, 13) ? 62678 : a
a := t == timestamp(2022, 9, 6) ? 54682 : a
a := t == timestamp(2022, 8, 30) ? 65752 : a
a := t == timestamp(2022, 8, 23) ? 68369 : a
a := t == timestamp(2022, 8, 16) ? 75443 : a
a := t == timestamp(2022, 8, 9) ? 59324 : a
a := t == timestamp(2022, 8, 2) ? 63807 : a
a := t == timestamp(2022, 7, 26) ? 58212 : a
a := t == timestamp(2022, 7, 19) ? 48581 : a
a := t == timestamp(2022, 7, 12) ? 44526 : a
a := t == timestamp(2022, 7, 5) ? 41851 : a
a := t == timestamp(2022, 6, 28) ? 39776 : a
a := t == timestamp(2022, 6, 21) ? 37519 : a
a := t == timestamp(2022, 6, 14) ? 39303 : a
a := t == timestamp(2022, 6, 7) ? 70728 : a
a := t == timestamp(2022, 5, 31) ? 72690 : a
a := t == timestamp(2022, 5, 24) ? 57380 : a
a := t == timestamp(2022, 5, 17) ? 62867 : a
a := t == timestamp(2022, 5, 10) ? 55937 : a
a := t == timestamp(2022, 5, 3) ? 73938 : a
a := t == timestamp(2022, 4, 26) ? 72323 : a
a := t == timestamp(2022, 4, 19) ? 94755 : a
a := t == timestamp(2022, 4, 12) ? 95484 : a
a := t == timestamp(2022, 4, 5) ? 106436 : a
a := t == timestamp(2022, 3, 29) ? 111617 : a
a := t == timestamp(2022, 3, 22) ? 103155 : a
a := t == timestamp(2022, 3, 15) ? 89372 : a
a := t == timestamp(2022, 3, 8) ? 84432 : a
a := t == timestamp(2022, 3, 1) ? 93635 : a
a := t == timestamp(2022, 2, 22) ? 100937 : a
a := t == timestamp(2022, 2, 15) ? 105043 : a
a := t == timestamp(2022, 2, 8) ? 113733 : a
a := t == timestamp(2022, 2, 1) ? 129142 : a
a := t == timestamp(2022, 1, 25) ? 130799 : a
a := t == timestamp(2022, 1, 18) ? 145536 : a
a := t == timestamp(2022, 1, 11) ? 147051 : a
a := t == timestamp(2022, 1, 4) ? 147489 : a
a := t == timestamp(2021, 12, 28) ? 148327 : a
a := t == timestamp(2021, 12, 21) ? 134743 : a
a := t == timestamp(2021, 12, 14) ? 119330 : a
a := t == timestamp(2021, 12, 7) ? 132515 : a
a := t == timestamp(2021, 11, 30) ? 138520 : a
a := t == timestamp(2021, 11, 23) ? 157081 : a
a := t == timestamp(2021, 11, 16) ? 156893 : a
a := t == timestamp(2021, 11, 9) ? 151806 : a
a := t == timestamp(2021, 11, 2) ? 152394 : a
a := t == timestamp(2021, 10, 26) ? 158516 : a
a := t == timestamp(2021, 10, 19) ? 156538 : a
a := t == timestamp(2021, 10, 12) ? 145503 : a
a := t == timestamp(2021, 10, 5) ? 157525 : a
a := t == timestamp(2021, 9, 28) ? 162138 : a
a := t == timestamp(2021, 9, 21) ? 169567 : a
a := t == timestamp(2021, 9, 14) ? 172802 : a
a := t == timestamp(2021, 9, 7) ? 184093 : a
a := t == timestamp(2021, 8, 31) ? 182931 : a
a := t == timestamp(2021, 8, 24) ? 177398 : a
a := t == timestamp(2021, 8, 17) ? 182265 : a
a := t == timestamp(2021, 8, 10) ? 185078 : a
a := t == timestamp(2021, 8, 3) ? 182127 : a
a := t == timestamp(2021, 7, 27) ? 184114 : a
a := t == timestamp(2021, 7, 20) ? 187789 : a
a := t == timestamp(2021, 7, 13) ? 193704 : a
a := t == timestamp(2021, 7, 6) ? 192496 : a
a := t == timestamp(2021, 6, 29) ? 192509 : a
a := t == timestamp(2021, 6, 22) ? 192792 : a
a := t == timestamp(2021, 6, 15) ? 191778 : a
a := t == timestamp(2021, 6, 8) ? 174815 : a
a := t == timestamp(2021, 6, 1) ? 172162 : a
a := t == timestamp(2021, 5, 25) ? 169470 : a
a := t == timestamp(2021, 5, 18) ? 166082 : a
a := t == timestamp(2021, 5, 11) ? 172411 : a
a := t == timestamp(2021, 5, 4) ? 176443 : a
a := t == timestamp(2021, 4, 27) ? 168087 : a
a := t == timestamp(2021, 4, 20) ? 166684 : a
a := t == timestamp(2021, 4, 13) ? 161622 : a
a := t == timestamp(2021, 4, 6) ? 158330 : a
a := t == timestamp(2021, 3, 30) ? 152736 : a
a := t == timestamp(2021, 3, 23) ? 146785 : a
a := t == timestamp(2021, 3, 16) ? 134909 : a
a := t == timestamp(2021, 3, 9) ? 135206 : a
a := t == timestamp(2021, 3, 2) ? 143218 : a
a := t == timestamp(2021, 2, 23) ? 162111 : a
a := t == timestamp(2021, 2, 16) ? 165288 : a
a := t == timestamp(2021, 2, 9) ? 164527 : a
a := t == timestamp(2021, 2, 2) ? 153961 : a
a := t == timestamp(2021, 1, 26) ? 168760 : a
a := t == timestamp(2021, 1, 19) ? 169130 : a
a := t == timestamp(2021, 1, 12) ? 162868 : a
a := t == timestamp(2021, 1, 5) ? 157861 : a
a := t == timestamp(2020, 12, 29) ? 154715 : a
a := t == timestamp(2020, 12, 21) ? 151089 : a
a := t == timestamp(2020, 12, 15) ? 151951 : a
a := t == timestamp(2020, 12, 8) ? 152369 : a
a := t == timestamp(2020, 12, 1) ? 143457 : a
a := t == timestamp(2020, 11, 24) ? 140641 : a
a := t == timestamp(2020, 11, 17) ? 133489 : a
a := t == timestamp(2020, 11, 10) ? 129209 : a
a := t == timestamp(2020, 11, 3) ? 113285 : a
a := t == timestamp(2020, 10, 27) ? 122308 : a
a := t == timestamp(2020, 10, 20) ? 127724 : a
a := t == timestamp(2020, 10, 13) ? 134100 : a
a := t == timestamp(2020, 10, 6) ? 118904 : a
a := t == timestamp(2020, 9, 29) ? 119807 : a
a := t == timestamp(2020, 9, 22) ? 132893 : a
a := t == timestamp(2020, 9, 15) ? 125514 : a
a := t == timestamp(2020, 9, 8) ? 123502 : a
a := t == timestamp(2020, 9, 1) ? 139405 : a
a := t == timestamp(2020, 8, 25) ? 144877 : a
a := t == timestamp(2020, 8, 18) ? 135663 : a
a := t == timestamp(2020, 8, 11) ? 134316 : a
a := t == timestamp(2020, 8, 4) ? 122903 : a
a := t == timestamp(2020, 7, 28) ? 111212 : a
a := t == timestamp(2020, 7, 21) ? 102713 : a
a := t == timestamp(2020, 7, 14) ? 99498 : a
a := t == timestamp(2020, 7, 7) ? 88500 : a
a := t == timestamp(2020, 6, 30) ? 81198 : a
a := t == timestamp(2020, 6, 23) ? 91477 : a
a := t == timestamp(2020, 6, 16) ? 102357 : a
a := t == timestamp(2020, 6, 9) ? 115989 : a
a := t == timestamp(2020, 6, 2) ? 100946 : a
a := t == timestamp(2020, 5, 26) ? 106144 : a
a := t == timestamp(2020, 5, 19) ? 93976 : a
a := t == timestamp(2020, 5, 12) ? 103666 : a
a := t == timestamp(2020, 5, 5) ? 96915 : a
a := t == timestamp(2020, 4, 28) ? 116595 : a
a := t == timestamp(2020, 4, 21) ? 111541 : a
a := t == timestamp(2020, 4, 14) ? 115378 : a
a := t == timestamp(2020, 4, 7) ? 90040 : a
a := t == timestamp(2020, 3, 31) ? 95679 : a
a := t == timestamp(2020, 3, 24) ? 71127 : a
a := t == timestamp(2020, 3, 17) ? 69730 : a
a := t == timestamp(2020, 3, 10) ? 111084 : a
a := t == timestamp(2020, 3, 3) ? 132728 : a
a := t == timestamp(2020, 2, 25) ? 179544 : a
a := t == timestamp(2020, 2, 18) ? 226804 : a
a := t == timestamp(2020, 2, 11) ? 222821 : a
a := t == timestamp(2020, 2, 4) ? 212874 : a
a := t == timestamp(2020, 1, 28) ? 209653 : a
a := t == timestamp(2020, 1, 21) ? 220247 : a
a := t == timestamp(2020, 1, 14) ? 217315 : a
a := t == timestamp(2020, 1, 7) ? 205810 : a
a := t == timestamp(2019, 12, 31) ? 204169 : a
a := t == timestamp(2019, 12, 24) ? 212716 : a
a := t == timestamp(2019, 12, 17) ? 174693 : a
a := t == timestamp(2019, 12, 10) ? 179093 : a
a := t == timestamp(2019, 12, 3) ? 170610 : a
a := t == timestamp(2019, 11, 26) ? 179909 : a
a := t == timestamp(2019, 11, 19) ? 180793 : a
a := t == timestamp(2019, 11, 12) ? 181440 : a
a := t == timestamp(2019, 11, 5) ? 171635 : a
a := t == timestamp(2019, 10, 29) ? 167092 : a
a := t == timestamp(2019, 10, 22) ? 157277 : a
a := t == timestamp(2019, 10, 15) ? 151832 : a
a := t == timestamp(2019, 10, 8) ? 142967 : a
a := t == timestamp(2019, 10, 1) ? 154946 : a
a := t == timestamp(2019, 9, 24) ? 163598 : a
a := t == timestamp(2019, 9, 17) ? 141220 : a
a := t == timestamp(2019, 9, 10) ? 153099 : a
a := t == timestamp(2019, 9, 3) ? 141289 : a
a := t == timestamp(2019, 8, 27) ? 140871 : a
a := t == timestamp(2019, 8, 20) ? 130718 : a
a := t == timestamp(2019, 8, 13) ? 149531 : a
a := t == timestamp(2019, 8, 6) ? 155360 : a
a := t == timestamp(2019, 7, 30) ? 180853 : a
a := t == timestamp(2019, 7, 23) ? 181470 : a
a := t == timestamp(2019, 7, 16) ? 190803 : a
a := t == timestamp(2019, 7, 9) ? 181085 : a
a := t == timestamp(2019, 7, 2) ? 179346 : a
a := t == timestamp(2019, 6, 25) ? 183223 : a
a := t == timestamp(2019, 6, 18) ? 159202 : a
a := t == timestamp(2019, 6, 11) ? 159612 : a
a := t == timestamp(2019, 6, 4) ? 142263 : a
a := t == timestamp(2019, 5, 28) ? 138703 : a
a := t == timestamp(2019, 5, 21) ? 140506 : a
a := t == timestamp(2019, 5, 14) ? 143511 : a
a := t == timestamp(2019, 5, 7) ? 151078 : a
a := t == timestamp(2019, 4, 30) ? 159477 : a
a := t == timestamp(2019, 4, 23) ? 159874 : a
a := t == timestamp(2019, 4, 16) ? 161581 : a
a := t == timestamp(2019, 4, 9) ? 155347 : a
a := t == timestamp(2019, 4, 2) ? 151676 : a
a := t == timestamp(2019, 3, 26) ? 151202 : a
a := t == timestamp(2019, 3, 19) ? 151136 : a
a := t == timestamp(2019, 3, 12) ? 135211 : a
a := t == timestamp(2019, 3, 5) ? 126261 : a
a := t == timestamp(2019, 2, 26) ? 124019 : a
a := t == timestamp(2019, 2, 19) ? 105650 : a
a := t == timestamp(2019, 2, 12) ? 107083 : a
a := t == timestamp(2019, 2, 5) ? 114681 : a
a := t == timestamp(2019, 1, 29) ? 123645 : a
a := t == timestamp(2019, 1, 22) ? 126555 : a
a := t == timestamp(2019, 1, 15) ? 127202 : a
a := t == timestamp(2019, 1, 8) ? 127500 : a
plot(a, "asset_mgr", color.green, 2, plot.style_stepline)
float l = na
l := t == timestamp(2023, 8, 15) ? 600683 : l
l := t == timestamp(2023, 8, 8) ? 668432 : l
l := t == timestamp(2023, 8, 1) ? 684991 : l
l := t == timestamp(2023, 7, 25) ? 689458 : l
l := t == timestamp(2023, 7, 18) ? 727289 : l
l := t == timestamp(2023, 7, 11) ? 641066 : l
l := t == timestamp(2023, 7, 3) ? 626847 : l
l := t == timestamp(2023, 6, 27) ? 583182 : l
l := t == timestamp(2023, 6, 20) ? 623678 : l
l := t == timestamp(2023, 6, 13) ? 812689 : l
l := t == timestamp(2023, 6, 6) ? 888238 : l
l := t == timestamp(2023, 5, 30) ? 857353 : l
l := t == timestamp(2023, 5, 23) ? 798118 : l
l := t == timestamp(2023, 5, 16) ? 701878 : l
l := t == timestamp(2023, 5, 9) ? 747073 : l
l := t == timestamp(2023, 5, 2) ? 692818 : l
l := t == timestamp(2023, 4, 25) ? 145415 : l
l := t == timestamp(2023, 4, 18) ? 152789 : l
l := t == timestamp(2023, 4, 11) ? 148508 : l
l := t == timestamp(2023, 4, 4) ? 144639 : l
l := t == timestamp(2023, 3, 28) ? 121938 : l
l := t == timestamp(2023, 3, 21) ? 122214 : l
l := t == timestamp(2023, 3, 14) ? 105225 : l
l := t == timestamp(2023, 3, 7) ? 118568 : l
l := t == timestamp(2023, 2, 28) ? 125960 : l
l := t == timestamp(2023, 2, 21) ? 120840 : l
l := t == timestamp(2023, 2, 14) ? 118432 : l
l := t == timestamp(2023, 2, 7) ? 119070 : l
l := t == timestamp(2023, 1, 31) ? 124045 : l
l := t == timestamp(2023, 1, 24) ? 121426 : l
l := t == timestamp(2023, 1, 17) ? 126451 : l
l := t == timestamp(2023, 1, 10) ? 118146 : l
l := t == timestamp(2023, 1, 3) ? 112542 : l
l := t == timestamp(2022, 12, 27) ? 103311 : l
l := t == timestamp(2022, 12, 20) ? 104326 : l
l := t == timestamp(2022, 12, 13) ? 139291 : l
l := t == timestamp(2022, 12, 6) ? 136979 : l
l := t == timestamp(2022, 11, 29) ? 136178 : l
l := t == timestamp(2022, 11, 22) ? 136873 : l
l := t == timestamp(2022, 11, 15) ? 148680 : l
l := t == timestamp(2022, 11, 8) ? 145456 : l
l := t == timestamp(2022, 11, 1) ? 138684 : l
l := t == timestamp(2022, 10, 25) ? 143414 : l
l := t == timestamp(2022, 10, 18) ? 142559 : l
l := t == timestamp(2022, 10, 11) ? 128226 : l
l := t == timestamp(2022, 10, 4) ? 122151 : l
l := t == timestamp(2022, 9, 27) ? 127447 : l
l := t == timestamp(2022, 9, 20) ? 116940 : l
l := t == timestamp(2022, 9, 13) ? 144456 : l
l := t == timestamp(2022, 9, 6) ? 141966 : l
l := t == timestamp(2022, 8, 30) ? 146133 : l
l := t == timestamp(2022, 8, 23) ? 149915 : l
l := t == timestamp(2022, 8, 16) ? 166022 : l
l := t == timestamp(2022, 8, 9) ? 148625 : l
l := t == timestamp(2022, 8, 2) ? 147936 : l
l := t == timestamp(2022, 7, 26) ? 137306 : l
l := t == timestamp(2022, 7, 19) ? 137801 : l
l := t == timestamp(2022, 7, 12) ? 121984 : l
l := t == timestamp(2022, 7, 5) ? 119319 : l
l := t == timestamp(2022, 6, 28) ? 109631 : l
l := t == timestamp(2022, 6, 21) ? 117221 : l
l := t == timestamp(2022, 6, 14) ? 141395 : l
l := t == timestamp(2022, 6, 7) ? 122397 : l
l := t == timestamp(2022, 5, 31) ? 121807 : l
l := t == timestamp(2022, 5, 24) ? 125018 : l
l := t == timestamp(2022, 5, 17) ? 122215 : l
l := t == timestamp(2022, 5, 10) ? 123757 : l
l := t == timestamp(2022, 5, 3) ? 123763 : l
l := t == timestamp(2022, 4, 26) ? 106519 : l
l := t == timestamp(2022, 4, 19) ? 105326 : l
l := t == timestamp(2022, 4, 12) ? 100255 : l
l := t == timestamp(2022, 4, 5) ? 109635 : l
l := t == timestamp(2022, 3, 29) ? 110076 : l
l := t == timestamp(2022, 3, 22) ? 104194 : l
l := t == timestamp(2022, 3, 15) ? 130939 : l
l := t == timestamp(2022, 3, 8) ? 128151 : l
l := t == timestamp(2022, 3, 1) ? 129644 : l
l := t == timestamp(2022, 2, 22) ? 117705 : l
l := t == timestamp(2022, 2, 15) ? 116926 : l
l := t == timestamp(2022, 2, 8) ? 104857 : l
l := t == timestamp(2022, 2, 1) ? 110161 : l
l := t == timestamp(2022, 1, 25) ? 119030 : l
l := t == timestamp(2022, 1, 18) ? 115715 : l
l := t == timestamp(2022, 1, 11) ? 113763 : l
l := t == timestamp(2022, 1, 4) ? 125117 : l
l := t == timestamp(2021, 12, 28) ? 116048 : l
l := t == timestamp(2021, 12, 21) ? 108654 : l
l := t == timestamp(2021, 12, 14) ? 110045 : l
l := t == timestamp(2021, 12, 7) ? 109515 : l
l := t == timestamp(2021, 11, 30) ? 113418 : l
l := t == timestamp(2021, 11, 23) ? 99287 : l
l := t == timestamp(2021, 11, 16) ? 103861 : l
l := t == timestamp(2021, 11, 9) ? 107392 : l
l := t == timestamp(2021, 11, 2) ? 112050 : l
l := t == timestamp(2021, 10, 26) ? 108603 : l
l := t == timestamp(2021, 10, 19) ? 107296 : l
l := t == timestamp(2021, 10, 12) ? 111100 : l
l := t == timestamp(2021, 10, 5) ? 113217 : l
l := t == timestamp(2021, 9, 28) ? 111304 : l
l := t == timestamp(2021, 9, 21) ? 105648 : l
l := t == timestamp(2021, 9, 14) ? 112963 : l
l := t == timestamp(2021, 9, 7) ? 118879 : l
l := t == timestamp(2021, 8, 31) ? 115823 : l
l := t == timestamp(2021, 8, 24) ? 121614 : l
l := t == timestamp(2021, 8, 17) ? 115143 : l
l := t == timestamp(2021, 8, 10) ? 122222 : l
l := t == timestamp(2021, 8, 3) ? 120779 : l
l := t == timestamp(2021, 7, 27) ? 113757 : l
l := t == timestamp(2021, 7, 20) ? 114335 : l
l := t == timestamp(2021, 7, 13) ? 115252 : l
l := t == timestamp(2021, 7, 6) ? 118363 : l
l := t == timestamp(2021, 6, 29) ? 112689 : l
l := t == timestamp(2021, 6, 22) ? 100686 : l
l := t == timestamp(2021, 6, 15) ? 127188 : l
l := t == timestamp(2021, 6, 8) ? 124056 : l
l := t == timestamp(2021, 6, 1) ? 131295 : l
l := t == timestamp(2021, 5, 25) ? 126091 : l
l := t == timestamp(2021, 5, 18) ? 126402 : l
l := t == timestamp(2021, 5, 11) ? 129681 : l
l := t == timestamp(2021, 5, 4) ? 136395 : l
l := t == timestamp(2021, 4, 27) ? 139272 : l
l := t == timestamp(2021, 4, 20) ? 138091 : l
l := t == timestamp(2021, 4, 13) ? 135002 : l
l := t == timestamp(2021, 4, 6) ? 134733 : l
l := t == timestamp(2021, 3, 30) ? 124611 : l
l := t == timestamp(2021, 3, 23) ? 115928 : l
l := t == timestamp(2021, 3, 16) ? 157220 : l
l := t == timestamp(2021, 3, 9) ? 156519 : l
l := t == timestamp(2021, 3, 2) ? 159557 : l
l := t == timestamp(2021, 2, 23) ? 159270 : l
l := t == timestamp(2021, 2, 16) ? 162521 : l
l := t == timestamp(2021, 2, 9) ? 156474 : l
l := t == timestamp(2021, 2, 2) ? 156156 : l
l := t == timestamp(2021, 1, 26) ? 147109 : l
l := t == timestamp(2021, 1, 19) ? 139111 : l
l := t == timestamp(2021, 1, 12) ? 137182 : l
l := t == timestamp(2021, 1, 5) ? 134778 : l
l := t == timestamp(2020, 12, 29) ? 131846 : l
l := t == timestamp(2020, 12, 21) ? 124495 : l
l := t == timestamp(2020, 12, 15) ? 134117 : l
l := t == timestamp(2020, 12, 8) ? 136833 : l
l := t == timestamp(2020, 12, 1) ? 132460 : l
l := t == timestamp(2020, 11, 24) ? 128120 : l
l := t == timestamp(2020, 11, 17) ? 124676 : l
l := t == timestamp(2020, 11, 10) ? 111673 : l
l := t == timestamp(2020, 11, 3) ? 117635 : l
l := t == timestamp(2020, 10, 27) ? 121912 : l
l := t == timestamp(2020, 10, 20) ? 115273 : l
l := t == timestamp(2020, 10, 13) ? 119238 : l
l := t == timestamp(2020, 10, 6) ? 113124 : l
l := t == timestamp(2020, 9, 29) ? 105948 : l
l := t == timestamp(2020, 9, 22) ? 101427 : l
l := t == timestamp(2020, 9, 15) ? 132315 : l
l := t == timestamp(2020, 9, 8) ? 142424 : l
l := t == timestamp(2020, 9, 1) ? 157956 : l
l := t == timestamp(2020, 8, 25) ? 153864 : l
l := t == timestamp(2020, 8, 18) ? 149452 : l
l := t == timestamp(2020, 8, 11) ? 151903 : l
l := t == timestamp(2020, 8, 4) ? 148605 : l
l := t == timestamp(2020, 7, 28) ? 143699 : l
l := t == timestamp(2020, 7, 21) ? 147605 : l
l := t == timestamp(2020, 7, 14) ? 142406 : l
l := t == timestamp(2020, 7, 7) ? 140764 : l
l := t == timestamp(2020, 6, 30) ? 144993 : l
l := t == timestamp(2020, 6, 23) ? 132727 : l
l := t == timestamp(2020, 6, 16) ? 175084 : l
l := t == timestamp(2020, 6, 9) ? 176043 : l
l := t == timestamp(2020, 6, 2) ? 169723 : l
l := t == timestamp(2020, 5, 26) ? 158153 : l
l := t == timestamp(2020, 5, 19) ? 149622 : l
l := t == timestamp(2020, 5, 12) ? 155533 : l
l := t == timestamp(2020, 5, 5) ? 153452 : l
l := t == timestamp(2020, 4, 28) ? 156015 : l
l := t == timestamp(2020, 4, 21) ? 152992 : l
l := t == timestamp(2020, 4, 14) ? 161964 : l
l := t == timestamp(2020, 4, 7) ? 155315 : l
l := t == timestamp(2020, 3, 31) ? 150499 : l
l := t == timestamp(2020, 3, 24) ? 148511 : l
l := t == timestamp(2020, 3, 17) ? 155541 : l
l := t == timestamp(2020, 3, 10) ? 155054 : l
l := t == timestamp(2020, 3, 3) ? 152179 : l
l := t == timestamp(2020, 2, 25) ? 132590 : l
l := t == timestamp(2020, 2, 18) ? 146139 : l
l := t == timestamp(2020, 2, 11) ? 154340 : l
l := t == timestamp(2020, 2, 4) ? 139602 : l
l := t == timestamp(2020, 1, 28) ? 147789 : l
l := t == timestamp(2020, 1, 21) ? 153935 : l
l := t == timestamp(2020, 1, 14) ? 146643 : l
l := t == timestamp(2020, 1, 7) ? 154267 : l
l := t == timestamp(2019, 12, 31) ? 151746 : l
l := t == timestamp(2019, 12, 24) ? 142308 : l
l := t == timestamp(2019, 12, 17) ? 160640 : l
l := t == timestamp(2019, 12, 10) ? 134775 : l
l := t == timestamp(2019, 12, 3) ? 131232 : l
l := t == timestamp(2019, 11, 26) ? 140658 : l
l := t == timestamp(2019, 11, 19) ? 132220 : l
l := t == timestamp(2019, 11, 12) ? 127586 : l
l := t == timestamp(2019, 11, 5) ? 128662 : l
l := t == timestamp(2019, 10, 29) ? 116854 : l
l := t == timestamp(2019, 10, 22) ? 107934 : l
l := t == timestamp(2019, 10, 15) ? 101051 : l
l := t == timestamp(2019, 10, 8) ? 90398 : l
l := t == timestamp(2019, 10, 1) ? 93214 : l
l := t == timestamp(2019, 9, 24) ? 98334 : l
l := t == timestamp(2019, 9, 17) ? 127146 : l
l := t == timestamp(2019, 9, 10) ? 126444 : l
l := t == timestamp(2019, 9, 3) ? 115296 : l
l := t == timestamp(2019, 8, 27) ? 107351 : l
l := t == timestamp(2019, 8, 20) ? 104167 : l
l := t == timestamp(2019, 8, 13) ? 106956 : l
l := t == timestamp(2019, 8, 6) ? 104957 : l
l := t == timestamp(2019, 7, 30) ? 126266 : l
l := t == timestamp(2019, 7, 23) ? 125616 : l
l := t == timestamp(2019, 7, 16) ? 130828 : l
l := t == timestamp(2019, 7, 9) ? 127832 : l
l := t == timestamp(2019, 7, 2) ? 126902 : l
l := t == timestamp(2019, 6, 25) ? 109065 : l
l := t == timestamp(2019, 6, 18) ? 150084 : l
l := t == timestamp(2019, 6, 11) ? 137685 : l
l := t == timestamp(2019, 6, 4) ? 129135 : l
l := t == timestamp(2019, 5, 28) ? 124505 : l
l := t == timestamp(2019, 5, 21) ? 128336 : l
l := t == timestamp(2019, 5, 14) ? 125234 : l
l := t == timestamp(2019, 5, 7) ? 129835 : l
l := t == timestamp(2019, 4, 30) ? 142201 : l
l := t == timestamp(2019, 4, 23) ? 145611 : l
l := t == timestamp(2019, 4, 16) ? 138999 : l
l := t == timestamp(2019, 4, 9) ? 133703 : l
l := t == timestamp(2019, 4, 2) ? 130006 : l
l := t == timestamp(2019, 3, 26) ? 117644 : l
l := t == timestamp(2019, 3, 19) ? 125302 : l
l := t == timestamp(2019, 3, 12) ? 130068 : l
l := t == timestamp(2019, 3, 5) ? 142104 : l
l := t == timestamp(2019, 2, 26) ? 138158 : l
l := t == timestamp(2019, 2, 19) ? 130580 : l
l := t == timestamp(2019, 2, 12) ? 121280 : l
l := t == timestamp(2019, 2, 5) ? 133663 : l
l := t == timestamp(2019, 1, 29) ? 120312 : l
l := t == timestamp(2019, 1, 22) ? 113282 : l
l := t == timestamp(2019, 1, 15) ? 102650 : l
l := t == timestamp(2019, 1, 8) ? 96084 : l
plot(l, "levfunds", color.purple, 2, plot.style_stepline)
float o = na
o := t == timestamp(2023, 8, 15) ? -114064 : o
o := t == timestamp(2023, 8, 8) ? -96498 : o
o := t == timestamp(2023, 8, 1) ? -85565 : o
o := t == timestamp(2023, 7, 25) ? -69056 : o
o := t == timestamp(2023, 7, 18) ? -93307 : o
o := t == timestamp(2023, 7, 11) ? -114394 : o
o := t == timestamp(2023, 7, 3) ? -140135 : o
o := t == timestamp(2023, 6, 27) ? -120164 : o
o := t == timestamp(2023, 6, 20) ? -180178 : o
o := t == timestamp(2023, 6, 13) ? -253157 : o
o := t == timestamp(2023, 6, 6) ? -170672 : o
o := t == timestamp(2023, 5, 30) ? -174748 : o
o := t == timestamp(2023, 5, 23) ? -149807 : o
o := t == timestamp(2023, 5, 16) ? -170879 : o
o := t == timestamp(2023, 5, 9) ? -160267 : o
o := t == timestamp(2023, 5, 2) ? -180855 : o
o := t == timestamp(2023, 4, 25) ? -28768 : o
o := t == timestamp(2023, 4, 18) ? -30813 : o
o := t == timestamp(2023, 4, 11) ? -27000 : o
o := t == timestamp(2023, 4, 4) ? -28315 : o
o := t == timestamp(2023, 3, 28) ? -23438 : o
o := t == timestamp(2023, 3, 21) ? -18300 : o
o := t == timestamp(2023, 3, 14) ? -23185 : o
o := t == timestamp(2023, 3, 7) ? -23521 : o
o := t == timestamp(2023, 2, 28) ? -18980 : o
o := t == timestamp(2023, 2, 21) ? -17124 : o
o := t == timestamp(2023, 2, 14) ? -11262 : o
o := t == timestamp(2023, 2, 7) ? -8932 : o
o := t == timestamp(2023, 1, 31) ? -5082 : o
o := t == timestamp(2023, 1, 24) ? -7992 : o
o := t == timestamp(2023, 1, 17) ? -5816 : o
o := t == timestamp(2023, 1, 10) ? -8575 : o
o := t == timestamp(2023, 1, 3) ? -8771 : o
o := t == timestamp(2022, 12, 27) ? -7409 : o
o := t == timestamp(2022, 12, 20) ? -6220 : o
o := t == timestamp(2022, 12, 13) ? -3817 : o
o := t == timestamp(2022, 12, 6) ? -1853 : o
o := t == timestamp(2022, 11, 29) ? -368 : o
o := t == timestamp(2022, 11, 22) ? 717 : o
o := t == timestamp(2022, 11, 15) ? 3162 : o
o := t == timestamp(2022, 11, 8) ? 5733 : o
o := t == timestamp(2022, 11, 1) ? 9024 : o
o := t == timestamp(2022, 10, 25) ? 1112 : o
o := t == timestamp(2022, 10, 18) ? 924 : o
o := t == timestamp(2022, 10, 11) ? -603 : o
o := t == timestamp(2022, 10, 4) ? -1331 : o
o := t == timestamp(2022, 9, 27) ? -5662 : o
o := t == timestamp(2022, 9, 20) ? -15057 : o
o := t == timestamp(2022, 9, 13) ? -18032 : o
o := t == timestamp(2022, 9, 6) ? -18416 : o
o := t == timestamp(2022, 8, 30) ? -16899 : o
o := t == timestamp(2022, 8, 23) ? -18866 : o
o := t == timestamp(2022, 8, 16) ? -16456 : o
o := t == timestamp(2022, 8, 9) ? -12904 : o
o := t == timestamp(2022, 8, 2) ? -7852 : o
o := t == timestamp(2022, 7, 26) ? 135 : o
o := t == timestamp(2022, 7, 19) ? -502 : o
o := t == timestamp(2022, 7, 12) ? 2473 : o
o := t == timestamp(2022, 7, 5) ? 3789 : o
o := t == timestamp(2022, 6, 28) ? -4731 : o
o := t == timestamp(2022, 6, 21) ? -7568 : o
o := t == timestamp(2022, 6, 14) ? -5624 : o
o := t == timestamp(2022, 6, 7) ? -9049 : o
o := t == timestamp(2022, 5, 31) ? -7627 : o
o := t == timestamp(2022, 5, 24) ? -7340 : o
o := t == timestamp(2022, 5, 17) ? -20281 : o
o := t == timestamp(2022, 5, 10) ? -26221 : o
o := t == timestamp(2022, 5, 3) ? -35729 : o
o := t == timestamp(2022, 4, 26) ? -33080 : o
o := t == timestamp(2022, 4, 19) ? -38763 : o
o := t == timestamp(2022, 4, 12) ? -36023 : o
o := t == timestamp(2022, 4, 5) ? -34843 : o
o := t == timestamp(2022, 3, 29) ? -35921 : o
o := t == timestamp(2022, 3, 22) ? -30358 : o
o := t == timestamp(2022, 3, 15) ? -28323 : o
o := t == timestamp(2022, 3, 8) ? -26000 : o
o := t == timestamp(2022, 3, 1) ? -27716 : o
o := t == timestamp(2022, 2, 22) ? -28121 : o
o := t == timestamp(2022, 2, 15) ? -29735 : o
o := t == timestamp(2022, 2, 8) ? -37006 : o
o := t == timestamp(2022, 2, 1) ? -42623 : o
o := t == timestamp(2022, 1, 25) ? -40124 : o
o := t == timestamp(2022, 1, 18) ? -44477 : o
o := t == timestamp(2022, 1, 11) ? -47984 : o
o := t == timestamp(2022, 1, 4) ? -44061 : o
o := t == timestamp(2021, 12, 28) ? -43708 : o
o := t == timestamp(2021, 12, 21) ? -42276 : o
o := t == timestamp(2021, 12, 14) ? -43103 : o
o := t == timestamp(2021, 12, 7) ? -43601 : o
o := t == timestamp(2021, 11, 30) ? -54653 : o
o := t == timestamp(2021, 11, 23) ? -58748 : o
o := t == timestamp(2021, 11, 16) ? -56355 : o
o := t == timestamp(2021, 11, 9) ? -55883 : o
o := t == timestamp(2021, 11, 2) ? -54100 : o
o := t == timestamp(2021, 10, 26) ? -53132 : o
o := t == timestamp(2021, 10, 19) ? -50944 : o
o := t == timestamp(2021, 10, 12) ? -45279 : o
o := t == timestamp(2021, 10, 5) ? -48396 : o
o := t == timestamp(2021, 9, 28) ? -50354 : o
o := t == timestamp(2021, 9, 21) ? -46500 : o
o := t == timestamp(2021, 9, 14) ? -51779 : o
o := t == timestamp(2021, 9, 7) ? -48415 : o
o := t == timestamp(2021, 8, 31) ? -46161 : o
o := t == timestamp(2021, 8, 24) ? -46066 : o
o := t == timestamp(2021, 8, 17) ? -43869 : o
o := t == timestamp(2021, 8, 10) ? -41114 : o
o := t == timestamp(2021, 8, 3) ? -39002 : o
o := t == timestamp(2021, 7, 27) ? -34752 : o
o := t == timestamp(2021, 7, 20) ? -38542 : o
o := t == timestamp(2021, 7, 13) ? -43942 : o
o := t == timestamp(2021, 7, 6) ? -44932 : o
o := t == timestamp(2021, 6, 29) ? -42838 : o
o := t == timestamp(2021, 6, 22) ? -42638 : o
o := t == timestamp(2021, 6, 15) ? -49208 : o
o := t == timestamp(2021, 6, 8) ? -47249 : o
o := t == timestamp(2021, 6, 1) ? -43081 : o
o := t == timestamp(2021, 5, 25) ? -39025 : o
o := t == timestamp(2021, 5, 18) ? -35580 : o
o := t == timestamp(2021, 5, 11) ? -36243 : o
o := t == timestamp(2021, 5, 4) ? -35470 : o
o := t == timestamp(2021, 4, 27) ? -36510 : o
o := t == timestamp(2021, 4, 20) ? -35504 : o
o := t == timestamp(2021, 4, 13) ? -38356 : o
o := t == timestamp(2021, 4, 6) ? -41168 : o
o := t == timestamp(2021, 3, 30) ? -38333 : o
o := t == timestamp(2021, 3, 23) ? -36821 : o
o := t == timestamp(2021, 3, 16) ? -46103 : o
o := t == timestamp(2021, 3, 9) ? -42557 : o
o := t == timestamp(2021, 3, 2) ? -44435 : o
o := t == timestamp(2021, 2, 23) ? -39719 : o
o := t == timestamp(2021, 2, 16) ? -43621 : o
o := t == timestamp(2021, 2, 9) ? -49450 : o
o := t == timestamp(2021, 2, 2) ? -47667 : o
o := t == timestamp(2021, 1, 26) ? -51599 : o
o := t == timestamp(2021, 1, 19) ? -48069 : o
o := t == timestamp(2021, 1, 12) ? -46560 : o
o := t == timestamp(2021, 1, 5) ? -52408 : o
o := t == timestamp(2020, 12, 29) ? -45901 : o
o := t == timestamp(2020, 12, 21) ? -45336 : o
o := t == timestamp(2020, 12, 15) ? -48748 : o
o := t == timestamp(2020, 12, 8) ? -50828 : o
o := t == timestamp(2020, 12, 1) ? -49542 : o
o := t == timestamp(2020, 11, 24) ? -52204 : o
o := t == timestamp(2020, 11, 17) ? -47482 : o
o := t == timestamp(2020, 11, 10) ? -46054 : o
o := t == timestamp(2020, 11, 3) ? -35140 : o
o := t == timestamp(2020, 10, 27) ? -41663 : o
o := t == timestamp(2020, 10, 20) ? -50165 : o
o := t == timestamp(2020, 10, 13) ? -51477 : o
o := t == timestamp(2020, 10, 6) ? -48218 : o
o := t == timestamp(2020, 9, 29) ? -41724 : o
o := t == timestamp(2020, 9, 22) ? -47072 : o
o := t == timestamp(2020, 9, 15) ? -48574 : o
o := t == timestamp(2020, 9, 8) ? -58700 : o
o := t == timestamp(2020, 9, 1) ? -68181 : o
o := t == timestamp(2020, 8, 25) ? -67680 : o
o := t == timestamp(2020, 8, 18) ? -66602 : o
o := t == timestamp(2020, 8, 11) ? -62085 : o
o := t == timestamp(2020, 8, 4) ? -59070 : o
o := t == timestamp(2020, 7, 28) ? -53028 : o
o := t == timestamp(2020, 7, 21) ? -56298 : o
o := t == timestamp(2020, 7, 14) ? -55786 : o
o := t == timestamp(2020, 7, 7) ? -55072 : o
o := t == timestamp(2020, 6, 30) ? -50702 : o
o := t == timestamp(2020, 6, 23) ? -52273 : o
o := t == timestamp(2020, 6, 16) ? -53492 : o
o := t == timestamp(2020, 6, 9) ? -62913 : o
o := t == timestamp(2020, 6, 2) ? -59208 : o
o := t == timestamp(2020, 5, 26) ? -55148 : o
o := t == timestamp(2020, 5, 19) ? -54537 : o
o := t == timestamp(2020, 5, 12) ? -56782 : o
o := t == timestamp(2020, 5, 5) ? -54028 : o
o := t == timestamp(2020, 4, 28) ? -50664 : o
o := t == timestamp(2020, 4, 21) ? -52423 : o
o := t == timestamp(2020, 4, 14) ? -49209 : o
o := t == timestamp(2020, 4, 7) ? -40065 : o
o := t == timestamp(2020, 3, 31) ? -43873 : o
o := t == timestamp(2020, 3, 24) ? -2393 : o
o := t == timestamp(2020, 3, 17) ? 37452 : o
o := t == timestamp(2020, 3, 10) ? -1208 : o
o := t == timestamp(2020, 3, 3) ? -9467 : o
o := t == timestamp(2020, 2, 25) ? -21771 : o
o := t == timestamp(2020, 2, 18) ? -28422 : o
o := t == timestamp(2020, 2, 11) ? -18927 : o
o := t == timestamp(2020, 2, 4) ? -18045 : o
o := t == timestamp(2020, 1, 28) ? -18767 : o
o := t == timestamp(2020, 1, 21) ? -32949 : o
o := t == timestamp(2020, 1, 14) ? -36545 : o
o := t == timestamp(2020, 1, 7) ? -41070 : o
o := t == timestamp(2019, 12, 31) ? -40130 : o
o := t == timestamp(2019, 12, 24) ? -43197 : o
o := t == timestamp(2019, 12, 17) ? -47717 : o
o := t == timestamp(2019, 12, 10) ? -41610 : o
o := t == timestamp(2019, 12, 3) ? -39052 : o
o := t == timestamp(2019, 11, 26) ? -40404 : o
o := t == timestamp(2019, 11, 19) ? -46085 : o
o := t == timestamp(2019, 11, 12) ? -50659 : o
o := t == timestamp(2019, 11, 5) ? -48338 : o
o := t == timestamp(2019, 10, 29) ? -51119 : o
o := t == timestamp(2019, 10, 22) ? -51863 : o
o := t == timestamp(2019, 10, 15) ? -49676 : o
o := t == timestamp(2019, 10, 8) ? -47913 : o
o := t == timestamp(2019, 10, 1) ? -51216 : o
o := t == timestamp(2019, 9, 24) ? -51316 : o
o := t == timestamp(2019, 9, 17) ? -55372 : o
o := t == timestamp(2019, 9, 10) ? -53227 : o
o := t == timestamp(2019, 9, 3) ? -50264 : o
o := t == timestamp(2019, 8, 27) ? -46179 : o
o := t == timestamp(2019, 8, 20) ? -44793 : o
o := t == timestamp(2019, 8, 13) ? -48393 : o
o := t == timestamp(2019, 8, 6) ? -48013 : o
o := t == timestamp(2019, 7, 30) ? -46900 : o
o := t == timestamp(2019, 7, 23) ? -48457 : o
o := t == timestamp(2019, 7, 16) ? -48366 : o
o := t == timestamp(2019, 7, 9) ? -49373 : o
o := t == timestamp(2019, 7, 2) ? -51007 : o
o := t == timestamp(2019, 6, 25) ? -53035 : o
o := t == timestamp(2019, 6, 18) ? -44853 : o
o := t == timestamp(2019, 6, 11) ? -43457 : o
o := t == timestamp(2019, 6, 4) ? -37904 : o
o := t == timestamp(2019, 5, 28) ? -36454 : o
o := t == timestamp(2019, 5, 21) ? -38879 : o
o := t == timestamp(2019, 5, 14) ? -36196 : o
o := t == timestamp(2019, 5, 7) ? -45776 : o
o := t == timestamp(2019, 4, 30) ? -42930 : o
o := t == timestamp(2019, 4, 23) ? -41252 : o
o := t == timestamp(2019, 4, 16) ? -41178 : o
o := t == timestamp(2019, 4, 9) ? -41847 : o
o := t == timestamp(2019, 4, 2) ? -39627 : o
o := t == timestamp(2019, 3, 26) ? -40106 : o
o := t == timestamp(2019, 3, 19) ? -38269 : o
o := t == timestamp(2019, 3, 12) ? -39076 : o
o := t == timestamp(2019, 3, 5) ? -40350 : o
o := t == timestamp(2019, 2, 26) ? -37783 : o
o := t == timestamp(2019, 2, 19) ? -34396 : o
o := t == timestamp(2019, 2, 12) ? -34127 : o
o := t == timestamp(2019, 2, 5) ? -33197 : o
o := t == timestamp(2019, 1, 29) ? -24456 : o
o := t == timestamp(2019, 1, 22) ? -19721 : o
o := t == timestamp(2019, 1, 15) ? -14253 : o
o := t == timestamp(2019, 1, 8) ? -5411 : o
plot(o, "other", color.orange, 2, plot.style_stepline) |
text_utils | https://www.tradingview.com/script/OS4xxXo4/ | Kaspricci | https://www.tradingview.com/u/Kaspricci/ | 1 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kaspricci
//@version=5
// @description a set of functions to handle placeholder in texts
library("text_utils")
// user defined type placeholder to be used in your local script to creat an array of placeholder objects e.g. array<placeholder> list = array.new<placeholder>()
export type placeholder
string key
string value
// @function add a placehodler key and value to a local list
// @param list - reference to a local string array containing all placeholders, add string[] list = array.new_string(0) to your code
// @param key - a string representing the placeholder in a text, e.g. '{ticker}'
// @param value - a string representing the value of the placeholder e.g. 'EURUSD'
// @returns void
export add_placeholder(string[] list, string key, string value) =>
// add key and string value to placeholder list
array.push(list, key + "=" + value)
// @function add a placehodler key and value to a local list
// @param list - reference to a local array of user defined type placeholder containing all placeholders, add "array<placeholder> list = array.new<placeholder>()" to your code
// @param key - a string representing the placeholder in a text, e.g. '{ticker}'
// @param value - a string representing the value of the placeholder e.g. 'EURUSD'
// @returns void
export add_placeholder(array<placeholder> list, string key, string value) =>
// add key and string value to placeholder list
newPlaceholder = placeholder.new(key, value)
array.push(list, newPlaceholder)
// @function add a placehodler key and value to a local list
// @param list - reference to a local string array containing all placeholders, add string[] list = array.new_string(0) to your code
// @param key - a string representing the placeholder in a text, e.g. '{ticker}'
// @param value - an integer value representing the value of the placeholder e.g. 10
// @param format - optional format string to be used when converting integer value to string, see str.format() for details, must contain '{0}'
// @returns void
export add_placeholder(string[] list, string key, int value, string format = "") =>
// set default fromat string
formatString = format == "" ? "{0}" : format
// add key and int value to placeholder list
array.push(list, key + "=" + str.format(formatString, value))
// @function add a placehodler key and value to a local list
// @param list - reference to a local array of user defined type placeholder containing all placeholders, add "array<placeholder> list = array.new<placeholder>()" to your code
// @param key - a string representing the placeholder in a text, e.g. '{quantity}'
// @param value - an integer value representing the value of the placeholder e.g. 10
// @param format - optional format string to be used when converting integer value to string, see str.format() for details, must contain '{0}'
// @returns void
export add_placeholder(array<placeholder> list, string key, int value, string format = "") =>
// set default fromat string
formatString = format == "" ? "{0}" : format
// add key and string value to placeholder list
newPlaceholder = placeholder.new(key, str.format(formatString, value))
array.push(list, newPlaceholder)
// @function add a placehodler key and value to a local list
// @param list - reference to a local string array containing all placeholders, add string[] list = array.new_string(0) to your code
// @param key - a string representing the placeholder in a text, e.g. '{ticker}'
// @param value - a float value representing the value of the placeholder e.g. 1.5
// @param format - optional format string to be used when converting float value to string, see str.format() for details, must contain '{0}'
// @returns void
export add_placeholder(string[] list, string key, float value, string format = "") =>
// set default fromat string
formatString = format == "" ? "{0}" : format
// add key and int value to placeholder list
array.push(list, key + "=" + str.format(formatString, value))
// @function add a placehodler key and value to a local list
// @param list - reference to a local array of user defined type placeholder containing all placeholders, add "array<placeholder> list = array.new<placeholder>()" to your code
// @param key - a string representing the placeholder in a text, e.g. '{quantity}'
// @param value - a float value representing the value of the placeholder e.g. 1.5
// @param format - optional format string to be used when converting integer value to string, see str.format() for details, must contain '{0}'
// @returns void
export add_placeholder(array<placeholder> list, string key, float value, string format = "") =>
// set default fromat string
formatString = format == "" ? "{0}" : format
// add key and string value to placeholder list
newPlaceholder = placeholder.new(key, str.format(formatString, value))
array.push(list, newPlaceholder)
// @function replace all placeholder keys with their value in a given text
// @param list - reference to a local string array containing all placeholders
// @param text_to_covert - a text with placeholder keys before their are replaced by their values
// @returns text with all replaced placeholder keys
export replace_all_placeholder(string[] list, string text_to_convert) =>
// get number of defined placeholders
n = nz(array.size(list), 0)
// save text locally
tempText = text_to_convert
// check if there is at least one placeholder defined
if (n > 1)
// replace all placeholders by their values
for i = 0 to n - 1
element = array.get(list, i)
values = str.split(element, "=") // returns a string array with key and value separated
key = array.get(values, 0)
value = array.get(values, 1)
tempText := str.replace_all(tempText, key, value)
// return text with replaced variables
tempText
// @function replace all placeholder keys with their value in a given text
// @param list - reference to a local array of user defined type placeholder containing all placeholders
// @param text_to_covert - a text with placeholder keys before they are replaced by their values
// @returns text with all replaced placeholder keys
export replace_all_placeholder(array<placeholder> list, string text_to_convert) =>
// get number of defined placeholders
n = nz(array.size(list), 0)
// save text locally
tempText = text_to_convert
// check if there is at least one placeholder defined
if (n > 1)
// replace all placeholders by their values
for i = 0 to n - 1
element = array.get(list, i)
key = element.key
value = element.value
tempText := str.replace_all(tempText, key, value)
// return text with replaced variables
tempText |
COT TFF Data (VIX_FUTURES) | https://www.tradingview.com/script/uijdnPNm-COT-TFF-Data-VIX-FUTURES/ | rippydave | https://www.tradingview.com/u/rippydave/ | 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/
// © dave50894
//@version=5
plot(close)
indicator("COT TFF Data (VIX_FUTURES)", overlay=false)
float d = na
t = timestamp(year, month, dayofmonth)
d := t == timestamp(2023, 8, 15) ? 16473 : d
d := t == timestamp(2023, 8, 8) ? 24540 : d
d := t == timestamp(2023, 8, 1) ? 25803 : d
d := t == timestamp(2023, 7, 25) ? 28807 : d
d := t == timestamp(2023, 7, 18) ? 32936 : d
d := t == timestamp(2023, 7, 11) ? 31750 : d
d := t == timestamp(2023, 7, 3) ? 32031 : d
d := t == timestamp(2023, 6, 27) ? 36922 : d
d := t == timestamp(2023, 6, 20) ? 27455 : d
d := t == timestamp(2023, 6, 13) ? 23187 : d
d := t == timestamp(2023, 6, 6) ? 19355 : d
d := t == timestamp(2023, 5, 30) ? 14489 : d
d := t == timestamp(2023, 5, 23) ? 22092 : d
d := t == timestamp(2023, 5, 16) ? 10701 : d
d := t == timestamp(2023, 5, 9) ? 20827 : d
d := t == timestamp(2023, 5, 2) ? 28284 : d
d := t == timestamp(2023, 4, 25) ? 24363 : d
d := t == timestamp(2023, 4, 18) ? 14925 : d
d := t == timestamp(2023, 4, 11) ? 13046 : d
d := t == timestamp(2023, 4, 4) ? 14663 : d
d := t == timestamp(2023, 3, 28) ? 14024 : d
d := t == timestamp(2023, 3, 21) ? 24932 : d
d := t == timestamp(2023, 3, 14) ? 31886 : d
d := t == timestamp(2023, 3, 7) ? 23775 : d
d := t == timestamp(2023, 2, 28) ? 21932 : d
d := t == timestamp(2023, 2, 21) ? 22638 : d
d := t == timestamp(2023, 2, 14) ? 26784 : d
d := t == timestamp(2023, 2, 7) ? 28432 : d
d := t == timestamp(2023, 1, 31) ? 22205 : d
d := t == timestamp(2023, 1, 24) ? 23166 : d
d := t == timestamp(2023, 1, 17) ? 20524 : d
d := t == timestamp(2023, 1, 10) ? 25520 : d
d := t == timestamp(2023, 1, 3) ? 24643 : d
d := t == timestamp(2022, 12, 27) ? 26574 : d
d := t == timestamp(2022, 12, 20) ? 26188 : d
d := t == timestamp(2022, 12, 13) ? 18209 : d
d := t == timestamp(2022, 12, 6) ? 19584 : d
d := t == timestamp(2022, 11, 29) ? 17368 : d
d := t == timestamp(2022, 11, 22) ? 18435 : d
d := t == timestamp(2022, 11, 15) ? 20302 : d
d := t == timestamp(2022, 11, 8) ? 21091 : d
d := t == timestamp(2022, 11, 1) ? 19665 : d
d := t == timestamp(2022, 10, 25) ? 16618 : d
d := t == timestamp(2022, 10, 18) ? 16422 : d
d := t == timestamp(2022, 10, 11) ? 21713 : d
d := t == timestamp(2022, 10, 4) ? 22118 : d
d := t == timestamp(2022, 9, 27) ? 30462 : d
d := t == timestamp(2022, 9, 20) ? 17723 : d
d := t == timestamp(2022, 9, 13) ? 14444 : d
d := t == timestamp(2022, 9, 6) ? 14692 : d
d := t == timestamp(2022, 8, 30) ? 12752 : d
d := t == timestamp(2022, 8, 23) ? 14584 : d
d := t == timestamp(2022, 8, 16) ? 12686 : d
d := t == timestamp(2022, 8, 9) ? 12398 : d
d := t == timestamp(2022, 8, 2) ? 11239 : d
d := t == timestamp(2022, 7, 26) ? 13528 : d
d := t == timestamp(2022, 7, 19) ? 13922 : d
d := t == timestamp(2022, 7, 12) ? 11869 : d
d := t == timestamp(2022, 7, 5) ? 14895 : d
d := t == timestamp(2022, 6, 28) ? 8334 : d
d := t == timestamp(2022, 6, 21) ? 7732 : d
d := t == timestamp(2022, 6, 14) ? 14582 : d
d := t == timestamp(2022, 6, 7) ? 9361 : d
d := t == timestamp(2022, 5, 31) ? 7139 : d
d := t == timestamp(2022, 5, 24) ? 13074 : d
d := t == timestamp(2022, 5, 17) ? 11020 : d
d := t == timestamp(2022, 5, 10) ? 10595 : d
d := t == timestamp(2022, 5, 3) ? 12436 : d
d := t == timestamp(2022, 4, 26) ? 18782 : d
d := t == timestamp(2022, 4, 19) ? 20128 : d
d := t == timestamp(2022, 4, 12) ? 16226 : d
d := t == timestamp(2022, 4, 5) ? 17898 : d
d := t == timestamp(2022, 3, 29) ? 20234 : d
d := t == timestamp(2022, 3, 22) ? 13338 : d
d := t == timestamp(2022, 3, 15) ? 11198 : d
d := t == timestamp(2022, 3, 8) ? 13843 : d
d := t == timestamp(2022, 3, 1) ? 14831 : d
d := t == timestamp(2022, 2, 22) ? 13585 : d
d := t == timestamp(2022, 2, 15) ? 20038 : d
d := t == timestamp(2022, 2, 8) ? 21113 : d
d := t == timestamp(2022, 2, 1) ? 16250 : d
d := t == timestamp(2022, 1, 25) ? 26020 : d
d := t == timestamp(2022, 1, 18) ? 27161 : d
d := t == timestamp(2022, 1, 11) ? 30828 : d
d := t == timestamp(2022, 1, 4) ? 31253 : d
d := t == timestamp(2021, 12, 28) ? 19702 : d
d := t == timestamp(2021, 12, 21) ? 19221 : d
d := t == timestamp(2021, 12, 14) ? 24950 : d
d := t == timestamp(2021, 12, 7) ? 23431 : d
d := t == timestamp(2021, 11, 30) ? 32811 : d
d := t == timestamp(2021, 11, 23) ? 42435 : d
d := t == timestamp(2021, 11, 16) ? 40910 : d
d := t == timestamp(2021, 11, 9) ? 43118 : d
d := t == timestamp(2021, 11, 2) ? 49050 : d
d := t == timestamp(2021, 10, 26) ? 49101 : d
d := t == timestamp(2021, 10, 19) ? 41710 : d
d := t == timestamp(2021, 10, 12) ? 30976 : d
d := t == timestamp(2021, 10, 5) ? 31620 : d
d := t == timestamp(2021, 9, 28) ? 29401 : d
d := t == timestamp(2021, 9, 21) ? 27564 : d
d := t == timestamp(2021, 9, 14) ? 38215 : d
d := t == timestamp(2021, 9, 7) ? 44995 : d
d := t == timestamp(2021, 8, 31) ? 46215 : d
d := t == timestamp(2021, 8, 24) ? 34994 : d
d := t == timestamp(2021, 8, 17) ? 37514 : d
d := t == timestamp(2021, 8, 10) ? 33836 : d
d := t == timestamp(2021, 8, 3) ? 32195 : d
d := t == timestamp(2021, 7, 27) ? 35921 : d
d := t == timestamp(2021, 7, 20) ? 32326 : d
d := t == timestamp(2021, 7, 13) ? 33515 : d
d := t == timestamp(2021, 7, 6) ? 38294 : d
d := t == timestamp(2021, 6, 29) ? 34627 : d
d := t == timestamp(2021, 6, 22) ? 35394 : d
d := t == timestamp(2021, 6, 15) ? 34846 : d
d := t == timestamp(2021, 6, 8) ? 42127 : d
d := t == timestamp(2021, 6, 1) ? 40688 : d
d := t == timestamp(2021, 5, 25) ? 35875 : d
d := t == timestamp(2021, 5, 18) ? 39135 : d
d := t == timestamp(2021, 5, 11) ? 52885 : d
d := t == timestamp(2021, 5, 4) ? 60705 : d
d := t == timestamp(2021, 4, 27) ? 51312 : d
d := t == timestamp(2021, 4, 20) ? 54897 : d
d := t == timestamp(2021, 4, 13) ? 53431 : d
d := t == timestamp(2021, 4, 6) ? 45866 : d
d := t == timestamp(2021, 3, 30) ? 37431 : d
d := t == timestamp(2021, 3, 23) ? 36586 : d
d := t == timestamp(2021, 3, 16) ? 34209 : d
d := t == timestamp(2021, 3, 9) ? 41040 : d
d := t == timestamp(2021, 3, 2) ? 38769 : d
d := t == timestamp(2021, 2, 23) ? 36131 : d
d := t == timestamp(2021, 2, 16) ? 25497 : d
d := t == timestamp(2021, 2, 9) ? 20212 : d
d := t == timestamp(2021, 2, 2) ? 21763 : d
d := t == timestamp(2021, 1, 26) ? 24164 : d
d := t == timestamp(2021, 1, 19) ? 16508 : d
d := t == timestamp(2021, 1, 12) ? 22994 : d
d := t == timestamp(2021, 1, 5) ? 19421 : d
d := t == timestamp(2020, 12, 29) ? 21962 : d
d := t == timestamp(2020, 12, 21) ? 26048 : d
d := t == timestamp(2020, 12, 15) ? 25919 : d
d := t == timestamp(2020, 12, 8) ? 25754 : d
d := t == timestamp(2020, 12, 1) ? 16787 : d
d := t == timestamp(2020, 11, 24) ? 12085 : d
d := t == timestamp(2020, 11, 17) ? 6391 : d
d := t == timestamp(2020, 11, 10) ? 5672 : d
d := t == timestamp(2020, 11, 3) ? 1419 : d
d := t == timestamp(2020, 10, 27) ? 10391 : d
d := t == timestamp(2020, 10, 20) ? 9115 : d
d := t == timestamp(2020, 10, 13) ? 15301 : d
d := t == timestamp(2020, 10, 6) ? 8494 : d
d := t == timestamp(2020, 9, 29) ? 12527 : d
d := t == timestamp(2020, 9, 22) ? 14830 : d
d := t == timestamp(2020, 9, 15) ? 10861 : d
d := t == timestamp(2020, 9, 8) ? 4530 : d
d := t == timestamp(2020, 9, 1) ? 4507 : d
d := t == timestamp(2020, 8, 25) ? 9200 : d
d := t == timestamp(2020, 8, 18) ? 8887 : d
d := t == timestamp(2020, 8, 11) ? 4402 : d
d := t == timestamp(2020, 8, 4) ? 2401 : d
d := t == timestamp(2020, 7, 28) ? -194 : d
d := t == timestamp(2020, 7, 21) ? 6168 : d
d := t == timestamp(2020, 7, 14) ? 3529 : d
d := t == timestamp(2020, 7, 7) ? 2036 : d
d := t == timestamp(2020, 6, 30) ? 13368 : d
d := t == timestamp(2020, 6, 23) ? 22343 : d
d := t == timestamp(2020, 6, 16) ? 24981 : d
d := t == timestamp(2020, 6, 9) ? 32807 : d
d := t == timestamp(2020, 6, 2) ? 35214 : d
d := t == timestamp(2020, 5, 26) ? 33843 : d
d := t == timestamp(2020, 5, 19) ? 37813 : d
d := t == timestamp(2020, 5, 12) ? 29447 : d
d := t == timestamp(2020, 5, 5) ? 23128 : d
d := t == timestamp(2020, 4, 28) ? 20675 : d
d := t == timestamp(2020, 4, 21) ? 19450 : d
d := t == timestamp(2020, 4, 14) ? 18083 : d
d := t == timestamp(2020, 4, 7) ? 16135 : d
d := t == timestamp(2020, 3, 31) ? 8089 : d
d := t == timestamp(2020, 3, 24) ? -8465 : d
d := t == timestamp(2020, 3, 17) ? -38256 : d
d := t == timestamp(2020, 3, 10) ? -22857 : d
d := t == timestamp(2020, 3, 3) ? -10416 : d
d := t == timestamp(2020, 2, 25) ? 42092 : d
d := t == timestamp(2020, 2, 18) ? 61164 : d
d := t == timestamp(2020, 2, 11) ? 64382 : d
d := t == timestamp(2020, 2, 4) ? 63392 : d
d := t == timestamp(2020, 1, 28) ? 72091 : d
d := t == timestamp(2020, 1, 21) ? 68504 : d
d := t == timestamp(2020, 1, 14) ? 70704 : d
d := t == timestamp(2020, 1, 7) ? 70724 : d
d := t == timestamp(2019, 12, 31) ? 74630 : d
d := t == timestamp(2019, 12, 24) ? 80081 : d
d := t == timestamp(2019, 12, 17) ? 81034 : d
d := t == timestamp(2019, 12, 10) ? 82711 : d
d := t == timestamp(2019, 12, 3) ? 97483 : d
d := t == timestamp(2019, 11, 26) ? 105468 : d
d := t == timestamp(2019, 11, 19) ? 116998 : d
d := t == timestamp(2019, 11, 12) ? 108192 : d
d := t == timestamp(2019, 11, 5) ? 97823 : d
d := t == timestamp(2019, 10, 29) ? 89265 : d
d := t == timestamp(2019, 10, 22) ? 86194 : d
d := t == timestamp(2019, 10, 15) ? 69425 : d
d := t == timestamp(2019, 10, 8) ? 61202 : d
d := t == timestamp(2019, 10, 1) ? 82107 : d
d := t == timestamp(2019, 9, 24) ? 86695 : d
d := t == timestamp(2019, 9, 17) ? 70489 : d
d := t == timestamp(2019, 9, 10) ? 49865 : d
d := t == timestamp(2019, 9, 3) ? 31740 : d
d := t == timestamp(2019, 8, 27) ? 37849 : d
d := t == timestamp(2019, 8, 20) ? 46195 : d
d := t == timestamp(2019, 8, 13) ? 56645 : d
d := t == timestamp(2019, 8, 6) ? 67332 : d
d := t == timestamp(2019, 7, 30) ? 96399 : d
d := t == timestamp(2019, 7, 23) ? 94771 : d
d := t == timestamp(2019, 7, 16) ? 78986 : d
d := t == timestamp(2019, 7, 9) ? 74225 : d
d := t == timestamp(2019, 7, 2) ? 57263 : d
d := t == timestamp(2019, 6, 25) ? 56703 : d
d := t == timestamp(2019, 6, 18) ? 25832 : d
d := t == timestamp(2019, 6, 11) ? 19097 : d
d := t == timestamp(2019, 6, 4) ? 17387 : d
d := t == timestamp(2019, 5, 28) ? 33035 : d
d := t == timestamp(2019, 5, 21) ? 29681 : d
d := t == timestamp(2019, 5, 14) ? 19714 : d
d := t == timestamp(2019, 5, 7) ? 60919 : d
d := t == timestamp(2019, 4, 30) ? 76559 : d
d := t == timestamp(2019, 4, 23) ? 79793 : d
d := t == timestamp(2019, 4, 16) ? 82140 : d
d := t == timestamp(2019, 4, 9) ? 71246 : d
d := t == timestamp(2019, 4, 2) ? 62235 : d
d := t == timestamp(2019, 3, 26) ? 39643 : d
d := t == timestamp(2019, 3, 19) ? 41241 : d
d := t == timestamp(2019, 3, 12) ? 32913 : d
d := t == timestamp(2019, 3, 5) ? 36414 : d
d := t == timestamp(2019, 2, 26) ? 32497 : d
d := t == timestamp(2019, 2, 19) ? 28328 : d
d := t == timestamp(2019, 2, 12) ? 23236 : d
d := t == timestamp(2019, 2, 5) ? 3338 : d
d := t == timestamp(2019, 1, 29) ? -19079 : d
d := t == timestamp(2019, 1, 22) ? -17584 : d
d := t == timestamp(2019, 1, 15) ? -34512 : d
d := t == timestamp(2019, 1, 8) ? -52718 : d
plot(d, "dealer", color.red, 2, plot.style_stepline)
float a = na
a := t == timestamp(2023, 8, 15) ? 15745 : a
a := t == timestamp(2023, 8, 8) ? 22186 : a
a := t == timestamp(2023, 8, 1) ? 21810 : a
a := t == timestamp(2023, 7, 25) ? 15382 : a
a := t == timestamp(2023, 7, 18) ? 7202 : a
a := t == timestamp(2023, 7, 11) ? 20728 : a
a := t == timestamp(2023, 7, 3) ? 2795 : a
a := t == timestamp(2023, 6, 27) ? -5178 : a
a := t == timestamp(2023, 6, 20) ? 3284 : a
a := t == timestamp(2023, 6, 13) ? 11461 : a
a := t == timestamp(2023, 6, 6) ? 12770 : a
a := t == timestamp(2023, 5, 30) ? 29572 : a
a := t == timestamp(2023, 5, 23) ? 23571 : a
a := t == timestamp(2023, 5, 16) ? 27668 : a
a := t == timestamp(2023, 5, 9) ? 20702 : a
a := t == timestamp(2023, 5, 2) ? 20564 : a
a := t == timestamp(2023, 4, 25) ? 18613 : a
a := t == timestamp(2023, 4, 18) ? 4838 : a
a := t == timestamp(2023, 4, 11) ? -7177 : a
a := t == timestamp(2023, 4, 4) ? -9818 : a
a := t == timestamp(2023, 3, 28) ? 1317 : a
a := t == timestamp(2023, 3, 21) ? 2148 : a
a := t == timestamp(2023, 3, 14) ? 5061 : a
a := t == timestamp(2023, 3, 7) ? 2914 : a
a := t == timestamp(2023, 2, 28) ? 16763 : a
a := t == timestamp(2023, 2, 21) ? 23795 : a
a := t == timestamp(2023, 2, 14) ? 8355 : a
a := t == timestamp(2023, 2, 7) ? 7592 : a
a := t == timestamp(2023, 1, 31) ? -1822 : a
a := t == timestamp(2023, 1, 24) ? 1662 : a
a := t == timestamp(2023, 1, 17) ? 6686 : a
a := t == timestamp(2023, 1, 10) ? 9510 : a
a := t == timestamp(2023, 1, 3) ? -12383 : a
a := t == timestamp(2022, 12, 27) ? -2872 : a
a := t == timestamp(2022, 12, 20) ? 2120 : a
a := t == timestamp(2022, 12, 13) ? 14058 : a
a := t == timestamp(2022, 12, 6) ? 19317 : a
a := t == timestamp(2022, 11, 29) ? 31192 : a
a := t == timestamp(2022, 11, 22) ? 18830 : a
a := t == timestamp(2022, 11, 15) ? 32054 : a
a := t == timestamp(2022, 11, 8) ? 22684 : a
a := t == timestamp(2022, 11, 1) ? 12722 : a
a := t == timestamp(2022, 10, 25) ? 36421 : a
a := t == timestamp(2022, 10, 18) ? 40164 : a
a := t == timestamp(2022, 10, 11) ? 44553 : a
a := t == timestamp(2022, 10, 4) ? 43307 : a
a := t == timestamp(2022, 9, 27) ? 41887 : a
a := t == timestamp(2022, 9, 20) ? 41118 : a
a := t == timestamp(2022, 9, 13) ? 52073 : a
a := t == timestamp(2022, 9, 6) ? 41246 : a
a := t == timestamp(2022, 8, 30) ? 55253 : a
a := t == timestamp(2022, 8, 23) ? 48941 : a
a := t == timestamp(2022, 8, 16) ? 45750 : a
a := t == timestamp(2022, 8, 9) ? 47263 : a
a := t == timestamp(2022, 8, 2) ? 46594 : a
a := t == timestamp(2022, 7, 26) ? 54003 : a
a := t == timestamp(2022, 7, 19) ? 45347 : a
a := t == timestamp(2022, 7, 12) ? 52960 : a
a := t == timestamp(2022, 7, 5) ? 56926 : a
a := t == timestamp(2022, 6, 28) ? 71255 : a
a := t == timestamp(2022, 6, 21) ? 67724 : a
a := t == timestamp(2022, 6, 14) ? 59215 : a
a := t == timestamp(2022, 6, 7) ? 41977 : a
a := t == timestamp(2022, 5, 31) ? 42819 : a
a := t == timestamp(2022, 5, 24) ? 39122 : a
a := t == timestamp(2022, 5, 17) ? 33474 : a
a := t == timestamp(2022, 5, 10) ? 56930 : a
a := t == timestamp(2022, 5, 3) ? 53697 : a
a := t == timestamp(2022, 4, 26) ? 39166 : a
a := t == timestamp(2022, 4, 19) ? 29420 : a
a := t == timestamp(2022, 4, 12) ? 36953 : a
a := t == timestamp(2022, 4, 5) ? 29953 : a
a := t == timestamp(2022, 3, 29) ? 31920 : a
a := t == timestamp(2022, 3, 22) ? 32421 : a
a := t == timestamp(2022, 3, 15) ? 44970 : a
a := t == timestamp(2022, 3, 8) ? 53232 : a
a := t == timestamp(2022, 3, 1) ? 62635 : a
a := t == timestamp(2022, 2, 22) ? 57294 : a
a := t == timestamp(2022, 2, 15) ? 44020 : a
a := t == timestamp(2022, 2, 8) ? 26815 : a
a := t == timestamp(2022, 2, 1) ? 41045 : a
a := t == timestamp(2022, 1, 25) ? 37482 : a
a := t == timestamp(2022, 1, 18) ? 18802 : a
a := t == timestamp(2022, 1, 11) ? 11383 : a
a := t == timestamp(2022, 1, 4) ? 18168 : a
a := t == timestamp(2021, 12, 28) ? 30261 : a
a := t == timestamp(2021, 12, 21) ? 39578 : a
a := t == timestamp(2021, 12, 14) ? 46789 : a
a := t == timestamp(2021, 12, 7) ? 63353 : a
a := t == timestamp(2021, 11, 30) ? 62071 : a
a := t == timestamp(2021, 11, 23) ? 38550 : a
a := t == timestamp(2021, 11, 16) ? 26027 : a
a := t == timestamp(2021, 11, 9) ? 16650 : a
a := t == timestamp(2021, 11, 2) ? -13524 : a
a := t == timestamp(2021, 10, 26) ? -3245 : a
a := t == timestamp(2021, 10, 19) ? -89 : a
a := t == timestamp(2021, 10, 12) ? 16771 : a
a := t == timestamp(2021, 10, 5) ? 37818 : a
a := t == timestamp(2021, 9, 28) ? 42336 : a
a := t == timestamp(2021, 9, 21) ? 56300 : a
a := t == timestamp(2021, 9, 14) ? 33228 : a
a := t == timestamp(2021, 9, 7) ? 17530 : a
a := t == timestamp(2021, 8, 31) ? 11610 : a
a := t == timestamp(2021, 8, 24) ? 18967 : a
a := t == timestamp(2021, 8, 17) ? 10388 : a
a := t == timestamp(2021, 8, 10) ? 24062 : a
a := t == timestamp(2021, 8, 3) ? 41581 : a
a := t == timestamp(2021, 7, 27) ? 37328 : a
a := t == timestamp(2021, 7, 20) ? 45961 : a
a := t == timestamp(2021, 7, 13) ? 32953 : a
a := t == timestamp(2021, 7, 6) ? 24490 : a
a := t == timestamp(2021, 6, 29) ? 26290 : a
a := t == timestamp(2021, 6, 22) ? 19173 : a
a := t == timestamp(2021, 6, 15) ? 19598 : a
a := t == timestamp(2021, 6, 8) ? 15081 : a
a := t == timestamp(2021, 6, 1) ? 29169 : a
a := t == timestamp(2021, 5, 25) ? 50631 : a
a := t == timestamp(2021, 5, 18) ? 51843 : a
a := t == timestamp(2021, 5, 11) ? 55372 : a
a := t == timestamp(2021, 5, 4) ? 38772 : a
a := t == timestamp(2021, 4, 27) ? 35437 : a
a := t == timestamp(2021, 4, 20) ? 27560 : a
a := t == timestamp(2021, 4, 13) ? 37475 : a
a := t == timestamp(2021, 4, 6) ? 53372 : a
a := t == timestamp(2021, 3, 30) ? 68048 : a
a := t == timestamp(2021, 3, 23) ? 74611 : a
a := t == timestamp(2021, 3, 16) ? 78521 : a
a := t == timestamp(2021, 3, 9) ? 92864 : a
a := t == timestamp(2021, 3, 2) ? 99636 : a
a := t == timestamp(2021, 2, 23) ? 99267 : a
a := t == timestamp(2021, 2, 16) ? 94243 : a
a := t == timestamp(2021, 2, 9) ? 82151 : a
a := t == timestamp(2021, 2, 2) ? 87791 : a
a := t == timestamp(2021, 1, 26) ? 80379 : a
a := t == timestamp(2021, 1, 19) ? 82371 : a
a := t == timestamp(2021, 1, 12) ? 72836 : a
a := t == timestamp(2021, 1, 5) ? 78350 : a
a := t == timestamp(2020, 12, 29) ? 61662 : a
a := t == timestamp(2020, 12, 21) ? 60958 : a
a := t == timestamp(2020, 12, 15) ? 62514 : a
a := t == timestamp(2020, 12, 8) ? 53847 : a
a := t == timestamp(2020, 12, 1) ? 59867 : a
a := t == timestamp(2020, 11, 24) ? 67215 : a
a := t == timestamp(2020, 11, 17) ? 67778 : a
a := t == timestamp(2020, 11, 10) ? 76643 : a
a := t == timestamp(2020, 11, 3) ? 98750 : a
a := t == timestamp(2020, 10, 27) ? 67542 : a
a := t == timestamp(2020, 10, 20) ? 45217 : a
a := t == timestamp(2020, 10, 13) ? 39818 : a
a := t == timestamp(2020, 10, 6) ? 37121 : a
a := t == timestamp(2020, 9, 29) ? 27610 : a
a := t == timestamp(2020, 9, 22) ? 30484 : a
a := t == timestamp(2020, 9, 15) ? 27781 : a
a := t == timestamp(2020, 9, 8) ? 48776 : a
a := t == timestamp(2020, 9, 1) ? 55700 : a
a := t == timestamp(2020, 8, 25) ? 53182 : a
a := t == timestamp(2020, 8, 18) ? 52219 : a
a := t == timestamp(2020, 8, 11) ? 60312 : a
a := t == timestamp(2020, 8, 4) ? 69398 : a
a := t == timestamp(2020, 7, 28) ? 74602 : a
a := t == timestamp(2020, 7, 21) ? 68502 : a
a := t == timestamp(2020, 7, 14) ? 78954 : a
a := t == timestamp(2020, 7, 7) ? 74854 : a
a := t == timestamp(2020, 6, 30) ? 74127 : a
a := t == timestamp(2020, 6, 23) ? 60595 : a
a := t == timestamp(2020, 6, 16) ? 55576 : a
a := t == timestamp(2020, 6, 9) ? 35573 : a
a := t == timestamp(2020, 6, 2) ? 30075 : a
a := t == timestamp(2020, 5, 26) ? 23489 : a
a := t == timestamp(2020, 5, 19) ? 33654 : a
a := t == timestamp(2020, 5, 12) ? 29849 : a
a := t == timestamp(2020, 5, 5) ? 46439 : a
a := t == timestamp(2020, 4, 28) ? 43840 : a
a := t == timestamp(2020, 4, 21) ? 46117 : a
a := t == timestamp(2020, 4, 14) ? 45180 : a
a := t == timestamp(2020, 4, 7) ? 51923 : a
a := t == timestamp(2020, 3, 31) ? 37077 : a
a := t == timestamp(2020, 3, 24) ? 35492 : a
a := t == timestamp(2020, 3, 17) ? 77990 : a
a := t == timestamp(2020, 3, 10) ? 77889 : a
a := t == timestamp(2020, 3, 3) ? 93458 : a
a := t == timestamp(2020, 2, 25) ? 60270 : a
a := t == timestamp(2020, 2, 18) ? -1964 : a
a := t == timestamp(2020, 2, 11) ? 233 : a
a := t == timestamp(2020, 2, 4) ? 18313 : a
a := t == timestamp(2020, 1, 28) ? -5774 : a
a := t == timestamp(2020, 1, 21) ? -21217 : a
a := t == timestamp(2020, 1, 14) ? -11082 : a
a := t == timestamp(2020, 1, 7) ? 12349 : a
a := t == timestamp(2019, 12, 31) ? 11854 : a
a := t == timestamp(2019, 12, 24) ? -10890 : a
a := t == timestamp(2019, 12, 17) ? -5565 : a
a := t == timestamp(2019, 12, 10) ? 25235 : a
a := t == timestamp(2019, 12, 3) ? 12598 : a
a := t == timestamp(2019, 11, 26) ? -6069 : a
a := t == timestamp(2019, 11, 19) ? -6977 : a
a := t == timestamp(2019, 11, 12) ? 5754 : a
a := t == timestamp(2019, 11, 5) ? 8158 : a
a := t == timestamp(2019, 10, 29) ? 4004 : a
a := t == timestamp(2019, 10, 22) ? 11122 : a
a := t == timestamp(2019, 10, 15) ? 13758 : a
a := t == timestamp(2019, 10, 8) ? 46308 : a
a := t == timestamp(2019, 10, 1) ? 39352 : a
a := t == timestamp(2019, 9, 24) ? 6721 : a
a := t == timestamp(2019, 9, 17) ? 9843 : a
a := t == timestamp(2019, 9, 10) ? 35174 : a
a := t == timestamp(2019, 9, 3) ? 59853 : a
a := t == timestamp(2019, 8, 27) ? 69600 : a
a := t == timestamp(2019, 8, 20) ? 60821 : a
a := t == timestamp(2019, 8, 13) ? 70975 : a
a := t == timestamp(2019, 8, 6) ? 55963 : a
a := t == timestamp(2019, 7, 30) ? 7997 : a
a := t == timestamp(2019, 7, 23) ? 7345 : a
a := t == timestamp(2019, 7, 16) ? -4367 : a
a := t == timestamp(2019, 7, 9) ? 19875 : a
a := t == timestamp(2019, 7, 2) ? 28105 : a
a := t == timestamp(2019, 6, 25) ? 29834 : a
a := t == timestamp(2019, 6, 18) ? 36981 : a
a := t == timestamp(2019, 6, 11) ? 61442 : a
a := t == timestamp(2019, 6, 4) ? 76855 : a
a := t == timestamp(2019, 5, 28) ? 60563 : a
a := t == timestamp(2019, 5, 21) ? 52172 : a
a := t == timestamp(2019, 5, 14) ? 81052 : a
a := t == timestamp(2019, 5, 7) ? 46063 : a
a := t == timestamp(2019, 4, 30) ? 22989 : a
a := t == timestamp(2019, 4, 23) ? 17200 : a
a := t == timestamp(2019, 4, 16) ? 14283 : a
a := t == timestamp(2019, 4, 9) ? 33417 : a
a := t == timestamp(2019, 4, 2) ? 23424 : a
a := t == timestamp(2019, 3, 26) ? 29370 : a
a := t == timestamp(2019, 3, 19) ? 10636 : a
a := t == timestamp(2019, 3, 12) ? 17595 : a
a := t == timestamp(2019, 3, 5) ? 9866 : a
a := t == timestamp(2019, 2, 26) ? 13620 : a
a := t == timestamp(2019, 2, 19) ? 14725 : a
a := t == timestamp(2019, 2, 12) ? -355 : a
a := t == timestamp(2019, 2, 5) ? 37686 : a
a := t == timestamp(2019, 1, 29) ? 63918 : a
a := t == timestamp(2019, 1, 22) ? 58370 : a
a := t == timestamp(2019, 1, 15) ? 42589 : a
a := t == timestamp(2019, 1, 8) ? 69166 : a
plot(a, "asset_mgr", color.green, 2, plot.style_stepline)
float l = na
l := t == timestamp(2023, 8, 15) ? -24699 : l
l := t == timestamp(2023, 8, 8) ? -40950 : l
l := t == timestamp(2023, 8, 1) ? -44969 : l
l := t == timestamp(2023, 7, 25) ? -39428 : l
l := t == timestamp(2023, 7, 18) ? -36615 : l
l := t == timestamp(2023, 7, 11) ? -50519 : l
l := t == timestamp(2023, 7, 3) ? -36666 : l
l := t == timestamp(2023, 6, 27) ? -32846 : l
l := t == timestamp(2023, 6, 20) ? -32327 : l
l := t == timestamp(2023, 6, 13) ? -39573 : l
l := t == timestamp(2023, 6, 6) ? -31951 : l
l := t == timestamp(2023, 5, 30) ? -41390 : l
l := t == timestamp(2023, 5, 23) ? -38069 : l
l := t == timestamp(2023, 5, 16) ? -32445 : l
l := t == timestamp(2023, 5, 9) ? -35242 : l
l := t == timestamp(2023, 5, 2) ? -48189 : l
l := t == timestamp(2023, 4, 25) ? -42374 : l
l := t == timestamp(2023, 4, 18) ? -19197 : l
l := t == timestamp(2023, 4, 11) ? -6980 : l
l := t == timestamp(2023, 4, 4) ? -9045 : l
l := t == timestamp(2023, 3, 28) ? -15512 : l
l := t == timestamp(2023, 3, 21) ? -28249 : l
l := t == timestamp(2023, 3, 14) ? -32437 : l
l := t == timestamp(2023, 3, 7) ? -23584 : l
l := t == timestamp(2023, 2, 28) ? -34179 : l
l := t == timestamp(2023, 2, 21) ? -35250 : l
l := t == timestamp(2023, 2, 14) ? -30148 : l
l := t == timestamp(2023, 2, 7) ? -31412 : l
l := t == timestamp(2023, 1, 31) ? -19377 : l
l := t == timestamp(2023, 1, 24) ? -21578 : l
l := t == timestamp(2023, 1, 17) ? -23330 : l
l := t == timestamp(2023, 1, 10) ? -30966 : l
l := t == timestamp(2023, 1, 3) ? -9178 : l
l := t == timestamp(2022, 12, 27) ? -17887 : l
l := t == timestamp(2022, 12, 20) ? -9971 : l
l := t == timestamp(2022, 12, 13) ? -24665 : l
l := t == timestamp(2022, 12, 6) ? -33467 : l
l := t == timestamp(2022, 11, 29) ? -42132 : l
l := t == timestamp(2022, 11, 22) ? -35278 : l
l := t == timestamp(2022, 11, 15) ? -49075 : l
l := t == timestamp(2022, 11, 8) ? -40755 : l
l := t == timestamp(2022, 11, 1) ? -27891 : l
l := t == timestamp(2022, 10, 25) ? -48839 : l
l := t == timestamp(2022, 10, 18) ? -57219 : l
l := t == timestamp(2022, 10, 11) ? -62064 : l
l := t == timestamp(2022, 10, 4) ? -63679 : l
l := t == timestamp(2022, 9, 27) ? -68517 : l
l := t == timestamp(2022, 9, 20) ? -58377 : l
l := t == timestamp(2022, 9, 13) ? -67176 : l
l := t == timestamp(2022, 9, 6) ? -57805 : l
l := t == timestamp(2022, 8, 30) ? -69389 : l
l := t == timestamp(2022, 8, 23) ? -67529 : l
l := t == timestamp(2022, 8, 16) ? -62547 : l
l := t == timestamp(2022, 8, 9) ? -60587 : l
l := t == timestamp(2022, 8, 2) ? -58745 : l
l := t == timestamp(2022, 7, 26) ? -67554 : l
l := t == timestamp(2022, 7, 19) ? -62155 : l
l := t == timestamp(2022, 7, 12) ? -63671 : l
l := t == timestamp(2022, 7, 5) ? -71895 : l
l := t == timestamp(2022, 6, 28) ? -75529 : l
l := t == timestamp(2022, 6, 21) ? -72843 : l
l := t == timestamp(2022, 6, 14) ? -68352 : l
l := t == timestamp(2022, 6, 7) ? -49171 : l
l := t == timestamp(2022, 5, 31) ? -45446 : l
l := t == timestamp(2022, 5, 24) ? -50499 : l
l := t == timestamp(2022, 5, 17) ? -44519 : l
l := t == timestamp(2022, 5, 10) ? -61800 : l
l := t == timestamp(2022, 5, 3) ? -65496 : l
l := t == timestamp(2022, 4, 26) ? -57307 : l
l := t == timestamp(2022, 4, 19) ? -49339 : l
l := t == timestamp(2022, 4, 12) ? -51331 : l
l := t == timestamp(2022, 4, 5) ? -45575 : l
l := t == timestamp(2022, 3, 29) ? -37618 : l
l := t == timestamp(2022, 3, 22) ? -41149 : l
l := t == timestamp(2022, 3, 15) ? -42998 : l
l := t == timestamp(2022, 3, 8) ? -61440 : l
l := t == timestamp(2022, 3, 1) ? -68004 : l
l := t == timestamp(2022, 2, 22) ? -59114 : l
l := t == timestamp(2022, 2, 15) ? -55758 : l
l := t == timestamp(2022, 2, 8) ? -45216 : l
l := t == timestamp(2022, 2, 1) ? -55751 : l
l := t == timestamp(2022, 1, 25) ? -59027 : l
l := t == timestamp(2022, 1, 18) ? -44645 : l
l := t == timestamp(2022, 1, 11) ? -41035 : l
l := t == timestamp(2022, 1, 4) ? -48086 : l
l := t == timestamp(2021, 12, 28) ? -47769 : l
l := t == timestamp(2021, 12, 21) ? -54249 : l
l := t == timestamp(2021, 12, 14) ? -57772 : l
l := t == timestamp(2021, 12, 7) ? -76095 : l
l := t == timestamp(2021, 11, 30) ? -85094 : l
l := t == timestamp(2021, 11, 23) ? -71862 : l
l := t == timestamp(2021, 11, 16) ? -57264 : l
l := t == timestamp(2021, 11, 9) ? -51872 : l
l := t == timestamp(2021, 11, 2) ? -35579 : l
l := t == timestamp(2021, 10, 26) ? -39773 : l
l := t == timestamp(2021, 10, 19) ? -37415 : l
l := t == timestamp(2021, 10, 12) ? -42905 : l
l := t == timestamp(2021, 10, 5) ? -62893 : l
l := t == timestamp(2021, 9, 28) ? -61193 : l
l := t == timestamp(2021, 9, 21) ? -75002 : l
l := t == timestamp(2021, 9, 14) ? -62808 : l
l := t == timestamp(2021, 9, 7) ? -57701 : l
l := t == timestamp(2021, 8, 31) ? -52804 : l
l := t == timestamp(2021, 8, 24) ? -51697 : l
l := t == timestamp(2021, 8, 17) ? -43765 : l
l := t == timestamp(2021, 8, 10) ? -56000 : l
l := t == timestamp(2021, 8, 3) ? -69207 : l
l := t == timestamp(2021, 7, 27) ? -67003 : l
l := t == timestamp(2021, 7, 20) ? -72733 : l
l := t == timestamp(2021, 7, 13) ? -61056 : l
l := t == timestamp(2021, 7, 6) ? -61888 : l
l := t == timestamp(2021, 6, 29) ? -60964 : l
l := t == timestamp(2021, 6, 22) ? -55191 : l
l := t == timestamp(2021, 6, 15) ? -54442 : l
l := t == timestamp(2021, 6, 8) ? -52749 : l
l := t == timestamp(2021, 6, 1) ? -67531 : l
l := t == timestamp(2021, 5, 25) ? -80740 : l
l := t == timestamp(2021, 5, 18) ? -83497 : l
l := t == timestamp(2021, 5, 11) ? -101123 : l
l := t == timestamp(2021, 5, 4) ? -90421 : l
l := t == timestamp(2021, 4, 27) ? -84157 : l
l := t == timestamp(2021, 4, 20) ? -77771 : l
l := t == timestamp(2021, 4, 13) ? -87644 : l
l := t == timestamp(2021, 4, 6) ? -90887 : l
l := t == timestamp(2021, 3, 30) ? -100068 : l
l := t == timestamp(2021, 3, 23) ? -106207 : l
l := t == timestamp(2021, 3, 16) ? -107804 : l
l := t == timestamp(2021, 3, 9) ? -126409 : l
l := t == timestamp(2021, 3, 2) ? -132446 : l
l := t == timestamp(2021, 2, 23) ? -130936 : l
l := t == timestamp(2021, 2, 16) ? -115771 : l
l := t == timestamp(2021, 2, 9) ? -99314 : l
l := t == timestamp(2021, 2, 2) ? -105341 : l
l := t == timestamp(2021, 1, 26) ? -109171 : l
l := t == timestamp(2021, 1, 19) ? -101107 : l
l := t == timestamp(2021, 1, 12) ? -99369 : l
l := t == timestamp(2021, 1, 5) ? -100987 : l
l := t == timestamp(2020, 12, 29) ? -87193 : l
l := t == timestamp(2020, 12, 21) ? -88339 : l
l := t == timestamp(2020, 12, 15) ? -88890 : l
l := t == timestamp(2020, 12, 8) ? -81766 : l
l := t == timestamp(2020, 12, 1) ? -81481 : l
l := t == timestamp(2020, 11, 24) ? -80733 : l
l := t == timestamp(2020, 11, 17) ? -76481 : l
l := t == timestamp(2020, 11, 10) ? -87091 : l
l := t == timestamp(2020, 11, 3) ? -106146 : l
l := t == timestamp(2020, 10, 27) ? -82826 : l
l := t == timestamp(2020, 10, 20) ? -60682 : l
l := t == timestamp(2020, 10, 13) ? -58578 : l
l := t == timestamp(2020, 10, 6) ? -50197 : l
l := t == timestamp(2020, 9, 29) ? -46398 : l
l := t == timestamp(2020, 9, 22) ? -47730 : l
l := t == timestamp(2020, 9, 15) ? -41589 : l
l := t == timestamp(2020, 9, 8) ? -52939 : l
l := t == timestamp(2020, 9, 1) ? -60436 : l
l := t == timestamp(2020, 8, 25) ? -60774 : l
l := t == timestamp(2020, 8, 18) ? -59072 : l
l := t == timestamp(2020, 8, 11) ? -64505 : l
l := t == timestamp(2020, 8, 4) ? -72534 : l
l := t == timestamp(2020, 7, 28) ? -70226 : l
l := t == timestamp(2020, 7, 21) ? -71253 : l
l := t == timestamp(2020, 7, 14) ? -78612 : l
l := t == timestamp(2020, 7, 7) ? -71885 : l
l := t == timestamp(2020, 6, 30) ? -88055 : l
l := t == timestamp(2020, 6, 23) ? -80198 : l
l := t == timestamp(2020, 6, 16) ? -78478 : l
l := t == timestamp(2020, 6, 9) ? -68079 : l
l := t == timestamp(2020, 6, 2) ? -63382 : l
l := t == timestamp(2020, 5, 26) ? -55675 : l
l := t == timestamp(2020, 5, 19) ? -69217 : l
l := t == timestamp(2020, 5, 12) ? -59303 : l
l := t == timestamp(2020, 5, 5) ? -68840 : l
l := t == timestamp(2020, 4, 28) ? -62288 : l
l := t == timestamp(2020, 4, 21) ? -70791 : l
l := t == timestamp(2020, 4, 14) ? -65307 : l
l := t == timestamp(2020, 4, 7) ? -68358 : l
l := t == timestamp(2020, 3, 31) ? -49108 : l
l := t == timestamp(2020, 3, 24) ? -28731 : l
l := t == timestamp(2020, 3, 17) ? -42849 : l
l := t == timestamp(2020, 3, 10) ? -55184 : l
l := t == timestamp(2020, 3, 3) ? -78467 : l
l := t == timestamp(2020, 2, 25) ? -108521 : l
l := t == timestamp(2020, 2, 18) ? -64921 : l
l := t == timestamp(2020, 2, 11) ? -67567 : l
l := t == timestamp(2020, 2, 4) ? -82627 : l
l := t == timestamp(2020, 1, 28) ? -71155 : l
l := t == timestamp(2020, 1, 21) ? -54461 : l
l := t == timestamp(2020, 1, 14) ? -65785 : l
l := t == timestamp(2020, 1, 7) ? -80927 : l
plot(l, "levfunds", color.purple, 2, plot.style_stepline)
float o = na
o := t == timestamp(2023, 8, 15) ? -1891 : o
o := t == timestamp(2023, 8, 8) ? -1298 : o
o := t == timestamp(2023, 8, 1) ? -547 : o
o := t == timestamp(2023, 7, 25) ? -511 : o
o := t == timestamp(2023, 7, 18) ? 706 : o
o := t == timestamp(2023, 7, 11) ? -565 : o
o := t == timestamp(2023, 7, 3) ? 4938 : o
o := t == timestamp(2023, 6, 27) ? 2890 : o
o := t == timestamp(2023, 6, 20) ? 1465 : o
o := t == timestamp(2023, 6, 13) ? 5367 : o
o := t == timestamp(2023, 6, 6) ? 1696 : o
o := t == timestamp(2023, 5, 30) ? 201 : o
o := t == timestamp(2023, 5, 23) ? -4071 : o
o := t == timestamp(2023, 5, 16) ? -4271 : o
o := t == timestamp(2023, 5, 9) ? -3190 : o
o := t == timestamp(2023, 5, 2) ? 302 : o
o := t == timestamp(2023, 4, 25) ? 454 : o
o := t == timestamp(2023, 4, 18) ? 1263 : o
o := t == timestamp(2023, 4, 11) ? 997 : o
o := t == timestamp(2023, 4, 4) ? 3505 : o
o := t == timestamp(2023, 3, 28) ? 3765 : o
o := t == timestamp(2023, 3, 21) ? 3613 : o
o := t == timestamp(2023, 3, 14) ? 320 : o
o := t == timestamp(2023, 3, 7) ? -2445 : o
o := t == timestamp(2023, 2, 28) ? -2484 : o
o := t == timestamp(2023, 2, 21) ? -4883 : o
o := t == timestamp(2023, 2, 14) ? 323 : o
o := t == timestamp(2023, 2, 7) ? 2008 : o
o := t == timestamp(2023, 1, 31) ? 1783 : o
o := t == timestamp(2023, 1, 24) ? 1860 : o
o := t == timestamp(2023, 1, 17) ? -640 : o
o := t == timestamp(2023, 1, 10) ? 2939 : o
o := t == timestamp(2023, 1, 3) ? 4247 : o
o := t == timestamp(2022, 12, 27) ? 2651 : o
o := t == timestamp(2022, 12, 20) ? -6021 : o
o := t == timestamp(2022, 12, 13) ? -5127 : o
o := t == timestamp(2022, 12, 6) ? -1535 : o
o := t == timestamp(2022, 11, 29) ? -574 : o
o := t == timestamp(2022, 11, 22) ? 3937 : o
o := t == timestamp(2022, 11, 15) ? 6629 : o
o := t == timestamp(2022, 11, 8) ? 4192 : o
o := t == timestamp(2022, 11, 1) ? 1051 : o
o := t == timestamp(2022, 10, 25) ? 3031 : o
o := t == timestamp(2022, 10, 18) ? 7569 : o
o := t == timestamp(2022, 10, 11) ? 5015 : o
o := t == timestamp(2022, 10, 4) ? 5841 : o
o := t == timestamp(2022, 9, 27) ? 3822 : o
o := t == timestamp(2022, 9, 20) ? 8580 : o
o := t == timestamp(2022, 9, 13) ? 7813 : o
o := t == timestamp(2022, 9, 6) ? 8344 : o
o := t == timestamp(2022, 8, 30) ? 4934 : o
o := t == timestamp(2022, 8, 23) ? 5857 : o
o := t == timestamp(2022, 8, 16) ? 7211 : o
o := t == timestamp(2022, 8, 9) ? 5835 : o
o := t == timestamp(2022, 8, 2) ? 8045 : o
o := t == timestamp(2022, 7, 26) ? 6982 : o
o := t == timestamp(2022, 7, 19) ? 9063 : o
o := t == timestamp(2022, 7, 12) ? 6277 : o
o := t == timestamp(2022, 7, 5) ? 6979 : o
o := t == timestamp(2022, 6, 28) ? 3160 : o
o := t == timestamp(2022, 6, 21) ? 3194 : o
o := t == timestamp(2022, 6, 14) ? 970 : o
o := t == timestamp(2022, 6, 7) ? 3503 : o
o := t == timestamp(2022, 5, 31) ? 3910 : o
o := t == timestamp(2022, 5, 24) ? 5691 : o
o := t == timestamp(2022, 5, 17) ? 8616 : o
o := t == timestamp(2022, 5, 10) ? 5758 : o
o := t == timestamp(2022, 5, 3) ? 7308 : o
o := t == timestamp(2022, 4, 26) ? 7545 : o
o := t == timestamp(2022, 4, 19) ? 6194 : o
o := t == timestamp(2022, 4, 12) ? 5138 : o
o := t == timestamp(2022, 4, 5) ? 3635 : o
o := t == timestamp(2022, 3, 29) ? 4352 : o
o := t == timestamp(2022, 3, 22) ? 3437 : o
o := t == timestamp(2022, 3, 15) ? -2262 : o
o := t == timestamp(2022, 3, 8) ? 1232 : o
o := t == timestamp(2022, 3, 1) ? -2630 : o
o := t == timestamp(2022, 2, 22) ? -4085 : o
o := t == timestamp(2022, 2, 15) ? -1926 : o
o := t == timestamp(2022, 2, 8) ? 6226 : o
o := t == timestamp(2022, 2, 1) ? 5599 : o
o := t == timestamp(2022, 1, 25) ? 3853 : o
o := t == timestamp(2022, 1, 18) ? 7667 : o
o := t == timestamp(2022, 1, 11) ? 7545 : o
o := t == timestamp(2022, 1, 4) ? 7630 : o
o := t == timestamp(2021, 12, 28) ? 6836 : o
o := t == timestamp(2021, 12, 21) ? 4088 : o
o := t == timestamp(2021, 12, 14) ? -1059 : o
o := t == timestamp(2021, 12, 7) ? -2393 : o
o := t == timestamp(2021, 11, 30) ? -2595 : o
o := t == timestamp(2021, 11, 23) ? 1020 : o
o := t == timestamp(2021, 11, 16) ? 1513 : o
o := t == timestamp(2021, 11, 9) ? 228 : o
o := t == timestamp(2021, 11, 2) ? 3649 : o
o := t == timestamp(2021, 10, 26) ? 1851 : o
o := t == timestamp(2021, 10, 19) ? 2633 : o
o := t == timestamp(2021, 10, 12) ? 3006 : o
o := t == timestamp(2021, 10, 5) ? -235 : o
o := t == timestamp(2021, 9, 28) ? -4843 : o
o := t == timestamp(2021, 9, 21) ? -3203 : o
o := t == timestamp(2021, 9, 14) ? -1886 : o
o := t == timestamp(2021, 9, 7) ? 1579 : o
o := t == timestamp(2021, 8, 31) ? 2673 : o
o := t == timestamp(2021, 8, 24) ? 4298 : o
o := t == timestamp(2021, 8, 17) ? 915 : o
o := t == timestamp(2021, 8, 10) ? 4332 : o
o := t == timestamp(2021, 8, 3) ? 3347 : o
o := t == timestamp(2021, 7, 27) ? 1729 : o
o := t == timestamp(2021, 7, 20) ? 3403 : o
o := t == timestamp(2021, 7, 13) ? 2438 : o
o := t == timestamp(2021, 7, 6) ? 3717 : o
o := t == timestamp(2021, 6, 29) ? 4863 : o
o := t == timestamp(2021, 6, 22) ? 4795 : o
o := t == timestamp(2021, 6, 15) ? 3877 : o
o := t == timestamp(2021, 6, 8) ? 3544 : o
o := t == timestamp(2021, 6, 1) ? 2887 : o
o := t == timestamp(2021, 5, 25) ? 1222 : o
o := t == timestamp(2021, 5, 18) ? 1879 : o
o := t == timestamp(2021, 5, 11) ? 1164 : o
o := t == timestamp(2021, 5, 4) ? 1615 : o
o := t == timestamp(2021, 4, 27) ? 3751 : o
o := t == timestamp(2021, 4, 20) ? 1916 : o
o := t == timestamp(2021, 4, 13) ? 2082 : o
o := t == timestamp(2021, 4, 6) ? 1532 : o
o := t == timestamp(2021, 3, 30) ? 2458 : o
o := t == timestamp(2021, 3, 23) ? 3065 : o
o := t == timestamp(2021, 3, 16) ? 5100 : o
o := t == timestamp(2021, 3, 9) ? 4425 : o
o := t == timestamp(2021, 3, 2) ? 3478 : o
o := t == timestamp(2021, 2, 23) ? 4733 : o
o := t == timestamp(2021, 2, 16) ? 4495 : o
o := t == timestamp(2021, 2, 9) ? 6095 : o
o := t == timestamp(2021, 2, 2) ? 4912 : o
o := t == timestamp(2021, 1, 26) ? 10016 : o
o := t == timestamp(2021, 1, 19) ? 10643 : o
o := t == timestamp(2021, 1, 12) ? 11749 : o
o := t == timestamp(2021, 1, 5) ? 9463 : o
o := t == timestamp(2020, 12, 29) ? 11403 : o
o := t == timestamp(2020, 12, 21) ? 10696 : o
o := t == timestamp(2020, 12, 15) ? 7790 : o
o := t == timestamp(2020, 12, 8) ? 9611 : o
o := t == timestamp(2020, 12, 1) ? 9480 : o
o := t == timestamp(2020, 11, 24) ? 8088 : o
o := t == timestamp(2020, 11, 17) ? 5912 : o
o := t == timestamp(2020, 11, 10) ? 4836 : o
o := t == timestamp(2020, 11, 3) ? 6005 : o
o := t == timestamp(2020, 10, 27) ? 4062 : o
o := t == timestamp(2020, 10, 20) ? 6636 : o
o := t == timestamp(2020, 10, 13) ? 6228 : o
o := t == timestamp(2020, 10, 6) ? 6063 : o
o := t == timestamp(2020, 9, 29) ? 6804 : o
o := t == timestamp(2020, 9, 22) ? 3940 : o
o := t == timestamp(2020, 9, 15) ? 5504 : o
o := t == timestamp(2020, 9, 8) ? 1980 : o
o := t == timestamp(2020, 9, 1) ? 2981 : o
o := t == timestamp(2020, 8, 25) ? 3773 : o
o := t == timestamp(2020, 8, 18) ? 2039 : o
o := t == timestamp(2020, 8, 11) ? 4966 : o
o := t == timestamp(2020, 8, 4) ? 4893 : o
o := t == timestamp(2020, 7, 28) ? 3757 : o
o := t == timestamp(2020, 7, 21) ? 4528 : o
o := t == timestamp(2020, 7, 14) ? 3812 : o
o := t == timestamp(2020, 7, 7) ? 3545 : o
o := t == timestamp(2020, 6, 30) ? 5059 : o
o := t == timestamp(2020, 6, 23) ? 2423 : o
o := t == timestamp(2020, 6, 16) ? 2707 : o
o := t == timestamp(2020, 6, 9) ? 3585 : o
o := t == timestamp(2020, 6, 2) ? 4926 : o
o := t == timestamp(2020, 5, 26) ? 4664 : o
o := t == timestamp(2020, 5, 19) ? 4263 : o
o := t == timestamp(2020, 5, 12) ? 4554 : o
o := t == timestamp(2020, 5, 5) ? 4870 : o
o := t == timestamp(2020, 4, 28) ? 3952 : o
o := t == timestamp(2020, 4, 21) ? 3403 : o
o := t == timestamp(2020, 4, 14) ? 3200 : o
o := t == timestamp(2020, 4, 7) ? 2596 : o
o := t == timestamp(2020, 3, 31) ? 8113 : o
o := t == timestamp(2020, 3, 24) ? 6268 : o
o := t == timestamp(2020, 3, 17) ? 5672 : o
o := t == timestamp(2020, 3, 10) ? 2796 : o
o := t == timestamp(2020, 3, 3) ? 2717 : o
o := t == timestamp(2020, 2, 25) ? 9196 : o
o := t == timestamp(2020, 2, 18) ? 14717 : o
o := t == timestamp(2020, 2, 11) ? 9925 : o
o := t == timestamp(2020, 2, 4) ? 7242 : o
o := t == timestamp(2020, 1, 28) ? 10111 : o
o := t == timestamp(2020, 1, 21) ? 10100 : o
o := t == timestamp(2020, 1, 14) ? 8795 : o
o := t == timestamp(2020, 1, 7) ? 7422 : o
o := t == timestamp(2019, 12, 31) ? 7484 : o
o := t == timestamp(2019, 12, 24) ? 7261 : o
o := t == timestamp(2019, 12, 17) ? 9457 : o
o := t == timestamp(2019, 12, 10) ? 7750 : o
o := t == timestamp(2019, 12, 3) ? 11892 : o
o := t == timestamp(2019, 11, 26) ? 11437 : o
o := t == timestamp(2019, 11, 19) ? 14812 : o
o := t == timestamp(2019, 11, 12) ? 9840 : o
o := t == timestamp(2019, 11, 5) ? 9218 : o
o := t == timestamp(2019, 10, 29) ? 6306 : o
o := t == timestamp(2019, 10, 22) ? 8184 : o
o := t == timestamp(2019, 10, 15) ? 4489 : o
o := t == timestamp(2019, 10, 8) ? 5684 : o
o := t == timestamp(2019, 10, 1) ? 6556 : o
o := t == timestamp(2019, 9, 24) ? 7122 : o
o := t == timestamp(2019, 9, 17) ? 4680 : o
o := t == timestamp(2019, 9, 10) ? 4145 : o
o := t == timestamp(2019, 9, 3) ? 3307 : o
o := t == timestamp(2019, 8, 27) ? 2252 : o
o := t == timestamp(2019, 8, 20) ? 4087 : o
o := t == timestamp(2019, 8, 13) ? 2891 : o
o := t == timestamp(2019, 8, 6) ? 2961 : o
o := t == timestamp(2019, 7, 30) ? 12906 : o
o := t == timestamp(2019, 7, 23) ? 11588 : o
o := t == timestamp(2019, 7, 16) ? 10080 : o
o := t == timestamp(2019, 7, 9) ? 9761 : o
o := t == timestamp(2019, 7, 2) ? 8586 : o
o := t == timestamp(2019, 6, 25) ? 8720 : o
o := t == timestamp(2019, 6, 18) ? 9176 : o
o := t == timestamp(2019, 6, 11) ? 6703 : o
o := t == timestamp(2019, 6, 4) ? 7810 : o
o := t == timestamp(2019, 5, 28) ? 9435 : o
o := t == timestamp(2019, 5, 21) ? 7871 : o
o := t == timestamp(2019, 5, 14) ? 4942 : o
o := t == timestamp(2019, 5, 7) ? 7025 : o
o := t == timestamp(2019, 4, 30) ? 13002 : o
o := t == timestamp(2019, 4, 23) ? 12929 : o
o := t == timestamp(2019, 4, 16) ? 12716 : o
o := t == timestamp(2019, 4, 9) ? 5005 : o
o := t == timestamp(2019, 4, 2) ? 7631 : o
o := t == timestamp(2019, 3, 26) ? 7681 : o
o := t == timestamp(2019, 3, 19) ? 9202 : o
o := t == timestamp(2019, 3, 12) ? 6973 : o
o := t == timestamp(2019, 3, 5) ? 6081 : o
o := t == timestamp(2019, 2, 26) ? 6387 : o
o := t == timestamp(2019, 2, 19) ? 4788 : o
o := t == timestamp(2019, 2, 12) ? 3435 : o
o := t == timestamp(2019, 2, 5) ? 2374 : o
o := t == timestamp(2019, 1, 29) ? 1624 : o
o := t == timestamp(2019, 1, 22) ? 2335 : o
o := t == timestamp(2019, 1, 15) ? 6264 : o
o := t == timestamp(2019, 1, 8) ? 5868 : o
plot(o, "other", color.orange, 2, plot.style_stepline) |
LineBreak | https://www.tradingview.com/script/J1LZ6MQ5-LineBreak/ | jac001 | https://www.tradingview.com/u/jac001/ | 82 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jac001
//@version=5
indicator("LineBreak", overlay=true)
linebreak_tickerid = ticker.linebreak(syminfo.tickerid, 3)
[lb_open, lb_high, lb_low, lb_close] = request.security(linebreak_tickerid, timeframe.period, [open, high, low, close])
plotshape(lb_close[0]>lb_close[1] and lb_close[1]<lb_close[2] and lb_close[1]<lb_open[1] and lb_close[2]<lb_open[2], title = "Buy", text = 'Buy', style = shape.labelup, location = location.belowbar, color= color.green,textcolor = color.white, size = size.tiny)
plotshape(lb_close[0]<lb_close[1] and lb_close[1]>lb_close[2] and lb_close[1]>lb_open[1] and lb_close[2]>lb_open[2], title = "Sell", text = 'Sell', style = shape.labeldown, location = location.abovebar, color= color.red,textcolor = color.white, size = size.tiny)
alertcondition(lb_close[0]>lb_close[1] and lb_close[1]<lb_close[2] and lb_close[1]<lb_open[1] and lb_close[2]<lb_open[2], title='Buy', message='Buy')
alertcondition(lb_close[0]<lb_close[1] and lb_close[1]>lb_close[2] and lb_close[1]>lb_open[1] and lb_close[2]>lb_open[2], title='Sell', message='Sell') |
Support and Resistance Signals MTF [LuxAlgo] | https://www.tradingview.com/script/iOrhpIqc-Support-and-Resistance-Signals-MTF-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 4,566 | 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("Support and Resistance Signals MTF [LuxAlgo]", 'LuxAlgo - Support Resistance Signals MTF', true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
srGR = 'Support & Resistance Settings'
srTT = 'tip : in ranging markets higher timeframe resolution or higher detection length might help reduce the noise'
srTF = input.string('Chart', 'Detection Timeframe', options=['Chart', '15 Minutes', '1 Hour', '4 Hours', '1 Day', '1 Week'], group = srGR, tooltip = srTT)
srLN = input(15, 'Detection Length', group = srGR)
srMR = input.float(2, 'Support Resistance Margin', minval = .1, maxval = 10, step = .1, group = srGR)
srSLC = input(color.new(#089981, 53), ' - Support, Lines', inline = 'srS', group = srGR)
srSZC = input(color.new(#089981, 83), 'Zones', inline = 'srS', group = srGR)
srRLC = input(color.new(#f23645, 53), ' - Resistance, Lines', inline = 'srR', group = srGR)
srRZC = input(color.new(#f23645, 83), 'Zones', inline = 'srR', group = srGR)
srHST = input.bool(true, 'Check Previous Historical S&R Zone', group = srGR)
mnGR = 'Manupulations'
mnSH = input.bool(true, 'Manupulation Zones', group = mnGR)
mnMR = input.float(1.3, 'Manupulation Margin', minval = .1, maxval = 10, step = .1, group = mnGR)
mnSZC = input(color.new(#2962ff, 73), 'Manupulation Zones, Support', inline = 'LQ', group = mnGR)
mnRZC = input(color.new(#ff9800, 73), 'Resistance', inline = 'LQ', group = mnGR)
sigGR = 'Signals'
srFBT = 'Filters the breakouts that failed to continue beyond a level'
srFBO = input.bool(true, 'Avoid False Breakouts', group = sigGR, tooltip = srFBT)
srBUC = input(color.new(#089981, 33), 'Breakouts, Bullish', inline = 'srB', group = sigGR)
srBDC = input(color.new(#f23645, 33), 'Bearish', inline = 'srB', group = sigGR)
srBS = input.string('Tiny', "", options=['Auto', 'Tiny', 'Small', 'Normal', 'None'], inline = 'srB', group = sigGR)
srTUC = input(color.new(#2962ff, 33), 'Tests, Bullish', inline = 'srT', group = sigGR)
srTDC = input(color.new(#e040fb, 33), 'Bearish', inline = 'srT', group = sigGR)
srTS = input.string('Tiny', "", options=['Auto', 'Tiny', 'Small', 'Normal', 'None'], inline = 'srT', group = sigGR)
srRUC = input(color.new(#089981, 33), 'Retests, Bullish', inline = 'srR', group = sigGR)
srRDC = input(color.new(#f23645, 33), 'Bearish', inline = 'srR', group = sigGR)
srRS = input.string('Tiny', "", options=['Auto', 'Tiny', 'Small', 'Normal', 'None'], inline = 'srR', group = sigGR)
srPUC = input(color.new(#089981, 33), 'Rejections, Bullish', inline = 'srP', group = sigGR)
srPDC = input(color.new(#f23645, 33), 'Bearish', inline = 'srP', group = sigGR)
srPS = input.string('Tiny', "", options=['Auto', 'Tiny', 'Small', 'Normal', 'None'], inline = 'srP', group = sigGR)
othGR = 'Others'
swSH = input.string('None', "Swing Levels", options=['Auto', 'Small', 'Normal', 'Large', 'None'], inline = 'sw', group = othGR)
swHC = input(color.new(#f23645, 33), 'H', inline = 'sw', group = othGR)
swLC = input(color.new(#089981, 33), 'L', inline = 'sw', group = othGR)
//-----------------------------------------------------------------------------}
// User Defined Types
//-----------------------------------------------------------------------------{
// @type bar properties with their values
//
// @field o (float) open price of the bar
// @field h (float) high price of the bar
// @field l (float) low price of the bar
// @field c (float) close price of the bar
// @field v (float) volume of the bar
// @field i (int) index of the bar
type bar
float o = open
float h = high
float l = low
float c = close
float v = volume
int i = bar_index
// @type store pivot high/low and index data
//
// @field x (int) last pivot bar index
// @field x1 (int) previous pivot bar index
// @field h (float) last pivot high
// @field h1 (float) previous pivot high
// @field l (float) last pivot low
// @field l1 (float) previous pivot low
// @field hx (bool) pivot high cross status
// @field lx (bool) pivot low cross status
type pivotPoint
int x
int x1
float h
float h1
float l
float l1
bool hx
bool lx
// @type stores support and resistance visuals and signal status
//
// @field bx (box) support and resistance zones
// @field lq (box) liquidity sweeps
// @field ln (line) support and resistance levels
// @field b (bool) breakout status
// @field b (bool) test status
// @field b (bool) retest status
// @field b (bool) liqudation status
// @field m (float) default margin
type SnR
box bx
box lq
line ln
bool b
bool t
bool r
bool l
float m
//-----------------------------------------------------------------------------}
// Variables
//-----------------------------------------------------------------------------{
bar b = bar.new()
var pivotPoint pp = pivotPoint.new()
var SnR[] R = array.new<SnR> (1, SnR.new(box(na), box(na), line(na), false, false, false, false, na))
var SnR[] S = array.new<SnR> (1, SnR.new(box(na), box(na), line(na), false, false, false, false, na))
var SnR lR = SnR.new(box(na), box(na), line(na), false, false, false, false, na)
var SnR lS = SnR.new(box(na), box(na), line(na), false, false, false, false, na)
var SnR lRt = SnR.new(box(na), box(na), line(na), false, false, false, false, na)
var SnR lSt = SnR.new(box(na), box(na), line(na), false, false, false, false, na)
var int mss = 0
//-----------------------------------------------------------------------------}
// General Calculations
//-----------------------------------------------------------------------------{
int tf_m = switch srTF
"Chart" => timeframe.isintraday ? timeframe.multiplier : timeframe.isdaily ? 1440 : timeframe.isweekly ? 10080 : 10080 * 30
"15 Minutes" => 15
"1 Hour" => 60
"4 Hours" => 240
"1 Day" => 1440
"1 Week" => 10080
ch_m = if timeframe.isintraday
timeframe.multiplier
else if timeframe.isdaily
1440
else if timeframe.isweekly
10080
else if timeframe.ismonthly
10080 * 30
srLN := srLN * tf_m / ch_m
pHST = ta.highest(b.h, srLN)
pLST = ta.lowest (b.l, srLN)
atr = ta.atr(17)
isLLS = math.abs(b.l - math.min(b.o, b.c)) >= 1.618 * atr
isLUS = math.abs(b.h - math.max(b.o, b.c)) >= 1.618 * atr
vSMA = ta.sma(nz(b.v), 17)
isHV = nz(b.v) >= 1.618 * vSMA
isLV = nz(b.v) <= 0.618 * vSMA
vST = isHV ? '\n *High Trading Activity' : isLV ? '\n *Low Trading Activity' : '\n *Average Trading Activity'
if nz(b.v) > vSMA * 4.669
alert('High trading activity (Volume SPIKE) detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
srBUC := srBS != 'None' ? srBUC : color(na)
srBDC := srBS != 'None' ? srBDC : color(na)
srBTC = srBS != 'None' ? color.white : color(na)
srTUC := srTS != 'None' ? srTUC : color(na)
srTDC := srTS != 'None' ? srTDC : color(na)
srTTC = srTS != 'None' ? color.white : color(na)
srRUC := srRS != 'None' ? srRUC : color(na)
srRDC := srRS != 'None' ? srRDC : color(na)
srRTC = srRS != 'None' ? color.white : color(na)
//-----------------------------------------------------------------------------}
// Functions/Methods
//-----------------------------------------------------------------------------{
// @function calcuates cumulative volume of the given range
//
// @param _l (int) length of the range
// @param _o (int) offset
//
// @returns (float) cumulative volume
f_getTradedVolume(_l, _o) =>
v = 0.
for x = 0 to _l - 1
v += volume[_o + x]
v
// @function converts size strings to enumerated values
//
// @param _l (string) size string
//
// @returns (enumeration) size enumerated value
f_getSize(_s) =>
switch _s
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Huge' => size.huge
=> size.auto
//-----------------------------------------------------------------------------}
// Calculations
//-----------------------------------------------------------------------------{
pp_h = ta.pivothigh(srLN, srLN)
if not na(pp_h)
pp.h1 := pp.h
pp.h := pp_h
pp.x1 := pp.x
pp.x := b.i[srLN]
pp.hx := false
if R.size() > 1
lR := R.get(0)
lRt := R.get(1)
if pp.h < lR.bx.get_bottom() * (1 - lR.m * .17 * srMR) or pp.h > lR.bx.get_top() * (1 + lR.m * .17 * srMR)
if pp.x < lR.bx.get_left() and pp.x + srLN > lR.bx.get_left() and b.c < lR.bx.get_bottom()
na
else
if pp.h < lRt.bx.get_bottom() * (1 - lRt.m * .17 * srMR) or pp.h > lRt.bx.get_top() * (1 + lRt.m * .17 * srMR)
R.unshift(
SnR.new(
box.new(pp.x, pp.h, b.i, pp.h * (1 - ((pHST - pLST) / pHST) * .17 * srMR), border_color = color(na), bgcolor = srRZC),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
line.new(pp.x, pp.h, b.i, pp.h, color = srRLC, width = srMR <= .5 ? 2 : 3),
false, false, false, false, (pHST - pLST) / pHST))
lS.t := false
else
lRt.bx.set_right(b.i)
lRt.ln.set_x2(b.i)
else if lR.bx.get_top() != lS.bx.get_top()
lR.bx.set_right(b.i)
lR.ln.set_x2(b.i)
else
R.unshift(
SnR.new(
box.new(pp.x, pp.h, b.i, pp.h * (1 - ((pHST - pLST) / pHST) * .17 * srMR), border_color = color(na), bgcolor = srRZC),
//box.new(pp.x, pp.h, b.i, pp.h * (1 - ((pHST - pLST) / pHST) * .17 * srMR), border_color = color(na), bgcolor = color.new(color.orange, 89)),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
line.new(pp.x, pp.h, b.i, pp.h, color = srRLC, width = srMR <= .5 ? 2 : 3),
false, false, false, false, (pHST - pLST) / pHST))
lS.t := false
if swSH != 'None'
StS = pp.x - pp.x1
tradedVolume = f_getTradedVolume(StS, srLN)
swH = pp.h > pp.h1 ? "Higher High" : pp.h < pp.h1 ? "Lower High" : na
rTT = 'Swing High (' + swH + ') : ' + str.tostring(pp.h, format.mintick) +
(mss == -1 and pp.h < pp.h1 ? '\n *Counter-Trend Move' : '') +
'\n -Price Change : ↑ %' + str.tostring((pp.h - pp.l) * 100 / pp.l , '#.##') +
(nz(b.v) ? '\n -Traded Volume : ' + str.tostring(tradedVolume, format.volume) + ' (' + str.tostring(StS - 1) + ' bars)' +
'\n *Average Volume/Bar : ' + str.tostring(tradedVolume / (StS - 1), format.volume) : '')
label.new(pp.x, pp.h, '◈', color = color(na), style = label.style_label_down, textcolor = swHC, size = f_getSize(swSH), tooltip = rTT)
alert('New ' + swH + (mss == -1 and pp.h < pp.h1 ? ' (counter-trend move)' : '') + ' formed\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
if b.c[1] > pp.h and b.c > pp.h and not pp.hx
pp.hx := true
mss := 1
pp_l = ta.pivotlow (srLN, srLN)
if not na(pp_l)
pp.l1 := pp.l
pp.l := pp_l
pp.x1 := pp.x
pp.x := b.i[srLN]
pp.lx := false
if S.size() > 2
lS := S.get(0)
lSt := S.get(1)
if pp.l < lS.bx.get_bottom() * (1 - lS.m * .17 * srMR) or pp.l > lS.bx.get_top() * (1 + lS.m * .17 * srMR)
if pp.x < lS.bx.get_left() and pp.x + srLN > lS.bx.get_left() and b.c > lS.bx.get_top() //not lR.b
na
else
if pp.l < lSt.bx.get_bottom() * (1 - lSt.m * .17 * srMR) or pp.l > lSt.bx.get_top() * (1 + lSt.m * .17 * srMR)
S.unshift(
SnR.new(
box.new(pp.x, pp.l * (1 + ((pHST - pLST) / pHST) * .17 * srMR), b.i, pp.l, border_color = color(na), bgcolor = srSZC),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
line.new(pp.x, pp.l, b.i, pp.l, color = srSLC, width = srMR <= .5 ? 2 : 3),
false, false, false, false, (pHST - pLST) / pHST))
lR.t := false
else
lSt.bx.set_right(b.i)
lSt.ln.set_x2(b.i)
else if lS.bx.get_bottom() != lR.bx.get_bottom()
lS.bx.set_right(b.i)
lS.ln.set_x2(b.i)
else
S.unshift(
SnR.new(
box.new(pp.x, pp.l * (1 + ((pHST - pLST) / pHST) * .17 * srMR), b.i, pp.l, border_color = color(na), bgcolor = srSZC),
//box.new(pp.x, pp.l * (1 + ((pHST - pLST) / pHST) * .17 * srMR), b.i, pp.l, border_color = color(na), bgcolor = color.new(color.aqua, 89)),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
line.new(pp.x, pp.l, b.i, pp.l, color = srSLC, width = srMR <= .5 ? 2 : 3),
false, false, false, false, (pHST - pLST) / pHST))
lR.t := false
if swSH != 'None'
StS = pp.x - pp.x1
tradedVolume = f_getTradedVolume(StS, srLN)
swL = pp.l < pp.l1 ? "Lower Low" : pp.l > pp.l1 ? "Higher Low" : na
sTT = 'Swing Low (' + swL + ') : ' + str.tostring(pp.l, format.mintick) +
(mss == 1 and pp.l > pp.l1 ? '\n *Counter-Trend Move' : '') +
'\n -Price Change : ↓ %' + str.tostring((pp.h - pp.l) * 100 / pp.h , '#.##') +
(nz(b.v) ? '\n -Traded Volume : ' + str.tostring(tradedVolume, format.volume) + ' (' + str.tostring(StS - 1) + ' bars)' +
'\n *Average Volume/Bar : ' + str.tostring(tradedVolume / (StS - 1), format.volume) : '')
label.new(pp.x, pp.l, '◈', color = color(na), style = label.style_label_up, textcolor = swLC, size = f_getSize(swSH), tooltip = sTT)
alert('New ' + swL + (mss == 1 and pp.l > pp.l1 ? ' (counter-trend move)' : '') + ' formed\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
if b.c[1] < pp.l and b.c < pp.l and not pp.lx
pp.lx := true
mss := -1
if R.size() > 0
lR := R.get(0)
if srFBO and b.c[1] > lR.bx.get_top() * (1 + lR.m * .17) and not lR.b
lR.bx.set_right(b.i[1])
lR.ln.set_x2(b.i[1])
lR.b := true
lR.r := false
label.new(b.i[1], b.l[1] * (1 - lR.m * .017), '▲\n\nB', color = srBUC, style = label.style_label_up , textcolor = srBTC, size = f_getSize(srBS), tooltip = 'Bullish Breakout' + vST[1])
//label.new(b.i[1], b.l[1] * (1 - lR.m * .017), '▲\n\nB', color = color.yellow, style = label.style_label_up , textcolor = srBTC, size = f_getSize(srBS), tooltip = 'Bullish Breakout' + vST[1])
S.unshift(
SnR.new(
box.new(b.i[1], lR.bx.get_top(), b.i + 1, lR.bx.get_bottom(), border_color = color(na), bgcolor = srSZC),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
line.new(b.i[1], lR.bx.get_bottom(), b.i + 1, lR.bx.get_bottom(), color = srSLC, width = srMR <= .5 ? 2 : 3),
false, false, false, false, lR.m))
//R.remove(0)
if srBS != 'None'
alert('Bullish breakout detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
else if b.c[1] > lR.bx.get_top() and not lR.b and not srFBO
lR.bx.set_right(b.i[1])
lR.ln.set_x2(b.i[1])
lR.b := true
lR.r := false
label.new(b.i[1], b.l[1] * (1 - lR.m * .017), '▲\n\nB', color = srBUC, style = label.style_label_up , textcolor = srBTC, size = f_getSize(srBS), tooltip = 'Bullish Breakout' + vST[1])
S.unshift(
SnR.new(
box.new(b.i[1], lR.bx.get_top(), b.i + 1, lR.bx.get_bottom(), border_color = color(na), bgcolor = srSZC),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
line.new(b.i[1], lR.bx.get_bottom(), b.i + 1, lR.bx.get_bottom(), color = srSLC, width = srMR <= .5 ? 2 : 3),
false, false, false, false, lR.m))
//R.remove(0)
if srBS != 'None'
alert('Bullish breakout detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
else if lS.b and b.o[1] < lR.bx.get_top() and b.h[1] > lR.bx.get_bottom() and b.c[1] < lR.bx.get_bottom() and not lR.r and b.i[1] != lR.bx.get_left()
label.new(b.i[1], b.h[1] * (1 + lR.m * .017), 'R', color = srRDC, style = label.style_label_down , textcolor = srRTC, size = f_getSize(srRS), tooltip = 'Re-test of Resistance Zone' + vST[1] )
lR.r := true //
lR.bx.set_right(b.i)
lR.ln.set_x2(b.i)
if srRS != 'None'
alert('Re-test of resistance zone detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
else if b.h[1] > lR.bx.get_bottom() and b.c[1] < lR.bx.get_top() and b.c < lR.bx.get_top() and not lR.t and not lR.r and not lR.b and not lS.b and b.i[1] != lR.bx.get_left()
label.new(b.i[1], b.h[1] * (1 + lR.m * .017), 'T', color = srTDC, style = label.style_label_down , textcolor = srTTC, size = f_getSize(srTS), tooltip = 'Test of Resistance Zone' + vST[1] )
lR.t := true
lR.bx.set_right(b.i)
lR.ln.set_x2(b.i)
if srTS != 'None'
alert('Test of resistance zone detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period, alert.freq_once_per_bar_close)
else if b.h > lR.bx.get_bottom() * (1 - lR.m * .17) and not lR.b //and lR.bx.get_top() != lS.bx.get_top()
if b.h > lR.bx.get_bottom()
lR.bx.set_right(b.i)
lR.ln.set_x2(b.i)
if isLLS[1] and isHV[1] and srPS != 'None'
label.new(b.i[1], b.l[1] * (1 - lR.m * .017), '', color = srPUC, style = label.style_label_up , textcolor = color.white, size = f_getSize(srPS), tooltip = 'Rejection of Lower Prices' + vST[1])
alert('Rejection of lower prices detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
if mnSH
if b.h > lR.bx.get_top() and b.c <= lR.bx.get_top() * (1 + lR.m * .17 * mnMR) and not lR.l and b.i == lR.bx.get_right()
if lR.lq.get_right() + srLN > b.i
lR.lq.set_right(b.i + 1)
lR.lq.set_top(math.min(math.max(b.h, lR.lq.get_top()), lR.bx.get_top() * (1 + lR.m * .17 * mnMR)))
else
lR.lq.set_lefttop(b.i[1], math.min(b.h, lR.bx.get_top() * (1 + lR.m * .17 * mnMR)))
lR.lq.set_rightbottom(b.i + 1, lR.bx.get_top())
lR.lq.set_bgcolor(mnRZC)
lR.l := true
else if b.h > lR.bx.get_top() and b.c <= lR.bx.get_top() * (1 + lR.m * .17 * mnMR) and lR.l and b.i == lR.bx.get_right()
lR.lq.set_right(b.i + 1)
lR.lq.set_top(math.min(math.max(b.h,lR.lq.get_top()), lR.bx.get_top() * (1 + lR.m * .17 * mnMR)))
else if lR.l and (b.c >= lR.bx.get_top() * (1 + lR.m * .17 * mnMR) or b.c < lR.bx.get_bottom())
lR.l := false
if R.size() > 1 and srHST //and (lR.b or lS.b)// and lR.bx.get_top() != lS.bx.get_top()
lRt := R.get(1)
if lR.bx.get_top() != lRt.bx.get_top()
if srFBO and b.c[1] > lRt.bx.get_top() * (1 + lRt.m * .17) and not lRt.b
lRt.bx.set_right(b.i[1])
lRt.ln.set_x2(b.i[1])
lRt.b := true
lRt.r := false
label.new(b.i[1], b.l[1] * (1 - lRt.m * .017), '▲\n\nB', color = srBUC, style = label.style_label_up , textcolor = srBTC, size = f_getSize(srBS), tooltip = 'Bullish Breakout' + vST[1])
S.unshift(
SnR.new(
box.new(b.i[1], lRt.bx.get_top(), b.i + 1, lRt.bx.get_bottom(), border_color = color(na), bgcolor = srSZC),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
line.new(b.i[1], lRt.bx.get_bottom(), b.i + 1, lRt.bx.get_bottom(), color = srSLC, width = srMR <= .5 ? 2 : 3),
false, false, false, false, lRt.m))
//R.remove(1)
if srBS != 'None'
alert('Bullish breakout detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
else if b.c[1] > lRt.bx.get_top() and not lRt.b and not srFBO
lRt.bx.set_right(b.i[1])
lRt.ln.set_x2(b.i[1])
lRt.b := true
lRt.r := false
label.new(b.i[1], b.l[1] * (1 - lRt.m * .017), '▲\n\nB', color = srBUC, style = label.style_label_up , textcolor = srBTC, size = f_getSize(srBS), tooltip = 'Bullish Breakout' + vST[1])
S.unshift(
SnR.new(
box.new(b.i[1], lRt.bx.get_top(), b.i + 1, lRt.bx.get_bottom(), border_color = color(na), bgcolor = srSZC),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
line.new(b.i[1], lRt.bx.get_bottom(), b.i + 1, lRt.bx.get_bottom(), color = srSLC, width = srMR <= .5 ? 2 : 3),
false, false, false, false, lRt.m))
//R.remove(1)
if srBS != 'None'
alert('Bullish breakout detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
else if lSt.b and b.o[1] < lRt.bx.get_top() and b.h[1] > lRt.bx.get_bottom() and b.c[1] < lRt.bx.get_bottom() and not lRt.r and b.i[1] != lRt.bx.get_left()
label.new(b.i[1], b.h[1] * (1 + lRt.m * .017), 'R', color = srRDC, style = label.style_label_down , textcolor = srRTC, size = f_getSize(srRS), tooltip = 'Re-test of Resistance Zone' + vST[1] )
lRt.r := true //
lRt.bx.set_right(b.i)
lRt.ln.set_x2(b.i)
if srRS != 'None'
alert('Re-test of resistance zone detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
else if b.h[1] > lRt.bx.get_bottom() and b.c[1] < lRt.bx.get_top() and b.c < lRt.bx.get_top() and not lRt.t and not lRt.b and not lSt.b and b.i[1] != lRt.bx.get_left()
label.new(b.i[1], b.h[1] * (1 + lRt.m * .017), 'T', color = srTDC, style = label.style_label_down , textcolor = srTTC, size = f_getSize(srTS), tooltip = 'Test of Resistance Zone' + vST[1] )
lRt.t := true
lRt.bx.set_right(b.i)
lRt.ln.set_x2(b.i)
if srTS != 'None'
alert('Test of resistance zone detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period, alert.freq_once_per_bar_close)
else if b.h > lRt.bx.get_bottom() * (1 - lRt.m * .17) and not lRt.b
if b.h > lRt.bx.get_bottom()
lRt.bx.set_right(b.i)
lRt.ln.set_x2(b.i)
if mnSH
if b.h > lRt.bx.get_top() and b.c <= lRt.bx.get_top() * (1 + lRt.m * .17 * mnMR) and not lRt.l and b.i == lRt.bx.get_right()
if lRt.lq.get_right() + srLN > b.i
lRt.lq.set_right(b.i + 1)
lRt.lq.set_top(math.min(math.max(b.h, lRt.lq.get_top()), lRt.bx.get_top() * (1 + lRt.m * .17 * mnMR)))
else
lRt.lq.set_lefttop(b.i[1], math.min(b.h, lRt.bx.get_top() * (1 + lRt.m * .17 * mnMR)))
lRt.lq.set_rightbottom(b.i + 1, lRt.bx.get_top())
lRt.lq.set_bgcolor(mnRZC)
lRt.l := true
else if b.h > lRt.bx.get_top() and b.c <= lRt.bx.get_top() * (1 + lRt.m * .17 * mnMR) and lRt.l and b.i == lRt.bx.get_right()
lRt.lq.set_right(b.i + 1)
lRt.lq.set_top(math.min(math.max(b.h, lRt.lq.get_top()), lRt.bx.get_top() * (1 + lRt.m * .17 * mnMR)))
else if lRt.l and (b.c >= lRt.bx.get_top() * (1 + lRt.m * .17 * mnMR) or b.c < lRt.bx.get_bottom())
lRt.l := false
if S.size() > 1
lS := S.get(0)
if srFBO and b.c[1] < lS.bx.get_bottom() * (1 - lS.m * .17) and not lS.b
lS.bx.set_right(b.i[1])
lS.ln.set_x2(b.i[1])
lS.b := true
lS.r := false
label.new(b.i[1], b.h[1] * (1 + lS.m * .017), 'B\n\n▼', color = srBDC, style = label.style_label_down , textcolor = srBTC, size = f_getSize(srBS), tooltip = 'Bearish Breakout' + vST[1] )
//label.new(b.i[1], b.h[1] * (1 + lS.m * .017), 'B\n\n▼', color = color.yellow, style = label.style_label_down , textcolor = srBTC, size = f_getSize(srBS), tooltip = 'Bearish Breakout' + vST[1] )
R.unshift(
SnR.new(
box.new(b.i[1], lS.bx.get_top(), b.i + 1, lS.bx.get_bottom(), border_color = color(na), bgcolor = srRZC),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
line.new(b.i[1], lS.bx.get_top(), b.i + 1, lS.bx.get_top(), color = srRLC, width = srMR <= .5 ? 2 : 3),
false, false, false, false, lS.m))
//S.remove(0)
if srBS != 'None'
alert('Bearish breakout detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
if b.c[1] < lS.bx.get_bottom() and not lS.b and not srFBO
lS.bx.set_right(b.i[1])
lS.ln.set_x2(b.i[1])
lS.b := true
lS.r := false
label.new(b.i[1], b.h[1] * (1 + lS.m * .017), 'B\n\n▼', color = srBDC, style = label.style_label_down , textcolor = srBTC, size = f_getSize(srBS), tooltip = 'Bearish Breakout' + vST[1] )
R.unshift(
SnR.new(
box.new(b.i[1], lS.bx.get_top(), b.i + 1, lS.bx.get_bottom(), border_color = color(na), bgcolor = srRZC),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
line.new(b.i[1], lS.bx.get_top(), b.i + 1, lS.bx.get_top(), color = srRLC, width = srMR <= .5 ? 2 : 3),
false, false, false, false, lS.m))
//S.remove(0)
if srBS != 'None'
alert('Bearish breakout detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
else if lR.b and b.o[1] > lS.bx.get_bottom() and b.l[1] < lS.bx.get_top() and b.c[1] > lS.bx.get_top() and not lS.r and b.i[1] != lS.bx.get_left()
label.new(b.i[1], b.l[1] * (1 - lS.m * .017), 'R', color = srRUC, style = label.style_label_up , textcolor = srRTC, size = f_getSize(srRS), tooltip = 'Re-test of Support Zone' + vST[1] )
lS.r := true //
lS.bx.set_right(b.i)
lS.ln.set_x2(b.i)
if srRS != 'None'
alert('Re-test of support zone detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
else if b.l[1] < lS.bx.get_top() and b.c[1] > lS.bx.get_bottom() and b.c > lS.bx.get_bottom() and not lS.t and not lS.b and not lR.b and b.i[1] != lS.bx.get_left()
label.new(b.i[1], b.l[1] * (1 - lS.m * .017), 'T', color = srTUC, style = label.style_label_up , textcolor = srTTC, size = f_getSize(srTS), tooltip = 'Test of Support Zone' + vST[1] )
lS.t := true
lS.bx.set_right(b.i)
lS.ln.set_x2(b.i)
if srTS != 'None'
alert('Test of support zone detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period, alert.freq_once_per_bar_close)
else if b.l < lS.bx.get_top() * (1 + lS.m * .17) and not lS.b //and lS.bx.get_bottom() != lR.bx.get_bottom()
if b.l < lS.bx.get_top()
lS.bx.set_right(b.i)
lS.ln.set_x2(b.i)
if isLUS[1] and isHV[1] and srPS != 'None'
label.new(b.i[1], b.h[1] * (1 + lS.m * .017), '', color = srPDC, style = label.style_label_down , textcolor = color.white, size = f_getSize(srPS), tooltip = 'Rejection of Higher Prices' + vST[1] )
alert('Rejection of higher prices detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
if mnSH
if b.l < lS.bx.get_bottom() and b.c >= lS.bx.get_bottom() * (1 - lS.m * .17 * mnMR) and not lS.l and b.i == lS.bx.get_right()
if lS.lq.get_right() + srLN > b.i
lS.lq.set_right(b.i + 1)
lS.lq.set_bottom(math.max(math.min(b.l, lS.lq.get_bottom()), lS.bx.get_bottom() * (1 - lS.m * .17 * mnMR)))
else
lS.lq.set_lefttop(b.i[1], lS.bx.get_bottom())
lS.lq.set_rightbottom(b.i + 1, math.max(b.l, lS.bx.get_bottom() * (1 - lS.m * .17 * mnMR)))
lS.lq.set_bgcolor(mnSZC)
lS.l := true
else if b.l < lS.bx.get_bottom() and b.c >= lS.bx.get_bottom() * (1 - lS.m * .17 * mnMR) and lS.l and b.i == lS.bx.get_right()
lS.lq.set_right(b.i + 1)
lS.lq.set_bottom(math.max(math.min(b.l, lS.lq.get_bottom()), lS.bx.get_bottom() * (1 - lS.m * .17 * mnMR)))
else if lS.l and (b.c <= lS.bx.get_bottom() * (1 - lS.m * .17 * mnMR) or b.c > lS.bx.get_top())
lS.l := false
if S.size() > 2 and srHST //and (lR.b or lS.b)// and lS.bx.get_bottom() != lR.bx.get_bottom()
lSt := S.get(1)
if lS.bx.get_bottom() != lSt.bx.get_bottom()
if srFBO and b.c[1] < lSt.bx.get_bottom() * (1 - lSt.m * .17) and not lSt.b //and b.i[1] != lR.bx.get_left()
lSt.bx.set_right(b.i[1])
lSt.ln.set_x2(b.i[1])
lSt.b := true
lSt.r := false
label.new(b.i[1], b.h[1] * (1 + lSt.m * .017), 'B\n\n▼', color = srBDC, style = label.style_label_down , textcolor = srBTC, size = f_getSize(srBS), tooltip = 'Bearish Breakout' + vST[1] )
R.unshift(
SnR.new(
box.new(b.i[1], lSt.bx.get_top(), b.i + 1, lSt.bx.get_bottom(), border_color = color(na), bgcolor = srRZC),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
line.new(b.i[1], lSt.bx.get_top(), b.i + 1, lSt.bx.get_top(), color = srRLC, width = srMR <= .5 ? 2 : 3),
false, false, false, false, lSt.m))
//S.remove(1)
if srBS != 'None'
alert('Bearish breakout detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
else if b.c[1] < lSt.bx.get_bottom() and not lSt.b and not srFBO //and b.i[1] != lR.bx.get_left()
lSt.bx.set_right(b.i[1])
lSt.ln.set_x2(b.i[1])
lSt.b := true
lSt.r := false
label.new(b.i[1], b.h[1] * (1 + lSt.m * .017), 'B\n\n▼', color = srBDC, style = label.style_label_down , textcolor = srBTC, size = f_getSize(srBS), tooltip = 'Bearish Breakout' + vST[1] )
R.unshift(
SnR.new(
box.new(b.i[1], lSt.bx.get_top(), b.i + 1, lSt.bx.get_bottom(), border_color = color(na), bgcolor = srRZC),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
line.new(b.i[1], lSt.bx.get_top(), b.i + 1, lSt.bx.get_top(), color = srRLC, width = srMR <= .5 ? 2 : 3),
false, false, false, false, lSt.m))
//S.remove(1)
if srBS != 'None'
alert('Bearish breakout detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
else if lRt.b and b.o[1] > lSt.bx.get_bottom() and b.l[1] < lSt.bx.get_top() and b.c[1] > lSt.bx.get_top() and not lSt.r and b.i[1] != lSt.bx.get_left() //and lSt.bx.get_top() != lS.bx.get_top() //DGT
label.new(b.i[1], b.l[1] * (1 - lSt.m * .017), 'R', color = srRUC, style = label.style_label_up , textcolor = srRTC, size = f_getSize(srRS), tooltip = 'Re-test of Support Zone' + vST[1] )
lSt.r := true
lSt.bx.set_right(b.i)
lSt.ln.set_x2(b.i)
if srRS != 'None'
alert('Re-test of support zone detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period)
else if b.l[1] < lSt.bx.get_top() and b.c[1] > lSt.bx.get_bottom() and b.c > lSt.bx.get_bottom() and not lSt.t and not lSt.b and not lRt.b and b.i[1] != lSt.bx.get_left()
label.new(b.i[1], b.l[1] * (1 - lSt.m * .017), 'T', color = srTUC, style = label.style_label_up , textcolor = srTTC, size = f_getSize(srTS), tooltip = 'Test of Support Zone' + vST[1] )
lSt.t := true
lSt.bx.set_right(b.i)
lSt.ln.set_x2(b.i)
if srTS != 'None'
alert('Test of support zone detected\n' + syminfo.ticker + ' price (' + str.tostring(b.c, format.mintick) + '), timeframe ' + timeframe.period, alert.freq_once_per_bar_close)
else if b.l < lSt.bx.get_top() * (1 + lSt.m * .17) and not lSt.b
if b.l < lSt.bx.get_top()
lSt.bx.set_right(b.i)
lSt.ln.set_x2(b.i)
if mnSH
if b.l < lSt.bx.get_bottom() and b.c >= lSt.bx.get_bottom() * (1 - lSt.m * .17 * mnMR) and not lSt.l and b.i == lSt.bx.get_right()
if lSt.lq.get_right() + srLN > b.i
lSt.lq.set_right(b.i + 1)
lSt.lq.set_bottom(math.max(math.min(b.l, lSt.lq.get_bottom()), lSt.bx.get_bottom() * (1 - lSt.m * .17 * mnMR)))
else
lSt.lq.set_lefttop(b.i[1], lSt.bx.get_bottom())
lSt.lq.set_rightbottom(b.i + 1, math.max(b.l, lSt.bx.get_bottom() * (1 - lSt.m * .17 * mnMR)))
lSt.lq.set_bgcolor(mnSZC)
lSt.l := true
else if b.l < lSt.bx.get_bottom() and b.c >= lSt.bx.get_bottom() * (1 - lSt.m * .17 * mnMR) and lSt.l and b.i == lSt.bx.get_right()
lSt.lq.set_right(b.i + 1)
lSt.lq.set_bottom(math.max(math.min(b.l, lSt.lq.get_bottom()), lSt.bx.get_bottom() * (1 - lSt.m * .17 * mnMR)))
else if lSt.l and (b.c <= lSt.bx.get_bottom() * (1 - lS.m * .17 * mnMR) or b.c > lSt.bx.get_top())
lSt.l := false
//-----------------------------------------------------------------------------} |
Double Supertrend HTF Filter | https://www.tradingview.com/script/2311ovwP-Double-Supertrend-HTF-Filter/ | Harrocop | https://www.tradingview.com/u/Harrocop/ | 87 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Harrocop
////////////////////////////////////////////////////////////////////////////////////////
// Double HTF Supertrend Filter:
// - The filter consists of two supertrend indicators of different higther time frames
// - Option to change the ATR and Factor of the Supertrends_Align_Down
// - Option to plot (or not) supertrend on the chart
// - The indicator is displayed as a horizontal line at the bottom of the chart:
// 1) Green: Both Supertrends are Up
// 2) Red: Both Supertrends are Down
// 3) Yellow: 1 supertrend is Up and the other id Down
// - The main idea is to combine the two supertrends as a filter in addition to a signal indicator to your liking.
////////////////////////////////////////////////////////////////////////////////////////
//@version=5
indicator(title = "Double Supertrend HTF Filter", shorttitle = "Supertrend HTF Filter", overlay = true)
////////////////////////////////////////////
////// Supertrend HTF 1 //////
////////////////////////////////////////////
SUPER = "Supertrend HTF 1 Settings"
Use_supertrend1 = input.bool(true, title = "Plot Supertrend?", inline = "start", group = SUPER)
TimeFrame_supertrend1 = input.timeframe(title='Higher Time Frame', defval='30', inline = "start", group = SUPER)
ATR = input.int(defval = 10, title = "ATR length", minval = 1, maxval = 1000, step = 1, inline = "super1", group = SUPER)
FACTOR = input.float(defval = 3, title = "ATR length", minval = 0.1, maxval = 10, step = 0.1, inline = "super1", group = SUPER)
[Supertrend_1, direction_1] = ta.supertrend(FACTOR, ATR)
Supertrend_HTF1 = request.security(syminfo.tickerid, TimeFrame_supertrend1, Supertrend_1)
Direction_HTF1 = request.security(syminfo.tickerid, TimeFrame_supertrend1, direction_1)
////////////////////////////////////////////
////// Supertrend HTF 2 //////
////////////////////////////////////////////
SUPER2 = "Supertrend HTF 2 Settings"
Use_supertrend2 = input.bool(true, title = "Plot Supertrend?", inline = "start2", group = SUPER2)
TimeFrame_supertrend2 = input.timeframe(title='Higher Time Frame', defval='240', inline = "start2", group = SUPER2)
ATR2 = input.int(defval = 10, title = "ATR length", minval = 1, maxval = 1000, step = 1, inline = "super2", group = SUPER2)
FACTOR2 = input.float(defval = 3, title = "ATR length", minval = 0.1, maxval = 10, step = 0.1, inline = "super2", group = SUPER2)
[Supertrend_2, direction_2] = ta.supertrend(FACTOR2, ATR2)
Supertrend_HTF2 = request.security(syminfo.tickerid, TimeFrame_supertrend2, Supertrend_2)
Direction_HTF2 = request.security(syminfo.tickerid, TimeFrame_supertrend2, direction_2)
// Define colors based on the Supertrend direction for the higher timeframe
color color_HTF1 = Direction_HTF1 < 0 ? color.green : color.red
plot(Use_supertrend1 ? Supertrend_HTF1 : na, title = "Supertrend HTF 1", color = color_HTF1)
color color_HTF2 = Direction_HTF2 < 0 ? color.green : color.red
plot(Use_supertrend2 ? Supertrend_HTF2 : na, title = "Supertrend HTF 2", color = color_HTF2)
// plot horizontal indicator at bottom of the chart
Supertrends_Align_Up = Direction_HTF1 < 0 and Direction_HTF2 < 0
Supertrends_Align_Down = Direction_HTF1 > 0 and Direction_HTF2 > 0
Suptertrends_Indecisive = Direction_HTF1 < 0 and Direction_HTF2 > 0 or Direction_HTF1 > 0 and Direction_HTF2 < 0
plotshape(Supertrends_Align_Up, title = "Supertrend are Up", style = shape.square, location = location.bottom, color = color.green)
plotshape(Supertrends_Align_Down, title = "Supertrend are Down", style = shape.square, location = location.bottom, color = color.red)
plotshape(Suptertrends_Indecisive, title = "Supertrend are Indecisive", style = shape.square, location = location.bottom, color = color.yellow) |
MACD 3D with Signals [Quantigenics] | https://www.tradingview.com/script/GahehghS-MACD-3D-with-Signals-Quantigenics/ | Quantigenics | https://www.tradingview.com/u/Quantigenics/ | 106 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Quantigenics
//@version=5
indicator("MACD 3D with Signals [Quantigenics]")
Length = input(defval = 10,title = "Length")
FirstDotSignal = input(defval = false,title = "Standard Signal")
YellowDotSignal = input(defval = true,title = "Momentum Crossover Signal")
UpColor = input(defval = color.rgb( 16,776,960 ),title = "Up Color")
DownColor = input(defval = color.red, title = "Down Color")
Trendline = input(defval = color.rgb(113, 113, 113),title = "Trend Line")
StandardDev(series float macd3, simple int len,simple int datatype )=>
val = ta.variance(macd3,len,datatype)//VariancePS(macd3,len,datatype)//
if(val>0)
val := math.sqrt(val)
else
val := 0
val
int FastLength = math.round(Length * 1.2)
int SlowLength = math.round(Length * 2.5)
MACD3D = (ta.ema( hlc3, FastLength ) - ta.ema( hlc3, SlowLength ))* 100//++
Avg = ta.ema(MACD3D, Length)//++
SDev = StandardDev(MACD3D, Length, 1)//++
UB = Avg + 0.43 * SDev
LB = Avg - 0.43 * SDev
chncolor = color.gray
int UporDown = na
if (MACD3D > MACD3D[1])
chncolor := UpColor
UporDown:=1
else
chncolor := DownColor
UporDown:=0
bool Crossover = false
bool Crossunder = false
Crossover := Crossover[1]
Crossunder := Crossunder[1]
dist = math.abs(ta.max(MACD3D)-ta.min(MACD3D))*.01
buysignal = (not Crossover and MACD3D > UB and YellowDotSignal) or (UporDown!= UporDown[1] and UporDown[1] == 0 and FirstDotSignal)
if (not Crossover and MACD3D > UB)
Crossover := true
Crossunder := false
chncolor := YellowDotSignal ? color.yellow : chncolor
alert( "Macd 3D cross up ", alert.freq_once_per_bar)
sellsignal = (not Crossunder and MACD3D < LB and YellowDotSignal) or (UporDown!= UporDown[1] and UporDown[1] == 1 and FirstDotSignal)
if (not Crossunder and MACD3D < LB)
Crossover := false
Crossunder := true
chncolor := YellowDotSignal? color.yellow : chncolor
alert( "Macd 3D cross down ", alert.freq_once_per_bar)
Med = ta.median(LB + UB, 3) / 2
DIFF = math.abs(Med - MACD3D)
float difplot = 0
plotcolor = color.green
if (MACD3D > Med and DIFF >= DIFF[1])
difplot := DIFF
plotcolor := color.green
else if (MACD3D > Med and DIFF < DIFF[1])
difplot := DIFF
plotcolor := color.rgb(43, 101, 45)
else if (MACD3D < Med and DIFF <= DIFF[1])
difplot := -DIFF
plotcolor := color.red
else if (MACD3D < Med and DIFF > DIFF[1] )
difplot := -DIFF
plotcolor := color.rgb(117, 40, 40)
plot(difplot, title = "Differential", color = plotcolor, style = plot.style_histogram,linewidth = 2)
plot(Med, title = "Trendline", color = Trendline)
plot(MACD3D,title = "Macd 3D", color = chncolor, style = plot.style_circles,linewidth = 2)
plotshape(buysignal? MACD3D-dist : na, 'Buy', shape.labelup,location=location.absolute, color=color.green, size=size.small, offset=0)
plotshape(sellsignal? MACD3D+dist : na, 'Sell', shape.labeldown,location=location.absolute, color=color.rgb(195, 57, 57), size=size.small, offset=0)
|
Machine Learning Regression Trend [LuxAlgo] | https://www.tradingview.com/script/58YCiPaa-Machine-Learning-Regression-Trend-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,470 | 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("Machine Learning Regression Trend [LuxAlgo]", "LuxAlgo - Machine Learning Regression Trend", overlay = true, max_labels_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input.int(100, minval = 5)
widthMult = input.float(2, 'Channel Width', minval = 0)
src = input(close, 'Source')
//RANSAC
inlineN = input.int(10, 'Minimum Inliners', minval = 1, group = 'RANSAC')
errorType = input.string('Auto', 'Allowed Error', options = ['Auto', 'Fixed'], inline = 'error', group = 'RANSAC')
minError = input.float(1., '', minval = 0, step = 0.5, inline = 'error', group = 'RANSAC')
maxIter = input(10000, 'Maximum Iteration Steps', group = 'RANSAC')
//Style
lineCss = input(#2157f3, 'Line Color', group = 'Style')
showMargin = input(true, 'Show Margin', inline = 'margin', group = 'Style')
marginCss = input(color.new(#2157f3, 80), '', inline = 'margin', group = 'Style')
showChannel = input(true, 'Show Channel', inline = 'channel', group = 'Style')
channelCss = input(color.new(color.gray, 90), '', inline = 'channel', group = 'Style')
showInliners = input(true, 'Show Inliners', inline = 'inliners', group = 'Style')
inlinersCss = input(#2157f3, '', inline = 'inliners', group = 'Style')
showOutliers = input(true, 'Show Outliers', inline = 'outliers', group = 'Style')
outliersCss = input(#ff1100, '', inline = 'outliers', group = 'Style')
//-----------------------------------------------------------------------------}
//UDT
//-----------------------------------------------------------------------------{
type LinearRegression
array<float> y
array<int> x
array<float> inliners_y
array<int> inliners_x
float a
float b
//-----------------------------------------------------------------------------}
//Methods
//-----------------------------------------------------------------------------{
method fit(LinearRegression id)=>
a = id.y.covariance(id.x) / id.x.variance()
b = id.y.avg() - a * id.x.avg()
id.a := a
id.b := b
method predict(LinearRegression id, x)=>
predicted = id.a * x + id.b
method rmse(LinearRegression id)=>
i = 0
rmse = 0.
for value in id.y
rmse += math.pow(value - id.predict(id.x.get(i)), 2)
i += 1
math.sqrt(rmse / i)
//-----------------------------------------------------------------------------}
//Get data
//-----------------------------------------------------------------------------{
var y = array.new<float>(0)
var x = array.new<int>(0)
n = bar_index
y.unshift(src)
x.unshift(n)
if y.size() > length
y.pop()
x.pop()
//Threshold
threshold = switch errorType
'Auto' => ta.cum(math.abs(close - open)) / (n+1) * minError
'Fixed' => minError
//-----------------------------------------------------------------------------}
//Display linear regression
//-----------------------------------------------------------------------------{
if barstate.islastconfirmedhistory
size = inlineN
LinearRegression final_model = na
for i = 0 to maxIter-1
//Possible inliners
inliners_y = array.new<float>(0)
inliners_x = array.new<int>(0)
//Determine random indices
for j = 0 to 1
idx = int(math.random(0, length-1))
inliners_y.unshift(y.get(idx))
inliners_x.unshift(x.get(idx))
//Get model
model = LinearRegression.new(inliners_y, inliners_x)
model.fit()
true_inliners_y = array.new<float>(0)
true_inliners_x = array.new<int>(0)
k = 0
for point in y
pred = model.predict(x.get(k))
if math.abs(point - pred) < threshold
true_inliners_y.unshift(point)
true_inliners_x.unshift(x.get(k))
k += 1
if true_inliners_y.size() >= size
final_model := LinearRegression.new(true_inliners_y, true_inliners_x
, inliners_y = true_inliners_y
, inliners_x = true_inliners_x)
final_model.fit()
size := true_inliners_y.size()
//Tets for suitable model
if na(final_model)
runtime.error('A suitable model could not be obtained from the provided data/hyperparameters')
//Set line
y1 = final_model.predict(n-length+1)
y2 = final_model.predict(n)
line.new(n-length+1, y1, n, y2, color = lineCss, extend = extend.right)
//Error Margins
if showMargin
upper = line.new(n-length+1, y1 + threshold, n, y2 + threshold, color = na)
lower = line.new(n-length+1, y1 - threshold, n, y2 - threshold, color = na)
linefill.new(upper, lower, marginCss)
//Channel
final_model.y := y
final_model.x := x
width = final_model.rmse() * widthMult
if showChannel
upper = line.new(n-length+1, y1 + width, n, y2 + width, color = na, extend = extend.right)
lower = line.new(n-length+1, y1 - width, n, y2 - width, color = na, extend = extend.right)
linefill.new(upper, lower, channelCss)
//Show inliners/outliners
k = 0
for value in y
if final_model.inliners_x.includes(n-k)
if showInliners
label.new(n-k, value, '•'
, color = color(na)
, textcolor = inlinersCss
, style = label.style_label_center)
else if showOutliers
label.new(n-k, value, '•'
, color = color(na)
, textcolor = outliersCss
, style = label.style_label_center)
k += 1
//-----------------------------------------------------------------------------} |
ICT Clean Midnight [dR-Algo] | https://www.tradingview.com/script/0Rdqv6CK/ | dR-Algo | https://www.tradingview.com/u/dR-Algo/ | 22 | 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/
// © dR-Algo
//@version=5
indicator('ICT Clean Midnight [dR-Algo]', shorttitle='Midnight [dR]', overlay=true)
//
// *** Input ***
//
var visualGroup = "Visual Settings"
var color defBlueColor = #2861ff2a
visualColor = input.color(defval = defBlueColor, title = "Color", group = visualGroup)
visualLineStyle = input.string(defval = "solid", title = "Line Style", options=["solid", "dotted", "dashed"], group = visualGroup)
visualShowLabel = input.bool(defval = false, title = "Show Labels", tooltip = "Show Labels")
visualLineStyleOption = switch visualLineStyle
"solid" => line.style_solid
"dotted" => line.style_dotted
"dashed" => line.style_dashed
//
// *** Draw on Chart ***
//
// Midnight
// hour = 23 => Midnight
if hour(time) == 23 and hour(time[1]) != 23
line.new(x1=bar_index, y1=low, x2=bar_index, y2=high, color=visualColor, width=1, extend=extend.both, style = visualLineStyleOption)
|
All Candlestick Patterns on Backtest [By MUQWISHI] | https://www.tradingview.com/script/OsTuKG4q-All-Candlestick-Patterns-on-Backtest-By-MUQWISHI/ | MUQWISHI | https://www.tradingview.com/u/MUQWISHI/ | 853 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MUQWISHI
//@version=5
indicator("Candlestick Patterns on Backtest", overlay = true, max_labels_count = 500, max_bars_back = 50)
import MUQWISHI/CandlestickPatterns/2 as cp
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | INPUT |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
s = " "
// +++++++++++++++ Table Settings
// Location
tablePos = input.string("Middle Right", "Table Location ",
["Top Right" , "Middle Right" , "Bottom Right" ,
"Top Center", "Middle Center" , "Bottom Center",
"Top Left" , "Middle Left" , "Bottom Left" ], inline = "1", group = "Table Setting")
// Size
tableSiz = input.string("Tiny", "",
["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], inline = "1", group = "Table Setting")
// Table Color
posCol = input.color(#006400, "Positive", group = "Table Setting", inline = "4")
neuCol = input.color(#ffffff, " Neutral", group = "Table Setting", inline = "4")
negCol = input.color(#882336, " Negative ", group = "Table Setting", inline = "4")
tBgCol = input.color(#696969, "Titles ", group = "Table Setting", inline = "2")
txtCl1 = input.color(#ffffff, " Text", group = "Table Setting", inline = "2")
txtCl2 = input.color(#000000, "", group = "Table Setting", inline = "2")
// +++++++++++++++ Label Color
labChk = input.bool(false, "Show Pattern Label", inline = "lab")
labCl1 = input.color(color.blue, "", inline = "lab")
labCl2 = input.color(color.red, "", inline = "lab")
labCl3 = input.color(color.white, "", inline = "lab")
// +++++++++++++++ Backtest Setting
sTim = input.time(timestamp("01 Jan 2000 20:00"), "From", inline = "0", group = "Backtest Setting",
tooltip = "Backtest Starting Period\n\nNote: If the datetime of the first candle on the chart" +
" is after the entered datetime, the calculation will start from the first candle on the chart.")
cash = input.float(100000, "Initial Equity ($) ", 1, group = "Backtest Setting")
mrgn = input.float(1, "Leverage", 1, group = "Backtest Setting")
enMod = input.string("At Close", "Entry Mode", ["At Close", "Breakout High (Low for Short)"], group = "Backtest Setting")
cnclC = input.bool(true, "Cancel Entry Within Bars", group = "Backtest Setting", inline = "cnc")
cnclN = input.int(3, "", 1, group = "Backtest Setting", inline = "cnc",
tooltip = "This option is applicable with\n {Entry Mode = Breakout High (Low for Short)}\n"+
"\nCancel the Entry Order if it's not executed within certain number of Bars.")
rngTy = input.string("ATR Range", "StopLoss"+s+s+s+s, ["ATR Range", "Pattern Range"], inline = "00")
stpls = input.float(1, ""+s+s, 0, step = 0.1,
tooltip = "Example & Illustration\n0.5 is half distance of range."+ "\n1 is distance of range."
+ "\n2 is twice distance of range.\n\nRange Types:\n1. Pattern Range: high of pattern - low of pattern"
+ "\n2. ATR: Average True Range\n\n*Range is calculated from entry level", inline = "00")
// Risk Rewards Inputs
rw01c = input.bool(true, "", inline = "01")
rw02c = input.bool(true, "", inline = "02")
rw03c = input.bool(true, "", inline = "03")
rw04c = input.bool(true, "", inline = "04")
rw05c = input.bool(true, "", inline = "05")
rw06c = input.bool(true, "", inline = "06")
rw07c = input.bool(true, "", inline = "07")
rw01v = input.float(1.0, "[01] Risk:Reward ", 0, inline = "01")
rw02v = input.float(1.5, "[02] Risk:Reward ", 0, inline = "02")
rw03v = input.float(2.0, "[03] Risk:Reward ", 0, inline = "03")
rw04v = input.float(3.0, "[04] Risk:Reward ", 0, inline = "04")
rw05v = input.float(4.0, "[05] Risk:Reward ", 0, inline = "05")
rw06v = input.float(5.0, "[06] Risk:Reward ", 0, inline = "06")
rw07v = input.float(6.0, "[07] Risk:Reward ", 0, inline = "07")
// +++++++++++++++ Technical Settings
// Moving Average
maChk = input.bool(true, "Detect Trend Based on SMA", inline = "0", group = "Technical")
maLen = input.int(50, "", 1, inline = "0", group = "Technical")
// +++++++++++++++ Candle Patterns
// Type
ptrnTyp = input.string("Both", "Pattern Type", ["Bullish", "Bearish", "Both"], group = "Candle Patterns")
// Patterns
abandonedBabyChk = input.bool(true, "Abandoned Baby", group = "Candle Patterns", inline = "01")
dbarkCloudCoverChk = input.bool(true, "Dark Cloud Cover", group = "Candle Patterns", inline = "01")
dojiStarChk = input.bool(true, "Doji Star", group = "Candle Patterns", inline = "02")
downsideTasukiGapChk = input.bool(true, "Downside Tasuki Gap", group = "Candle Patterns", inline = "02")
dragonflyDojiChk = input.bool(true, "Dragonfly Doji", group = "Candle Patterns", inline = "03")
engulfingChk = input.bool(true, "Engulfing", group = "Candle Patterns", inline = "03")
eveningDojiStarChk = input.bool(true, "Evening Doji Star", group = "Candle Patterns", inline = "03")
eveningStarChk = input.bool(true, "Evening Star", group = "Candle Patterns", inline = "04")
fallingThreeMethodsChk = input.bool(true, "Falling Three Methods", group = "Candle Patterns", inline = "04")
fallingWindowChk = input.bool(true, "Falling Window", group = "Candle Patterns", inline = "05")
gravestoneDojiChk = input.bool(true, "Gravestone Doji", group = "Candle Patterns", inline = "05")
hammerChk = input.bool(true, "Hammer", group = "Candle Patterns", inline = "05")
hangingManChk = input.bool(true, "Hanging Man", group = "Candle Patterns", inline = "06")
haramiCrossChk = input.bool(true, "Harami Cross", group = "Candle Patterns", inline = "06")
haramiChk = input.bool(true, "Harami", group = "Candle Patterns", inline = "06")
invertedHammerChk = input.bool(true, "Inverted Hammer", group = "Candle Patterns", inline = "07")
kickingChk = input.bool(true, "Kicking", group = "Candle Patterns", inline = "07")
longLowerShadowChk = input.bool(true, "Long Lower Shadow", group = "Candle Patterns", inline = "08")
longUpperShadowChk = input.bool(true, "Long Upper Shadow", group = "Candle Patterns", inline = "08")
marubozuBlackChk = input.bool(true, "Marubozu Black", group = "Candle Patterns", inline = "09")
marubozuWhiteChk = input.bool(true, "Marubozu White", group = "Candle Patterns", inline = "09")
morningDojiStarChk = input.bool(true, "Morning Doji Star", group = "Candle Patterns", inline = "10")
morningStarChk = input.bool(true, "Morning Star", group = "Candle Patterns", inline = "10")
onNeckChk = input.bool(true, "On Neck", group = "Candle Patterns", inline = "10")
piercingChk = input.bool(true, "Piercing", group = "Candle Patterns", inline = "11")
risingThreeMethodsChk = input.bool(true, "Rising Three Methods", group = "Candle Patterns", inline = "11")
risingWindowChk = input.bool(true, "Rising Window", group = "Candle Patterns", inline = "12")
shootingStarChk = input.bool(true, "Shooting Star", group = "Candle Patterns", inline = "12")
threeBlackCrowsChk = input.bool(true, "Three Black Crows", group = "Candle Patterns", inline = "14")
threeWhiteSoldiersChk = input.bool(true, "Three White Soldiers", group = "Candle Patterns", inline = "14")
triStarChk = input.bool(true, "Tri-Star", group = "Candle Patterns", inline = "15")
tweezerBottomChk = input.bool(true, "Tweezer Bottom", group = "Candle Patterns", inline = "15")
tweezerTopChk = input.bool(true, "Tweezer Top", group = "Candle Patterns", inline = "15")
upsideTasukiGapChk = input.bool(true, "Upside Tasuki Gap", group = "Candle Patterns", inline = "16")
pattern(a, x) =>
switch a
01 => x == "d" ? "Abandoned Baby (Bear)" : "AB"
02 => x == "d" ? "Abandoned Baby (Bull)" : "AB"
03 => x == "d" ? "Dark Cloud Cover (Bear)" : "DCC"
04 => x == "d" ? "Doji Star (Bear)" : "DS"
05 => x == "d" ? "Doji Star (Bull)" : "DS"
06 => x == "d" ? "Downside Tasuki Gap (Bear)" : "DTG"
07 => x == "d" ? "Dragonfly Doji (Bull)" : "DD"
08 => x == "d" ? "Engulfing (Bear)" : "BE"
09 => x == "d" ? "Engulfing (Bull)" : "BE"
10 => x == "d" ? "Evening Doji Star (Bear)" : "EDS"
11 => x == "d" ? "Evening Star (Bear)" : "ES"
12 => x == "d" ? "Falling Three Methods (Bear)" : "FTM"
13 => x == "d" ? "Falling Window (Bear)" : "FW"
14 => x == "d" ? "Gravestone Doji (Bear)" : "GD"
15 => x == "d" ? "Hammer (Bull)" : "H"
16 => x == "d" ? "Hanging Man (Bear)" : "HM"
17 => x == "d" ? "Harami Cross (Bear)" : "HC"
18 => x == "d" ? "Harami Cross (Bull)" : "HC"
19 => x == "d" ? "Harami (Bear)" : "BH"
20 => x == "d" ? "Harami (Bull)" : "BH"
21 => x == "d" ? "Inverted Hammer (Bull)" : "IH"
22 => x == "d" ? "Kicking (Bear)" : "K"
23 => x == "d" ? "Kicking (Bull)" : "K"
24 => x == "d" ? "Long Lower Shadow (Bull)" : "LLS"
25 => x == "d" ? "Long Upper Shadow (Bear)" : "LUS"
26 => x == "d" ? "Marubozu Black (Bear)" : "MB"
27 => x == "d" ? "Marubozu White (Bull)" : "MW"
28 => x == "d" ? "Morning Doji Star (Bull)" : "MDS"
29 => x == "d" ? "Morning Star (Bull)" : "MS"
30 => x == "d" ? "On Neck (Bear)" : "ON"
31 => x == "d" ? "Piercing (Bull)" : "P"
32 => x == "d" ? "Rising Three Methods (Bull)" : "RTM"
33 => x == "d" ? "Rising Window (Bull)" : "RW"
34 => x == "d" ? "Shooting Star (Bear)" : "SS"
35 => x == "d" ? "Three Black Crows (Bear)" : "3BC"
36 => x == "d" ? "Three White Soldiers (Bull)" : "3WS"
37 => x == "d" ? "Tri-Star (Bear)" : "TS"
38 => x == "d" ? "Tri-Star (Bull)" : "TS"
39 => x == "d" ? "Tweezer Bottom (Bull)" : "TB"
40 => x == "d" ? "Tweezer Top (Bear)" : "TT"
41 => x == "d" ? "Upside Tasuki Gap (Bull)" : "UTG"
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | CALCULATION |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// Create Matrices
var strt = sTim
var rwIn = array.new<string>(na)
rwInFun(flg, val) =>
if flg
array.push(rwIn, "1:" + str.tostring(val))
if barstate.isfirst
strt := time > sTim ? time : sTim
rwInFun(true, "0"), rwInFun(rw01c, rw01v), rwInFun(rw02c, rw02v), rwInFun(rw03c, rw03v)
rwInFun(rw04c, rw04v), rwInFun(rw05c, rw05v), rwInFun(rw06c, rw06v), rwInFun(rw07c, rw07v)
var rtnMtx = matrix.new<float>(na, array.size(rwIn), na)
var infMtx = matrix.new<string>(na, array.size(rwIn), na)
// Get Label Location
loc = ta.sma(high - low, 14)/2
// Label ToolTip
lbTip(id, lb, row, tp, ent, ext, pnl, rtn) =>
sign1 = (math.sign((rtn - 1)) < 0 ? "-" : "")
sign2 = (math.sign((rtn - 1)) < 0 ? "-" : "+")
label.set_tooltip(lb, "Pattern = " + pattern(row, "d") + "\nRisk:Reward = 1:" + str.tostring(tp) +
"\n\nResult = " + id + "\nEntry = " + str.tostring(ent, format.mintick) +
"\nExit = " + str.tostring(ext, format.mintick) + "\nPnL = " + str.tostring(pnl * 100, format.percent) +
"\n\nEquity = " + sign1 + "$" + str.tostring(math.abs((rtn - 1) * cash + cash), "#.00") +
" (" + sign2 + str.tostring(math.abs(rtn - 1) * 100, format.percent) + ")")
// Matrix ToolTip
mxTip(infMtx, idx, col, nmTrd, nmWin, nmLos, rtn) =>
matrix.set(infMtx, idx, col, "Number of Trades: " + str.tostring(nmTrd) +
"\nWon: " + str.tostring(nmWin) + "\nLost: " + str.tostring(nmLos) +
"\nCum PnL: " + str.tostring((rtn - 1) * 100, format.percent) +
"\nEquity: $" + str.tostring((rtn - 1) * cash + cash, "#.00"))
// Pattern Type
bull = not(ptrnTyp == "Bearish")
bear = not(ptrnTyp == "Bullish")
// Trend Detection (Moving Average)
uTrd = maChk ? close > ta.sma(close, maLen) : true
dTrd = maChk ? close < ta.sma(close, maLen) : true
// Backtest Function
backtest(int side, bool ptrn, int cand, float tp, int row, int col) =>
// [0] Declaring Variables
idx = array.indexof(matrix.col(rtnMtx, 0), row)
var label lb = na, var nmTrd = 0, var nmWin = 0, var nmLos = 0
var bn = 0, var rtn = 1.0, var onTrd = false,
var enTrd = float(na), var exTrd = float(na),
var tpTrd = float(na), var slTrd = float(na)
// [2] Exit Singal
if onTrd
// TakeProfit
if (side == 1 ? high >= tpTrd : low <= tpTrd)
exTrd := (side == 1 ? open >= tpTrd ? open : tpTrd :
open <= tpTrd ? open : tpTrd)
// Calculate Return
pnl = math.abs((exTrd - enTrd)/enTrd) * mrgn
rtn := rtn * (1 + pnl)
nmWin += 1
// Fill Label Tooltip
lbTip("Won", lb, row, tp, enTrd, exTrd, pnl, rtn)
// Fill Mtrix
matrix.set(rtnMtx, idx, col, math.round((rtn - 1) * 100, 2))
mxTip(infMtx, idx, col, nmTrd, nmWin, nmLos, rtn)
// Rest
onTrd := false, enTrd := float(na), exTrd := float(na)
// StopLoss
else if (side == 1 ? low <= slTrd : high >= slTrd)
exTrd := (side == 1 ? open <= slTrd ? open : slTrd :
open >= slTrd ? open : slTrd)
// Calculate Return
pnl = math.abs((exTrd - enTrd)/enTrd) * mrgn
rtn := rtn * (1 - pnl)
nmLos += 1
// Fill Label Tooltip
lbTip("Lost", lb, row, tp, enTrd, exTrd, -pnl, rtn)
// Fill Mtrix
matrix.set(rtnMtx, idx, col, math.round((rtn - 1) * 100, 2))
mxTip(infMtx, idx, col, nmTrd, nmWin, nmLos, rtn)
// Rest
onTrd := false, enTrd := float(na), exTrd := float(na)
// [1] Entry Signals
var upRng = float(na), upRng1 = ta.highest(cand)
var dnRng = float(na), dnRng1 = ta.lowest(cand)
var trRng = float(na), trRng1 = ta.rma(ta.tr, 14)
if ptrn and stpls > 0 and na(exTrd) and not(side == 1 ? high > enTrd : low < enTrd)
upRng := upRng1, dnRng := dnRng1, trRng := na(trRng1) ? ta.tr : trRng1
enTrd := enMod == "At Close" ? close : side == 1 ? high : low
bn := bar_index
if not(onTrd)
if (enMod == "At Close" ? enTrd : (side == 1 ? high > enTrd : low < enTrd)) and
(enMod != "At Close" and cnclC ? cnclN >= bar_index - bn : true) and rtn > 0
enTrd := side == 1 ? open >= enTrd ? open : enTrd :
open <= enTrd ? open : enTrd
onTrd := true, nmTrd += 1, exTrd := enTrd
// Set TP & SL
slRng = (rngTy == "Pattern Range" ? upRng - dnRng : trRng) * stpls
tpTrd := enTrd + (side == 1 ? slRng : -slRng) * tp
slTrd := enTrd + (side == 1 ? -slRng : slRng)
// Draw Trade
if labChk
color = side == 1 ? labCl1 : labCl2
prce = side == 1 ? low [bar_index - bn] - loc[bar_index - bn] * col :
high[bar_index - bn] + loc[bar_index - bn] * col
lb := label.new(bar_index[bar_index - bn], prce, pattern(row, "") + "\n1:" + str.tostring(tp),
xloc.bar_index, yloc.price, color, label.style_label_center, labCl3, size.small,
tooltip = "Pattern = " + pattern(row, "d") + "\nRisk:Reward = 1:" + str.tostring(tp)
+ "\n\n" + "Entry = " + str.tostring(enTrd, format.mintick) + "\nTakeProfit = " +
str.tostring(tpTrd, format.mintick) + "\nStopLoss = " + str.tostring(slTrd, format.mintick))
enTrd := not(onTrd) and enMod != "At Close" and cnclC and cnclN < bar_index - bn ? float(na) : enTrd
// Run Function
run(side, flg, ptrn, cndl, row) =>
if flg
if barstate.isfirst
matrix.add_row(rtnMtx, matrix.rows(rtnMtx), array.new<float>(array.size(rwIn), 0))
matrix.add_row(infMtx, matrix.rows(infMtx), array.new<string>(array.size(rwIn), "No Trades"))
matrix.set(rtnMtx, matrix.rows(rtnMtx) - 1, 0, row)
matrix.set(infMtx, matrix.rows(infMtx) - 1, 0, str.tostring(row))
i = 0, p = ptrn and time >= strt
if rw01c
i += 1, backtest(side, p, cndl, rw01v, row, i)
if rw02c
i += 1, backtest(side, p, cndl, rw02v, row, i)
if rw03c
i += 1, backtest(side, p, cndl, rw03v, row, i)
if rw04c
i += 1, backtest(side, p, cndl, rw04v, row, i)
if rw05c
i += 1, backtest(side, p, cndl, rw05v, row, i)
if rw06c
i += 1, backtest(side, p, cndl, rw06v, row, i)
if rw07c
i += 1, backtest(side, p, cndl, rw07v, row, i)
// Call Run on Patterns
run(-1, bear and abandonedBabyChk, cp.abandonedBaby("bear") and uTrd[2], 3, 1)
run( 1, bull and abandonedBabyChk, cp.abandonedBaby("bull") and dTrd[2], 3, 2)
run(-1, bear and dbarkCloudCoverChk, cp.darkCloudCover() and uTrd[1], 2, 3)
run(-1, bear and dojiStarChk, cp.dojiStar("bear") and uTrd, 2, 4)
run( 1, bull and dojiStarChk, cp.dojiStar("bull") and dTrd, 2, 5)
run(-1, bear and downsideTasukiGapChk, cp.downsideTasukiGap() and dTrd, 3, 6)
run( 1, bull and dragonflyDojiChk, cp.dragonflyDoji(), 1, 7)
run(-1, bear and engulfingChk, cp.engulfing("bear") and uTrd, 2, 08)
run( 1, bull and engulfingChk, cp.engulfing("bull") and dTrd, 2, 09)
run(-1, bear and eveningDojiStarChk, cp.eveningDojiStar() and uTrd, 3, 10)
run(-1, bear and eveningStarChk, cp.eveningStar() and uTrd, 3, 11)
run(-1, bear and fallingThreeMethodsChk, cp.fallingThreeMethods() and dTrd[4], 5, 12)
run(-1, bear and fallingWindowChk, cp.fallingWindow() and dTrd[1], 1, 13)
run(-1, bear and gravestoneDojiChk, cp.gravestoneDoji() and bear, 1, 14)
run( 1, bull and hammerChk, cp.hammer() and dTrd, 1, 15)
run(-1, bear and hangingManChk, cp.hangingMan() and uTrd, 1, 16)
run(-1, bear and haramiCrossChk, cp.haramiCross("bear") and uTrd[1], 2, 17)
run( 1, bull and haramiCrossChk, cp.haramiCross("bull") and dTrd[1], 2, 18)
run(-1, bear and haramiChk, cp.harami("bear") and uTrd[1], 2, 19)
run( 1, bull and haramiChk, cp.harami("bull") and dTrd[1], 2, 20)
run( 1, bull and invertedHammerChk, cp.invertedHammer() and dTrd, 1, 21)
run(-1, bear and kickingChk, cp.kicking("bear") and bear, 2, 22)
run( 1, bull and kickingChk, cp.kicking("bull"), 2, 23)
run( 1, bull and longLowerShadowChk, cp.longLowerShadow(), 1, 24)
run(-1, bear and longUpperShadowChk, cp.longUpperShadow() and bear, 1, 25)
run(-1, bear and marubozuBlackChk, cp.marubozuBlack() and bear, 1, 26)
run( 1, bull and marubozuWhiteChk, cp.marubozuWhite(), 1, 27)
run( 1, bull and morningDojiStarChk, cp.morningDojiStar() and dTrd, 3, 28)
run( 1, bull and morningStarChk, cp.morningStar() and dTrd, 3, 29)
run(-1, bear and onNeckChk, cp.onNeck() and dTrd, 2, 30)
run( 1, bull and piercingChk, cp.piercing() and dTrd[1], 2, 31)
run( 1, bull and risingThreeMethodsChk, cp.risingThreeMethods() and uTrd[4], 5, 32)
run( 1, bull and risingWindowChk, cp.risingWindow() and uTrd[1], 1, 33)
run(-1, bear and shootingStarChk, cp.shootingStar() and uTrd, 1, 34)
run(-1, bear and threeBlackCrowsChk, cp.threeBlackCrows() and bear, 3, 35)
run( 1, bull and threeWhiteSoldiersChk, cp.threeWhiteSoldiers(), 3, 36)
run(-1, bear and triStarChk, cp.triStar("bear") and uTrd[2], 3, 37)
run( 1, bull and triStarChk, cp.triStar("bull") and dTrd[2], 3, 38)
run( 1, bull and tweezerBottomChk, cp.tweezerBottom() and dTrd[1], 2, 39)
run(-1, bear and tweezerTopChk, cp.tweezerTop() and uTrd[1], 2, 40)
run( 1, bull and upsideTasukiGapChk, cp.upsideTasukiGap() and uTrd, 3, 41)
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | TABLE |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// Get Tbale Location & Size
locNsze(x) =>
y = str.split(str.lower(x), " ")
out = ""
for i = 0 to array.size(y) - 1
out := out + array.get(y, i)
if i != array.size(y) - 1
out := out + "_"
out
// Create Table
nCols = matrix.columns(rtnMtx)
nRows = matrix.rows(rtnMtx)
var tbl = table.new(locNsze(tablePos), nCols, nRows+2, color.new(tBgCol, 100),
color.new(tBgCol, 100), 1, color.new(tBgCol, 100), 1)
// Cell Function
cell(col, row, txt, color, txtCol, tip) =>
table.cell(tbl, col, row, text = txt, text_color = txtCol, bgcolor = color,
text_size = locNsze(tableSiz), tooltip = tip)
if barstate.islast
table.clear(tbl, 0, 0, nCols-1, nRows+1)
// Find Max Min Values
maxVal = 100.0, minVal = -50.0
if nCols > 1 and nRows > 0
mtxVal = matrix.submatrix(rtnMtx, 0, nRows, 1, nCols)
maxVal := matrix.max(mtxVal) < 100 and matrix.max(mtxVal) != 0 ? matrix.max(mtxVal) : 100
minVal := matrix.min(mtxVal) > -50 and matrix.min(mtxVal) != 0 ? matrix.min(mtxVal) : -50
if array.size(rwIn) > 1
cell(1, 0, "R E T U R N (%)", tBgCol, txtCl1, "Return (%)"), table.merge_cells(tbl, 1, 0, nCols-1, 0)
start = "Backtest Start From\n" + str.format_time(strt, "yyyy-MM-dd", syminfo.timezone)
cell(0, 0, start, tBgCol, txtCl1, start)
cell(0, 1, "P A T T E R N S", tBgCol, txtCl1, "Patterns")
y = 2
if array.size(rwIn) > 0
for j = 0 to array.size(rwIn) - 1
if j > 0
a = array.get(rwIn, j), cell(j, 1, a, tBgCol, txtCl1, a)
if nCols - 1 >= j and nRows > 0
for i = 0 to nRows - 1
if j == 0
p = pattern(matrix.get(rtnMtx, i, 0), "d"), cell(j, y, p, tBgCol, txtCl1, p)
else
val = matrix.get(rtnMtx, i, j)
col = val >= 0 ? color.from_gradient(val, 0, maxVal, neuCol, posCol) :
color.from_gradient(val, minVal, 0, negCol, neuCol)
cell(j, y, str.tostring(val, format.percent), col, txtCl2, matrix.get(infMtx, i, j))
y += 1
y := 2
|
CE - 42MACRO Equity Factor Table | https://www.tradingview.com/script/b3PcU8qn-CE-42MACRO-Equity-Factor-Table/ | Celestial-Eye | https://www.tradingview.com/u/Celestial-Eye/ | 194 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Celestial-Eye
//@version=5
indicator("🌌 CE - 42MACRO Equity Factor Table 🌌", "🌌 CE - EFT 🌌")
showCorrTab = input.bool(true, "Show Correlation Table", tooltip = "Plots the Correlation table", group = "🌌 Table Settings Correlation 🌌")
l = input.int (14, "Correlation Length", tooltip = "Defines the time horizon for the Correlation Table", group = "🌌 Table Settings Correlation 🌌")
showPerfTab = input.bool(true, "Show Performance Table", tooltip = "Plots the Performance table", group = "🌌 Table Settings Performance 🌌")
rocPeriod = input.int (14, "RoC Period", minval=1, tooltip = "Defines the time horizon for the Equity Table", group = "🌌 Table Settings Performance 🌌")
useSharpe = input.bool(false, "Use Sharpe instead of Rate of Change", group = "🌌 Table Settings Performance 🌌")
showImplied = input.bool(false, "Show Implied Correlation?", tooltip = "Shows Implied Correlation on Chart, disable all other Visuals for best Experience", group = "Implied Correlation - ONLY ENABLE A SINGLE IMPLIED CORRELATION OPTION")
showImpliedNorm = input.bool(false, "Show Normalized Implied Correlation?", tooltip = "Better for Crypto... As Crypto Moves faster", group = "Implied Correlation - ONLY ENABLE A SINGLE IMPLIED CORRELATION OPTION")
norm_periodImpl = input.int (50, "Normalization lookback", minval=1, tooltip = "Defines the time horizon for the Normalization - 40 to 70 is a good start", group = "Implied Correlation - ONLY ENABLE A SINGLE IMPLIED CORRELATION OPTION")
showImpliedNorm2 = input.bool(false, "Show double Normalized Implied Correlation?",tooltip = "Even better for Crypto... As Crypto Moves faster", group = "Implied Correlation - ONLY ENABLE A SINGLE IMPLIED CORRELATION OPTION")
norm_periodImpl2 = input.int (40, "Second Normalization lookback", minval=1, tooltip = "Defines the time horizon for the second Normalization - usually 10 - 20 less than first Normalization is best", group = "Implied Correlation - ONLY ENABLE A SINGLE IMPLIED CORRELATION OPTION")
useMA = input.bool(true, "Overlay HMA for slightly earlier signals?", group = "HMA for Implied Correlation")
MALen = input.int (3, "Lenght of HMA", group = "HMA for Implied Correlation")
HMASigCol = input.bool(false, "Background Coloring for HMA Signals", tooltip = "Uses HMA to give signals, might be earlier but contain some false positives", group = "HMA for Implied Correlation")
implBarCol = input.bool(false, "Barcoloring for Impl. Correlation?", tooltip = "Barcoloring for chosen Implied Correlation", group = "Visuals")
reg = input.bool(false, "Show approximate Macroeconomic GRID Regimes", group = "Visuals")
col = input.bool(false, "Show Risk On - Risk Off periods", tooltip = "Works better with higher timeframes/RoC Periods; Macro data takes a while to be realized", group = "Visuals")
//request securities
VO = request.security("VO", "D", close, barmerge.gaps_off)
SPHD = request.security("SPHD", "D", close, barmerge.gaps_off)
EEM = request.security("EEM", "D", close, barmerge.gaps_off)
DXJ = request.security("DXJ", "D", close, barmerge.gaps_off)
QQQ = request.security("QQQ", "D", close, barmerge.gaps_off)
EWZ = request.security("EWZ", "D", close, barmerge.gaps_off)
EWU = request.security("EWU", "D", close, barmerge.gaps_off)
IWF = request.security("IWF", "D", close, barmerge.gaps_off)
SPY = request.security("SPY", "D", close, barmerge.gaps_off)
INDA = request.security("INDA", "D", close, barmerge.gaps_off)
FXI = request.security("FXI", "D", close, barmerge.gaps_off)
SPLV = request.security("SPLV", "D", close, barmerge.gaps_off)
ACWX = request.security("ACWX", "D", close, barmerge.gaps_off)
EZU = request.security("EZU", "D", close, barmerge.gaps_off)
QUAL = request.security("QUAL", "D", close, barmerge.gaps_off)
SPHB = request.security("SPHB", "D", close, barmerge.gaps_off)
MTUM = request.security("MTUM", "D", close, barmerge.gaps_off)
OEF = request.security("OEF", "D", close, barmerge.gaps_off)
IWM = request.security("IWM", "D", close, barmerge.gaps_off)
//calculate the average RoC
avgROC = (ta.roc(VO, rocPeriod) +
ta.roc(SPHD, rocPeriod) +
ta.roc(EEM, rocPeriod) +
ta.roc(DXJ, rocPeriod) +
ta.roc(QQQ, rocPeriod) +
ta.roc(EWZ, rocPeriod) +
ta.roc(EWU, rocPeriod) +
ta.roc(IWF, rocPeriod) +
ta.roc(SPY, rocPeriod) +
ta.roc(INDA, rocPeriod) +
ta.roc(FXI, rocPeriod) +
ta.roc(ACWX, rocPeriod) +
ta.roc(EZU, rocPeriod) +
ta.roc(QUAL, rocPeriod) +
ta.roc(SPHB, rocPeriod) +
ta.roc(SPLV, rocPeriod) +
ta.roc(OEF, rocPeriod) +
ta.roc(IWM, rocPeriod) +
ta.roc(MTUM, rocPeriod)) / 19
//function to calculate Sharpe Ratio
f_sharpe(src, lookback) =>
float daily_return = src / src[1] - 1
returns_array = array.new_float(0)
for i = 0 to lookback
array.push(returns_array, daily_return[i])
standard_deviation = array.stdev(returns_array)
mean = array.avg(returns_array)
math.round(mean / standard_deviation * math.sqrt(lookback), 2)
var float rocVO = na
var float rocSPHD = na
var float rocEEM = na
var float rocDXJ = na
var float rocQQQ = na
var float rocEWZ = na
var float rocEWU = na
var float rocIWF = na
var float rocSPY = na
var float rocINDA = na
var float rocFXI = na
var float rocSPLV = na
var float rocACWX = na
var float rocEZU = na
var float rocQUAL = na
var float rocSPHB = na
var float rocMTUM = na
var float rocIWM = na
var float rocOEF = na
if useSharpe == false
// Calculate the relative RoC for each asset - Standard
rocVO := ta.roc(VO, rocPeriod) - avgROC
rocSPHD := ta.roc(SPHD, rocPeriod) - avgROC
rocEEM := ta.roc(EEM, rocPeriod) - avgROC
rocDXJ := ta.roc(DXJ, rocPeriod) - avgROC
rocQQQ := ta.roc(QQQ, rocPeriod) - avgROC
rocEWZ := ta.roc(EWZ, rocPeriod) - avgROC
rocEWU := ta.roc(EWU, rocPeriod) - avgROC
rocIWF := ta.roc(IWF, rocPeriod) - avgROC
rocSPY := ta.roc(SPY, rocPeriod) - avgROC
rocINDA := ta.roc(INDA, rocPeriod) - avgROC
rocFXI := ta.roc(FXI, rocPeriod) - avgROC
rocSPLV := ta.roc(SPLV, rocPeriod) - avgROC
rocACWX := ta.roc(ACWX, rocPeriod) - avgROC
rocEZU := ta.roc(EZU, rocPeriod) - avgROC
rocQUAL := ta.roc(QUAL, rocPeriod) - avgROC
rocSPHB := ta.roc(SPHB, rocPeriod) - avgROC
rocMTUM := ta.roc(MTUM, rocPeriod) - avgROC
rocIWM := ta.roc(IWM, rocPeriod) - avgROC
rocOEF := ta.roc(OEF, rocPeriod) - avgROC
else if useSharpe == true
// Calculate the Sharpe ratio for each asset - Optional
rocVO := f_sharpe(VO, rocPeriod)
rocSPHD := f_sharpe(SPHD, rocPeriod)
rocEEM := f_sharpe(EEM, rocPeriod)
rocDXJ := f_sharpe(DXJ, rocPeriod)
rocQQQ := f_sharpe(QQQ, rocPeriod)
rocEWZ := f_sharpe(EWZ, rocPeriod)
rocEWU := f_sharpe(EWU, rocPeriod)
rocIWF := f_sharpe(IWF, rocPeriod)
rocSPY := f_sharpe(SPY, rocPeriod)
rocINDA := f_sharpe(INDA, rocPeriod)
rocFXI := f_sharpe(FXI, rocPeriod)
rocSPLV := f_sharpe(SPLV, rocPeriod)
rocACWX := f_sharpe(ACWX, rocPeriod)
rocEZU := f_sharpe(EZU, rocPeriod)
rocQUAL := f_sharpe(QUAL, rocPeriod)
rocSPHB := f_sharpe(SPHB, rocPeriod)
rocMTUM := f_sharpe(MTUM, rocPeriod)
rocIWM := f_sharpe(IWM, rocPeriod)
rocOEF := f_sharpe(OEF, rocPeriod)
//calculate the correlation for each asset
correlation_VO = ta.correlation(close, VO, l)
correlation_SPHD = ta.correlation(close, SPHD, l)
correlation_EEM = ta.correlation(close, EEM, l)
correlation_DXJ = ta.correlation(close, DXJ, l)
correlation_QQQ = ta.correlation(close, QQQ, l)
correlation_EWZ = ta.correlation(close, EWZ, l)
correlation_EWU = ta.correlation(close, EWU, l)
correlation_IWF = ta.correlation(close, IWF, l)
correlation_SPY = ta.correlation(close, SPY, l)
correlation_INDA = ta.correlation(close, INDA, l)
correlation_FXI = ta.correlation(close, FXI, l)
correlation_SPLV = ta.correlation(close, SPLV, l)
correlation_ACWX = ta.correlation(close, ACWX, l)
correlation_EZU = ta.correlation(close, EZU, l)
correlation_QUAL = ta.correlation(close, QUAL, l)
correlation_SPHB = ta.correlation(close, SPHB, l)
correlation_MTUM = ta.correlation(close, MTUM, l)
correlation_IWM = ta.correlation(close, IWM, l)
correlation_OEF = ta.correlation(close, OEF, l)
//Calculate Trend Value for each Asset with Normalized KAMA Oscillator by IKKE OMAR
// -> https://www.tradingview.com/script/OwtiIzT3-Normalized-KAMA-Oscillator-Ikke-Omar/
// For best performance use this Indicator on the underlying Assets and adjust the Normalization lookback to the moves you want to capture
kama(asset) =>
// Define input parameters
fast_period = input.int(title='Fast Period', defval=7, minval=1, group = "Norm KAMA", tooltip = "Normalized KAMA Oscillator by IkkeOmar")
slow_period = input.int(title='Slow Period', defval=19, minval=1, group = "Norm KAMA")
er_period = input.int(title='Efficiency Ratio Period', defval=8, minval=1, group = "Norm KAMA")
norm_period = input.int(title='Normalization lookback', defval=10, minval=1, group = "Norm KAMA", tooltip = "Defines the time horizon for the Trend calculation of the ETF's - For longer term Trends over weeks or months a length of 50 is usually pretty accurate")
// Calculate the efficiency ratio
change = math.abs(asset - asset[er_period])
volatility = math.sum(math.abs(asset - asset[1]), er_period)
er = change / volatility
// Calculate the smoothing constant
sc = er * (2 / (fast_period + 1) - 2 / (slow_period + 1)) + 2 / (slow_period + 1)
// Calculate the KAMA
kama = ta.ema(asset, fast_period) + sc * (asset - ta.ema(asset, fast_period))
// Normalize the Oscillator
lowest = ta.lowest (kama, norm_period)
highest = ta.highest(kama, norm_period)
normalized = (kama - lowest) / (highest - lowest) - 0.5
normalized
//Calculate trend for assets
kamaVO = kama(VO) > 0? 1 : -1
kamaSPHD = kama(SPHD) > 0? 1 : -1
kamaEEM = kama(EEM) > 0? 1 : -1
kamaDXJ = kama(DXJ) > 0? 1 : -1
kamaQQQ = kama(QQQ) > 0? 1 : -1
kamaEWZ = kama(EWZ) > 0? 1 : -1
kamaEWU = kama(EWU) > 0? 1 : -1
kamaIWF = kama(IWF) > 0? 1 : -1
kamaSPY = kama(SPY) > 0? 1 : -1
kamaINDA = kama(INDA) > 0? 1 : -1
kamaFXI = kama(FXI) > 0? 1 : -1
kamaSPLV = kama(SPLV) > 0? 1 : -1
kamaACWX = kama(ACWX) > 0? 1 : -1
kamaEZU = kama(EZU) > 0? 1 : -1
kamaQUAL = kama(QUAL) > 0? 1 : -1
kamaSPHB = kama(SPHB) > 0? 1 : -1
kamaMTUM = kama(MTUM) > 0? 1 : -1
kamaIWM = kama(IWM) > 0? 1 : -1
kamaOEF = kama(OEF) > 0? 1 : -1
//Calculate Average Implied Correlation
ImplCorrAvg = math.avg(
math.round(correlation_VO* kamaVO, 2),
math.round(correlation_SPHD* kamaSPHD, 2),
math.round(correlation_EEM* kamaEEM, 2),
math.round(correlation_DXJ* kamaDXJ, 2),
math.round(correlation_QQQ* kamaQQQ, 2),
math.round(correlation_EWZ* kamaEWZ, 2),
math.round(correlation_EWU* kamaEWU, 2),
math.round(correlation_IWF* kamaIWF, 2),
math.round(correlation_SPY* kamaSPY, 2),
math.round(correlation_INDA* kamaINDA, 2),
math.round(correlation_FXI* kamaFXI, 2),
math.round(correlation_SPLV* kamaSPLV, 2),
math.round(correlation_ACWX* kamaACWX, 2),
math.round(correlation_EZU* kamaEZU, 2),
math.round(correlation_QUAL* kamaQUAL, 2),
math.round(correlation_SPHB* kamaSPHB, 2),
math.round(correlation_IWM* kamaIWM, 2),
math.round(correlation_OEF* kamaOEF, 2),
math.round(correlation_MTUM* kamaMTUM, 2))
// Display correlation values
var string G3 = "🌌 Table Settings Correlation 🌌"
string table0_y_pos = input.string(defval = "top", title = "Table Position", options = ["top", "middle", "bottom"], group = G3, inline = "1")
string table0_x_pos = input.string(defval = "right", title = "", options = ["left", "center", "right"], group = G3, inline = "1")
string i_text_size = input.string(defval = size.tiny,title='Text Size:', options=[size.tiny, size.small, size.normal, size.large, size.huge, size.auto], group = G3 )
var table table0 = table.new(
table0_y_pos + "_" + table0_x_pos,
columns = 20, rows = 6, frame_color = color.white,
frame_width = 1,
border_color = color.white,
border_width = 1)
if showCorrTab
table.merge_cells(table0, 0, 0, 19, 0)
table.merge_cells(table0, 0, 4, 19, 4)
if showCorrTab and barstate.islast
table.cell(table0, 0, 0, "🌌 CE - EQUITY FACTOR CORRELATION "+str.tostring(l)+"D 🌌", text_size = i_text_size, text_color = color.purple)
table.cell(table0, 0, 1, "Symbol:", text_size = i_text_size, text_color = color.white, bgcolor = color.black)
table.cell(table0, 0, 2, "Correlation:", text_size = i_text_size, text_color = color.white, bgcolor = color.black)
table.cell(table0, 0, 3, "Trend:", text_size = i_text_size, text_color = color.white, bgcolor = color.black)
table.cell(table0, 0, 4, "Implied Trend to Chart "+str.tostring(l)+"D :", text_size = i_text_size, text_color = color.white, bgcolor = color.black)
table.cell(table0, 0, 5, "Avg: " + str.tostring(math.round(ImplCorrAvg,2)), text_size = i_text_size, text_color = math.round(ImplCorrAvg,2) > 0 ?color.green:color.red)
table.cell(table0, 1, 1, "VO", text_size = i_text_size, text_color = color.teal)
table.cell(table0, 1, 2, str.tostring(math.round(correlation_VO, 2)), text_size = i_text_size, text_color = correlation_VO > 0 ? color.green : color.red)
table.cell(table0, 1, 3, str.tostring(kamaVO), text_size = i_text_size, text_color = kamaVO > 0 ? color.green : color.red)
table.cell(table0, 1, 5, str.tostring(math.round(correlation_VO*kamaVO, 2)), text_size = i_text_size, text_color = math.round(correlation_VO*kamaVO, 2) > 0 ? color.green : color.red)
table.cell(table0, 2, 1, "SPHD", text_size = i_text_size, text_color = color.aqua)
table.cell(table0, 2, 2, str.tostring(math.round(correlation_SPHD, 2)), text_size = i_text_size, text_color = correlation_SPHD > 0 ? color.green : color.red)
table.cell(table0, 2, 3, str.tostring(kamaSPHD), text_size = i_text_size, text_color = kamaSPHD > 0 ? color.green : color.red)
table.cell(table0, 2, 5, str.tostring(math.round(correlation_SPHD*kamaSPHD, 2)), text_size = i_text_size, text_color = math.round(correlation_SPHD*kamaSPHD, 2) > 0 ? color.green : color.red)
table.cell(table0, 3, 1, "EEM", text_size = i_text_size, text_color = color.gray)
table.cell(table0, 3, 2, str.tostring(math.round(correlation_EEM, 2)), text_size = i_text_size, text_color = correlation_EEM > 0 ? color.green : color.red)
table.cell(table0, 3, 3, str.tostring(kamaEEM), text_size = i_text_size, text_color = kamaEEM > 0 ? color.green : color.red)
table.cell(table0, 3, 5, str.tostring(math.round(correlation_EEM*kamaEEM, 2)), text_size = i_text_size, text_color = math.round(correlation_EEM*kamaEEM, 2) > 0 ? color.green : color.red)
table.cell(table0, 4, 1, "QUAL", text_size = i_text_size, text_color = color.maroon)
table.cell(table0, 4, 2, str.tostring(math.round(correlation_QUAL, 2)), text_size = i_text_size, text_color = correlation_QUAL > 0 ? color.green : color.red)
table.cell(table0, 4, 3, str.tostring(kamaQUAL), text_size = i_text_size, text_color = kamaQUAL > 0 ? color.green : color.red)
table.cell(table0, 4, 5, str.tostring(math.round(correlation_QUAL*kamaQUAL, 2)), text_size = i_text_size, text_color = math.round(correlation_QUAL*kamaQUAL, 2) > 0 ? color.green : color.red)
table.cell(table0, 5, 1, "QQQ", text_size = i_text_size, text_color = color.orange)
table.cell(table0, 5, 2, str.tostring(math.round(correlation_QQQ, 2)), text_size = i_text_size, text_color = correlation_QQQ > 0 ? color.green : color.red)
table.cell(table0, 5, 3, str.tostring(kamaQQQ), text_size = i_text_size, text_color = kamaQQQ > 0 ? color.green : color.red)
table.cell(table0, 5, 5, str.tostring(math.round(correlation_QQQ*kamaQQQ, 2)), text_size = i_text_size, text_color = math.round(correlation_QQQ*kamaQQQ, 2) > 0 ? color.green : color.red)
table.cell(table0, 6, 1, "EWZ", text_size = i_text_size, text_color = color.rgb(239, 136, 227))
table.cell(table0, 6, 2, str.tostring(math.round(correlation_EWZ, 2)), text_size = i_text_size, text_color = correlation_EWZ > 0 ? color.green : color.red)
table.cell(table0, 6, 3, str.tostring(kamaEWZ), text_size = i_text_size, text_color = kamaEWZ > 0 ? color.green : color.red)
table.cell(table0, 6, 5, str.tostring(math.round(correlation_EWZ*kamaEWZ, 2)), text_size = i_text_size, text_color = math.round(correlation_EWZ*kamaEWZ, 2) > 0 ? color.green : color.red)
table.cell(table0, 7, 1, "EWU", text_size = i_text_size, text_color = color.yellow)
table.cell(table0, 7, 2, str.tostring(math.round(correlation_EWU, 2)), text_size = i_text_size, text_color = correlation_EWU > 0 ? color.green : color.red)
table.cell(table0, 7, 3, str.tostring(kamaEWU), text_size = i_text_size, text_color = kamaEWU > 0 ? color.green : color.red)
table.cell(table0, 7, 5, str.tostring(math.round(correlation_EWU*kamaEWU, 2)), text_size = i_text_size, text_color = math.round(correlation_EWU*kamaEWU, 2) > 0 ? color.green : color.red)
table.cell(table0, 8, 1, "IWF", text_size = i_text_size, text_color = color.yellow)
table.cell(table0, 8, 2, str.tostring(math.round(correlation_IWF, 2)), text_size = i_text_size, text_color = correlation_IWF > 0 ? color.green : color.red)
table.cell(table0, 8, 3, str.tostring(kamaIWF), text_size = i_text_size, text_color = kamaIWF > 0 ? color.green : color.red)
table.cell(table0, 8, 5, str.tostring(math.round(correlation_IWF*kamaIWF, 2)), text_size = i_text_size, text_color = math.round(correlation_IWF*kamaIWF, 2) > 0 ? color.green : color.red)
table.cell(table0, 9, 1, "SPY", text_size = i_text_size, text_color = color.fuchsia)
table.cell(table0, 9, 2, str.tostring(math.round(correlation_SPY, 2)), text_size = i_text_size, text_color = correlation_SPY > 0 ? color.green : color.red)
table.cell(table0, 9, 3, str.tostring(kamaSPY), text_size = i_text_size, text_color = kamaSPY > 0 ? color.green : color.red)
table.cell(table0, 9, 5, str.tostring(math.round(correlation_SPY*kamaSPY, 2)), text_size = i_text_size, text_color = math.round(correlation_SPY*kamaSPY, 2) > 0 ? color.green : color.red)
table.cell(table0, 10, 1, "DXJ", text_size = i_text_size, text_color = color.purple)
table.cell(table0, 10, 2, str.tostring(math.round(correlation_DXJ, 2)), text_size = i_text_size, text_color = correlation_DXJ > 0 ? color.green : color.red)
table.cell(table0, 10, 3, str.tostring(kamaDXJ), text_size = i_text_size, text_color = kamaDXJ > 0 ? color.green : color.red)
table.cell(table0, 10, 5, str.tostring(math.round(correlation_DXJ*kamaDXJ, 2)), text_size = i_text_size, text_color = math.round(correlation_DXJ*kamaDXJ, 2) > 0 ? color.green : color.red)
table.cell(table0, 11, 1, "INDA", text_size = i_text_size, text_color = color.blue)
table.cell(table0, 11, 2, str.tostring(math.round(correlation_INDA, 2)), text_size = i_text_size, text_color = correlation_INDA > 0 ? color.green : color.red)
table.cell(table0, 11, 3, str.tostring(kamaINDA), text_size = i_text_size, text_color = kamaINDA > 0 ? color.green : color.red)
table.cell(table0, 11, 5, str.tostring(math.round(correlation_INDA*kamaINDA, 2)), text_size = i_text_size, text_color = math.round(correlation_INDA*kamaINDA, 2) > 0 ? color.green : color.red)
table.cell(table0, 12, 1, "FXI", text_size = i_text_size, text_color = color.red)
table.cell(table0, 12, 2, str.tostring(math.round(correlation_FXI, 2)), text_size = i_text_size, text_color = correlation_FXI > 0 ? color.green : color.red)
table.cell(table0, 12, 3, str.tostring(kamaFXI), text_size = i_text_size, text_color = kamaFXI > 0 ? color.green : color.red)
table.cell(table0, 12, 5, str.tostring(math.round(correlation_FXI*kamaFXI, 2)), text_size = i_text_size, text_color = math.round(correlation_FXI*kamaFXI, 2) > 0 ? color.green : color.red)
table.cell(table0, 13, 1, "SPLV", text_size = i_text_size, text_color = color.olive)
table.cell(table0, 13, 2, str.tostring(math.round(correlation_SPLV, 2)), text_size = i_text_size, text_color = correlation_SPLV > 0 ? color.green : color.red)
table.cell(table0, 13, 3, str.tostring(kamaSPLV), text_size = i_text_size, text_color = kamaSPLV > 0 ? color.green : color.red)
table.cell(table0, 13, 5, str.tostring(math.round(correlation_SPLV*kamaSPLV, 2)), text_size = i_text_size, text_color = math.round(correlation_SPLV*kamaSPLV, 2) > 0 ? color.green : color.red)
table.cell(table0, 14, 1, "EZU", text_size = i_text_size, text_color = color.lime)
table.cell(table0, 14, 2, str.tostring(math.round(correlation_EZU, 2)), text_size = i_text_size, text_color = correlation_EZU > 0 ? color.green : color.red)
table.cell(table0, 14, 3, str.tostring(kamaEZU), text_size = i_text_size, text_color = kamaEZU > 0 ? color.green : color.red)
table.cell(table0, 14, 5, str.tostring(math.round(correlation_EZU*kamaEZU, 2)), text_size = i_text_size, text_color = math.round(correlation_EZU*kamaEZU, 2) > 0 ? color.green : color.red)
table.cell(table0, 15, 1, "ACWX", text_size = i_text_size, text_color = color.silver)
table.cell(table0, 15, 2, str.tostring(math.round(correlation_ACWX, 2)), text_size = i_text_size, text_color = correlation_ACWX > 0 ? color.green : color.red)
table.cell(table0, 15, 3, str.tostring(kamaACWX), text_size = i_text_size, text_color = kamaACWX > 0 ? color.green : color.red)
table.cell(table0, 15, 5, str.tostring(math.round(correlation_ACWX*kamaACWX, 2)), text_size = i_text_size, text_color = math.round(correlation_ACWX*kamaACWX, 2) > 0 ? color.green : color.red)
table.cell(table0, 16, 1, "SPHB", text_size = i_text_size, text_color = color.silver)
table.cell(table0, 16, 2, str.tostring(math.round(correlation_SPHB, 2)), text_size = i_text_size, text_color = correlation_SPHB > 0 ? color.green : color.red)
table.cell(table0, 16, 3, str.tostring(kamaSPHB), text_size = i_text_size, text_color = kamaSPHB > 0 ? color.green : color.red)
table.cell(table0, 16, 5, str.tostring(math.round(correlation_SPHB*kamaSPHB, 2)), text_size = i_text_size, text_color = math.round(correlation_SPHB*kamaSPHB, 2) > 0 ? color.green : color.red)
table.cell(table0, 17, 1, "MTUM", text_size = i_text_size, text_color = color.silver)
table.cell(table0, 17, 2, str.tostring(math.round(correlation_MTUM, 2)), text_size = i_text_size, text_color = correlation_MTUM > 0 ? color.green : color.red)
table.cell(table0, 17, 3, str.tostring(kamaMTUM), text_size = i_text_size, text_color = kamaMTUM > 0 ? color.green : color.red)
table.cell(table0, 17, 5, str.tostring(math.round(correlation_MTUM*kamaMTUM, 2)), text_size = i_text_size, text_color = math.round(correlation_MTUM*kamaMTUM, 2) > 0 ? color.green : color.red)
table.cell(table0, 18, 1, "IWM", text_size = i_text_size, text_color = color.silver)
table.cell(table0, 18, 2, str.tostring(math.round(correlation_IWM, 2)), text_size = i_text_size, text_color = correlation_IWM > 0 ? color.green : color.red)
table.cell(table0, 18, 3, str.tostring(kamaIWM), text_size = i_text_size, text_color = kamaIWM > 0 ? color.green : color.red)
table.cell(table0, 18, 5, str.tostring(math.round(correlation_IWM*kamaIWM, 2)), text_size = i_text_size, text_color = math.round(correlation_IWM*kamaIWM, 2) > 0 ? color.green : color.red)
table.cell(table0, 19, 1, "OEF", text_size = i_text_size, text_color = color.silver)
table.cell(table0, 19, 2, str.tostring(math.round(correlation_OEF, 2)), text_size = i_text_size, text_color = correlation_OEF > 0 ? color.green : color.red)
table.cell(table0, 19, 3, str.tostring(kamaOEF), text_size = i_text_size, text_color = kamaOEF > 0 ? color.green : color.red)
table.cell(table0, 19, 5, str.tostring(math.round(correlation_OEF*kamaOEF, 2)), text_size = i_text_size, text_color = math.round(correlation_OEF*kamaOEF, 2) > 0 ? color.green : color.red)
// Implied Correlation Normalization
lowest = ta.lowest (ImplCorrAvg, norm_periodImpl)
highest = ta.highest(ImplCorrAvg, norm_periodImpl)
ImplCorrAvgNorm = (ImplCorrAvg - lowest) / (highest - lowest) - 0.5
lowest2 = ta.lowest (ImplCorrAvgNorm, norm_periodImpl2)
highest2 = ta.highest(ImplCorrAvgNorm, norm_periodImpl2)
ImplCorrAvgNormDouble = (ImplCorrAvgNorm - lowest2) / (highest2 - lowest2) - 0.5
// Implied Correlation Visuals
plot(showImplied? ImplCorrAvg:na, "Implied Correlation Avg", ImplCorrAvg > 0.1 ?color.green : ImplCorrAvg < -0.1 ? color.red : color.gray, style = plot.style_columns)
plot(showImpliedNorm? ImplCorrAvgNorm:na, "Implied Correlation Avg Normalized", ImplCorrAvgNorm > 0.1 ?color.green : ImplCorrAvgNorm < -0.1 ? color.red : color.gray, style = plot.style_columns)
plot(showImpliedNorm2? ImplCorrAvgNormDouble:na, "Implied Correlation Avg double Normalized", ImplCorrAvgNormDouble > 0.1 ?color.green : ImplCorrAvgNormDouble < -0.1 ? color.red : color.gray, style = plot.style_columns)
hline(showImplied or showImpliedNorm or showImpliedNorm2? 0.1 : na, color = color.green, linewidth = 2)
hline(showImplied or showImpliedNorm or showImpliedNorm2? 0 : na)
hline(showImplied or showImpliedNorm or showImpliedNorm2? -0.1 : na, color = color.red , linewidth = 2)
// Decide on the barcolor
barcolor(implBarCol and showImpliedNorm? ImplCorrAvgNorm > 0.1 ?color.green : ImplCorrAvgNorm < -0.1 ? color.red : color.gray :
implBarCol and showImpliedNorm2? ImplCorrAvgNormDouble > 0.1 ?color.green : ImplCorrAvgNormDouble < -0.1 ? color.red : color.gray :
implBarCol and not showImpliedNorm? ImplCorrAvg > 0.1 ?color.green : ImplCorrAvg < -0.1 ? color.red : color.gray : na)
// HMA
ImplValue = showImpliedNorm? ImplCorrAvgNorm : showImpliedNorm2? ImplCorrAvgNormDouble : showImplied? ImplCorrAvg: na
HMA = ta.hma(ImplValue, MALen)
HMAL = ta.crossover(HMA,0)
HMAS = ta.crossunder(HMA,0)
plot(useMA? HMA : na, "HMA", color.purple, 2)
bgcolor(HMASigCol? color.new(HMAL? color.green: HMAS? color.red: na, 60): na)
// Calculate the different regime probabilities based on asset performance - Could certainly be enhanced and brought to higher sophistication... but works anyways... open to suggestions though
Goldilocks = (rocVO>0?+1:0) + (rocSPHD>0?+1:0) + (rocEEM>0?+1:0) + (rocIWM>0?+1:0) + (rocQQQ>0?+1:0) + (rocEWZ<0?+1:0) + (rocEWU<0?+1:0) + (rocIWF<0?+1:0) + (rocSPY<0?+1:0) + (rocDXJ<0?+1:0)
Reflation = (rocVO>0?+1:0) + (rocQQQ>0?+1:0) + (rocMTUM>0?+1:0) + (rocSPY>0?+1:0) + (rocIWM>0?+1:0) + (rocFXI<0?+1:0) + (rocEWZ<0?+1:0) + (rocEWU<0?+1:0) + (rocSPLV<0?+1:0) + (rocSPHD<0?+1:0)
Inflation = (rocINDA>0?+1:0) + (rocQQQ>0?+1:0) + (rocEWZ>0?+1:0) + (rocSPHD>0?+1:0) + (rocMTUM>0?+1:0) + (rocEEM<0?+1:0) + (rocACWX<0?+1:0) + (rocFXI<0?+1:0) + (rocEWU<0?+1:0) + (rocEZU<0?+1:0)
Deflation = (rocEWU>0?+1:0) + (rocSPLV>0?+1:0) + (rocSPHD>0?+1:0) + (rocFXI>0?+1:0) + (rocQUAL>0?+1:0) + (rocEWZ<0?+1:0) + (rocDXJ<0?+1:0) + (rocSPHB<0?+1:0) + (rocEEM<0?+1:0) + (rocOEF<0?+1:0)
Denumerator = Goldilocks + Reflation + Inflation + Deflation
// Find the greatest value among the scenarios
maxValue = math.max(Goldilocks, Reflation, Inflation, Deflation)
// Determine the market scenario based on the greatest value
Risk = ""
if maxValue == Goldilocks or maxValue == Reflation
Risk := "RISK ON"
else
Risk := "RISK OFF"
RiskCol = (Risk == "RISK ON"? color.green : color.red)
RiskBg = (Risk == "RISK ON"? color.new(color.green, 40) : color.new(color.red, 40))
regime = ""
color regCol = na
if maxValue == Goldilocks
regime := "Goldilocks"
regCol := color.new(color.green, 50)
else if maxValue == Reflation
regime := "Reflation"
regCol := color.new(color.lime, 50)
else if maxValue == Inflation
regime := "Inflation"
regCol := color.new(color.red, 50)
else if maxValue == Deflation
regime := "Deflation"
regCol := color.new(color.blue, 50)
plot (col? Risk == "RISK ON"? 1 : -1 : na )
bgcolor(col? Risk == "RISK ON"? color.new(color.green, 60) : color.new(color.red, 60):na)
bgcolor(reg? regCol : na)
// Table
var string G2 = "🌌 Table Settings Performance 🌌"
string table_y_pos = input.string(defval = "bottom", title = "Table Position", options = ["top", "middle", "bottom"], group = G2, inline = "1")
string table_x_pos = input.string(defval = "right", title = "", options = ["left", "center", "right"], group = G2, inline = "1")
color positive_color_input = color(color.new(color.green, 0))
color negative_color_input = color(color.new(color.red, 0))
var table table = table.new(table_y_pos + "_" + table_x_pos, columns = 10, rows = 17, frame_color = color.white,
frame_width = 1, border_color = color.white, border_width = 1)
if showPerfTab
table.merge_cells(table, 0, 0, 7, 0)
table.merge_cells(table, 0, 1, 1, 1)
table.merge_cells(table, 2, 1, 3, 1)
table.merge_cells(table, 4, 1, 5, 1)
table.merge_cells(table, 6, 1, 7, 1)
table.merge_cells(table, 0, 2, 7, 2)
table.merge_cells(table, 0, 8, 7, 8)
table.merge_cells(table, 0, 14, 7, 14)
table.merge_cells(table, 0, 16, 7, 16)
// Definitions
if showPerfTab and barstate.islast
table.cell(table, 0, 0, text = "🌌 CE - EQUITY FACTOR "+str.tostring(rocPeriod)+"D 🌌", text_size = i_text_size, text_color = color.purple)
table.cell(table, 0, 2, text = "Top 5 Equity Factors ", text_size = i_text_size, text_color = color.green)
table.cell(table, 0, 8, text = "Bottom 5 Equity Factors ", text_size = i_text_size, text_color = color.red)
table.cell(table, 0, 14, text = "Risk Period: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 0, 16, text = Risk, text_size = i_text_size, text_color = color.white , bgcolor = RiskBg, text_font_family = font.family_monospace)
table.cell(table, 0, 1,"GOLDILOCKS", text_size = i_text_size, text_color = color.green)
table.cell(table, 0, 3,"Mid Caps (VO)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 3,str.tostring(math.round(rocVO,2)), text_size = i_text_size, text_color = rocVO > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 4,"Dividend Compounders (SPHD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 4,str.tostring(math.round(rocSPHD,2)), text_size = i_text_size, text_color = rocSPHD > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 5,"Emerging Markets (EEM)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 5,str.tostring(math.round(rocEEM,2)), text_size = i_text_size, text_color = rocEEM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 6,"Small Caps (IWM)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 6,str.tostring(math.round(rocIWM,2)), text_size = i_text_size, text_color = rocIWM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 7,"Mega Cap Growth (QQQ)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 7,str.tostring(math.round(rocQQQ,2)), text_size = i_text_size, text_color = rocQQQ > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 9, text = "Brazil (EWZ)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 9,str.tostring(math.round(rocEWZ,2)), text_size = i_text_size, text_color = rocEWZ > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 10, text = "United Kingdom (EWU)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 10,str.tostring(math.round(rocEWU,2)), text_size = i_text_size, text_color = rocEWU > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 11, text = "Growth (IWF)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 11,str.tostring(math.round(rocIWF,2)), text_size = i_text_size, text_color = rocIWF > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 12, text = "United States (SPY)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 12,str.tostring(math.round(rocSPY,2)), text_size = i_text_size, text_color = rocSPY > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 13, text = "Japan (DXJ)", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 13,str.tostring(math.round(rocDXJ,2)), text_size = i_text_size, text_color = rocDXJ > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 15, text = "Goldilocks Probability: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 15,str.tostring(math.round(Goldilocks/Denumerator*100, 2))+"% | "+str.tostring(Goldilocks)+ " / 10", text_size = i_text_size, text_color = RiskCol)
table.cell(table, 2, 1,"REFLATION", text_size = i_text_size, text_color = color.lime)
table.cell(table, 2, 3,"Mid Caps (VO)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 3,str.tostring(math.round(rocVO,2)), text_size = i_text_size, text_color = rocVO > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 4,"Mega Cap Growth (QQQ)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 4,str.tostring(math.round(rocQQQ,2)), text_size = i_text_size, text_color = rocQQQ > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 5,"Momentum (MTUM)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 5,str.tostring(math.round(rocMTUM,2)), text_size = i_text_size, text_color = rocMTUM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 6,"United States (SPY)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 6,str.tostring(math.round(rocSPY,2)), text_size = i_text_size, text_color = rocSPY > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 7,"Small Caps (IWM)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 7,str.tostring(math.round(rocIWM,2)), text_size = i_text_size, text_color = rocIWM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 9, text = "China (FXI)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 9,str.tostring(math.round(rocFXI,2)), text_size = i_text_size, text_color = rocFXI > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 10, text = "Brazil (EWZ)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 10,str.tostring(math.round(rocEWZ,2)), text_size = i_text_size, text_color = rocEWZ > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 11, text = "United Kingdom (EWU)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 11,str.tostring(math.round(rocEWU,2)), text_size = i_text_size, text_color = rocEWU > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 12, text = "Low Beta (SPLV)", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 12,str.tostring(math.round(rocSPLV,2)), text_size = i_text_size, text_color = rocSPLV > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 13, text = "Dividend Compounders (SPHD)",text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 13,str.tostring(math.round(rocSPHD,2)), text_size = i_text_size, text_color = rocSPHD > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 15, text = "Reflation Probability: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 15,str.tostring(math.round(Reflation/Denumerator*100, 2))+"% | "+str.tostring(Reflation)+ " / 10", text_size = i_text_size, text_color = RiskCol)
table.cell(table, 4, 1,"INFLATION", text_size = i_text_size, text_color = color.red)
table.cell(table, 4, 3,"India (INDA)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 3,str.tostring(math.round(rocINDA,2)), text_size = i_text_size, text_color = rocINDA > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 4,"Mega Cap Growth (QQQ)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 4,str.tostring(math.round(rocQQQ,2)), text_size = i_text_size, text_color = rocQQQ > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 5,"Brazil (EWZ)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 5,str.tostring(math.round(rocEWZ,2)), text_size = i_text_size, text_color = rocEWZ > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 6,"Dividend Compounders (SPHD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 6,str.tostring(math.round(rocSPHD,2)), text_size = i_text_size, text_color = rocSPHD > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 7,"Momentum (MTUM)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 7,str.tostring(math.round(rocMTUM,2)), text_size = i_text_size, text_color = rocMTUM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 9, text = "Emerging Markets (EEM)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 9,str.tostring(math.round(rocEEM,2)), text_size = i_text_size, text_color = rocEEM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 10, text = "International ex-US (ACWX)",text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 10,str.tostring(math.round(rocACWX,2)), text_size = i_text_size, text_color = rocACWX > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 11, text = "China (FXI)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 11,str.tostring(math.round(rocFXI,2)), text_size = i_text_size, text_color = rocFXI > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 12, text = "United Kingdom (EWU)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 12,str.tostring(math.round(rocEWU,2)), text_size = i_text_size, text_color = rocEWU > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 13, text = "Eurozone (EZU)", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 13,str.tostring(math.round(rocEZU,2)), text_size = i_text_size, text_color = rocEZU > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 15, text = "Inflation Probability: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 15,str.tostring(math.round(Inflation/Denumerator*100, 2))+"% | "+str.tostring(Inflation)+ " / 10", text_size = i_text_size, text_color = RiskCol)
table.cell(table, 6, 1,"DEFLATION", text_size = i_text_size, text_color = color.blue)
table.cell(table, 6, 3,"United Kingdom (EWU)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 3,str.tostring(math.round(rocEWU,2)), text_size = i_text_size, text_color = rocEWU > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 4,"Low Beta (SPLV)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 4,str.tostring(math.round(rocSPLV,2)), text_size = i_text_size, text_color = rocSPLV > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 5,"Dividend Compounders (SPHD)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 5,str.tostring(math.round(rocSPHD,2)), text_size = i_text_size, text_color = rocSPHD > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 6,"China (FXI)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 6,str.tostring(math.round(rocFXI,2)), text_size = i_text_size, text_color = rocFXI > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 7,"Quality (QUAL)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 7,str.tostring(math.round(rocQUAL,2)), text_size = i_text_size, text_color = rocQUAL > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 9, text = "Brazil (EWZ)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 9,str.tostring(math.round(rocEWZ,2)), text_size = i_text_size, text_color = rocEWZ > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 10, text = "Japan (DXJ)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 10,str.tostring(math.round(rocDXJ,2)), text_size = i_text_size, text_color = rocDXJ > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 11, text = "High Beta (SPHB)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 11,str.tostring(math.round(rocSPHB,2)), text_size = i_text_size, text_color = rocSPHB > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 12, text = "Emerging Markets (EEM)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 12,str.tostring(math.round(rocEEM,2)), text_size = i_text_size, text_color = rocEEM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 13, text = "Size (OEF)", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 13,str.tostring(math.round(rocOEF,2)), text_size = i_text_size, text_color = rocOEF > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 15, text = "Deflation Probability: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 15,str.tostring(math.round(Deflation/Denumerator*100, 2))+"% | "+str.tostring(Deflation)+ " / 10", text_size = i_text_size, text_color = RiskCol)
|
MarketSmith Indicator | https://www.tradingview.com/script/b1ykQ879/ | Fred6724 | https://www.tradingview.com/u/Fred6724/ | 569 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//
//@version=5
indicator('MarketSmith Indicator', overlay=true, max_bars_back = 500, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
//------------------ BARS ---------------------//
// Color of bars
prevClose = input(true, title='Color Based On Previous Close', group='----------BARS----------', inline='x')
i_posColor = input(color.rgb(39, 54,233,0), title='Candle Color Positive', group='----------BARS----------', inline = '1')
i_negColor = input(color.rgb(222,50,174,0), title='Negative', group='----------BARS----------', inline = '1')
colorCandle = close>=open ? i_posColor:i_negColor
if(prevClose)
colorCandle := close>=close[1] ? i_posColor:i_negColor
// Full Body (without border without wick)
plotcandle(low, high, low, high, title='MarketSmith Bars', color = colorCandle, wickcolor = color.rgb(255,255,255,100), bordercolor = color.rgb(255,255,255,100), editable = true)
// PlotChar - on close
plotchar(close, char='-', location=location.absolute, size=size.small, color=colorCandle, editable = true)
//------------------ SMA's ---------------------//
// Input SMA for Daily TF and others
iSma10 = input(true, title='MA 1', group='----------SMAs----------', inline='sma10')
iSmaV10 = input(10, title='Lenght', group='----------SMAs----------', inline='sma10')
iExp10 = input(true, title='Exponential', group='----------SMAs----------', inline='sma10')
iCol10 = input(color.rgb(68,186,76), title='', group='----------SMAs----------', inline='sma10')
iSma21 = input(true, title='MA 2', group='----------SMAs----------', inline='sma21')
iSmaV21 = input(21, title='Lenght', group='----------SMAs----------', inline='sma21')
iExp21 = input(true, title='Exponential', group='----------SMAs----------', inline='sma21')
iCol21 = input(color.rgb(240,141,240,0), title='', group='----------SMAs----------', inline='sma21')
iSma50 = input(true, title='MA 3', group='----------SMAs----------', inline='sma50')
iSmaV50 = input(50, title='Lenght', group='----------SMAs----------', inline='sma50')
iExp50 = input(false, title='Exponential', group='----------SMAs----------', inline='sma50')
iCol50 = input(color.rgb(255,33,33), title='', group='----------SMAs----------', inline='sma50')
iSma200 = input(true, title='MA 4', group='----------SMAs----------', inline='sma200')
iSmaV200 = input(200, title='Lenght', group='----------SMAs----------', inline='sma200')
iExp200 = input(false, title='Exponential', group='----------SMAs----------', inline='sma200')
iCol200 = input(color.rgb(0,0,0,0), title='', group='----------SMAs----------', inline='sma200')
// Input SMA for Weekly TimeFrame
iSma10We = input(true, title='SMA 1', group='----------SMAs We----------', inline='sma10We')
iSmaV10We = input(10, title='Lenght', group='----------SMAs We----------', inline='sma10We')
iExp10We = input(false, title='Exponential', group='----------SMAs We----------', inline='sma10We')
iCol10We = input(color.rgb(255,33,33), title='', group='----------SMAs We----------', inline='sma10We')
iEma20We = input(true, title='EMA 2', group='----------SMAs We----------', inline='ema20We')
iSmaV20We = input(20, title='Lenght', group='----------SMAs We----------', inline='ema20We')
iExp20We = input(true, title='Exponential', group='----------SMAs We----------', inline='ema20We')
iCol20We = input(color.rgb(240,141,240,0), title='', group='----------SMAs We----------', inline='ema20We')
iSma30We = input(true, title='SMA 3', group='----------SMAs We----------', inline='sma30We')
iSmaV30We = input(30, title='Lenght', group='----------SMAs We----------', inline='sma30We')
iExp30We = input(false, title='Exponential', group='----------SMAs We----------', inline='sma30We')
iCol30We = input(color.rgb(68,186,76), title='', group='----------SMAs We----------', inline='sma30We')
iSma40We = input(true, title='SMA 4', group='----------SMAs We----------', inline='sma40We')
iSmaV40We = input(40, title='Lenght', group='----------SMAs We----------', inline='sma40We')
iExp40We = input(false, title='Exponential', group='----------SMAs We----------', inline='sma40We')
iCol40We = input(color.rgb(0,0,0,0), title='', group='----------SMAs We----------', inline='sma40We')
// SMA calculation Daily & others TF
sma10 = iExp10 ? ta.ema(close,iSmaV10) :ta.sma(close,iSmaV10)
sma21 = iExp21 ? ta.ema(close,iSmaV21) :ta.sma(close,iSmaV21)
sma50 = iExp50 ? ta.ema(close,iSmaV50) :ta.sma(close,iSmaV50)
sma200 = iExp200 ? ta.ema(close,iSmaV200):ta.sma(close,iSmaV200)
// SMA calculation We
sma10We = iExp10We ? ta.ema(close,iSmaV10We):ta.sma(close,iSmaV10We)
ema20We = iExp20We ? ta.ema(close,iSmaV20We):ta.sma(close,iSmaV20We)
sma30We = iExp30We ? ta.ema(close,iSmaV30We):ta.sma(close,iSmaV30We)
sma40We = iExp40We ? ta.ema(close,iSmaV40We):ta.sma(close,iSmaV40We)
// Ploting SMA/EMA Daily and other TF
tfWeekly = timeframe.isweekly
psma10 = plot(iSma10 and not tfWeekly ? sma10:na, linewidth=1, color=iCol10)
pema21 = plot(iSma21 and not tfWeekly ? sma21:na, linewidth=1, color=iCol21)
psma50 = plot(iSma50 and not tfWeekly ? sma50:na, linewidth=1, color=iCol50)
psma200 = plot(iSma200 and not tfWeekly ? sma200:na, linewidth=1, color=iCol200)
// Ploting SMA/EMA We
psma10We = plot(iSma10We and tfWeekly ? sma10We:na, linewidth=1, color=iCol10We)
pema20We = plot(iEma20We and tfWeekly ? ema20We:na, linewidth=1, color=iCol20We)
psma30We = plot(iSma30We and tfWeekly ? sma30We:na, linewidth=1, color=iCol30We)
psma40We = plot(iSma40We and tfWeekly ? sma40We:na, linewidth=1, color=iCol40We)
//------------------ RS Rating ---------------------// and // SP500 -> 0S&P5 //
//Relative Price Strength (RS) Rating or Relative Strenght.
//This is a measure of a stock's price performance over the last
//twelve months, compared to all stocks in IBD's Database.
//The rating scale ranges frome 1 (lowest) to 99 (highest)
//At least this is the IBD proprietary rating's defintion.
//Let's create an equivalent here for TradingView!
//
// © RaviYendru thanks for providing the intial script
// Fred6724 - Let's see if it is possible to get better results
// Constant Value
comparativeTickerId = 'SP:SPX' // For RS Score Calculation, the SPX Value only makes sens because of the GitHub project
hideRSLine = input(false, title='Hide RS Line', group='----------RS Rating----------', inline='0')
hideRSRat = input(false, title='Hide Rating', group = '----------RS Rating----------', inline='0')
//seedetail = input(false, title='Display the 3 results', group = 'Parameters', inline='0')
ratingOnly = input(false, title='Rating Only', group = '----------RS Rating----------')
lineTicker = input('SP:SPX', title='Comparative Symbol for Line', group = '----------RS Rating----------', tooltip = 'Reference ticker used for calculation of the RS Line.')
SpxValue = input(4200, title='Value of Comparative Symbol', group = '----------RS Rating----------', tooltip = 'Used to gather a constant value')
offset = input.int(80, minval = 0, maxval = 300, title='Offset (%)', group = '----------RS Rating----------', tooltip = 'Used to display the RS Line under the price.')
colorRS = input(color.rgb(0, 0, 255), title = 'Color of RS Line & Rating', group = '----------RS Rating----------')
plotNewHigh = input(true, title = 'Plot RS New Highs', group = '----------RS Rating----------')
rsNewHigh = input.string('RS New Highs', title = 'Type', options=['RS New Highs','RS New Highs Before Price', 'Historical RS New Highs', 'Historical RS New Highs Before Price'], group = '----------RS Rating----------')
blueDotCol = input(color.rgb(121, 213, 242,62), title = 'Color of Dots', group = '----------RS Rating----------')
lookback = input.int(250, title = 'Look-back', minval = 1, maxval = 252, group = '----------RS Rating----------', tooltip = 'The lookback for calculation of price and RS New Highs.')
sizeLabHigh = input.string('Tiny', title = 'Size', options = ['Tiny', 'Small', 'Normal', 'Large'], group = '----------RS Rating----------')
plotNewLow = input(false, title = 'Plot RS New Lows', group = '----------RS Rating----------')
rsNewLow = input.string('Historical RS New Lows', title = 'Type', options=['RS New Lows','RS New Lows Before Price', 'Historical RS New Lows', 'Historical RS New Lows Before Price'], group = '----------RS Rating----------')
redDotCol = input(color.rgb(255, 82, 82, 62), title = 'Color', group = '----------RS Rating----------')
lookback2 = input.int(250, title = 'Look-back', minval = 1, maxval = 252, group = '----------RS Rating----------', tooltip = 'The lookback for calculation of price and RS New Lows.')
sizeLabLow = input.string('Tiny', title = 'Size', options = ['Tiny', 'Small', 'Normal', 'Large'], group = '----------RS Rating----------')
boolMa = input(false, title = 'Display MA 1 on RS Line', group = '1st MA on RS Line')
lenMa = input(21, title = 'Lenght Da', group = '1st MA on RS Line', inline = 'c')
colMa = input(color.orange, title = 'Color', group = '1st MA on RS Line', inline = 'c')
typMa = input.string('EMA', title = 'Type Da', options = ['SMA', 'EMA'], group = '1st MA on RS Line', inline = 'c')
lenMaWe = input(10, title = 'Lenght We', group = '1st MA on RS Line', inline = 'c')
typMaWe = input.string('SMA', title = 'Type We', options = ['SMA', 'EMA'], group = '1st MA on RS Line', inline = 'c')
fillMa = input(false, title = 'Area Color', group = '1st MA on RS Line')
posCol = input(color.rgb(0, 230, 119, 75), title = 'Positive Area', group = '1st MA on RS Line', inline = 'd')
negCol = input(color.rgb(255, 82, 82, 75), title = 'Negative Area', group = '1st MA on RS Line', inline = 'd')
boolMa2 = input(false, title = 'Display MA 2 on RS Line', group = '2nd MA on RS Line')
lenMa2 = input(50, title = 'Lenght Da', group = '2nd MA on RS Line', inline = 'c')
colMa2 = input(color.red, title = 'Color', group = '2nd MA on RS Line', inline = 'c')
typMa2 = input.string('EMA', title = 'Type Da', options = ['SMA', 'EMA'], group = '2nd MA on RS Line', inline = 'c')
lenMa2We = input(21, title = 'Lenght We', group = '2nd MA on RS Line', inline = 'c')
typMa2We = input.string('SMA', title = 'Type We', options = ['SMA', 'EMA'], group = '2nd MA on RS Line', inline = 'c')
allowReplay = input(false, title = 'Use fix values for replay mode', group = 'RS Replay mode (Approximate Method)', tooltip = 'Here we use constant values in order to provide the environment regardless of the date. See RSRATING ticker and report close values to have the last data.')
first2 = input(195.93, title='For 99 stocks' , group = 'RS Replay mode (Approximate Method)')
scnd2 = input(117.11, title='For 90+ stocks', group = 'RS Replay mode (Approximate Method)')
thrd2 = input(99.04, title='For 70+ stocks' , group = 'RS Replay mode (Approximate Method)')
frth2 = input(91.66, title='For 50+ stocks' , group = 'RS Replay mode (Approximate Method)')
ffth2 = input(80.96, title='For 30+ stocks' , group = 'RS Replay mode (Approximate Method)')
sxth2 = input(53.64, title='For 10+ stocks' , group = 'RS Replay mode (Approximate Method)')
svth2 = input(24.86, title='For 1- stocks' , group = 'RS Replay mode (Approximate Method)')
// Blue Dot
// If Blue Dot is ste to 250 Da, than we want it to be set on 52 We on the Weekly TimeFrame
if (lookback == 250 and timeframe.isweekly)
lookback := 52
if (lookback2 == 250 and timeframe.isweekly)
lookback2 := 52
// Switch Label Size
highLabel = switch sizeLabHigh
'Normal' => size.normal
'Tiny' => size.tiny
'Small' => size.small
'Large' => size.large
lowLabel = switch sizeLabLow
'Normal' => size.normal
'Tiny' => size.tiny
'Small' => size.small
'Large' => size.large
// Using bar index in case of IPO to avoid NaN results
// Added max_bars_max = 253 to improve display speed
n63 = bar_index < 63 ? bar_index:63
n126 = bar_index < 126 ? bar_index:126
n189 = bar_index < 189 ? bar_index:189
n252 = bar_index < 252 ? bar_index:252
// Comparative Ticker for RS Line
comparativeSymbol = request.security(comparativeTickerId, timeframe.period, close)
// RS Line but multiplied by a little bit less than the constant value of the comparative ticker for correct display
rsCurve = (close/comparativeSymbol)
// Adapt Ratio for Sectors and Indices
if (syminfo.industry == 'Investment Trusts/Mutual Funds')
offset := 90
// We use a wider offset for Weekly timeframe for a smoother display
rsRatio = timeframe.isweekly ? SpxValue*(offset-10)/100:SpxValue*offset/100
rs = rsCurve*rsRatio
prevlookback = lookback
prevlookback2 = lookback2 // For RS New Lows
lookback := math.min(lookback - 1, bar_index)
rsPlot = plot(hideRSLine ? na:rs, title='RS Line', style=plot.style_line, linewidth=1, color=colorRS)
// 1st MA on RS Line
// SMA and EMA
rsMA = ta.sma(rs, lenMa)
if(typMa == 'SMA' and not timeframe.isweekly)
rsMA := ta.sma(rs, lenMa)
if(typMa == 'EMA' and not timeframe.isweekly)
rsMA := ta.ema(rs, lenMa)
if(typMaWe == 'SMA' and timeframe.isweekly)
rsMA := ta.sma(rs, lenMaWe)
if(typMaWe == 'EMA' and timeframe.isweekly)
rsMA := ta.ema(rs, lenMaWe)
maPlot = plot(boolMa ? rsMA :na, color = colMa, linewidth = 1)
// Color Filling
// I will use an invisible MA to be able to choose or not the display of the fill
maPlot2 = plot(boolMa and fillMa ? rsMA:na, color = color.rgb(0,0,0,100), linewidth = 1)
// This variable gets the color that will be used for the fill
fillCol = rs > rsMA ? posCol:negCol
// Here if a MA is missing, there is no fill
fill(rsPlot, maPlot2 , color=fillCol)
// 2nd MA on RS Line
// SMA and EMA
rsMA2 = ta.sma(rs, lenMa2)
if (typMa2 == 'SMA' and not timeframe.isweekly)
rsMA2 := ta.sma(rs, lenMa2)
if (typMa2 == 'EMA' and not timeframe.isweekly)
rsMA2 := ta.ema(rs, lenMa2)
if (typMa2We == 'SMA' and timeframe.isweekly)
rsMA2 := ta.sma(rs, lenMa2We)
if (typMa2We == 'EMA' and timeframe.isweekly)
rsMA2 := ta.ema(rs, lenMa2We)
maPlot3 = plot(boolMa2 ? rsMA2 :na, color = colMa2, linewidth = 1)
// Historical New Highs & New Highs Before Price
var label newHigh = na
histNH = ta.highest(rs , prevlookback)
histCl = ta.highest(high, prevlookback)
// Historical RS New High
if(rsNewHigh == 'Historical RS New Highs' and plotNewHigh and rs == histNH)
newHigh := label.new(x = bar_index, y = rs, color = blueDotCol, style = label.style_circle, size = highLabel)
// Historical RS New High Before Price
if(rsNewHigh == 'Historical RS New Highs Before Price' and plotNewHigh and rs == histNH and high < histCl)
newHigh := label.new(x = bar_index, y = rs, color = blueDotCol, style = label.style_circle, size = highLabel)
// RS New High
if(barstate.islast and rsNewHigh == 'RS New Highs' and plotNewHigh and rs == histNH)
label.delete(newHigh)
newHigh := label.new(x = bar_index, y = rs, color = blueDotCol, style = label.style_circle, size = highLabel)
// RS New High Before Price
if(barstate.islast and rsNewHigh == 'RS New Highs Before Price' and plotNewHigh and rs == histNH and high < histCl)
label.delete(newHigh)
newHigh := label.new(x = bar_index, y = rs, color = blueDotCol, style = label.style_circle, size = highLabel)
// Historical New Lows & New Lows Before Price
var label newLow = na
histNL = ta.lowest(rs , prevlookback2)
histClL = ta.lowest(low, prevlookback2)
// Historical RS New Low
if(rsNewLow == 'Historical RS New Lows' and plotNewLow and rs == histNL)
newLow := label.new(x = bar_index, y = rs, color = redDotCol, style = label.style_circle, size = lowLabel)
// Historical RS New Low Before Price
if(rsNewLow == 'Historical RS New Lows Before Price' and plotNewLow and rs == histNL and low > histClL)
newLow := label.new(x = bar_index, y = rs, color = redDotCol, style = label.style_circle, size = lowLabel)
// RS New Low
if(barstate.islast and rsNewLow == 'RS New Lows' and plotNewLow and rs == histNL)
label.delete(newLow)
newLow := label.new(x = bar_index, y = rs, color = redDotCol, style = label.style_circle, size = lowLabel)
// RS New Low Before Price
if(barstate.islast and rsNewLow == 'RS New Lows Before Price' and plotNewLow and rs == histNL and low > histClL)
label.delete(newLow)
newLow := label.new(x = bar_index, y = rs, color = redDotCol, style = label.style_circle, size = lowLabel)
// Calculation of the RS Rating
// Getting ticker and reference ticker daily data
closeDa = request.security(syminfo.tickerid, 'D', close)
spxCloseDa = request.security(comparativeTickerId, 'D', close)
// Calculation of the performance from 1 to 4 last quarters
// Ticker
perfTicker63 = closeDa/closeDa[n63]
perfTicker126 = closeDa/closeDa[n126]
perfTicker189 = closeDa/closeDa[n189]
perfTicker252 = closeDa/closeDa[n252]
// SP500 of reference ticker
perfComp63 = spxCloseDa/spxCloseDa[n63]
perfComp126 = spxCloseDa/spxCloseDa[n126]
perfComp189 = spxCloseDa/spxCloseDa[n189]
perfComp252 = spxCloseDa/spxCloseDa[n252]
// Using Formula to calculate a relative score of the ticker and the SP500 with the last quarter weighted double
float rs_stock = 0.4*perfTicker63 + 0.2*perfTicker126 + 0.2*perfTicker189 + 0.2*perfTicker252
float rs_ref = 0.4*perfComp63 + 0.2*perfComp126 + 0.2*perfComp189 + 0.2*perfComp252
// Calculation of the total relative score or rs performance
float totalRsScore = (rs_stock) / (rs_ref) * 100
float totalRsRating = -1
// Here we calculated the relative score of the stock. The goal is now to assign the percentile correctly
// For this I took the curve given by my fork repo of Skyte on Rs Log and tried to calibrate the better possible
// the output curve of the relative performance of the 6,6xx stocks.
// Link: https://github.com/Fred6725/rs-log/blob/main/output/rs_stocks.csv
// Here is the curve in ASCII Art; on the x-axis, the Rs Rating and on the y-axis, the calculated performance.
//
// /
// /
// /
// /
//,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,/,,,,,,,,,,,,,,,,,
// /
// /
// /
// /
// |
// /
// ‾
// ‾
// -‾
// _____, ‾
// _____----------------‾‾‾‾‾‾‾‾‾‾‾‾‾
// __ */‾‾‾‾‾‾‾‾‾‾‾‾
// __ ,,----‾‾
// _/
// /
// |
// ______|________________ _______________________________ _____________________________________
// |0 |20 |40 |60 |80 |100
//
// I decided to cut this curve in 7 different levels that needs to be entered each day.
// These are relative strength scores corresponding to percentiles 98, 89, 69, 49, 29, 9 and 1.
// Finally I used the request.seed() function to auto update these levels automatically on a daily basis.
// Everything is managed in this repo if you're curious:
// https://github.com/Fred6725/relative-strength/tree/main (Fork from Skyte)
// More precisly in rs_ranking.py for extracting what I needed and in workflows/output.yml for the auto update.
// The update is done in the private fork of the seed tradingview original repo, checked and synchronised automatically
// I tried to uplad the full 6,6xx list of relative strength score and rs rating but the display speed was too long.
// Use the request.seed() function to access the RS Score environment of all the market
curveRsPerf = request.seed('seed_fred6725_rs_rating', 'RSRATING', close)
// To prevent loosing data because of week-ends and public holidays I decided to send the value 5 times in a row.
// Which gives 5*7 = 35 bars.
// Depending of the day we look at the graph we will have a variable amount of bars.
// The goal is to get these 7 numbers anyway.
// In case the graph is not updated, we count the number of bars since we have the first data.
// Calculation of the number of bar since we have the first data
delta = ta.barssince(na(curveRsPerf)!=true)
// Table to store the different values
var float[] different_values = array.new_float(7)
// Counter for stored values
var int counter = 0
// Variable for storage of the environment
float first = 0
float scnd = 0
float thrd = 0
float frth = 0
float ffth = 0
float sxth = 0
float svth = 0
// Browse seed's values and store the first 7 different values
if (not allowReplay)
for i = delta to 34+delta
close_value = nz(curveRsPerf[i])
if (not array.includes(different_values, close_value) and counter < 7 and close_value!=0)
array.set(different_values, counter, close_value)
counter := counter + 1
// Assign stored values to variables
first := array.get(different_values, 0)
scnd := array.get(different_values, 1)
thrd := array.get(different_values, 2)
frth := array.get(different_values, 3)
ffth := array.get(different_values, 4)
sxth := array.get(different_values, 5)
svth := array.get(different_values, 6)
// Replay mode
if (allowReplay)
first := first2
scnd := scnd2
thrd := thrd2
frth := frth2
ffth := ffth2
sxth := sxth2
svth := svth2
// Now that we've recovered the environment, we can assign a percentile using a simple linear approximation of the curve (+ adjustment).
if(totalRsScore >= first)
totalRsRating := 99
if(totalRsScore <= svth)
totalRsRating := 1
// Function to attribute the percentile with a simple linear approximation
f_attributePercentile(totalRsScore, tallerPerf, smallerPerf, rangeUp, rangeDn, weight) =>
sum = totalRsScore + (totalRsScore-smallerPerf)*weight // weight is used for manual calibration
if(sum > tallerPerf - 1)
sum := tallerPerf - 1
k1 = smallerPerf/rangeDn
k2 = (tallerPerf-1)/rangeUp
k3 = (k1-k2)/(tallerPerf-1-smallerPerf)
RsRating = sum/(k1-k3*(totalRsScore-smallerPerf))
if (RsRating > rangeUp)
RsRating := rangeUp
if (RsRating < rangeDn)
RsRating := rangeDn
RsRating
// Between 199 & 120 the score where approx 98 to 90.
if(totalRsScore < first and totalRsScore >= scnd)
totalRsRating := f_attributePercentile(totalRsScore, first, scnd, 98, 90, 0.33)
// Between 119 and 100 we ave scores between 89 and 70.
if (totalRsScore < scnd and totalRsScore >= thrd)
totalRsRating := f_attributePercentile(totalRsScore, scnd, thrd, 89, 70, 2.1)
// Between 100 and 91 we ave scores between 69 and 50.
if (totalRsScore < thrd and totalRsScore >= frth)
totalRsRating := f_attributePercentile(totalRsScore, thrd, frth, 69, 50, 0)
// Between 90 and 82 we ave scores between 49 and 30.
if (totalRsScore < frth and totalRsScore >= ffth)
totalRsRating := f_attributePercentile(totalRsScore, frth, ffth, 49, 30, 0)
// Between 81 and 56 we ave scores between 29 and 10.
if (totalRsScore < ffth and totalRsScore >= sxth)
totalRsRating := f_attributePercentile(totalRsScore, ffth, sxth, 29, 10, 0)
// Between 55 and 28 we ave scores between 9 and 2.
if (totalRsScore < sxth and totalRsScore >= svth)
totalRsRating := f_attributePercentile(totalRsScore, sxth, svth, 9, 2, 0)
// Check if one of this value is empty for replay mode
for i = 0 to 6
if (nz(array.get(different_values, i)) == 0 and not allowReplay)
totalRsRating := -1
// Display the RS Rating
// The results can only be used in Daily TimeFrame
isDaily = timeframe.isdaily
labelText1 = ' RS Rating'
labelText2 = ''
// Here we want to display 'RS' without value if one of the constants is missing
if(isDaily and totalRsRating != -1)
labelText2 := '\n\n '+str.tostring(totalRsRating,'#0')
// Rating Only
if (ratingOnly)
labelText1 := ''
labelText2 := '\n '+str.tostring(totalRsRating,'#0')
// Display the labels
label1 = (hideRSRat == false) and barstate.islast ? label.new(bar_index, rs, text=labelText1 , color = color.rgb(0,0,0,100), size=size.normal, textcolor=colorRS, style=label.style_label_center, textalign=text.align_left, yloc=yloc.price) : na
label2 = (hideRSRat == false) and barstate.islast ? label.new(bar_index, rs, text=labelText2 , color = color.rgb(0,0,0,100), size=size.large, textcolor=colorRS, style=label.style_label_center, textalign=text.align_left, yloc=yloc.price) : na
// Delete previous Labels (When new candle opens or when replay mode, the labels were piling on)
label.delete(label1[1])
label.delete(label2[1])
// Weekly Tight Closes Detector
//input
WtClose = input(false, title='Weekly Tight Closes Detector', group='TIGHT CLOSES DETECTOR')
colorTightCloses = input(color.aqua, title='Color of Tight Closes Boxes', group='TIGHT CLOSES DETECTOR')
// Calculation
if(tfWeekly)
// Open
WkO2 = open[2]
//Closes
WkC = close
WkC1 = close[1]
WkC2 = close[2]
// Highs
WkH = high
WkH1 = high[1]
WkH2 = high[2]
// Lows
WkL = low
WkL1 = low[1]
WkL2 = low[2]
// WEMA
Wema10 = ta.ema(close,10)
Wema20 = ta.ema(close,20)
// ATR Weekly (Used to have an auto-adaptive tight closes detector. Formula = Averages High-Low of the 14 previous bars. (Volatility measurement)
atr = ta.atr(14)
// Conditions (I like to have 3 tiny candle with tight closes so I add High and Low cond as well)
condTightClose = WkC < WkC1+(WkC1*atr/(close*2)) and WkC > WkC1-(WkC1*atr/(close*2)) and WkC1 < WkC2+(WkC2*atr/(close*2)) and WkC1 > WkC2-(WkC2*atr/(close*2)) and WkC < WkC2+(WkC2*atr/(close*2)) and WkC > WkC2-(WkC2*atr/(close*2))
condTightHigh = WkH < WkH1+(WkH1*atr/(close*2)) and WkH > WkH1-(WkH1*atr/(close*2)) and WkH1 < WkH2+(WkH2*atr/(close*2)) and WkH1 > WkH2-(WkH2*atr/(close*2))
condTightLow = WkL < WkL1+(WkL1*atr/(close*2)) and WkL > WkL1-(WkL1*atr/(close*2)) and WkL1 < WkL2+(WkL2*atr/(close*2)) and WkL1 > WkL2-(WkL2*atr/(close*2))
//condNotLowerLows = WkL2 > WkL1 and WkL1 > WkL
// I would like the script not to show me 3 tight candles when the first candle of the three is nearly full and big
// For that I wrote that the total size of the weekly wick of the candle must be 2 times bigger than the body
// But I noticed somtimes very small candle with little or no wick are still valide so added an exception ! (Yes it is far-fetched)
condFirstCandle = false
// For positive bars
if(WkC2 >= WkO2)
condFirstCandle := WkH2 - WkC2 + WkO2 - WkL2 > 2*(WkC2 - WkO2) or (WkH2-WkL2<WkH1-WkL1)
// For negative bars
if(WkC2 < WkO2)
condFirstCandle := WkH2 - WkO2 + WkC2 - WkL2 > 2*(WkO2 - WkC2) or (WkH2-WkL2<WkH1-WkL1)
// All condition together
condTot3WTight = condTightClose and (condTightHigh or condTightLow) and condFirstCandle //and not condNotLowerLows
//Plot Boxes Arround Weekly Tight Closes
highestW = ta.highest(WkH,3)
lowestW = ta.lowest (WkL,3)
if(condTot3WTight and WtClose)
box.new(bar_index[2], highestW, bar_index, lowestW, border_color = color.new(colorTightCloses,20), border_width = 1, border_style=line.style_dotted, bgcolor = color.new(colorTightCloses,85))
//------------------ Marked Highs and Lows ---------------------//
// Price Peak/Valley Points
// Highlights exact price at high or low points over a 19-period interval.
// For example, on a Daily chart, a High Price point is marked on the date
// where there has been no higher price the 9 days prior to that date and
// the 9 days following that date.
// Inputs
i_displayHL = input(true, title='Display H/L Points', group='High/Low Price Points')
i_colorHL = input(color.rgb(0,0,0,0), title='Labels Color', group='High/Low Price Points')
i_displayPc = input(false, title='%Change', group='High/Low Price Points')
i_colorPctP = input(color.rgb(0, 0, 255), title='Positive % Color', group='High/Low Price Points', inline = 'z')
i_colorPctN = input(color.rgb(222,50,174,0), title='Negative %', group='High/Low Price Points', inline = 'z')
i_pivot = input(9, title='Length for peak/valey points', group='High/Low Price Points')
// Definr arrays to store pivot values
var pivotHighValues = array.new_float(0)
var pivotLowValues = array.new_float(0)
if(i_displayHL and not tfWeekly)
// Use the function ta.pivothigh/low()
pivotHigh = ta.pivothigh(high, i_pivot, i_pivot)
pivotLow = ta.pivotlow (low, i_pivot, i_pivot)
// High Price Point
if(pivotHigh)
array.unshift(pivotHighValues, high[i_pivot])
textHigh9 = i_displayPc ? str.tostring(high[i_pivot], '0.00')+'\n':str.tostring(high[i_pivot], '0.00')
highestHigh = label.new(bar_index-i_pivot, array.get(pivotHighValues, 0), xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, text=textHigh9, textcolor=i_colorHL)
// Low Price Point
if(pivotLow)
array.unshift(pivotLowValues, low[i_pivot]) //low[i_pivot]
textLow9 = '\n' + str.tostring(low[i_pivot], '0.00')
lowestLow = label.new(bar_index-i_pivot, array.get(pivotLowValues, 0), xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_center, text=textLow9, textcolor=i_colorHL, color=color.rgb(0,0,0,100))
// Percentage Variation
float pHigh = na
float pLow = na
if array.size(pivotHighValues) > 0
pHigh := array.get(pivotHighValues, 0)
if array.size(pivotLowValues) > 0
pLow := array.get(pivotLowValues, 0)
prcVarHigh = (pHigh - pLow)/pLow * 100
prcVarLow = (pLow/pHigh - 1) * 100 // Formula to calculate percentage decline
prcVarHighText = prcVarHigh>=0 ? '+'+str.tostring(prcVarHigh, '0.0') + '%':str.tostring(prcVarHigh, '0.0') + '%'
prcVarLowText = prcVarLow>=0 ? '+'+str.tostring(prcVarLow , '0.0') + '%':str.tostring(prcVarLow, '0.0') + '%'
colorPctUp = prcVarHigh>=0 ? i_colorPctP:i_colorPctN
colorPctDn = prcVarLow >=0 ? i_colorPctP:i_colorPctN
// High Price Point Percent Variation
if(pivotHigh and i_displayPc)
pctPivotHigh = na(prcVarHigh)==true ? na:label.new(bar_index-i_pivot, array.get(pivotHighValues, 0), xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, text=prcVarHighText, textcolor=colorPctUp)
if(pivotLow and i_displayPc)
pctPivotLow = na(prcVarLow)==true ? na:label.new(bar_index-i_pivot, array.get(pivotLowValues, 0), xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_center, text='\n\n\n' + prcVarLowText, textcolor=colorPctDn, color=color.rgb(0,0,0,100))
//------------------ Chart Pattern Recognition ---------------------//
// INPUTS
i_displayPattern = input(true, title='Display Pattern', group='Chart Pattern Recognition')
i_displayBoxes = input(true, title='Display Trade Boxes', group='Chart Pattern Recognition')
i_displayHistoricalBoxes = input(false, title='Display Historical Trade Boxes', group='Chart Pattern Recognition')
i_baseDepth = input(50, title='Base: Depth (%)', group='Chart Pattern Recognition', inline='Parameters Base')
i_baseLength = input(65, title='Length (Weeks)', group='Chart Pattern Recognition', inline='Parameters Base')
i_dbDepth = input(50, title='Double Bottom: Depth (%)', group='Chart Pattern Recognition', inline='Parameters DB')
i_dbLength = input(65, title='Length (Weeks)', group='Chart Pattern Recognition', inline='Parameters DB')
// FUTURE PART TO HANDLE WE TF
i_baseDepth := i_baseDepth /100
i_dbDepth := i_dbDepth /100
// if (timeframe.isdaily)
i_baseLength := i_baseLength *5
i_dbLength := i_dbLength *5
// if (timeframe.isweekly)
// i_pivot := 2
// ARRAYS
// PIVOTS
var pivotHighPrices = array.new_float(0)
var pivotLowPrices = array.new_float(0)
// BASE PATTERN
// Prices
var startBasePrice = array.new_float(0)
var lowBasePrice = array.new_float(0)
var lowOfpivotHighPrices = array.new_float(0)
var float lowOfBaseHigh = 0
// Bars
var int startBaseBar = 0
var int lowerBaseBar = 0
var pivotHighBars = array.new_int(0)
var pivotLowBars = array.new_int(0)
// DOUBLE BOTTOM PATTERN
// Prices
var topDBPrice = array.new_float(0)
var bottomDBPrice = array.new_float(0)
// Bars
var int topDBBar = 0
var int bottomDBBar = 0
// CUP PATTERN
var baseCloses = array.new_float(0)
// PIVOTS HIGH/LOW
// Use the function ta.pivothigh/low()
pivotHigh = ta.pivothigh(high, i_pivot, i_pivot)
pivotLow = ta.pivotlow (low, i_pivot, i_pivot)
// When it occurs, store key points values in arrays
if (pivotHigh)
array.unshift(pivotHighPrices, high[i_pivot])
array.unshift(lowOfpivotHighPrices, low[i_pivot])
array.unshift(pivotHighBars, bar_index[i_pivot])
if (pivotLow)
array.unshift(pivotLowPrices, low[i_pivot])
array.unshift(pivotLowBars, bar_index[i_pivot])
// Calculation for the conditions of base detection (out of scope)
boolHighbase = false
boolHigherPiv = false
highestOfBase = ta.highest(high, 25 )
highestOfComp = ta.highest(high, 50 )
lowestBaseLow = ta.lowest (low , 25 )
lowestPointLeg = ta.lowest (low , 103)
var baseCond = false
isBase = false
// CONDITIONS FOR BASE DETECTION (Consolidation: (6 to 65 weeks)(8% to 50%) Flat Base: (5 to 65 week) (0% with a maximum of 15%)
if(array.size(pivotHighPrices) > 2)
// In case the base is made of multiple Pivots High without Pivot Low
boolHighbase := high[25]==array.get(pivotHighPrices, 0) or high[25]==array.get(pivotHighPrices, 1) or high[25]==array.get(pivotHighPrices, 2)
boolHigherPiv := high[25]>=highestOfComp
// Minimal Leg Up Calculation
legUp = lowestPointLeg * 1.20 // 20%
legUpCond = high[25] >= legUp
// Maximal Base Depth
firstBaseDepth = high[25] * (1-i_baseDepth) <= lowestBaseLow
// No candle is above high[25]
noCandleAbove = highestOfBase <= high[25]
// The candle of the begining of the base isn't in a previous base
noBaseInBase = isBase[25] == false
// Every Conditions with spikes for detection
baseCond := boolHighbase and boolHigherPiv and legUpCond and firstBaseDepth and noCandleAbove and noBaseInBase
// If Base Detected we store key points
lowestBar = ta.barssince(low==lowestBaseLow)
if (baseCond and not isBase[1])
array.unshift(startBasePrice, high[25])
startBaseBar := bar_index[25]
array.unshift(lowOfpivotHighPrices, low[25])
lowOfBaseHigh := low[25]
array.unshift(lowBasePrice , lowestBaseLow)
lowerBaseBar := bar_index[lowestBar] // Needs to be incremented and reset when base is over
// Get every close of the Base for Cup Detection
for i = 0 to 25
array.unshift(baseCloses, close[i])
// Bool for base that is true while the base is still valid
if (baseCond or isBase[1])
isBase := true
// Candle Base Counter
var int baseCount = 0
// When a base is detected, reset the bar count
if (baseCond and not isBase[1])
baseCount := bar_index-startBaseBar
// Increment the bar count if we are in a base
if (isBase)
baseCount := baseCount + 1
// Boolean for Trades Box Gestion
isBox = false
boxOver = true
if(isBox[1] and not boxOver[1])
isBox := true
// CONDITIONS FOR DOUBLE BOTTOM DETECTION (10% to 50%) (7 to 65 weeks)
detectDoubleBottom = false
if(isBase)
if (array.size(pivotHighPrices) > 1 and array.size(pivotLowPrices) > 1)
firstPivHigh = array.get(pivotHighPrices, 1)
scndPivHigh = array.get(pivotHighPrices, 0)
firstPivLow = array.get(pivotLowPrices, 1)
scndPivLow = array.get(pivotLowPrices, 0)
// Price Conditions
condPricesA = firstPivHigh > scndPivHigh and firstPivLow*0.97 > scndPivLow and firstPivLow < scndPivHigh
condPricesB = scndPivLow >= (1-i_dbDepth) * firstPivHigh // Depth Condition
condPricesC = scndPivLow <= 0.9 * firstPivHigh
condPricesD = (firstPivHigh-scndPivLow) * 0.6 + scndPivLow <= scndPivHigh // Buy point is above 60% of the base
condPricesE = (firstPivHigh-scndPivLow) * 0.95 + scndPivLow >= scndPivHigh // Buy point is at least under 10% of the high of the base
condPricesF = (firstPivHigh-firstPivLow)/(scndPivHigh-scndPivLow) >= 0.70
condPricesG = (firstPivHigh-firstPivLow)/2 + firstPivLow <= scndPivHigh // The first up leg of the first V must retrace at least 50% of the first down leg
condPricesH = true
if (array.size(startBasePrice) > 0)
condPricesH := firstPivHigh == array.get(startBasePrice, 0)
// Assigned in order of Time
firstPivTime = array.get(pivotHighBars, 1)
scndPivTime = array.get(pivotLowBars, 1)
thrdPivTime = array.get(pivotHighBars, 0)
frthPivTime = array.get(pivotLowBars, 0)
// Time Conditions
condTimeA = firstPivTime < scndPivTime and scndPivTime < thrdPivTime and thrdPivTime < frthPivTime
condTimeB = frthPivTime - firstPivTime <= 100
condTimeC = (thrdPivTime-firstPivTime) * 2 >= (bar_index-thrdPivTime) // Pattern Propreties A-C x 2 > E-D
condTimeD = (thrdPivTime-firstPivTime) <= (bar_index-thrdPivTime) * 2 // Same as above but for the other side
// Here we use bars between the two first legs. For the 2 last legs it will be done later as the pattern is being created
condTimeE = scndPivTime-firstPivTime <= 2 * (thrdPivTime-scndPivTime) and thrdPivTime-scndPivTime <= (scndPivTime-firstPivTime) * 2
condTimeF = frthPivTime-thrdPivTime <= 2 * (thrdPivTime-scndPivTime) and frthPivTime-thrdPivTime >= 0.5 * (thrdPivTime-scndPivTime) // Third leg must match size against second leg
// Time and Price Conditions
condBothA = ta.highest(high, bar_index-frthPivTime) <= scndPivHigh
// All Conditions
if (condPricesA and condPricesB and condPricesC and condPricesD and condPricesE and condPricesF and condPricesG and condPricesH and condTimeA and condTimeB and condTimeC and condTimeD and condTimeE and condTimeF and condBothA)
detectDoubleBottom := true
array.unshift(bottomDBPrice, scndPivLow)
array.unshift(topDBPrice, firstPivHigh)
topDBBar := array.get(pivotHighBars, 1)
// Boolean to store the information of a current Double Bottom
isDoubleBottom = false
if (detectDoubleBottom or isDoubleBottom[1])
isDoubleBottom := true
// For every bar in the base we store the closes in an array in order to compare
if (isBase)
array.unshift(baseCloses, close)
// CONDITIONS FOR CUP DETECTION (6 to 65 weeks) (8% to 50% depth)
detectCup = false
isCup = false
// Depth
float highCup = 0
float lowCup = 0
//Condition Cup
condThird = false
condFourth = false
condThirdTwo = false
condFourthTwo = false
// condPartThree = false
// Reference points
float middleOfCup = 0
baseTier = baseCount/3
baseFourth = baseCount/4
numberOfValidCl1 = 0
numberOfValidCl2 = 0
if (isBase)
if (array.size(startBasePrice) > 0 and array.size(lowBasePrice) > 0)
highCup := array.get(startBasePrice, 0)
lowCup := array.get(lowBasePrice, 0)
middleOfCup := lowCup + (highCup-lowCup)*0.5
// Depth
condMaxDepth = lowCup >= (1-i_baseDepth) * highCup
condMinDepth = lowCup <= 0.92 * highCup
// Length
condMaxLength = bar_index-startBaseBar <= i_baseLength
condMinLength = bar_index-startBaseBar >= 30
// Asolute Position against the Cup (50%)
condAbsolutePos = (highCup-lowCup)*0.5 + lowCup <= high
// Technical (80% of closes above 40% of base in the first tier, 80% under in the second.)
for i= baseCount to 2*baseTier
if (close[i]>=middleOfCup)
numberOfValidCl1 := numberOfValidCl1+1
condThirdTwo := numberOfValidCl1/baseTier >= 0.3
for i = baseCount-baseTier to baseTier
if (close[i]<=middleOfCup)
numberOfValidCl2 := numberOfValidCl2+1
condThird := numberOfValidCl2/baseTier >= 0.90 // 85% of closes must be contained in the middle thrid of the cup
// Technical 2 (Same with 2*Fourth (half))
numberOfValidCl1 := 0
numberOfValidCl2 := 0
for i= baseCount to 3*baseFourth
if (close[i]>=middleOfCup)
numberOfValidCl1 := numberOfValidCl1+1
condThirdTwo := numberOfValidCl1/baseFourth >= 0.3
for i = baseCount-baseFourth to baseFourth
if (close[i]<=middleOfCup)
numberOfValidCl2 := numberOfValidCl2+1
condFourth := numberOfValidCl2/(2*baseFourth) >= 0.90 // or 85% of the closes must be contained in the middle half of the cup
cupForm = (condThird and condThird[1] and condThirdTwo and condThirdTwo[1]) or (condFourth and condFourth[1] and condFourthTwo and condFourthTwo[1])
detectCup := condMaxDepth and condMinDepth and condMaxLength and condMinLength and condAbsolutePos and cupForm
// Boolean to store the information
if (detectCup or isCup[1])
isCup := true
// CUP MAINTENANCE
// plot (condThirdTwo ? 15:13, color=color.red)
// plot (condFourthTwo ? 12:9, color=color.orange)
// plot (detectCup ? 25:20, color=color.lime)
// Graphical Objects Declaration
// Horizontal Lines
var line highLine = na
var line lowLine = na
var line dbLine1 = na
var line dbLine2 = na
var line dbLine3 = na
var line cupLineLeft = na
var line cupLineRight = na
var line cupLineLeftLive = na
var line cupLineRightLive = na
// Box for Entry/Take Profit/ SL
var box entryBox = na
var box slBox = na
var box tpBox = na
// DRAWING BASE ON CHART IF DETECTION
if (baseCond and not isBase[1] and timeframe.isdaily and i_displayPattern)
highLine := line.new(x1=startBaseBar, y1=array.get(startBasePrice, 0), x2=bar_index, y2=array.get(startBasePrice, 0), width=3, style = line.style_dotted, color=color.rgb(146,193,131,0))
lowLine := line.new(x1=startBaseBar, y1=array.get(lowBasePrice, 0), x2=bar_index, y2=array.get(lowBasePrice, 0), width=2, style = line.style_solid, color=color.rgb(146,193,131,0))
select = i_displayHistoricalBoxes ? false:boxOver
// Optional Trade Boxes
if(select)
box.delete(entryBox)
box.delete(slBox)
box.delete(tpBox)
isBox := false
boxOver := true
// // // DRAWING CURRENT CUP IF DETECTED
var line[] linesLeft = array.new_line(na)
var line[] linesRight = array.new_line(na)
// Exception with ta.lowest() series not equal to lower low (eg IOT)
if (lowerBaseBar-startBaseBar <= 0)
lowValue = low
for i=baseCount to 0
if(low[i]<lowValue)
lowerBaseBar := bar_index[i]
lowValue := low[i]
lengthLeft = lowerBaseBar-startBaseBar
lengthRight = bar_index-lowerBaseBar
if (detectCup and isBase and timeframe.isdaily and i_displayPattern and not isDoubleBottom[1] and barstate.islast)
// Draw Current Cup
if (array.size(linesRight) > (lengthRight-1))
for i = 0 to (lengthRight-1)
line.delete(array.get(linesRight, i))
line.delete(lowLine)
var int x1 = 0
var float y1 = na
var int x2 = 0
var float y2 = na
// Some Reference Points
var float startUpPrice = 0
var float bottomPrice = 0
// Drawing Informations
isLeftDrawn = false
// Out of scope calculation
if(array.size(lowBasePrice) > 0) // array.size(lowOfpivotHighPrices) > 0 and
startUpPrice := lowOfBaseHigh * (1-0.01)
bottomPrice := array.get(lowBasePrice, 0) * (1-0.01)
endUpPrice = low[1]*(1-0.01)
// We want a curve with an exp(x) form
if(timeframe.isdaily and i_displayPattern and array.size(lowBasePrice) > 0 and startUpPrice>bottomPrice) // and array.size(lowOfpivotHighPrices) > 0
// First Part
for i = 0 to (lengthLeft-1)
float k = 1/math.exp(0)/(startUpPrice-bottomPrice)
x1 := bar_index[(lengthLeft-1)-(i-1)]
x2 := bar_index[(lengthLeft-1)-(i )]
y1 := bottomPrice + (1/math.exp(i *6/lengthLeft))/k
y2 := bottomPrice + (1/math.exp((i+1)*6/lengthLeft))/k
// Remove spread at the bottom of the cup
if (i==lengthLeft-1)
y2 := bottomPrice
// Magical Drawing Left Part
cupLineLeftLive := line.new(x1=x1-lengthRight, y1=y1, x2=x2-lengthRight, y2=y2, color=color.rgb(146,193,131,0), width=3)
array.unshift(linesLeft, cupLineLeftLive)
isLeftDrawn := true
// Second Part
if (isLeftDrawn)
for i = 0 to (lengthRight-1) // 1 to 6 is the sample from e^1 to e^6 for the part of the curve I've selected
float k = math.exp(6)/(endUpPrice-bottomPrice)
x1 := bar_index[(lengthRight-1)-(i-1)]
x2 := bar_index[(lengthRight-1)-i ]
y1 := bottomPrice + (math.exp(i *6/lengthRight)-1)/k
// Remove spread at the bottom of the cup
if(i==0)
y1 := bottomPrice
y2 := bottomPrice + (math.exp((i+1)*6/lengthRight)-1)/k
// Magical Drawing Right Part
cupLineRightLive := line.new(x1=x1, y1=y1, x2=x2, y2=y2, color=color.rgb(146,193,131,0), width=3)
array.unshift(linesRight, cupLineRightLive)
// Deletes Current cup if not a cup anymore
// if (not isCup and array.size(linesLeft) > (lengthLeft-1))
// for i = 0 to (lengthLeft-1)
// line.delete(array.get(linesLeft, i))
// if (not isCup and array.size(linesRight) > (lengthRight-1))
// for i = 0 to (lengthRight-1)
// line.delete(array.get(linesRight, i))
// DRAWING DOUBLE BOTTOM ON CHART IF DETECTION
lowCompare = bar_index-topDBBar > 0 ? ta.lowest(low, bar_index-topDBBar):low
if (detectDoubleBottom and not isDoubleBottom[1] and timeframe.isdaily and i_displayPattern)
line.delete(highLine)
line.delete(lowLine )
bottomDBBar := array.get(pivotLowBars, 0)
// If Lower Low But Double Bottom Still valid (CASY)
//if (array.size(bottomDBPrice) > 0) // This part is generating Error on SPX ticker due to too much candle on study
// if (lowCompare < array.get(bottomDBPrice, 0))
// array.unshift(bottomDBPrice, lowCompare)
// bottomDBBar := bar_index - ta.barssince(low==lowCompare)
// if (low[1] == array.get(bottomDBPrice, 0))
// bottomDBBar := bar_index[1]
highLine := line.new(x1=array.get(pivotHighBars, 0), y1=array.get(pivotHighPrices, 0), x2=bar_index, y2=array.get(pivotHighPrices, 0), width=3, style = line.style_dotted, color=color.rgb(146,193,131,0))
dbLine1 := line.new(x1=array.get(pivotHighBars, 1), y1=array.get(lowOfpivotHighPrices, 1)*(100-1)/100 , x2=array.get(pivotLowBars, 1), y2=array.get(pivotLowPrices, 1)*(100-1)/100 , width=2, style = line.style_solid, color=color.rgb(146,193,131,0))
dbLine2 := line.new(x1=array.get(pivotLowBars, 1), y1=array.get(pivotLowPrices, 1)*(100-1)/100, x2=array.get(pivotHighBars, 0), y2=array.get(lowOfpivotHighPrices, 0)*(100-1)/100 , width=2, style = line.style_solid, color=color.rgb(146,193,131,0))
dbLine3 := line.new(x1=array.get(pivotHighBars, 0), y1=array.get(lowOfpivotHighPrices, 0)*(100-1)/100 , x2=bottomDBBar , y2=array.get(bottomDBPrice, 0)*(100-1)/100 , width=2, style = line.style_solid, color=color.rgb(146,193,131,0))
lowLine := line.new(x1=bottomDBBar , y1=array.get(bottomDBPrice, 0)*(100-1)/100 , x2=bar_index , y2=low * (100-1)/100 , width=2, style = line.style_solid, color=color.rgb(146,193,131,0))
select = i_displayHistoricalBoxes ? false:boxOver
// Optional Trade Boxes
if(select)
box.delete(entryBox)
box.delete(slBox)
box.delete(tpBox)
isBox := false
boxOver := true
// Check Bottom Break
// Adjust Double Bottom Base
if (array.size(bottomDBPrice) > 0)
if (low < array.get(bottomDBPrice, 0) and isDoubleBottom)
line.delete(highLine)
line.delete(lowLine )
line.delete(dbLine1 )
line.delete(dbLine2 )
line.delete(dbLine3 )
isDoubleBottom := false
// Redraw Original base if Double Bottom disabled
highLine := line.new(x1=startBaseBar, y1=array.get(startBasePrice, 0), x2=bar_index, y2=array.get(startBasePrice, 0), width=3, style = line.style_dotted, color=color.rgb(146,193,131,0))
lowLine := line.new(x1=startBaseBar, y1=array.get(lowBasePrice,0), x2=bar_index, y2=array.get(lowBasePrice, 0), width=2, style = line.style_solid, color=color.rgb(146,193,131,0))
// Check Double Bottom base Length
if (isDoubleBottom and bar_index-topDBBar>i_dbLength)
line.delete(highLine)
line.delete(lowLine )
line.delete(dbLine1 )
line.delete(dbLine2 )
line.delete(dbLine3 )
isDoubleBottom := false
// Check Double Bottom Pattern Propreties
firstPivTime = line.get_x1(dbLine1)
thrdPivTime = line.get_x2(dbLine2)
if (isDoubleBottom and (thrdPivTime-firstPivTime) * 2 <= bar_index-thrdPivTime or (thrdPivTime-firstPivTime) >= (bar_index-thrdPivTime) * 2)
line.delete(highLine)
line.delete(lowLine )
line.delete(dbLine1 )
line.delete(dbLine2 )
line.delete(dbLine3 )
isDoubleBottom := false
// Redraw Original base if Double Bottom disabled
highLine := line.new(x1=startBaseBar, y1=array.get(startBasePrice, 0), x2=bar_index, y2=array.get(startBasePrice, 0), width=3, style = line.style_dotted, color=color.rgb(146,193,131,0))
lowLine := line.new(x1=startBaseBar, y1=array.get(lowBasePrice,0), x2=bar_index, y2=array.get(lowBasePrice,0), width=2, style = line.style_solid, color=color.rgb(146,193,131,0))
// Adjust Base Bottom
if (low < line.get_y1(lowLine) and isBase and not isDoubleBottom)
line.set_y1(lowLine, low)
line.set_y2(lowLine, low)
lowerBaseBar := bar_index
if (array.size(lowBasePrice) > 0)
array.unshift(lowBasePrice, low)
// Check Base Max Depth and Max Length
if ((low < line.get_y1(highLine) * (1-i_baseDepth) or baseCount>i_baseLength) and isBase[1] and not isDoubleBottom[1])
line.delete(highLine)
line.delete(lowLine)
isBase := false
// Check Depth of base to adjust style of line (Depth above 15% = Dashed Line, defined as flat base by IBD)
if (line.get_y1(highLine) * 0.85 >= line.get_y1(lowLine) and isBase and not isDoubleBottom)
line.set_style(lowLine, line.style_dotted)
line.set_width(lowLine, 3)
// While the base is still valid, we extend lines
if (high<=line.get_y1(highLine) and low>=line.get_y1(lowLine) and isBase)
line.set_x2(highLine, bar_index)
line.set_x2(lowLine , bar_index)
if (isDoubleBottom)
line.set_y2(lowLine, low*(100-1)/100)
line.set_x2(lowLine, bar_index)
// Check Top Break
if (high>line.get_y1(highLine) and (isBase[1] or isDoubleBottom[1]))
isBase := false
if (isDoubleBottom)
isDoubleBottom := false
// Drawing historical cups if they are cups during the break out
if (detectCup and timeframe.isdaily and i_displayPattern and not isDoubleBottom[1])
// Draw historical fix Cups
line.delete(lowLine)
var int x1 = 0
var float y1 = na
var int x2 = 0
var float y2 = na
// Some reference points
var float startUpPrice = 0
var float bottomPrice = 0
// Drawing Informations
isLeftDrawn = false
// Out of scope calculation
if(array.size(lowBasePrice) > 0) // array.size(lowOfpivotHighPrices) > 0 and
startUpPrice := lowOfBaseHigh * (1-0.01)
bottomPrice := array.get(lowBasePrice, 0) * (1-0.01)
endUpPrice = low[1]*(1-0.01)
// Exception with ta.lowest() series not equal to lower low (eg IOT)
if (lowerBaseBar-startBaseBar <= 0)
lowValue = low
for i=baseCount-1 to 0
if(low[i]<lowValue)
lowerBaseBar := bar_index[i]
lowValue := low[i]
lengthLeft := lowerBaseBar-startBaseBar // := au lieu de =
lengthRight := bar_index-lowerBaseBar
// We want a curve with an exp(x) form
if(timeframe.isdaily and i_displayPattern and array.size(lowBasePrice) > 0 and startUpPrice>bottomPrice) // and array.size(lowOfpivotHighPrices) > 0
// First Part
for i = 0 to (lengthLeft-1)
float k = 1/math.exp(0)/(startUpPrice-bottomPrice)
x1 := bar_index[(lengthLeft-1)-(i-1)]
x2 := bar_index[(lengthLeft-1)-(i )]
y1 := bottomPrice + (1/math.exp(i *6/lengthLeft))/k
y2 := bottomPrice + (1/math.exp((i+1)*6/lengthLeft))/k
// Remove spread at the bottom of the cup
if (i==lengthLeft-1)
y2 := bottomPrice
// Magical Drawing Left Part
cupLineLeft := line.new(x1=x1-lengthRight, y1=y1, x2=x2-lengthRight, y2=y2, color=color.rgb(146,193,131,0), width=3)
isLeftDrawn := true
// Second Part
if (isLeftDrawn)
for i = 0 to (lengthRight-1) // 1 to 6 is the sample from e^1 to e^6 for the part of the curve I've selected
float k = math.exp(6)/(endUpPrice-bottomPrice)
x1 := bar_index[(lengthRight-1)-(i-1)]
x2 := bar_index[(lengthRight-1)-i ]
y1 := bottomPrice + (math.exp(i *6/lengthRight)-1)/k
// Remove spread at the bottom of the cup
if(i==0)
y1 := bottomPrice
y2 := bottomPrice + (math.exp((i+1)*6/lengthRight)-1)/k
// Magical Drawing Right Part
cupLineRight := line.new(x1=x1, y1=y1, x2=x2, y2=y2, color=color.rgb(146,193,131,0), width=3)
// END CUP DRAWING
if(i_displayBoxes)
topBase = line.get_y1(highLine)
entryBox := box.new(bar_index[1], topBase*(1+0.05), bar_index, topBase , border_color=color.rgb(0,0,0,100), border_width=0, bgcolor=color.rgb(0,0,255,92))
slBox := box.new(bar_index[1], topBase*(1-0.05), bar_index, topBase*(1-0.08), border_color=color.rgb(0,0,0,100), border_width=0, bgcolor=color.rgb(255, 0, 0, 92))
tpBox := box.new(bar_index[1], topBase*(1+0.20), bar_index, topBase*(1+0.25), border_color=color.rgb(0,0,0,100), border_width=0, bgcolor=color.rgb(60, 243, 4, 88))
isBox := true
boxOver := false
// TRADE BOX GESTION
// Extend Boxes while the trade runs
if (high<=line.get_y1(highLine)*(1+0.25) and low>=line.get_y1(highLine)*(1-0.08) and isBox)
box.set_right(entryBox, bar_index)
box.set_right(slBox , bar_index)
box.set_right(tpBox , bar_index)
isBox := true
boxOver := false
// MEMORY LIMIT GESTION (ARRAY SIZE)
if (array.size(linesLeft) > 500)
line.delete(array.pop(linesLeft))
if (array.size(linesRight) > 500)
line.delete(array.pop(linesRight))
|
Swing Point Oscillator with Trend Filter [Quantigenics] | https://www.tradingview.com/script/9bkvdAtu-Swing-Point-Oscillator-with-Trend-Filter-Quantigenics/ | Quantigenics | https://www.tradingview.com/u/Quantigenics/ | 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/
// © Quantigenics
//@version=5
indicator("Swing Point Oscillator with Trend Filter",overlay = false)
OscLength = input.int(defval = 9, title = "Oscillator Length" )
TrendFiltLength = input.int(defval = 18, title = "Trend Filter Length")
TopLine = input(defval = .85, title = "Top Line")
MidHigh = input(defval = .4, title = "Mid High")
MidLow = input(defval = -.4, title = "Mid Low")
Bottom = input(defval = -.85, title = "Bottom")
showZone = input.bool(defval = true,title = "Show Zones")
UpZoneColor = input.color(defval = color.rgb(255, 58, 222, 90),title = "Up Zone Color")
DownZoneColor = input.color(defval = color.rgb(255, 58, 222, 90),title = "Down Zone Color")
OscColor = input.color(defval = color.yellow, title = "Osc Color")
TopLineColor = input.color(defval = color.rgb(255,0,255), title = "Top Line Color")
MidHighColor = input.color(defval = color.rgb(24, 255, 24), title = "Mid High Color")
MidLineColor = input.color(defval = color.blue, title = "Mid Line Color")
MidLowColor = input.color(defval = color.rgb(24, 255, 24))
BottomColor = input.color(defval = color.rgb(255,0,255), title = "Bottom Color")
var oFastK = 0.
var oFastD = 0.
var oSlowK = 0.
var oSlowD = 0.
var phase = 25
var upbox = box.new(bar_index,TopLine,bar_index,MidHigh,border_width = 0,bgcolor = showZone ? UpZoneColor: #00000000)
var downbox = box.new(bar_index,MidLow,bar_index,Bottom,border_width = 0,bgcolor = showZone ? DownZoneColor: #00000000)
box.set_right(upbox,bar_index)
box.set_right(downbox,bar_index)
Cum(series float price)=>
var res = 0
res[1]+price
Num2 = 0.
Den2 = 0.
BarsToGo1 = 0
BarsToGo2 = 0
LL = ta.lowest( low, OscLength )
HH = ta.highest( high, OscLength )
Num1 = close - LL
Den1 = HH - LL
if( Den1 > 0)
oFastK := Num1 / Den1 * 100
else
oFastK := 0
CurrentBar = bar_index+1
BarsToGo1 := 1 - CurrentBar
Num2 := Num1
Den2 := Den1
if (Den2 > 0)
oFastD := Num2 / Den2 * 100
else
oFastD := 0
BarsToGo2 := 3 - CurrentBar
oFastDCum = Cum( oFastD )
if (BarsToGo2 > 0 and CurrentBar > 0)
oSlowD := ( oFastDCum + BarsToGo2 * oFastD[ CurrentBar - 1 ] ) / 3
else
oSlowD := (oFastD+oFastD[1]+oFastD[2])/ 3
oSlowK := oFastD
int Length = math.round(math.sqrt(phase))
Value2 = .1 * (oFastK - 50)
xavg = ta.ema(Value2, Length)
Value3 = ta.ema(xavg, Length)
Osckk = (math.exp(1 * Value3) - 1) / (math.exp(1 * Value3) + 1)
RE = (high-high[2])+(low-low[2])
REABS = math.abs(high-high[2])+math.abs(low-low[2])
SUM = 0.
SUMABS = 0.
for Z=0 to OscLength*.5-1
SUM += RE[Z]
SUMABS += REABS[Z]
OscB= SUMABS > 0 ? SUM/SUMABS : 0
OscA=OscB
CCIValue = (ta.cci( high + low + close, OscLength ))/100
MainOsc = Osckk+OscA+CCIValue
var MaxMainOsc = 0.
MaxMainOsc := MaxMainOsc > math.abs(MainOsc)?MaxMainOsc:math.abs(MainOsc) //Keep track of maximum absolute value of MainOsc
if (MaxMainOsc != 0 )
MainOsc := MainOsc / MaxMainOsc //Normalize MainOsc
plot(MainOsc, title = "Swing Point Oscillator",color = OscColor)
plot(TopLine,title = "Top",color = TopLineColor)
plot(MidHigh,title = "Mid High", color = (bar_index%2==0?MidHighColor:color.rgb(0, 0, 0, 100)))
plot(0, title = "Mid Line",color = MidLineColor)
plot(MidLow,title = "Mid Low",color = (bar_index%2==0?MidLowColor:color.rgb(0, 0, 0, 100)))
plot(Bottom,title = "Bottom",color = BottomColor)
TrendFilt = ta.sma(MainOsc, TrendFiltLength)
var TrendColor = color.red
if (TrendFilt>MidHigh or TrendFilt<MidLow)
TrendColor := color.red
else
TrendColor := color.rgb(150, 150, 150)
plot(TrendFilt, title = "Trend Filter", color = TrendColor) |
Heikin-Ashi Rolling Time Decay Volume Oscillator | https://www.tradingview.com/script/lvLnKtu5-Heikin-Ashi-Rolling-Time-Decay-Volume-Oscillator/ | tkarolak | https://www.tradingview.com/u/tkarolak/ | 46 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tkarolak
//@version=5
// ====================
// ==== Background ====
// ====================
// This script defines a custom Heikin-Ashi Rolling Time Decay Volume Oscillator indicator.
// Users can choose candle types and set the rolling window size and smoothing period.
// The indicator calculates time-decayed moving sums of bullish (green) and bearish (red) volume data.
// It generates a volume share oscillator by smoothing and weighting these volumes relative to total volume.
// Traders can gauge market sentiment from the color-coded area plots and horizontal lines.
// Customizable channel levels and gradient fills in overbought/oversold regions enhance usability.
// By interpreting the indicator's values, traders can make informed decisions about market dynamics.
indicator("Heikin-Ashi Rolling Time Decay Volume Oscillator", shorttitle="HA Time Decay Volume Oscillator", format=format.percent, precision=2)
// Custom types
type SettingsTdVol
string source
int lookback
int smoothing
// Settings Group & Tooltips
string gRollingVolumeTdVol = "Rolling Volume Oscillator Settings"
string ttSourceTdVol = "Select the type of candles to use for calculations."
string ttLookbackTdVol = "Set the rolling window size for volume calculations."
string ttSmoothingTdVol = "Set the smoothing period for the indicator."
string ttChannelTdVol = "Set the overbought/oversold channel level."
// Initialize the settings for Rolling Volume
SettingsTdVol settingsTdVol =
SettingsTdVol.new(
input.string ("Heikin-Ashi Candles", "Source - candles type", group = gRollingVolumeTdVol, options=["Heikin-Ashi Candles", "Japanese Candles"], tooltip = ttSourceTdVol),
input.int (50, "Rolling Window", group = gRollingVolumeTdVol, minval = 4, step = 1, tooltip = ttLookbackTdVol),
input.int (3, "Smoothing", group = gRollingVolumeTdVol, minval = 1, maxval = 10, tooltip = ttSmoothingTdVol)
)
settingsTdVolChannel = input.float(30, "OB/OS Channel", group = gRollingVolumeTdVol, minval = 1, maxval = 100, step = 1, tooltip = ttChannelTdVol)
// Runtime error indicating the absence of volume data from the data vendor
if barstate.islast and ta.cum(volume) == 0
runtime.error("No volume is provided by the data vendor.")
// Heiken Ashi Candles
cHA = ohlc4
oHA = float(na)
oHA := na(oHA[1]) ? (open + close) / 2 : (nz(oHA[1]) + nz(cHA[1])) / 2
// Source selection based on user input
float closeUsed = na
float openUsed = na
if settingsTdVol.source == "Heikin-Ashi Candles"
closeUsed := cHA
openUsed := oHA
else
closeUsed := close
openUsed := open
// Calculate the time decay moving sum for red and green volumes
float decaySumRed = 0.0
for i = 0 to settingsTdVol.lookback - 1
iterationVolume = closeUsed[settingsTdVol.lookback - 1 - i] < openUsed[settingsTdVol.lookback - 1 - i] ? volume[settingsTdVol.lookback - 1 - i] : 0
weight = i + 1 / settingsTdVol.lookback
decaySumRed := decaySumRed + iterationVolume * weight
float decaySumGreen = 0.0
for i = 0 to settingsTdVol.lookback - 1
iterationVolume = closeUsed[settingsTdVol.lookback - 1 - i] >= openUsed[settingsTdVol.lookback - 1 - i] ? volume[settingsTdVol.lookback - 1 - i] : 0
weight = i + 1 / settingsTdVol.lookback
decaySumGreen := decaySumGreen + iterationVolume * weight
// Calculate the final volume indicator with time decay and smoothing
float volIndicatorDecayed = math.round(ta.sma(decaySumGreen / (decaySumGreen + decaySumRed), settingsTdVol.smoothing) * 100 - 50, 2)
////////////////////////////////////////////////////////////////////////////////
// ====== DRAWING and PLOTTING ====== //
////////////////////////////////////////////////////////////////////////////////
// Colors for the volume area plot
colorArea = volIndicatorDecayed > 0 ? color.new(color.green, 60) : color.new(color.red, 60)
// Plot the volume indicator
indicatorPlot = plot(volIndicatorDecayed, "Volume Share", color = colorArea, style = plot.style_area)
// Horizontal lines for OB/OS levels
uppermax = hline(50, "Max", color.new(color.silver, 60))
upper = hline(settingsTdVolChannel, "OB Extreme", color.new(color.silver, 60))
median = hline(0, "Median", color.new(color.orange, 60), hline.style_dotted)
lower = hline(-settingsTdVolChannel, "OS Extreme", color.new(color.silver, 60))
lowermin = hline(-50, "Min", color.new(color.silver, 60))
// Gradient Fill for OB/OS regions
midLinePlot = plot(0, color = na, editable = false, display = display.none)
fill(indicatorPlot, midLinePlot, 50, settingsTdVolChannel, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100), title = "Overbought Gradient Fill")
fill(indicatorPlot, midLinePlot, -settingsTdVolChannel, -50, top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0), title = "Oversold Gradient Fill") |
Volume Profile (Maps) [LuxAlgo] | https://www.tradingview.com/script/Z8loUcRj-Volume-Profile-Maps-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 891 | 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("Volume Profile (Maps) [LuxAlgo]", shorttitle="LuxAlgo - Volume Profile (Maps)", max_lines_count = 500, max_boxes_count = 500, max_bars_back=2000, overlay=true)
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
sp1 =' ' , sp2 = ' '
src = input.source( close , 'source' )
mtV = input.bool ( false , sp2 + 'Volume * currency'
,tooltip= 'Example BTCUSD -> volume in USD' )
barsBack = input.int ( 5000 , 'Amount of bars' , maxval=50000 )
maxLines = input.int ( 500 , 'Max lines' , minval= 100 , maxval= 1000
,tooltip= 'max 1000' )
iStep = input.string( 'Round' , '' , group ='Round', options=['Round', 'Step'])
mlt = input.int ( 0 , 'Round' , group ='Round', minval= -8 , maxval= 4
,tooltip= 'Example: 123456.789 \n 0->123456.789\n 1->123456.79\n 2->123456.8\n 3->123457\n-1->123460\n-2->123500' )
step = input.float ( 1 , group ='Round' )
offset = input.int ( 200 , 'Offset' , group ='display Volume Profile', maxval=500 )
width = input.int ( 205 , 'Max width Volume Profile' , group ='display Volume Profile' )
cReg = input.color(color.rgb(178, 181, 190, 50), sp1 , group ='display Volume Profile', inline='c' )
cH_1 = input.color(color.rgb(255, 0, 0, 25), '' , group ='display Volume Profile', inline='c' )
cH_2 = input.color(color.rgb(255, 153, 0, 25), '' , group ='display Volume Profile', inline='c' )
sTab = input.bool ( false , sp1 + ' Show table' , group ='display Volume Profile' )
m = mlt > 0 ? math.pow (10, mlt) : 1
src := iStep == 'Step' ? math.round(src / step) * step : mlt > 0 ? math.round(src / m) * m : math.round(src, math.round(math.abs(math.log10(syminfo.mintick)) +mlt))
//------------------------------------------------------------------------------
// Methods
//-----------------------------------------------------------------------------{
method set (line ln, int x, float y, int o) =>
ln .set_xy1 (math.max(0, bar_index + o ), y)
ln .set_xy2 (math.max(0, bar_index + o - nz(x)), y)
method set (box bx, int x, float y, int o) =>
bx .set_lefttop (math.max(0, bar_index + o ), y)
bx .set_rightbottom(math.max(0, bar_index + o - nz(x)), y)
method inOut(int [] a, int val) => a.unshift(val), a.pop()
method inOut(float[] a, float val) => a.unshift(val), a.pop()
//------------------------------------------------------------------------------
// Variables
//-----------------------------------------------------------------------------{
var originalMap = map .new <float, float>() // key: close, value: volume
var lines = array.new < line >() // array of lines
var boxes = array.new < box >() // array of boxes
var tab = table.new(position.top_right, 2, 7, chart.bg_color, chart.bg_color, 1, chart.bg_color, 1)
//------------------------------------------------------------------------------
// Execution
//-----------------------------------------------------------------------------{
n = bar_index
barsBack := math.min (barsBack , last_bar_index) // minimum of ['Amount of bars' - total available bars]
mxLines2 = math.round(maxLines / 2)
if barstate.isfirst
for i = 0 to math.min(500, maxLines ) // fill line array till "maxLines" or "500" reached
lines.unshift(line.new(na, na, na, na, width=2))
for i = 0 to math.min(500, math.max(0, maxLines - 500)) // fill box array till "maxLines" or "500" reached (only after line array is filled)
boxes.unshift(box .new(na, na, na, na, border_width=1))
if last_bar_index - n == barsBack
line.new(n, close, n, close+ syminfo.mintick, extend=extend.both)
if last_bar_index - n <= barsBack
if originalMap.contains(src)
originalMap.put(src, originalMap.get(src) + (volume * (mtV ? src : 1))) // if originalMap already contains the close value, add volume on that same key level (instead of replace)
else
originalMap.put(src, (volume * (mtV ? src : 1))) // key (close) :value (volume)
if barstate.islast
maxVol = 0.
for ln in lines
ln.set_color(cReg) // set colour of all lines to default
for bx in boxes
bx.set_border_color(color.new(cReg, 70)) // set colour of all boxes to default
if originalMap.size() > 1
copyK = originalMap.keys().copy() // make a copy of the keys -> array
copyK.sort() // sort (ascending)
idx = copyK.binary_search_leftmost(src) // look for position of 'current' src in copyK
szL = idx, szR = copyK.size() -1 - idx // check how many left (lower) and right (higher) of idx (size: left - idx - right)
sml = math.min(szL, szR) // smallest side
if szR == sml
szL := math.min(maxLines - math.min(mxLines2, szR), szL) // if R side has 'unused' lines -> give them to L side
szR := math.min(mxLines2, szR)
else
szL := math.min(mxLines2, szL)
szR := math.min(maxLines - math.min(mxLines2, szL), szR) // if L side has 'unused' lines -> give them to R side
sliceK = copyK.slice(idx - szL, idx + szR) // grab (max. 500) keys around 'current' close
newMap = map.new<float, float>() // new map
for i = 0 to sliceK.size() -1 // all keys from sliceK : values from originalMap
getKey = sliceK.get(i) // key from sliceK
getVal = originalMap.get(getKey) // values from originalMap
if getVal > maxVol // get max volume of the set
maxVol := getVal
newMap.put(getKey, getVal) // put in 'newMap'
w = width / maxVol // make sure lines don't exceed 'max width Volume Profile'
aMaxI = array.from(0 , 0 ) // index of largest and second largest volume
aMaxV = array.from(0., 0.) // value of largest and second largest volume
max = 0., keys = newMap.keys(), vals = newMap.values()
for i = 0 to keys.size()-1
clo = keys.get(i)
vol = vals.get(i)
if vol > max // when largest volume is found -> set index so line can be coloured later
max := vol
aMaxI.inOut( i )
aMaxV.inOut(vol)
else if vol > aMaxV.get(1) // when second largest volume is found -> set index so line can be coloured later
aMaxI.set(1, i )
aMaxV.set(1,vol)
if i < 500
lines.get(i ).set(math.round(vol * w), clo, offset) // update 'lines' array
else
boxes.get(i - 500).set(math.round(vol * w), clo, offset) // update 'boxes' array (line array is full -> box array)
uno = aMaxI.first( ), duo = aMaxI.get (1)
if uno < 500
lines .get(uno) .set_color(cH_1) // colour line with largest volume
else
boxes .get(uno - 500) .set_border_color(cH_1) // colour line (box) with largest volume
if duo < 500
lines .get(duo) .set_color(cH_2) // colour line with second largest volume
else
boxes .get(duo - 500) .set_border_color(cH_2) // colour line (box) with second largest volume
//------------------------------------------------------------------------------
// Table
//-----------------------------------------------------------------------------{
if sTab
tab.cell(0, 0, text='size originalMap' , text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
tab.cell(1, 0, text=str.tostring(originalMap.size()) , text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
tab.cell(0, 1, text= '# higher' , text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
tab.cell(1, 1, text=str.tostring(originalMap.size() - idx), text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
tab.cell(0, 2, text= 'index "close"' , text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
tab.cell(1, 2, text=str.tostring( idx ) , text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
tab.cell(0, 3, text= ' ' , text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
tab.cell(0, 4, text= 'size newMap' , text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
tab.cell(1, 4, text=str.tostring( newMap.size() ) , text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
tab.cell(0, 5, text= '# higher' , text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
tab.cell(1, 5, text=str.tostring( szR ) , text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
tab.cell(0, 6, text= '# lower' , text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
tab.cell(1, 6, text=str.tostring( szL ) , text_font_family=font.family_monospace, text_color=chart.fg_color, height=2)
//-----------------------------------------------------------------------------} |
Smart Money Range [ChartPrime] | https://www.tradingview.com/script/84zEwHEm-Smart-Money-Range-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 1,216 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime
//@version=5
indicator("Smart Money Range [ChartPrime]",shorttitle = "SMR [ChartPrime]" ,overlay = true,max_boxes_count = 500,max_bars_back = 2000)
string visual = "➞ Visuals Settings🔸"
string core = "➞ Main Core Settings 🔸"
int atrLen = 30
float mult = 0.3
float per = 10.0
float perc = close * (per/100)
float srdatr = ta.atr (atrLen) * mult
float band = math.min (srdatr, perc) [20] /2
int sync = bar_index
var BINDEX = 0
var line [] Lines = array.new_line()
var label [] Labels = array.new_label()
float [] TotalVolume = array.new_float()
float [] Greenvolume = array.new_float()
float [] redvolume = array.new_float()
var ph = float(na)
var phL = int(na)
var pl = float(na)
float lowestValue = low
float HighValue = high
float Midhigh = high
float Midindex = bar_index
int lowestIndex = bar_index
int HighIndex = bar_index
float HH = low
int prd = input.int(30,"period",group = core)
int levs = input.int(24,"Volume Levels",tooltip = "Number of the Volume levels to check", group = core)
bool ShowVolume = input.bool(true,"Show Volume ❓ ",inline = "01",group = visual)
bool randomcolor = input.bool(false,"Random Coloring ❓ ",inline = "01",group = visual)
color Bull = input.color(color.new(#42f07f, 35),"1st",inline = "01",group = visual)
color Bear = input.color(color.new(#f37451, 70),"2nd",inline = "01",group = visual)
bool Showlines = input.bool(true,"Show Zigzag ❓ ",inline = "02",group = visual)
bool randomcolor1 = input.bool(false,"Random Coloring ❓ ",inline = "02",group = visual)
color LineZ = input.color(color.yellow,"",inline = "02",group = visual)
//~~~~~~~~~}
// ~~ Pivots {
pvtHi = ta.pivothigh(high,prd,prd)
pvtLo = ta.pivotlow(low,prd,prd)
if pvtHi
ph := high[prd]
phL:= sync[prd]
if pvtLo
pl:=low[prd]
Points = array.new_float(2,0)
Counter(lev,sup = true)=>
if sup
for i = 0 to 2000
max_bars_back(low,2000)
if low[ i + 1 ] < lev and lev < close[i]
array.set(Points,0,array.get(Points,0)+1)
Points.get(0)
else
for i = 0 to 2000
max_bars_back(high,2000)
if high[ i + 1 ] > lev and lev > close[i]
array.set(Points,1,array.get(Points,1)+1)
Points.get(1)
if barstate.islast
Count = (bar_index - phL)
// levs= math.floor(Count/3)
// levs= math.floor(24)
float [] VPlevels = array.new_float(levs+1)
var box [] VPboxes = array.new_box(levs+3)
var box [] VPboxes2 = array.new_box(levs+3)
int [] ticks = array.new_int(levs,0)
float [] Volumes = array.new_float(levs,0.0)
float [] SCR = array.new_float()
for i = 0 to Count
SCR.push(close[i])
for i = 1 to Count
if low[i] <= lowestValue
lowestValue := low[i]
lowestIndex := bar_index[i]
if high[i] >= HighValue
HighValue := high[i]
HighIndex := bar_index[i]
//
// M = bar_index + 135
// CC = int( (M - lowestIndex) / 2) s
Value = Counter(pl)
Value2 = Counter(HighValue,false)
max_bars_back(Value,2000)
max_bars_back(Value2,2000)
for i = 1 to 20
if high[i] >= Midhigh
Midhigh := high[i]
Midindex := bar_index[i]
step = ( HighValue-lowestValue ) / levs
for i=0 to levs by 1
array.set(VPlevels,i, lowestValue + step * i)
Col=color.rgb(math.random(10,200),math.random(10,160),math.random(10,180))
Gcolo = color.rgb(math.random(25,32),math.random(40,200),math.random(15,100))
//color.rgb(9, 155, 99, 90)
var box BOX1 = na , box.delete(BOX1)
var box BOX2 = na , box.delete(BOX2)
LA = sync - HighIndex
labelplace = (170 + LA ) / 2
BOX1:=box.new(lowestIndex,lowestValue+ (band* 2),bar_index+170,lowestValue,bgcolor = color.rgb(9, 155, 99, 90),border_color = color.rgb(9, 155, 99, 50))
BOX2:=box.new(HighIndex,HighValue + (band* 2),bar_index+170,HighValue,bgcolor = color.rgb(255, 4, 4, 90) ,border_color = color.rgb(255, 4, 4, 50))
Labels.push(label.new(lowestIndex ,lowestValue - (band * 13),str.tostring(Value),style = label.style_none,textcolor= color.white,color = color.new(color.black, 100),xloc=xloc.bar_index,size= size.large))
Labels.push(label.new(bar_index+135 ,lowestValue - (band * 13),str.tostring(Value + 1),style = label.style_none,textcolor= color.white,color = color.new(color.black, 100),xloc=xloc.bar_index,size= size.large))
Labels.push(label.new(HighIndex + labelplace ,HighValue + (band * 10),str.tostring(Value2),style = label.style_none,textcolor= color.white,color = color.new(color.black, 100),xloc=xloc.bar_index,size= size.large))
if Showlines
// 2
Lines.push(line.new(HighIndex,HighValue,lowestIndex + 50,lowestValue+ (band* 2),color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(HighIndex + 2 ,HighValue,lowestIndex + 52,lowestValue+ (band* 2),color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
// 3
Lines.push(line.new(lowestIndex + 50,lowestValue+ (band* 2),HighIndex + (labelplace-2) ,HighValue,color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(lowestIndex + 52,lowestValue+ (band* 2),HighIndex + labelplace,HighValue,color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
// 4
Lines.push(line.new(HighIndex + (labelplace-2),HighValue,bar_index+133,lowestValue+ (band* 2),color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(HighIndex + labelplace,HighValue,bar_index+135,lowestValue+ (band* 2),color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(bar_index+135,lowestValue+ (band* 2),bar_index+170,HighValue,color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(bar_index+133,lowestValue+ (band* 2),bar_index+168,HighValue,color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
if array.size(Lines) > 8
for i = 0 to 7
line.delete(Lines.shift())
if array.size(Labels) > 3
for i = 0 to 2
label.delete(Labels.shift())
for i=0 to array.size(SCR) -1
for x=0 to array.size(VPlevels) - 2 by 1
if low[ i + 1 ] < array.get(VPlevels,x+1) and array.get(VPlevels,x) < close[i]
array.set(ticks,x,array.get(ticks,x)+1)
array.set(Volumes,x,array.get(Volumes,x)+Counter(close[x]))
break
// label.new(bar_index+20 , low , str.tostring(ticks.size()))
if ShowVolume
for i = 0 to array.size(ticks) -2
box.delete(array.get(VPboxes,i))
array.set(VPboxes,i,
box.new(sync + 170+array.get(ticks,i),
array.get(VPlevels,i+1)+(band* 2),
sync + 170,
array.get(VPlevels,i)+(band* 2),
border_color = color.from_gradient(array.get(ticks,i),0,
array.max(ticks),
color.new(randomcolor ? Col : Bull , 70),
color.new(randomcolor ? Col : Bull , 35)),
bgcolor=color.from_gradient(array.get(ticks,i),0,
array.max(ticks),
color.new(randomcolor ? Col : Bull , 70),
color.new(randomcolor ? Col : Bull , 35)),
text=array.get(Volumes,i) > 0 ? str.tostring(array.get(Volumes,i),format.volume): "",
text_color=color.white))
for i = 0 to array.size(ticks) -2
box.delete(array.get(VPboxes2,i))
array.set(VPboxes2,i,
box.new(sync + 170-array.get(ticks,i),
array.get(VPlevels,i+1)+(band* 2),
sync + 170,
array.get(VPlevels,i)+(band* 2),
border_color = color.from_gradient(array.get(ticks,i),0,
array.max(ticks),
color.new(randomcolor ? Gcolo : Bear , 70),
color.new(randomcolor ? Gcolo : Bear , 35)),
bgcolor=color.from_gradient(array.get(ticks,i),0,
array.max(ticks),
color.new(randomcolor ? Gcolo : Bear , 70),
color.new(randomcolor ? Gcolo : Bear , 35)),
text=str.tostring(array.get(ticks,i)),
text_color=color.white))
// )
|
Map example | https://www.tradingview.com/script/znMMXbW8-Map-example/ | Sharad_Gaikwad | https://www.tradingview.com/u/Sharad_Gaikwad/ | 64 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sharad_Gaikwad
tt1 = "Maximum number of crossover/crossunder. Each time price crosses support/resistance line, it is counted as a cross and when such crosses reaches 'Max crossover/crossunder' the support/resistance line is removed"
//@version=5
indicator('Map example', overlay=true, max_lines_count = 500)
lb = input.int(title = 'Left bars', defval = 5, minval = 2)
rb = input.int(title = 'Right bars', defval = 5, minval = 2)
max_cross_cnt = input.int(title = 'Max crossover/crossunder', defval = 3, minval = 1, maxval = 10, tooltip = tt1)
cross_cnt_as_width = input.bool(title = 'Set line width based on cross count', defval = true)
start_date = input.time(timestamp("01 Jan 1900"))
var map_sr_cross = map.new<int, int>()
var map_sr_type = map.new<int, string>()
var color_map = map.new<string, color>()
var style_map = map.new<string, string>()
if bar_index == 0
color_map.put("S", color.green)
color_map.put("R", color.red)
style_map.put("S", line.style_solid)
style_map.put("R", line.style_solid)
style_map.put("StR", line.style_dotted)
style_map.put("RtS", line.style_dotted)
//@function returns color
method get(map<string, color> clr, string key) => clr.get(key)
//@function returns line style
method get(map<string, string> style, string key) => style.get(key)
//@function Returns count of price crosses from a map
method count(map<int, int> cnt, int key) => cnt.get(key)
//@function increments cross count in a map
method increment(map<int, int> cnt, int key) => cnt.put(key, cnt.get(key) + 1)
//@function Returns type S=support, R=reistance from a map.
method get(map <int, string> types, int key) => types.get(key)
//@function sets type S=support, R=reistance in a map
method set(map <int, string> types, int key, string val ) => types.put(key, val)
//@function deletes a map element
method delete(map<int, int> lines, int key) => lines.remove(key)
method delete(map<int, string> lines, int key) => lines.remove(key)
//@function returns crossover/crossunder if price crosses swing point
method state(float pp) => math.max(open, close) > pp and math.min(open, close) < pp ? 'Crossover' : math.min(open, close) < pp and math.max(open, close) > pp ? 'Crossunder' : na
//@function manipulate support/resistance lines based on price action
method price_action(array<line> lines) =>
size = lines.size()
if(size > 0)
for i = size - 1 to 0
price_point = line.get_y1(lines.get(i))
state = price_point.state()
if(not na(state))
bar_id = line.get_x1(lines.get(i))
if(map_sr_cross.count(bar_id) + 1 >= max_cross_cnt)
line.delete(lines.get(i))
map_sr_cross.delete(i)
map_sr_type.delete(i)
if(map_sr_cross.count(bar_id) + 1 < max_cross_cnt)
this_sr_type = map_sr_type.get(bar_id)
map_sr_type.set(bar_id, this_sr_type == 'R' ? 'S' : 'R')
style_key = this_sr_type + 't' + (this_sr_type == 'R' ? 'S' : 'R')
map_sr_cross.increment(bar_id)
line.set_style(lines.get(i), style_map.get(style_key))
line.set_color(lines.get(i), color_map.get(this_sr_type == 'R' ? 'S' : 'R'))
line.set_width(lines.get(i), cross_cnt_as_width ? map_sr_cross.count(bar_id) : 1)
//main code
ph = ta.pivothigh(high, lb, rb)
pl = ta.pivotlow(low, lb, rb)
if(ph and time >= start_date)
line.new(bar_index-rb, high[rb], bar_index, high[rb], color = color_map.get('R'), style = style_map.get('R'), extend = extend.right)
map_sr_cross.put(bar_index-rb, 0)
map_sr_type.set(bar_index-rb, 'R')
// map_sr_type.put(bar_index-rb, 'R')
if(pl and time >= start_date)
line.new(bar_index-rb, low[rb], bar_index, low[rb], color = color_map.get('S'), style = style_map.get('S'), extend = extend.right)
map_sr_cross.put(bar_index-rb, 0)
map_sr_type.set(bar_index-rb, 'S')
// map_sr_type.put(bar_index-rb, 'S')
//manipulate support/resistance lines based on price action
line.all.price_action()
|
HTF Oscillators RSI/ROC/MFI/CCI/AO - Dynamic Smoothing | https://www.tradingview.com/script/v4RLkfEB-HTF-Oscillators-RSI-ROC-MFI-CCI-AO-Dynamic-Smoothing/ | Harrocop | https://www.tradingview.com/u/Harrocop/ | 35 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Harrocop
////////////////////////////////////////////////////////////////////////////////////////
// HTF Oscillator multy type filter - Dynamic Smoothing
// - Option to change high time frame settings
// - Option to choose from different oscillators (RSI/ROC/MFI/CCI/AO)
// - The Dynamic smoothing makes a sleek line, taking the ratio of minutes of the higher time frame to the current time frame
// - options for notification in case of crossover / crossunder of MACD
// - Includes a table of value of all Oscillators
////////////////////////////////////////////////////////////////////////////////////////
//@version=5
indicator("HTF Oscillators RSI/ROC/MFI/CCI/AO - Dynamic Smoothing", "HTF Oscillators", overlay = false)
//////////////////////////////////////////////////////
////////// Input MACD HTF ////////////
//////////////////////////////////////////////////////
OSCI_settings = "Higher Time Frame MACD Settings"
Osci_Type = input.string(defval="RSI" , options=["RSI","ROC","MFI","CCI", "AO"], title="Oscillator type", inline = "1", group = OSCI_settings)
TimeFrame_OSCI = input.timeframe(title='Higher Time Frame', defval='30', inline = "1", group = OSCI_settings)
Length = input.int(14, title="Length # Bars HTF", minval=1, inline = "2", group = OSCI_settings)
LengthSmoothing = input.int(1, title="Smoothing SMA?", minval=1, inline = "2", group = OSCI_settings)
Plot_Bands = input.bool(true, title = "plot lower and upper band?", inline = "3", group = OSCI_settings)
middle_line = input.float(50, title = "Middle line plot", minval = -1000, maxval = 1000, step = 0.1, tooltip = "change accordingly to the Oscillator you are using", inline = "3", group = OSCI_settings)
overbought_level = input.float(70, title = "overbought level", minval = -1000, maxval = 1000, step = 0.1, tooltip = "change accordingly to the Oscillator you are using", inline = "4", group = OSCI_settings)
oversold_level = input.float(30, title = "oversold level", minval = -1000, maxval = 1000, step = 0.1, tooltip = "change accordingly to the Oscillator you are using", inline = "4", group = OSCI_settings)
Plot_Signal = input.bool(true, title = "Plot Signal?", inline = "5", group = OSCI_settings)
osci(type, src, length) =>
float result = 0
if type == 'RSI' // Relative Strength Index
result := ta.rsi(src, length)
result
if type == 'ROC' // Rate of Change
result := 100 * (src - src[length])/src[length]
result
if type == 'MFI' // Money Flow Index
result := ta.mfi(src, length)
result
if type == 'CCI' // Commodity Channel Index
result := (src -ta.sma(src, length)) / (0.015 * ta.dev(src, length))
result
if type == 'AO' // Awesome Oscillator
ao = ta.sma(hl2,5) - ta.sma(hl2,34)
diff = ao - ao[1]
result := diff
result
result
Oscillator_type = osci(Osci_Type, close, Length)
Osci_HTF = request.security(syminfo.ticker, TimeFrame_OSCI, Oscillator_type)
// Get minutes for current and higher timeframes
// Function to convert a timeframe string to its equivalent in minutes
timeframeToMinutes(tf) =>
multiplier = 1
if (str.endswith(tf, "D"))
multiplier := 1440
else if (str.endswith(tf, "W"))
multiplier := 10080
else if (str.endswith(tf, "M"))
multiplier := 43200
else if (str.endswith(tf, "H"))
multiplier := int(str.tonumber(str.replace(tf, "H", "")))
else
multiplier := int(str.tonumber(str.replace(tf, "m", "")))
multiplier
// Get minutes for current and higher timeframes
currentTFMinutes = timeframeToMinutes(timeframe.period)
higherTFMinutes = timeframeToMinutes(TimeFrame_OSCI)
// Calculate the smoothing factor
dynamicSmoothing = math.round(higherTFMinutes / currentTFMinutes)
Osci_HTF_Dynamic = ta.sma(Osci_HTF, dynamicSmoothing)
Osci_HTF_Smooth = ta.sma(Osci_HTF_Dynamic, LengthSmoothing)
// calc signals
LongCondition = ta.crossover(Osci_HTF_Smooth, oversold_level)
ShortCondition = ta.crossunder(Osci_HTF_Smooth, overbought_level)
/////////////////////////////////////////////////
/////////// Plots ////////////////
/////////////////////////////////////////////////
hline(Plot_Bands ? middle_line : na, "Zero Line", color=color.new(#ffffff, 50))
upperband = plot(Plot_Bands ? overbought_level : na, "overbought level", color = color.orange)
lowerband = plot(Plot_Bands ? oversold_level : na, "oversold level", color = color.orange)
plot(Osci_HTF_Smooth, title="Oscillator", color=#7E57C2)
fill(upperband, lowerband, color=color.rgb(126, 87, 194, 90), title="Background Fill")
plot(Plot_Signal ? LongCondition ? oversold_level : na : na, "Long Condition", style = plot.style_circles, color = color.rgb(0, 255, 8), linewidth = 4)
plot(Plot_Signal ? ShortCondition ? overbought_level : na : na, "Short Condition", style = plot.style_circles, color = color.rgb(255, 0, 0), linewidth = 4)
// Oscillator Values for the table
RSI_value = request.security(syminfo.ticker, TimeFrame_OSCI, osci("RSI", close, Length))
ROC_value = request.security(syminfo.ticker, TimeFrame_OSCI, osci("ROC", close, Length))
MFI_value = request.security(syminfo.ticker, TimeFrame_OSCI, osci("MFI", close, Length))
CCI_value = request.security(syminfo.ticker, TimeFrame_OSCI, osci("CCI", close, Length))
AO_value = request.security(syminfo.ticker, TimeFrame_OSCI, osci("AO", close, Length))
// Create Table
var table panel = table.new("top_right", 2, 7) // Now, 7 rows: 1 for the header, 5 for the oscillators, and 1 for the HTF and TimeFrame
if barstate.islast // Only update the table on the last bar to minimize computation
// Table Headers
table.cell(panel, 0, 0, "Indicator", bgcolor=color.new(color.blue, 90), text_color=color.white, text_size = size.large)
table.cell(panel, 1, 0, "Value", bgcolor=color.new(color.blue, 90), text_color=color.white, text_size = size.large)
// HTF and TimeFrame
table.cell(panel, 0, 1, "HTF_min", bgcolor=color.new(color.blue, 90), text_color=color.white, text_size = size.large)
table.cell(panel, 1, 1, TimeFrame_OSCI, bgcolor=color.new(color.blue, 90), text_color=color.white, text_size = size.large)
// RSI
table.cell(panel, 0, 2, "RSI", bgcolor=color.new(color.gray, 70), text_color=color.white, text_size = size.large)
table.cell(panel, 1, 2, str.tostring(RSI_value, format.mintick), bgcolor=color.new(color.gray, 90), text_color=color.white, text_size = size.large)
// ROC
table.cell(panel, 0, 3, "ROC", bgcolor=color.new(color.gray, 70), text_color=color.white, text_size = size.large)
table.cell(panel, 1, 3, str.tostring(ROC_value, format.mintick), bgcolor=color.new(color.gray, 90), text_color=color.white, text_size = size.large)
// MFI
table.cell(panel, 0, 4, "MFI", bgcolor=color.new(color.gray, 70), text_color=color.white, text_size = size.large)
table.cell(panel, 1, 4, str.tostring(MFI_value, format.mintick), bgcolor=color.new(color.gray, 90), text_color=color.white, text_size = size.large)
// CCI
table.cell(panel, 0, 5, "CCI", bgcolor=color.new(color.gray, 70), text_color=color.white, text_size = size.large)
table.cell(panel, 1, 5, str.tostring(CCI_value, format.mintick), bgcolor=color.new(color.gray, 90), text_color=color.white, text_size = size.large)
// AO
table.cell(panel, 0, 6, "AO", bgcolor=color.new(color.gray, 70), text_color=color.white, text_size = size.large)
table.cell(panel, 1, 6, str.tostring(AO_value, format.mintick), bgcolor=color.new(color.gray, 90), text_color=color.white, text_size = size.large) |
Adaptive MACD [LuxAlgo] | https://www.tradingview.com/script/kBHEpriQ-Adaptive-MACD-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,662 | 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("Adaptive MACD [LuxAlgo]", "LuxAlgo - Adaptive MACD")
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input.int(20, 'R2 Period', minval = 2)
fast = input.int(10, minval = 2)
slow = input.int(20, minval = 2)
signal = input.int(9, minval = 2)
//-----------------------------------------------------------------------------}
//Ultimate MACD
//-----------------------------------------------------------------------------{
var macd = 0.
var lag = (signal - 1) / 2
var a1 = 2 / (fast + 1)
var a2 = 2 / (slow + 1)
r2 = .5 * math.pow(ta.correlation(close, bar_index, length), 2) + .5
K = r2 * ((1 - a1) * (1 - a2)) + (1 - r2) * ((1 - a1) / (1 - a2))
macd := (close - close[1]) * (a1 - a2) + (-a2 - a1 + 2) * nz(macd[1]) - K * nz(macd[2])
ema = ta.ema(macd, signal)
hist = macd - ema
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
hist_css = hist > 0 and hist > hist[1] ? #5b9cf6
: hist > 0 and hist < hist[1] ? color.new(#5b9cf6, 50)
: hist < 0 and hist < hist[1] ? #f77c80
: color.new(#f77c80, 50)
plot(hist, 'Histogram', hist_css, 1, plot.style_columns)
plot(macd, 'MACD', chart.fg_color)
plot(ema, 'Signal', #ff5d00)
//-----------------------------------------------------------------------------} |
TICK Strength Background Shade | https://www.tradingview.com/script/gVMdJLH5-TICK-Strength-Background-Shade/ | BigGuavaTrading | https://www.tradingview.com/u/BigGuavaTrading/ | 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/
// © BigGuavaTrading
//@version=5
indicator("TICK Strength Background Shade", "TICK Strength", true)
//get TICK data
tH = input(599, "Strong TICK Strength", group = "Background Color TICK Strength Identifier")
tM = input(299, "Moderate TICK Strength", group = "Background Color TICK Strength Identifier")
tL = input(1, "Weak TICK Strength", group = "Background Color TICK Strength Identifier")
tickH = request.security("USI:TICK.US", "1", high)
tickC = request.security("USI:TICK.US", "1", close)
tickL = request.security("USI:TICK.US", "1", low)
//Background for TICK
bgcolor(tickH > tH ? color.new(color.green, 50) : tickL < -tH ? color.new(color.red, 50) : tickC > tM ? color.new(color.green, 70) : tickC < -tM ? color.new(color.red, 70) : tickC > tL ? color.new(color.green, 90) : tickC < -tL ? color.new(color.red, 90) : na)
|
Rain Flow Candles | https://www.tradingview.com/script/d4Zis74s-Rain-Flow-Candles/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 597 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KioseffTrading
//
//@version=5
indicator("Rain Flow Candles", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
auto = input.bool (defval = true, title = "Auto Calculate Everything (Deselect Before Changing Settings)", group = "Auto")
trad = input.bool (defval = false, title = "Traditional Look", group = "Traditional Look")
tim = input.timeframe (defval = "1D", title = "Higher Timeframe", group = "Settings")
strx = input.string (defval = "1", title = "Lower Timeframe", group = "Settings")
size = input.int (defval = 25, minval = 5,group = "Settings",title = "Columns")
profWidthx = input.int (minval = 2, title = "Profile Width", defval = 6,group = "Settings"), var profWidth = profWidthx,
showTxt = input.bool (defval = true, title = "Show Volume Values",group = "Settings"), var int [] timeArr = array.new_int()
upcol = input.color (defval = #14D990, title = "VWAP Higher Color", inline = "1",group = "Settings"), var int timeTrack = 0
dncol = input.color (defval = #F24968, title = "VWAP Lower Color" , inline = "1",group = "Settings")
lbcol = input.color (defval = #6929F2, title = "Last Bar Color", group = "Settings")
vwapS = input.bool (defval = true, title = "Show VWAP Lines", group = "Settings")
div = input.bool (defval = true, title = "Segment Higher Timeframe", group = "Settings")
import RicardoSantos/MathOperator/2
import HeWhoMustNotBeNamed/arraymethods/1
method float (int id) =>
float(id)
method determine (bool id, a, b) =>
switch id
true => a
=> b
str = switch auto
false => str.tostring(math.max(1, math.round(timeframe.in_seconds(timeframe.period) / 60 / 100)))
=> strx
if barstate.isfirst
if not auto
if timeframe.in_seconds(str).float().over_equal(timeframe.in_seconds(timeframe.period))
runtime.error("Please Select A Lower Timeframe Less Than What's On Your Chart")
if timeframe.in_seconds(tim).float().under_equal(timeframe.in_seconds(timeframe.period))
runtime.error("Please Select A Higher Timeframe Greater Than What's On Your Chart")
[hx, lx, vw1x, vw2x] = request.security_lower_tf(syminfo.tickerid, str, [high, low, hlc3 * volume, volume])
type values
array <float> h
array <float> l
array <float> vw1
array <float> vw2
line rainLineL
box rainBoxL
line rainLineR
box rainBoxR
var val = values.new(array.new_float(), array.new_float(),
array.new_float(), array.new_float()), var Half = 0
method locate (matrix <float> id, array <float> id2) =>
for x = 0 to val.vw1.size() - 1
up = id2.binary_search_leftmost (val.h.get(x))
dn = id2.binary_search_rightmost(val.l.get(x))
for i = dn to up
switch x.float().under(Half + 1)
true => id.set(0, i, id.get(0, i) + (val.vw2.get(x) / (math.abs(up - dn) + 1)))
=> id.set(1, i, id.get(1, i) + (val.vw2.get(x) / (math.abs(up - dn) + 1)))
method rankCalc (matrix <float> id, int end, matrix <float> id2) =>
for i = 0 to end
num = math.floor(100 / (end + 1))
id.add_col(id.columns(),
array.from(
id2.row(0).percentile_nearest_rank(num * (i + 1)),
id2.row(1).percentile_nearest_rank(num * (i + 1))))
id.add_col(id.columns(), array.from(
id2.row(0).max(),
id2.row(1).max()))
method appendLevels (matrix <float> id, increments) =>
for i = 0 to size
id.set(2, i, val.l.min() + increments * i)
method widthCalc (array <float> id, matrix <float> id2, matrix <float> id3, int i) =>
index = 1, index2 = 1
for x = 0 to id3.columns() - 1
if id2.get(0, i).under_equal(id3.get(0, x))
index := math.max(x - 1, 1)
break
if id2.row(1).sum().over(0)
for x = 0 to id3.columns() - 1
if id2.get(1, i).under_equal(id3.get(1, x))
index2 := math.max(x - 1, 1)
break
id.set(0, index), id.set(1, index2)
cond = auto.determine(bar_index % 30 == 0, timeframe.change(tim)), timeArr.push(time)
if cond and val.h.size().float().over(0) and last_bar_index - bar_index <= 10000
drips = matrix.new<values>(4, 0), var barCount = 0, var barCount2 = 0
levelsVol = matrix.new<float>(3, size + 1, 0), width = array.new_int(2)
Half := math.round(val.h.size() / 2)
barCount2 := barCount
barCount := auto.determine(timeArr.get(timeArr.size() - 16), int(math.avg(time, timeTrack)))
ind = auto.determine(timeArr.size() - 16, timeArr.binary_search_leftmost(barCount))
increments = (val.h.max() - val.l.min()) / size
firstHalf = val.vw1.slice(0, Half + 1).sum().divide(val.vw2.slice(0, Half + 1).sum())
secndHalf = val.vw1.slice(Half + 1, val.vw1.size()).sum().divide(val.vw2.slice(Half + 1, val.vw2.size()).sum())
levelsVol.appendLevels(increments)
levelsVol.locate(levelsVol.row(2))
txtcol = showTxt.determine(color.white, color(na))
if barCount2 != 0
if timeArr.get(ind - profWidth).float().under_equal(timeArr.get(
math.min(timeArr.indexof(barCount2) + profWidth, timeArr.size() - 1)))
for i = profWidth to 0
if timeArr.get(ind - i).float().over( timeArr.get(
math.min(timeArr.indexof(barCount2) - i, timeArr.size() - 1)))
profWidth := math.max(i - 1, 0)
break
percRank = matrix.new<float>(2, 0), levels = levelsVol.row(2)
percRank.rankCalc(profWidth, levelsVol)
col = switch
firstHalf.under(secndHalf) => upcol
firstHalf.over (secndHalf) => dncol
firstHalf.equal(secndHalf) => color.blue
if vwapS
for i = 0 to 2
[x1, y1, x2, y2] = switch
i.float().equal(0) => [barCount, val.h.max(), barCount, val.l.min()]
i.float().equal(1) => [timeArr.get(ind - profWidth), firstHalf, barCount , firstHalf]
=> [timeArr.get(math.min(ind + profWidth, timeArr.size() - 1)), secndHalf, barCount , secndHalf]
line.new(x1, y1, x2, y2, color = col, xloc = xloc.bar_time)
lineOnly = matrix.new<line>(2, 0)
switch trad
true => lineOnly.add_col(0, array.from( line.new(barCount, levels.first(), barCount, levels.first(), color = col, xloc = xloc.bar_time),
line.new(barCount, levels.first(), barCount, levels.first(), color = col, xloc = xloc.bar_time)))
=>
drips.add_col(0,
array.from(
values.new(rainBoxL = box.new(barCount, levels.first(), barCount, levels.get(1),xloc = xloc.bar_time,
text_color = txtcol,
text = str.tostring(levelsVol.get(0, 0),format.volume),
border_color = #00000000,
text_halign = text.align_right,
bgcolor = color.new(col, 75)
)),
values.new(rainBoxR = box.new(barCount, levels.first(), barCount, levels.get(1), xloc = xloc.bar_time,
text_color = txtcol,
text = str.tostring(levelsVol.get(1, 0),format.volume),
border_color = #00000000,
text_halign = text.align_left ,
bgcolor = color.new(col, 75)
)),
values.new(rainLineL = line.new(barCount, levels.first(), barCount, levels.get(1),
xloc = xloc.bar_time, color = col)),
values.new(rainLineR = line.new(barCount, levels.first(), barCount, levels.get(1),
xloc = xloc.bar_time, color = col)
)))
for i = 1 to levels.size() - 1
width.widthCalc(levelsVol, percRank, i)
switch trad
true => lineOnly.add_col(lineOnly.columns(),
array.from(line.new(lineOnly.get(0, i - 1).get_x2(), levels.get(i - 1), timeArr.get(ind - width.first()),
levels.get(i), color = col, xloc = xloc.bar_time),
line.new(lineOnly.get(1, i - 1).get_x2(), levels.get(i - 1), timeArr.get(math.min(ind + width.get(1), timeArr.size() - 1)),
levels.get(i), color = col, xloc = xloc.bar_time)))
=>
drips.add_col(0,
array.from(
values.new(rainBoxL = box.new(barCount, levels.get(i - 1), timeArr.get(ind - width.first()) , levels.get(i),
xloc = xloc.bar_time,
text = str.tostring(levelsVol.get(0, i), format.volume),
text_color = txtcol, border_color = #00000000,
bgcolor = color.new(col, 75),
text_halign = text.align_right)),
values.new(rainBoxR = box.new(barCount, levels.get(i - 1), timeArr.get(math.min(ind + width.get(1), timeArr.size() - 1)),
levels.get(i),
text = str.tostring(levelsVol.get(1, i), format.volume),
text_color = txtcol,
xloc = xloc.bar_time,
border_color = #00000000,
bgcolor = color.new(col, 75),
text_halign = text.align_left))
,
values.new(rainLineL = line.new(timeArr.get(ind - width.first()) , levels.get(i - 1), timeArr.get(ind - width.first()) ,
levels.get(i), xloc = xloc.bar_time, color = col)),
values.new(rainLineR = line.new(timeArr.get(math.min(ind + width.get(1), timeArr.size()-1)), levels.get(i - 1),
timeArr.get(math.min(ind + width.get(1), timeArr.size()-1)), levels.get( i ),
xloc = xloc.bar_time, color = col
))))
if not trad
switch drips.get(2, 0).rainLineL.get_x2().float().equal(drips.get(0, 1).rainLineL.get_x2())
true => drips.get(2, 0).rainLineL.set_y1(levels.get(i - 1)), drips.set(0, 1, values.new(rainLineL = line(na)))
=> line.new(drips.get(2, 0).rainLineL.get_x1(), levels.get(i - 1), drips.get(2, 1).rainLineL.get_x1(), levels.get(i - 1),
xloc = xloc.bar_time, color = col)
switch drips.get(3, 0).rainLineR.get_x2().float().equal(drips.get(3, 1).rainLineR.get_x2())
true => drips.get(3, 0).rainLineR.set_y1(levels.get(i - 1)), drips.set(3, 1, values.new(rainLineR = line(na)))
=> line.new(drips.get(3, 0).rainLineR.get_x1(), levels.get(i - 1), drips.get(3, 1).rainLineR.get_x1(), levels.get(i - 1),
xloc = xloc.bar_time, color = col)
if i == levels.size() - 1
switch trad
false => line.new(timeArr.get(ind - width.first()), levels.get(i), timeArr.get(math.min(ind + width.get(1), timeArr.size() - 1)),
levels.get(i),
color = col,
xloc = xloc.bar_time
)
=>
lineOnly.row(0).last().set_x2(barCount),
lineOnly.row(1).last().set_x2(barCount)
if barstate.islast
bo = box.all, li = line.all
if bo.size() > 0
for i = 0 to bo.size() - 1
if bo.get(i).get_left().float().under(bar_index + 50)
bo.get(i).delete()
if li.size() > 0
for i = 0 to li.size() - 1
if li.get(i).get_x2().float().under(bar_index + 50)
li.get(i).delete()
firstHalf = switch
val.vw1.size().float().over(0) => val.vw1.slice(0, math.min(val.vw1.size(), Half + 1)).sum().divide(val.vw2.slice(0, math.min(val.vw2.size(), Half + 1)).sum())
=> float(na)
secondHalf = switch
val.vw1.size().float().over(Half) => val.vw1.slice(Half + 1, val.vw1.size()).sum().divide(val.vw2.slice(Half + 1, val.vw2.size()).sum())
=> float(na)
if vwapS
for i = 0 to 2
[x1, y1, x2, y2] = switch
i.float().equal(0) => [bar_index + 15, val.h.max(), bar_index + 15, val.l.min()]
i.float().equal(1) => [bar_index + 10, firstHalf , bar_index + 15, firstHalf ]
=> [bar_index + 15, secondHalf , bar_index + 20, secondHalf ]
line.new(x1, y1, x2, y2, color = lbcol)
levelsVol = matrix.new<float>(3, size + 1, 0)
increments = (val.h.max() - val.l.min()) / size
levelsVol.appendLevels(increments), levels = levelsVol.row(2)
if val.vw1.size() > 0
dripsL = matrix.new<values>(2, 0), dripsR = matrix.new<values>(2, 0)
percRank = matrix.new<float> (2, 0), width = array.new_int (2, 0)
levelsVol.locate(levels)
percRank.rankCalc(5, levelsVol)
lineOnlyL = array.new_line(), lineOnlyR = array.new_line()
if not trad
dripsL.add_col(0,
array.from(
values.new(rainBoxL = box.new(bar_index + 15, levels.first(), bar_index+ 15, levels.get(1),
bgcolor = color.new(lbcol, 75),
border_color = #00000000
)),
values.new(rainLineL = line.new(bar_index + 15, levels.first(), bar_index + 15, levels.get(1),
color = lbcol))
))
if levelsVol.row(1).sum().over(0)
dripsR.add_col(0,
array.from(
values.new(rainBoxR =
box.new(bar_index + 15, levels.first(), bar_index+ 15, levels.get(1),
bgcolor = color.new(lbcol, 75),
border_color = #00000000)),
values.new(rainLineR =
line.new(bar_index + 15, levels.first(), bar_index + 15, levels.get(1), color = lbcol))
))
else
lineOnlyL.unshift(line.new(bar_index + 15, levels.first(), bar_index + 15, levels.first(), color = lbcol))
lineOnlyR.unshift(line.new(bar_index + 15, levels.first(), bar_index + 15, levels.first(), color = lbcol))
for i = 1 to levels.size() - 1
width.widthCalc(levelsVol, percRank, i)
if not trad
dripsL.add_col(0,
array.from(
values.new(rainBoxL = box.new(bar_index + 15, levels.get(i - 1), bar_index + 15 - width.first(), levels.get(i),
text = str.tostring(levelsVol.get(0, i), format.volume),
text_color = showTxt.determine(color.white, color(na)), border_color = #00000000,
bgcolor = color.new(lbcol, 75),
text_halign = text.align_right)),
values.new(rainLineL = line.new(bar_index + 15 - width.first(), levels.get(i - 1), bar_index + 15 - width.first(), levels.get(i),
color = lbcol))
))
switch dripsL.get(1, 0).rainLineL.get_x2().float().equal(dripsL.get(1, 1).rainLineL.get_x2())
true => dripsL.get(1, 0).rainLineL.set_y1(levels.get(i - 1)), dripsL.set(1, 1, values.new(rainLineL = line(na)))
=> line.new(bar_index + 15 - width.first(), levels.get(i - 1), dripsL.get(1, 1).rainLineL.get_x1(), levels.get(i - 1),
color = lbcol)
else
lineOnlyL.push(line.new(lineOnlyL.last().get_x2(), levels.get(i - 1), bar_index + 15 - width.first(), levels.get(i), color = lbcol))
if levelsVol.row(1).sum().over(0)
if not trad
dripsR.add_col(0,
array.from(
values.new(rainBoxR = box.new(bar_index + 15, levels.get(i - 1), bar_index + 15 + width.get(1), levels.get(i),
text = str.tostring(levelsVol.get(1, i), format.volume),
text_color = showTxt ? color.white : na, border_color = #00000000,
bgcolor = color.new(lbcol, 75),
text_halign = text.align_left)),
values.new(rainLineR = line.new(bar_index + 15 + width.get(1), levels.get(i - 1), bar_index + 15 + width.get(1), levels.get(i),
color = lbcol))
))
switch dripsR.get(1, 0).rainLineR.get_x2().float().equal(dripsR.get(1, 1).rainLineR.get_x2())
true => dripsR.get(1, 0).rainLineR.set_y1(levels.get(i - 1)), dripsR.set(1, 1, values.new(rainLineR = line(na)))
=> line.new(dripsR.get(1, 0).rainLineR.get_x1(), levels.get(i - 1), dripsR.get(1, 1).rainLineR.get_x1(), levels.get(i - 1),
color = lbcol)
else
lineOnlyR.push(line.new(lineOnlyR.last().get_x2(), levels.get(i - 1), bar_index + 15 + width.get(1), levels.get(i), color = lbcol))
if i.float().equal(levels.size() - 1)
if not trad
x2 = switch levelsVol.row(1).sum().over(0)
false => bar_index + 15
=> bar_index + 15 + width.get(1)
line.new(bar_index + 15 - width.first(), levels.get(i), x2,
levels.get(i),
color = lbcol
)
else
lineOnlyL.last().set_x2(bar_index + 15)
if levelsVol.row(1).sum().over(0)
lineOnlyR.last().set_x2(bar_index + 15)
if cond
timeTrack := time
val.h .clear(), val .l.clear()
val.vw1.clear(), val.vw2.clear()
if hx.size().float().over(0)
for i = 0 to hx.size() - 1
val.h.push (hx.get (i)), val.l.push (lx .get(i))
val.vw1.push(vw1x.get(i)), val.vw2.push(vw2x.get(i))
bgcolor(cond and div ? color.new(color.white, 80) : color(na))
|
Adaptive Trend Indicator [Quantigenics] | https://www.tradingview.com/script/tYda13WA-Adaptive-Trend-Indicator-Quantigenics/ | Quantigenics | https://www.tradingview.com/u/Quantigenics/ | 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/
// © Quantigenics
//@version=5
indicator("Adaptive Trend ",overlay = true)
AdapTrendLength = input.int(defval = 5,title = "Adaptive Trend Length")
UpColor = input.color(defval = color.aqua,title = "Up Color")
DownColor = input.color(defval = color.red,title = "Down Color")
Avg = ta.ema(ohlc4, AdapTrendLength)
MedAvg =ta.ema(high-(high-low)/2,3)
Adcalc = (MedAvg+(ta.ema(ta.ema(Avg, AdapTrendLength), AdapTrendLength)+Avg))/3
AdapTrend = ta.linreg( Adcalc, AdapTrendLength*2, 0 )
var linecolor = color.aqua
if AdapTrend > AdapTrend[1]
linecolor := UpColor
else if AdapTrend < AdapTrend[1]
linecolor := DownColor
plot(AdapTrend,title = "Adaptive Trend",color = linecolor[1])
|
Price Action Concepts [StratifyTrade] | https://www.tradingview.com/script/dqfTA4kM-Price-Action-Concepts-StratifyTrade/ | StratifyTrade | https://www.tradingview.com/u/StratifyTrade/ | 2,248 | 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/
// © StratifyTrade - formerly know as HunterAlgos
//@version=5
indicator("Price Action Concepts [StratifyTrade]", shorttitle = "Price Action Concepts [1.2.1]", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_bars_back = 500, max_polylines_count = 100)
//-----------------------------------------------------------------------------{
//Boolean set
//-----------------------------------------------------------------------------{
s_BREAK = 0
s_CHANGE = 1
i_BREAK = 2
i_CHANGE = 3
i_pp_CHANGE = 4
green_candle = 5
red_candle = 6
s_CHANGEP = 7
i_CHANGEP = 8
boolean =
array.from(
false
, false
, false
, false
, false
, false
, false
, false
, false
)
//-----------------------------------------------------------------------------{
// User inputs
//-----------------------------------------------------------------------------{
show_swing_ms = input.string ("All" , "Swing " , inline = "1", group = "MARKET STRUCTURE" , options = ["All", "CHANGE", "CHANGE+", "BREAK", "None"])
show_internal_ms = input.string ("All" , "Internal " , inline = "2", group = "MARKET STRUCTURE" , options = ["All", "CHANGE", "CHANGE+", "BREAK", "None"])
internal_r_lookback = input.int (5 , "" , inline = "2", group = "MARKET STRUCTURE" , minval = 2)
swing_r_lookback = input.int (50 , "" , inline = "1", group = "MARKET STRUCTURE" , minval = 2)
ms_mode = input.string ("Manual" , "Market Structure Mode" , inline = "a", group = "MARKET STRUCTURE" , tooltip = "[Manual] Use selected lenght\n[Dynamic] Use automatic lenght" ,options = ["Manual", "Dynamic"])
show_mtf_str = input.bool (true , "MTF Scanner" , inline = "9", group = "MARKET STRUCTURE" , tooltip = "Display Multi-Timeframe Market Structure Trend Directions. Green = Bullish. Red = Bearish")
show_eql = input.bool (false , "Show EQH/EQL" , inline = "6", group = "MARKET STRUCTURE")
plotcandle_bool = input.bool (false , "Plotcandle" , inline = "3", group = "MARKET STRUCTURE" , tooltip = "Displays a cleaner colored candlestick chart in place of the default candles. (requires hiding the current ticker candles)")
barcolor_bool = input.bool (false , "Bar Color" , inline = "4", group = "MARKET STRUCTURE" , tooltip = "Color the candle bodies according to market strucutre trend")
i_ms_up_BREAK = input.color (#089981 , "" , inline = "2", group = "MARKET STRUCTURE")
i_ms_dn_BREAK = input.color (#f23645 , "" , inline = "2", group = "MARKET STRUCTURE")
s_ms_up_BREAK = input.color (#089981 , "" , inline = "1", group = "MARKET STRUCTURE")
s_ms_dn_BREAK = input.color (#f23645 , "" , inline = "1", group = "MARKET STRUCTURE")
lvl_daily = input.bool (false , "Day " , inline = "1", group = "HIGHS & LOWS MTF")
lvl_weekly = input.bool (false , "Week " , inline = "2", group = "HIGHS & LOWS MTF")
lvl_monthly = input.bool (false , "Month" , inline = "3", group = "HIGHS & LOWS MTF")
lvl_yearly = input.bool (false , "Year " , inline = "4", group = "HIGHS & LOWS MTF")
css_d = input.color (color.blue , "" , inline = "1", group = "HIGHS & LOWS MTF")
css_w = input.color (color.blue , "" , inline = "2", group = "HIGHS & LOWS MTF")
css_m = input.color (color.blue , "" , inline = "3", group = "HIGHS & LOWS MTF")
css_y = input.color (color.blue , "" , inline = "4", group = "HIGHS & LOWS MTF")
s_d = input.string ('⎯⎯⎯' , '' , inline = '1', group = 'HIGHS & LOWS MTF' , options = ['⎯⎯⎯', '----', '····'])
s_w = input.string ('⎯⎯⎯' , '' , inline = '2', group = 'HIGHS & LOWS MTF' , options = ['⎯⎯⎯', '----', '····'])
s_m = input.string ('⎯⎯⎯' , '' , inline = '3', group = 'HIGHS & LOWS MTF' , options = ['⎯⎯⎯', '----', '····'])
s_y = input.string ('⎯⎯⎯' , '' , inline = '4', group = 'HIGHS & LOWS MTF' , options = ['⎯⎯⎯', '----', '····'])
ob_show = input.bool (true , "Show Last " , inline = "1", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Display volumetric order blocks on the chart \n\n[Input] Ammount of volumetric order blocks to show")
ob_num = input.int (2 , "" , inline = "1", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Orderblocks number", minval = 1, maxval = 10)
ob_metrics_show = input.bool (true , "Internal Buy/Sell Activity" , inline = "2", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Display volume metrics that have formed the orderblock")
css_metric_up = input.color (color.new(#089981, 50) , " " , inline = "2", group = "VOLUMETRIC ORDER BLOCKS")
css_metric_dn = input.color (color.new(#f23645 , 50) , "" , inline = "2", group = "VOLUMETRIC ORDER BLOCKS")
ob_swings = input.bool (false , "Swing Order Blocks" , inline = "a", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Display swing volumetric order blocks")
css_swing_up = input.color (color.new(color.gray , 90) , " " , inline = "a", group = "VOLUMETRIC ORDER BLOCKS")
css_swing_dn = input.color (color.new(color.silver, 90) , "" , inline = "a", group = "VOLUMETRIC ORDER BLOCKS")
ob_filter = input.string ("None" , "Filtering " , inline = "d", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Filter out volumetric order blocks by BREAK/CHANGE/CHANGE+", options = ["None", "BREAK", "CHANGE", "CHANGE+"])
ob_mitigation = input.string ("Absolute" , "Mitigation " , inline = "4", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Trigger to remove volumetric order blocks", options = ["Absolute", "Middle"])
use_grayscale = input.bool (false , "Grayscale" , inline = "6", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Use gray as basic order blocks color")
use_show_metric = input.bool (true , "Show Metrics" , inline = "7", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Show volume associated with the orderblock and his relevance")
use_middle_line = input.bool (true , "Show Middle-Line" , inline = "8", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Show mid-line order blocks")
use_overlap = input.bool (true , "Hide Overlap" , inline = "9", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Hide overlapping order blocks")
use_overlap_method = input.string ("Previous" , "Overlap Method " , inline = "Z", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "[Recent] Preserve the most recent volumetric order blocks\n\n[Previous] Preserve the previous volumetric order blocks", options = ["Recent", "Previous"])
ob_bull_css = input.color (color.new(#089981 , 90) , "" , inline = "1", group = "VOLUMETRIC ORDER BLOCKS")
ob_bear_css = input.color (color.new(#f23645 , 90) , "" , inline = "1", group = "VOLUMETRIC ORDER BLOCKS")
show_acc_dist_zone = input.bool (false , "" , inline = "1", group = "Accumulation And Distribution")
zone_mode = input.string ("Fast" , "" , inline = "1", group = "Accumulation And Distribution" , tooltip = "[Fast] Find small zone pattern formation\n[Slow] Find bigger zone pattern formation" ,options = ["Slow", "Fast"])
acc_css = input.color (color.new(#089981 , 60) , "" , inline = "1", group = "Accumulation And Distribution")
dist_css = input.color (color.new(#f23645 , 60) , "" , inline = "1", group = "Accumulation And Distribution")
show_lbl = input.bool (false , "Show swing point" , inline = "1", group = "High and Low" , tooltip = "Display swing point")
show_mtb = input.bool (false , "Show High/Low/Equilibrium" , inline = "2", group = "High and Low" , tooltip = "Display Strong/Weak High And Low and Equilibrium")
toplvl = input.color (color.red , "Premium Zone " , inline = "3", group = "High and Low")
midlvl = input.color (color.white , "Equilibrium Zone" , inline = "4", group = "High and Low")
btmlvl = input.color (#089981 , "Discount Zone " , inline = "5", group = "High and Low")
fvg_enable = input.bool (false , " " , inline = "1", group = "FAIR VALUE GAP" , tooltip = "Display fair value gap")
what_fvg = input.string ("FVG" , "" , inline = "1", group = "FAIR VALUE GAP" , tooltip = "Display fair value gap", options = ["FVG", "VI", "OG"])
fvg_num = input.int (5 , "Show Last " , inline = "1a", group = "FAIR VALUE GAP" , tooltip = "Number of fvg to show")
fvg_upcss = input.color (color.new(#089981, 80) , "" , inline = "1", group = "FAIR VALUE GAP")
fvg_dncss = input.color (color.new(color.red , 80) , "" , inline = "1", group = "FAIR VALUE GAP")
fvg_extend = input.int (10 , "Extend FVG" , inline = "2", group = "FAIR VALUE GAP" , tooltip = "Extend the display of the FVG.")
fvg_src = input.string ("Close" , "Mitigation " , inline = "3", group = "FAIR VALUE GAP" , tooltip = "[Close] Use the close of the body as trigger\n\n[Wick] Use the extreme point of the body as trigger", options = ["Close", "Wick"])
fvg_tf = input.timeframe ("" , "Timeframe " , inline = "4", group = "FAIR VALUE GAP" , tooltip = "Timeframe of the fair value gap")
t = color.t (ob_bull_css)
invcol = color.new (color.white , 100)
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - UDT }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
type bar
float o = open
float c = close
float h = high
float l = low
float v = volume
int n = bar_index
int t = time
type Zphl
line top
line bottom
label top_label
label bottom_label
bool stopcross
bool sbottomcross
bool itopcross
bool ibottomcross
string txtup
string txtdn
float topy
float bottomy
float topx
float bottomx
float tup
float tdn
int tupx
int tdnx
float itopy
float itopx
float ibottomy
float ibottomx
type FVG
box [] box
line[] ln
bool bull
float top
float btm
int left
int right
type ms
float[] p
int [] n
float[] l
type msDraw
int n
float p
color css
string txt
bool bull
type obC
float[] top
float[] btm
int [] left
float[] avg
float[] dV
float[] cV
int [] wM
int [] blVP
int [] brVP
int [] dir
float[] h
float[] l
int [] n
type obD
box [] ob
box [] eOB
box [] blB
box [] brB
line[] mL
type zone
chart.point points
float p
int c
int t
type hqlzone
box pbx
box ebx
box lbx
label plb
label elb
label lbl
type ehl
float pt
int t
float pb
int b
type pattern
string found = "None"
bool isfound = false
int period = 0
bool bull = false
type alerts
bool chochswing = false
bool chochplusswing = false
bool swingbos = false
bool chochplus = false
bool choch = false
bool bos = false
bool equal = false
bool ob = false
bool swingob = false
bool zone = false
bool fvg = false
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - General Setup }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
bar b = bar.new()
var pattern p = pattern.new()
alerts blalert = alerts.new()
alerts bralert = alerts.new()
if p.isfound
p.period += 1
if p.period == 50
p.period := 0
p.found := "None"
p.isfound := false
p.bull := na
switch
b.c > b.o => boolean.set(green_candle, true)
b.c < b.o => boolean.set(red_candle , true)
f_zscore(src, lookback) =>
(src - ta.sma(src, lookback)) / ta.stdev(src, lookback)
var int iLen = internal_r_lookback
var int sLen = swing_r_lookback
vv = f_zscore(((close - close[iLen]) / close[iLen]) * 100,iLen)
if ms_mode == "Dynamic"
switch
vv >= 1.5 or vv <= -1.5 => iLen := 10
vv >= 1.6 or vv <= -1.6 => iLen := 9
vv >= 1.7 or vv <= -1.7 => iLen := 8
vv >= 1.8 or vv <= -1.8 => iLen := 7
vv >= 1.9 or vv <= -1.9 => iLen := 6
vv >= 2.0 or vv <= -2.0 => iLen := 5
=> iLen
var msline = array.new<line>(0)
iH = ta.pivothigh(high, iLen, iLen)
sH = ta.pivothigh(high, sLen, sLen)
iL = ta.pivotlow (low , iLen, iLen)
sL = ta.pivotlow (low , sLen, sLen)
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - ARRAYS }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
hl () => [high, low]
[pdh, pdl] = request.security(syminfo.tickerid , 'D' , hl() , lookahead = barmerge.lookahead_on)
[pwh, pwl] = request.security(syminfo.tickerid , 'W' , hl() , lookahead = barmerge.lookahead_on)
[pmh, pml] = request.security(syminfo.tickerid , 'M' , hl() , lookahead = barmerge.lookahead_on)
[pyh, pyl] = request.security(syminfo.tickerid , '12M', hl() , lookahead = barmerge.lookahead_on)
lstyle(style) =>
out = switch style
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted
mtfphl(h, l ,tf ,css, pdhl_style) =>
var line hl = line.new(
na
, na
, na
, na
, xloc = xloc.bar_time
, color = css
, style = lstyle(pdhl_style)
)
var line ll = line.new(
na
, na
, na
, na
, xloc = xloc.bar_time
, color = css
, style = lstyle(pdhl_style)
)
var label lbl = label.new(
na
, na
, xloc = xloc.bar_time
, text = str.format('P{0}L', tf)
, color = invcol
, textcolor = css
, size = size.small
, style = label.style_label_left
)
var label hlb = label.new(
na
, na
, xloc = xloc.bar_time
, text = str.format('P{0}H', tf)
, color = invcol
, textcolor = css
, size = size.small
, style = label.style_label_left
)
hy = ta.valuewhen(h != h[1] , h , 1)
hx = ta.valuewhen(h == high , time , 1)
ly = ta.valuewhen(l != l[1] , l , 1)
lx = ta.valuewhen(l == low , time , 1)
if barstate.islast
extension = time + (time - time[1]) * 50
line.set_xy1(hl , hx , hy)
line.set_xy2(hl , extension , hy)
label.set_xy(hlb, extension , hy)
line.set_xy1(ll , lx , ly)
line.set_xy2(ll , extension , ly)
label.set_xy(lbl, extension , ly)
if lvl_daily
mtfphl(pdh , pdl , 'D' , css_d, s_d)
if lvl_weekly
mtfphl(pwh , pwl , 'W' , css_w, s_w)
if lvl_monthly
mtfphl(pmh , pml, 'M' , css_m, s_m)
if lvl_yearly
mtfphl(pyh , pyl , '12M', css_y, s_y)
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - Market Structure }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
method darkcss(color css, float factor, bool bull) =>
blue = color.b(css) * (1 - factor)
red = color.r(css) * (1 - factor)
green = color.g(css) * (1 - factor)
color.rgb(red, green, blue, 0)
method f_line(msDraw d, size, style) =>
var line id = na
var label lbl = na
id := line.new(
d.n
, d.p
, b.n
, d.p
, color = d.css
, width = 1
, style = style
)
if msline.size() >= 250
line.delete(msline.shift())
msline.push(id)
lbl := label.new(
int(math.avg(d.n, b.n))
, d.p
, d.txt
, color = invcol
, textcolor = d.css
, style = d.bull ? label.style_label_down : label.style_label_up
, size = size
, text_font_family = font.family_monospace
)
structure(bool mtf) =>
msDraw drw = na
bool isdrw = false
bool isdrwS = false
var color css = na
var color icss = na
var int itrend = 0
var int trend = 0
bool bull_ob = false
bool bear_ob = false
bool s_bull_ob = false
bool s_bear_ob = false
n = bar_index
var ms up = ms.new(
array.new<float>()
, array.new< int >()
, array.new<float>()
)
var ms dn = ms.new(
array.new<float>()
, array.new< int >()
, array.new<float>()
)
var ms sup = ms.new(
array.new<float>()
, array.new< int >()
, array.new<float>()
)
var ms sdn = ms.new(
array.new<float>()
, array.new< int >()
, array.new<float>()
)
switch show_swing_ms
"All" => boolean.set(s_BREAK , true ), boolean.set(s_CHANGE, true ) , boolean.set(s_CHANGEP, true )
"CHANGE" => boolean.set(s_BREAK , false), boolean.set(s_CHANGE, true ) , boolean.set(s_CHANGEP, false )
"CHANGE+" => boolean.set(s_BREAK , false), boolean.set(s_CHANGE, false) , boolean.set(s_CHANGEP, true )
"BREAK" => boolean.set(s_BREAK , true ), boolean.set(s_CHANGE, false) , boolean.set(s_CHANGEP, false )
"None" => boolean.set(s_BREAK , false), boolean.set(s_CHANGE, false) , boolean.set(s_CHANGEP, false )
=> na
switch show_internal_ms
"All" => boolean.set(i_BREAK, true ), boolean.set(i_CHANGE, true ), boolean.set(i_CHANGEP, true )
"CHANGE" => boolean.set(i_BREAK, false), boolean.set(i_CHANGE, true ), boolean.set(i_CHANGEP, false)
"CHANGE+" => boolean.set(i_BREAK, false), boolean.set(i_CHANGE, false ), boolean.set(i_CHANGEP, true )
"BREAK" => boolean.set(i_BREAK, true ), boolean.set(i_CHANGE, false ), boolean.set(i_CHANGEP, false)
"None" => boolean.set(i_BREAK, false), boolean.set(i_CHANGE, false ), boolean.set(i_CHANGEP, false)
=> na
switch
iH =>
up.p.unshift(b.h[iLen])
up.l.unshift(b.h[iLen])
up.n.unshift(n [iLen])
iL =>
dn.p.unshift(b.l[iLen])
dn.l.unshift(b.l[iLen])
dn.n.unshift(n [iLen])
sL =>
sdn.p.unshift(b.l[sLen])
sdn.l.unshift(b.l[sLen])
sdn.n.unshift(n [sLen])
sH =>
sup.p.unshift(b.h[sLen])
sup.l.unshift(b.h[sLen])
sup.n.unshift(n [sLen])
// INTERNAL BULLISH STRUCTURE
if up.p.size() > 0 and dn.l.size() > 1
if ta.crossover(b.c, up.p.first())
bool CHANGE = na
string txt = na
if itrend < 0
CHANGE := true
switch
not CHANGE =>
txt := "BREAK"
css := i_ms_up_BREAK
blalert.bos := true
if boolean.get(i_BREAK) and mtf == false and na(drw)
isdrw := true
drw := msDraw.new(
up.n.first()
, up.p.first()
, i_ms_up_BREAK
, txt
, true
)
CHANGE =>
dn.l.first() > dn.l.get(1) ? blalert.chochplus : blalert.choch
txt := dn.l.first() > dn.l.get(1) ? "CHANGE+" : "CHANGE"
css := i_ms_up_BREAK.darkcss(0.25, true)
if (dn.l.first() > dn.l.get(1) ? boolean.get(i_CHANGEP) : boolean.get(i_CHANGE)) and mtf == false and na(drw)
isdrw := true
drw := msDraw.new(
up.n.first()
, up.p.first()
, i_ms_up_BREAK.darkcss(0.25, true)
, txt
, true
)
if mtf == false
switch
ob_filter == "None" => bull_ob := true
ob_filter == "BREAK" and txt == "BREAK" => bull_ob := true
ob_filter == "CHANGE" and txt == "CHANGE" => bull_ob := true
ob_filter == "CHANGE+" and txt == "CHANGE+" => bull_ob := true
itrend := 1
up.n.clear()
up.p.clear()
// INTERNAL BEARISH STRUCTURE
if dn.p.size() > 0 and up.l.size() > 1
if ta.crossunder(b.c, dn.p.first())
bool CHANGE = na
string txt = na
if itrend > 0
CHANGE := true
switch
not CHANGE =>
bralert.bos := true
txt := "BREAK"
css := i_ms_dn_BREAK
if boolean.get(i_BREAK) and mtf == false and na(drw)
isdrw := true
drw := msDraw.new(
dn.n.first()
, dn.p.first()
, i_ms_dn_BREAK
, txt
, false
)
CHANGE =>
if up.l.first() < up.l.get(1)
bralert.chochplus := true
else
bralert.choch := true
txt := up.l.first() < up.l.get(1) ? "CHANGE+" : "CHANGE"
css := i_ms_dn_BREAK.darkcss(0.25, false)
if (up.l.first() < up.l.get(1) ? boolean.get(i_CHANGEP) : boolean.get(i_CHANGE)) and mtf == false and na(drw)
isdrw := true
drw := msDraw.new(
dn.n.first()
, dn.p.first()
, i_ms_dn_BREAK.darkcss(0.25, false)
, txt
, false
)
if mtf == false
switch
ob_filter == "None" => bear_ob := true
ob_filter == "BREAK" and txt == "BREAK" => bear_ob := true
ob_filter == "CHANGE" and txt == "CHANGE" => bear_ob := true
ob_filter == "CHANGE+" and txt == "CHANGE+" => bear_ob := true
itrend := -1
dn.n.clear()
dn.p.clear()
// SWING BULLISH STRUCTURE
if sup.p.size() > 0 and sdn.l.size() > 1
if ta.crossover(b.c, sup.p.first())
bool CHANGE = na
string txt = na
if trend < 0
CHANGE := true
switch
not CHANGE =>
blalert.swingbos := true
txt := "BREAK"
icss := s_ms_up_BREAK
if boolean.get(s_BREAK) and mtf == false and na(drw)
isdrwS := true
drw := msDraw.new(
sup.n.first()
, sup.p.first()
, s_ms_up_BREAK
, txt
, true
)
CHANGE =>
if sdn.l.first() > sdn.l.get(1)
blalert.chochplusswing := true
else
blalert.chochswing := true
txt := sdn.l.first() > sdn.l.get(1) ? "CHANGE+" : "CHANGE"
icss := s_ms_up_BREAK.darkcss(0.25, true)
if (sdn.l.first() > sdn.l.get(1) ? boolean.get(s_CHANGEP) : boolean.get(s_CHANGE)) and mtf == false and na(drw)
isdrwS := true
drw := msDraw.new(
sup.n.first()
, sup.p.first()
, s_ms_up_BREAK.darkcss(0.25, true)
, txt
, true
)
if mtf == false
switch
ob_filter == "None" => s_bull_ob := true
ob_filter == "BREAK" and txt == "BREAK" => s_bull_ob := true
ob_filter == "CHANGE" and txt == "CHANGE" => s_bull_ob := true
ob_filter == "CHANGE+" and txt == "CHANGE+" => s_bull_ob := true
trend := 1
sup.n.clear()
sup.p.clear()
// SWING BEARISH STRUCTURE
if sdn.p.size() > 0 and sup.l.size() > 1
if ta.crossunder(b.c, sdn.p.first())
bool CHANGE = na
string txt = na
if trend > 0
CHANGE := true
switch
not CHANGE =>
bralert.swingbos := true
txt := "BREAK"
icss := s_ms_dn_BREAK
if boolean.get(s_BREAK) and mtf == false and na(drw)
isdrwS := true
drw := msDraw.new(
sdn.n.first()
, sdn.p.first()
, s_ms_dn_BREAK
, txt
, false
)
CHANGE =>
if sup.l.first() < sup.l.get(1)
bralert.chochplusswing := true
else
bralert.chochswing := true
txt := sup.l.first() < sup.l.get(1) ? "CHANGE+" : "CHANGE"
icss := s_ms_dn_BREAK.darkcss(0.25, false)
if (sup.l.first() < sup.l.get(1) ? boolean.get(s_CHANGEP) : boolean.get(s_CHANGE)) and mtf == false and na(drw)
isdrwS := true
drw := msDraw.new(
sdn.n.first()
, sdn.p.first()
, s_ms_dn_BREAK.darkcss(0.25, false)
, txt
, false
)
if mtf == false
switch
ob_filter == "None" => s_bear_ob := true
ob_filter == "BREAK" and txt == "BREAK" => s_bear_ob := true
ob_filter == "CHANGE" and txt == "CHANGE" => s_bear_ob := true
ob_filter == "CHANGE+" and txt == "CHANGE+" => s_bear_ob := true
trend := -1
sdn.n.clear()
sdn.p.clear()
[css, bear_ob, bull_ob, itrend, drw, isdrw, s_bear_ob, s_bull_ob, trend, icss, isdrwS]
[css, bear_ob, bull_ob, itrend, drw, isdrw, s_bear_ob, s_bull_ob, trend, icss, isdrwS] = structure(false)
if isdrw
f_line(drw, size.small, line.style_dashed)
if isdrwS
f_line(drw, size.small, line.style_solid)
[_, _, _, itrend15, _, _, _, _, _, _, _] = request.security("", "15" , structure(true))
[_, _, _, itrend1H, _, _, _, _, _, _, _] = request.security("", "60" , structure(true))
[_, _, _, itrend4H, _, _, _, _, _, _, _] = request.security("", "240" , structure(true))
[_, _, _, itrend1D, _, _, _, _, _, _, _] = request.security("", "1440" , structure(true))
if show_mtf_str
var tab = table.new(position = position.top_right, columns = 10, rows = 10, bgcolor = na, frame_color = color.rgb(54, 58, 69, 0), frame_width = 1, border_color = color.rgb(54, 58, 69, 100), border_width = 1)
table.cell(tab, 0, 1, text = "15" , text_color = color.silver, text_halign = text.align_center, text_size = size.normal, bgcolor = chart.bg_color, text_font_family = font.family_monospace, width = 2)
table.cell(tab, 0, 2, text = "1H" , text_color = color.silver, text_halign = text.align_center, text_size = size.normal, bgcolor = chart.bg_color, text_font_family = font.family_monospace, width = 2)
table.cell(tab, 0, 3, text = "4H" , text_color = color.silver, text_halign = text.align_center, text_size = size.normal, bgcolor = chart.bg_color, text_font_family = font.family_monospace, width = 2)
table.cell(tab, 0, 4, text = "1D" , text_color = color.silver, text_halign = text.align_center, text_size = size.normal, bgcolor = chart.bg_color, text_font_family = font.family_monospace, width = 2)
table.cell(tab, 1, 1, text = itrend15 == 1 ? "BULLISH" : itrend15 == -1 ? "BEARISH" : na , text_halign = text.align_center, text_size = size.normal, text_color = itrend15 == 1 ? i_ms_up_BREAK.darkcss(-0.25, true) : itrend15 == -1 ? i_ms_dn_BREAK.darkcss(0.25, false) : color.gray, bgcolor = chart.bg_color, text_font_family = font.family_monospace)
table.cell(tab, 1, 2, text = itrend1H == 1 ? "BULLISH" : itrend1H == -1 ? "BEARISH" : na , text_halign = text.align_center, text_size = size.normal, text_color = itrend1H == 1 ? i_ms_up_BREAK.darkcss(-0.25, true) : itrend1H == -1 ? i_ms_dn_BREAK.darkcss(0.25, false) : color.gray, bgcolor = chart.bg_color, text_font_family = font.family_monospace)
table.cell(tab, 1, 3, text = itrend4H == 1 ? "BULLISH" : itrend4H == -1 ? "BEARISH" : na , text_halign = text.align_center, text_size = size.normal, text_color = itrend4H == 1 ? i_ms_up_BREAK.darkcss(-0.25, true) : itrend4H == -1 ? i_ms_dn_BREAK.darkcss(0.25, false) : color.gray, bgcolor = chart.bg_color, text_font_family = font.family_monospace)
table.cell(tab, 1, 4, text = itrend1D == 1 ? "BULLISH" : itrend1D == -1 ? "BEARISH" : na , text_halign = text.align_center, text_size = size.normal, text_color = itrend1D == 1 ? i_ms_up_BREAK.darkcss(-0.25, true) : itrend1D == -1 ? i_ms_dn_BREAK.darkcss(0.25, false) : color.gray, bgcolor = chart.bg_color, text_font_family = font.family_monospace)
table.cell(tab, 0, 5, text = "Detected Pattern", text_halign = text.align_center, text_size = size.normal, text_color = color.silver, bgcolor = chart.bg_color, text_font_family = font.family_monospace)
table.cell(tab, 0, 6, text = p.found, text_halign = text.align_center, text_size = size.normal, text_color = na(p.bull) ? color.white : p.bull ? i_ms_up_BREAK.darkcss(-0.25, true) : p.bull == false ? i_ms_dn_BREAK.darkcss(0.25, false) : na, bgcolor = chart.bg_color, text_font_family = font.family_monospace)
table.merge_cells(tab, 0, 5, 1, 5)
table.merge_cells(tab, 0, 6, 1, 6)
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - Strong/Weak High/Low And Equilibrium }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
var phl = Zphl.new(
na
, na
, label.new(na , na , color = invcol , textcolor = i_ms_dn_BREAK , style = label.style_label_down , size = size.tiny , text = "")
, label.new(na , na , color = invcol , textcolor = i_ms_up_BREAK , style = label.style_label_up , size = size.tiny , text = "")
, true
, true
, true
, true
, ""
, ""
, 0
, 0
, 0
, 0
, high
, low
, 0
, 0
, 0
, 0
, 0
, 0
)
zhl(len)=>
upper = ta.highest(len)
lower = ta.lowest(len)
var float out = 0
out := b.h[len] > upper ? 0 : b.l[len] < lower ? 1 : out[1]
top = out == 0 and out[1] != 0 ? b.h[len] : 0
btm = out == 1 and out[1] != 1 ? b.l[len] : 0
[top, btm]
[top , btm ] = zhl(sLen)
[itop, ibtm] = zhl(iLen)
upphl(trend) =>
var label lbl = label.new(
na
, na
, color = invcol
, textcolor = toplvl
, style = label.style_label_down
, size = size.small
)
if top
phl.stopcross := true
phl.txtup := top > phl.topy ? "HH" : "HL"
if show_lbl
topl = label.new(
b.n - swing_r_lookback
, top
, phl.txtup
, color = invcol
, textcolor = toplvl
, style = label.style_label_down
, size = size.small
)
line.delete(phl.top[1])
phl.top := line.new(
b.n - sLen
, top
, b.n
, top
, color = toplvl)
phl.topy := top
phl.topx := b.n - sLen
phl.tup := top
phl.tupx := b.n - sLen
if itop
phl.itopcross := true
phl.itopy := itop
phl.itopx := b.n - iLen
phl.tup := math.max(high, phl.tup)
phl.tupx := phl.tup == high ? b.n : phl.tupx
if barstate.islast
line.set_xy1(
phl.top
, phl.tupx
, phl.tup
)
line.set_xy2(
phl.top
, b.n + 50
, phl.tup
)
label.set_x(
lbl
, b.n + 50
)
label.set_y(
lbl
, phl.tup
)
dist = math.abs((phl.tup - close) / close) * 100
label.set_text (lbl, trend < 0 ? "Strong High" + " (" + str.tostring(math.round(dist,0)) + "%)" : "Weak High" + " (" + str.tostring(math.round(dist,0)) + "%)")
dnphl(trend) =>
var label lbl = label.new(
na
, na
, color = invcol
, textcolor = btmlvl
, style = label.style_label_up
, size = size.small
)
if btm
phl.sbottomcross := true
phl.txtdn := btm > phl.bottomy ? "LL" : "LH"
if show_lbl
btml = label.new(
b.n - swing_r_lookback
, btm, phl.txtdn
, color = invcol
, textcolor = btmlvl
, style = label.style_label_up
, size = size.small
)
line.delete(phl.bottom[1])
phl.bottom := line.new(
b.n - sLen
, btm
, b.n
, btm
, color = btmlvl
)
phl.bottomy := btm
phl.bottomx := b.n - sLen
phl.tdn := btm
phl.tdnx := b.n - sLen
if ibtm
phl.ibottomcross := true
phl.ibottomy := ibtm
phl.ibottomx := b.n - iLen
phl.tdn := math.min(low, phl.tdn)
phl.tdnx := phl.tdn == low ? b.n : phl.tdnx
if barstate.islast
line.set_xy1(
phl.bottom
, phl.tdnx
, phl.tdn
)
line.set_xy2(
phl.bottom
, b.n + 50
, phl.tdn
)
label.set_x(
lbl
, b.n + 50
)
label.set_y(
lbl
, phl.tdn
)
dist = math.abs((phl.tdn - close) / close) * 100
label.set_text (lbl, trend > 0 ? "Strong Low" + " (" + str.tostring(math.round(dist,0)) + "%)" : "Weak Low" + " (" + str.tostring(math.round(dist,0)) + "%)")
midphl() =>
avg = math.avg(phl.bottom.get_y2(), phl.top.get_y2())
var line l = line.new(
y1 = avg
, y2 = avg
, x1 = b.n - sLen
, x2 = b.n + 50
, color = midlvl
, style = line.style_solid
)
var label lbl = label.new(
x = b.n + 50
, y = avg
, text = "Equilibrium"
, style = label.style_label_left
, color = invcol
, textcolor = midlvl
, size = size.small
)
if barstate.islast
more = (phl.bottom.get_x1() + phl.bottom.get_x2()) > (phl.top.get_x1() + phl.top.get_x2()) ? phl.top.get_x1() : phl.bottom.get_x1()
line.set_xy1(l , more , avg)
line.set_xy2(l , b.n + 50, avg)
label.set_x (lbl , b.n + 50 )
label.set_y (lbl , avg )
dist = math.abs((l.get_y2() - close) / close) * 100
label.set_text (lbl, "Equilibrium (" + str.tostring(math.round(dist,0)) + "%)")
hqlzone() =>
if barstate.islast
var dZone = hqlzone.new(
box.new(left = int(math.max(phl.topx, phl.bottomx)), top = phl.tup , right = b.n + 50, bottom = 0.95 * phl.tup + 0.05 * phl.tdn , bgcolor = color.new(toplvl, 70), border_color = na)
, box.new(left = int(math.max(phl.topx, phl.bottomx)), top = 0.535 * phl.tup + 0.465 * phl.tdn, right = b.n + 50, bottom = 0.535 * phl.tdn + 0.465 * phl.tup , bgcolor = color.new(midlvl, 70), border_color = na)
, box.new(left = int(math.max(phl.topx, phl.bottomx)), top = 0.95 * phl.tdn + 0.05 * phl.tup, right = b.n + 50, bottom = phl.tdn , bgcolor = color.new(btmlvl, 70), border_color = na)
, label.new(x = int(math.avg(math.max(phl.topx, phl.bottomx), int(b.n + 50))), y = phl.tup, text = "Premium" , color = invcol, textcolor = toplvl, style = label.style_label_down, size = size.small)
, label.new(x = int(b.n + 50) , y = math.avg(phl.tup, phl.tdn), text = "Equilibrium", color = invcol, textcolor = midlvl, style = label.style_label_left, size = size.small)
, label.new(x = int(math.avg(math.max(phl.topx, phl.bottomx), int(b.n + 50))), y = phl.tdn, text = "Discount", color = invcol, textcolor = btmlvl, style = label.style_label_up, size = size.small)
)
if show_mtb
upphl (trend)
dnphl (trend)
hqlzone()
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - Volumetric Order Block }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
method eB(box[] b, bool ext, color css) =>
b.unshift(
box.new(
na
, na
, na
, na
, xloc = xloc.bar_time
, text_font_family = font.family_monospace
, extend = ext ? extend.right : extend.none
, border_color = color.new(color.white,100)
, bgcolor = css
)
)
method eL(line[] l, bool ext, bool solid, color css) =>
l.unshift(
line.new(
na
, na
, na
, na
, width = 1
, color = css
, xloc = xloc.bar_time
, extend = ext ? extend.right : extend.none
, style = solid ? line.style_solid : line.style_dashed
)
)
method drawVOB(bool cdn, bool bull, color css, int loc) =>
[cC, oO, hH, lL, vV] = request.security(
syminfo.tickerid
, ""
, [
close
, open
, high
, low
, volume
]
, lookahead = barmerge.lookahead_off
)
var obC obj = obC.new(
array.new<float>()
, array.new<float>()
, array.new< int >()
, array.new<float>()
, array.new<float>()
, array.new<float>()
, array.new< int >()
, array.new< int >()
, array.new< int >()
, array.new< int >()
, array.new<float>()
, array.new<float>()
, array.new< int >()
)
var obD draw = obD.new(
array.new<box >()
, array.new<box >()
, array.new<box >()
, array.new<box >()
, array.new<line>()
)
if barstate.isfirst
for i = 0 to ob_num - 1
draw.mL .eL(false, false, use_grayscale ? color.new(color.gray, 0) : color.new(css,0))
draw.ob .eB(false, use_grayscale ? color.new(color.gray, 90) : css )
draw.blB.eB(false, css_metric_up )
draw.brB.eB(false, css_metric_dn )
draw.eOB.eB(true , use_grayscale ? color.new(color.gray, 90) : css )
if cdn
obj.h.clear()
obj.l.clear()
obj.n.clear()
for i = 1 to math.abs((loc - b.n))
obj.h.unshift(hH[i])
obj.l.unshift(lL[i])
obj.n.unshift(b.t[i])
int iU = obj.l.indexof(obj.l.min())
int iD = obj.h.indexof(obj.h.max())
obj.dir.unshift(
bull
? (b.c[iU] > b.o[iU] ? 1 : -1)
: (b.c[iD] > b.o[iD] ? 1 : -1)
)
obj.top.unshift(
bull
? (
math.avg(
obj.h.max(), obj.l.min()) > obj.h.get(iU)
? obj.h.get(iU)
: math.avg(obj.h.max(), obj.l.min())
)
: obj.h.max()
)
obj.btm.unshift(
bull
? obj.l.min()
: (
math.avg(
obj.h.max(), obj.l.min()) < obj.l.get(iD)
? obj.l.get(iD)
: math.avg(obj.h.max(), obj.l.min())
)
)
obj.left.unshift(
bull
? obj.n.get(obj.l.indexof(obj.l.min()))
: obj.n.get(obj.h.indexof(obj.h.max()))
)
obj.avg.unshift(
math.avg(obj.top.first(), obj.btm.first())
)
obj.cV.unshift(
bull
? b.v[iU]
: b.v[iD]
)
obj.blVP.unshift ( 0 )
obj.brVP.unshift ( 0 )
obj.wM .unshift ( 1 )
if use_overlap
int rmP = use_overlap_method == "Recent" ? 1 : 0
if obj.avg.size() > 1
if bull
? obj.btm.first() < obj.top.get(1)
: obj.top.first() > obj.btm.get(1)
obj.wM .remove(rmP)
obj.cV .remove(rmP)
obj.dir .remove(rmP)
obj.top .remove(rmP)
obj.avg .remove(rmP)
obj.btm .remove(rmP)
obj.left .remove(rmP)
obj.blVP .remove(rmP)
obj.brVP .remove(rmP)
if barstate.isconfirmed
for x = 0 to ob_num - 1
tg = switch ob_mitigation
"Middle" => obj.avg
"Absolute" => bull ? obj.btm : obj.top
for [idx, pt] in tg
if (bull ? cC < pt : cC > pt)
obj.wM .remove(idx)
obj.cV .remove(idx)
obj.dir .remove(idx)
obj.top .remove(idx)
obj.avg .remove(idx)
obj.btm .remove(idx)
obj.left .remove(idx)
obj.blVP .remove(idx)
obj.brVP .remove(idx)
if barstate.islast
if obj.avg.size() > 0
float tV = 0
obj.dV.clear()
seq = math.min(ob_num - 1, obj.avg.size() - 1)
for j = 0 to seq
tV += obj.cV.get(j)
if j == seq
for y = 0 to seq
obj.dV.unshift(
math.floor(
(obj.cV.get(y) / tV) * 100)
)
for i = 0 to math.min(ob_num - 1, obj.avg.size() - 1)
dmL = draw.mL .get(i)
dOB = draw.ob .get(i)
dblB = draw.blB.get(i)
dbrB = draw.brB.get(i)
deOB = draw.eOB.get(i)
dOB.set_lefttop (obj.left .get(i) , obj.top.get(i))
deOB.set_lefttop (b.t , obj.top.get(i))
dOB.set_rightbottom (b.t , obj.btm.get(i))
deOB.set_rightbottom(b.t + (b.t - b.t[1]) * 100 , obj.btm.get(i))
if use_middle_line
dmL.set_xy1(obj.left.get(i), obj.avg.get(i))
dmL.set_xy2(b.t , obj.avg.get(i))
if ob_metrics_show
dblB.set_lefttop (obj.left.get(i), obj.top.get(i))
dbrB.set_lefttop (obj.left.get(i), obj.avg.get(i))
dblB.set_rightbottom(obj.left.get(i), obj.avg.get(i))
dbrB.set_rightbottom(obj.left.get(i), obj.btm.get(i))
rpBL = dblB.get_right()
rpBR = dbrB.get_right()
dbrB.set_right(rpBR + (b.t - b.t[1]) * obj.brVP.get(i))
dblB.set_right(rpBL + (b.t - b.t[1]) * obj.blVP.get(i))
if use_show_metric
txt = switch
obj.cV.get(i) >= 1000000000 => str.tostring(math.round(obj.cV.get(i) / 1000000000,3)) + "B"
obj.cV.get(i) >= 1000000 => str.tostring(math.round(obj.cV.get(i) / 1000000,3)) + "M"
obj.cV.get(i) >= 1000 => str.tostring(math.round(obj.cV.get(i) / 1000,3)) + "K"
obj.cV.get(i) < 1000 => str.tostring(math.round(obj.cV.get(i)))
deOB.set_text(
str.tostring(
txt + " (" + str.tostring(obj.dV.get(i)) + "%)")
)
deOB.set_text_size (size.auto)
deOB.set_text_halign(text.align_left)
deOB.set_text_color (use_grayscale ? color.silver : color.new(css, 0))
if ob_metrics_show and barstate.isconfirmed
if obj.wM.size() > 0
for i = 0 to obj.avg.size() - 1
switch obj.dir.get(i)
1 =>
switch obj.wM.get(i)
1 => obj.blVP.set(i, obj.blVP.get(i) + 1), obj.wM.set(i, 2)
2 => obj.blVP.set(i, obj.blVP.get(i) + 1), obj.wM.set(i, 3)
3 => obj.brVP.set(i, obj.brVP.get(i) + 1), obj.wM.set(i, 1)
-1 =>
switch obj.wM.get(i)
1 => obj.brVP.set(i, obj.brVP.get(i) + 1), obj.wM.set(i, 2)
2 => obj.brVP.set(i, obj.brVP.get(i) + 1), obj.wM.set(i, 3)
3 => obj.blVP.set(i, obj.blVP.get(i) + 1), obj.wM.set(i, 1)
var hN = array.new<int>(1, b.n)
var lN = array.new<int>(1, b.n)
var hS = array.new<int>(1, b.n)
var lS = array.new<int>(1, b.n)
if iH
hN.pop()
hN.unshift(int(b.n[iLen]))
if iL
lN.pop()
lN.unshift(int(b.n[iLen]))
if sH
hS.pop()
hS.unshift(int(b.n[sLen]))
if sL
lS.pop()
lS.unshift(int(b.n[sLen]))
if ob_show
bull_ob.drawVOB(true , ob_bull_css, hN.first())
bear_ob.drawVOB(false, ob_bear_css, lN.first())
if ob_swings
s_bull_ob.drawVOB(true , css_swing_up, hS.first())
s_bear_ob.drawVOB(false, css_swing_dn, lS.first())
if bull_ob
blalert.ob := true
if bear_ob
bralert.ob := true
if s_bull_ob
blalert.swingob := true
if s_bear_ob
blalert.swingob := true
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - FVG | VI | OG }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
ghl() => request.security(syminfo.tickerid, fvg_tf, [high[2], low[2], close[1], open[1]])
tfG() => request.security(syminfo.tickerid, fvg_tf, [open, high, low, close])
cG(bool bull) =>
[h, l, c, o] = ghl()
[go, gh, gl, gc] = tfG()
var FVG draw = FVG.new(
array.new<box>()
, array.new<line>()
)
var FVG[] cords = array.new<FVG>()
float pup = na
float pdn = na
bool cdn = na
int pos = 2
change_tf = timeframe.change(fvg_tf)
if barstate.isfirst
for i = 0 to fvg_num - 1
draw.box.unshift(box.new (na, na, na, na, border_color = color.new(color.white, 100), xloc = xloc.bar_time))
draw.ln.unshift (line.new(na, na, na, na, xloc = xloc.bar_time, width = 1, style = line.style_solid))
switch what_fvg
"FVG" =>
pup := bull ? gl : l
pdn := bull ? h : gh
cdn := bull ? gl > h and change_tf : gh < l and change_tf
pos := 2
"VI" =>
pup := bull
? (gc > go
? go
: gc)
: (gc[1] > go[1]
? go[1]
: gc[1])
pdn := bull
? (gc[1] > go[1]
? gc[1]
: go[1])
: (gc > go
? gc
: go)
cdn := bull
? go > gc[1] and gh[1] > gl and gc > gc[1] and go > go[1] and gh[1] < math.min(gc, go) and change_tf
: go < gc[1] and gl[1] < gh and gc < gc[1] and go < go[1] and gl[1] > math.max(gc, go) and change_tf
pos := 1
"OG" =>
pup := bull ? b.l : gl[1]
pdn := bull ? gh[1] : gh
cdn := bull ? gl > gh[1] and change_tf : gh < gl[1] and change_tf
pos := 1
if not na(cdn) and cdn
cords.unshift(
FVG.new(
na
, na
, bull
? true
: false
, pup
, pdn
, b.t - (b.t - b.t[1]) * pos
, b.t + (b.t - b.t[1]) * fvg_extend)
)
if bull
blalert.fvg := true
else
bralert.fvg := true
if barstate.isconfirmed
for [idx, obj] in cords
if obj.bull ? b.c < obj.btm : b.c > obj.top
cords.remove(idx)
if barstate.islast
if cords.size() > 0
for i = math.min(fvg_num - 1, cords.size() - 1) to 0
gbx = draw.box.get(i)
gln = draw.ln.get(i)
gcd = cords.get(i)
gtop = gcd.top
gbtm = gcd.btm
left = gcd.left
right = gcd.right
gbx.set_lefttop(left, gtop)
gbx.set_rightbottom(right, gbtm)
gbx.set_bgcolor(gcd.bull ? fvg_upcss : fvg_dncss)
gln.set_xy1(left, math.avg(gbx.get_top(), gbx.get_bottom()))
gln.set_xy2(right, math.avg(gbx.get_top(), gbx.get_bottom()))
gln.set_color(gcd.bull ? fvg_upcss : fvg_dncss)
if fvg_enable
cG(true )
cG(false)
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - END }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - Accumulation And Distribution }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
drawZone(int len) =>
var zone[] z = array.new<zone>()
if iH
z.unshift(
zone.new(
chart.point.from_time(
time[len]
, high[len]
)
, high[len]
, 1
, time[len]
)
)
if iL
z.unshift(
zone.new(
chart.point.from_time(
time[len]
, low [len]
)
, low [len]
, -1
, time[len]
)
)
if z.size() > 1
if z.get(0).c == z.get(1).c
z.clear()
switch
zone_mode == "Slow" =>
if z.size() > 5
if z.get(0).c == -1 and z.get(1).c == 1 and z.get(2).c == -1 and z.get(3).c == 1 and z.get(4).c == -1 and z.get(5).c == 1
if z.get(0).p > z.get(2).p and z.get(2).p > z.get(4).p
if z.get(1).p < z.get(3).p and z.get(3).p < z.get(5).p
blalert.zone := true
box.new(top = z.get(5).p, bottom = z.get(4).p, left = z.get(5).t, right = z.get(0).t, bgcolor = acc_css, border_color = color.new(color.white, 100), xloc = xloc.bar_time)
slice = array.new<chart.point>()
for i = 0 to 5
slice.unshift(z.get(i).points)
polyline.new(slice, xloc = xloc.bar_time, line_color = color.new(acc_css, 0), line_width = 2)
p.found := "Accumulation Zone"
p.bull := true
p.isfound := true
p.period := 0
z.clear()
if z.size() > 5
if z.get(0).c == 1 and z.get(1).c == -1 and z.get(2).c == 1 and z.get(3).c == -1 and z.get(4).c == 1 and z.get(5).c == -1
if z.get(0).p < z.get(2).p and z.get(2).p < z.get(4).p
if z.get(1).p > z.get(3).p and z.get(3).p > z.get(5).p
bralert.zone := true
box.new(top = z.get(4).p, bottom = z.get(5).p, left = z.get(5).t, right = z.get(0).t, bgcolor = dist_css, border_color = color.new(color.white, 100), xloc = xloc.bar_time)
slice = array.new<chart.point>()
for i = 0 to 5
slice.unshift(z.get(i).points)
polyline.new(slice, xloc = xloc.bar_time, line_color = color.new(dist_css, 0), line_width = 2)
p.found := "Distribution Zone"
p.bull := false
p.isfound := true
p.period := 0
z.clear()
zone_mode == "Fast" =>
if z.size() > 3
if z.get(0).c == -1 and z.get(1).c == 1 and z.get(2).c == -1 and z.get(3).c == 1
if z.get(0).p > z.get(2).p
if z.get(1).p < z.get(3).p
blalert.zone := true
box.new(top = z.get(3).p, bottom = z.get(2).p, left = z.get(3).t, right = z.get(0).t, bgcolor = acc_css, border_color = color.new(color.white, 100), xloc = xloc.bar_time)
slice = array.new<chart.point>()
for i = 0 to 3
slice.unshift(z.get(i).points)
polyline.new(slice, xloc = xloc.bar_time, line_color = color.new(acc_css, 0), line_width = 2)
p.found := "Accumulation Zone"
p.bull := true
p.isfound := true
p.period := 0
z.clear()
if z.size() > 3
if z.get(0).c == 1 and z.get(1).c == -1 and z.get(2).c == 1 and z.get(3).c == -1
if z.get(0).p < z.get(2).p
if z.get(1).p > z.get(3).p
bralert.zone := true
box.new(top = z.get(2).p, bottom = z.get(3).p, left = z.get(3).t, right = z.get(0).t, bgcolor = dist_css, border_color = color.new(color.white, 100), xloc = xloc.bar_time)
slice = array.new<chart.point>()
for i = 0 to 3
slice.unshift(z.get(i).points)
polyline.new(slice, xloc = xloc.bar_time, line_color = color.new(dist_css, 0), line_width = 2)
p.found := "Distribution Zone"
p.bull := false
p.isfound := true
p.period := 0
z.clear()
if show_acc_dist_zone
drawZone(iLen)
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - END }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - EQH / EQL }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
dEHL() =>
var ehl w = ehl.new(0, 0, 0, 0)
top = ta.pivothigh(high, 1, 1)
btm = ta.pivotlow(low , 1, 1)
atr = ta.atr(200)
switch
top =>
mx = math.max(top, w.pt)
mn = math.min(top, w.pt)
switch
mx < mn + atr * 0.1 =>
var aZ = array.new<line>()
var aL = array.new<label>()
if aZ.size() > 50
aZ.pop().delete()
aL.pop().delete()
aZ.unshift(line.new(w.t, w.pt, b.n - 1, top, color = i_ms_dn_BREAK, style = line.style_dotted))
aL.unshift(label.new(int(math.avg(b.n - 1, w.t)), top, "EQH", color = invcol, textcolor = i_ms_dn_BREAK, style = label.style_label_down, size = size.tiny))
bralert.equal := true
w.pt := top
w.t := b.n - 1
btm =>
mx = math.max(btm, w.pb)
mn = math.min(btm, w.pb)
switch
mn > mx - atr * 0.1 =>
var aZ = array.new<line>()
var aL = array.new<label>()
if aZ.size() > 50
aZ.pop().delete()
aL.pop().delete()
aZ.unshift(line.new(w.b, w.pb, b.n - 1, btm, color = i_ms_up_BREAK, style = line.style_dotted))
aL.unshift(label.new(int(math.avg(b.n - 1, w.b)), btm, "EQL", color = invcol, textcolor = i_ms_up_BREAK, style = label.style_label_up, size = size.tiny))
blalert.equal := true
w.pb := btm
w.b := b.n - 1
if show_eql
dEHL()
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - End }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - Plotting And Coloring }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
p_css = css
b_css = css
w_css = css
p_css := plotcandle_bool ? (css) : na
b_css := barcolor_bool ? (css) : na
w_css := plotcandle_bool ? color.rgb(120, 123, 134, 50) : na
plotcandle(open,high,low,close , color = p_css , wickcolor = w_css , bordercolor = p_css , editable = false)
barcolor(b_css, editable = false)
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{ - END }
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
//{----------------------------------------------------------------------------------------------------------------------------------------------}
alertcondition(blalert.bos , "Bullish BOS", "Bullish BOS")
alertcondition(blalert.choch , "Bullish CHOCH", "Bullish CHOCH")
alertcondition(blalert.chochplus , "Bullish CHOCH+", "Bullish CHOCH+")
alertcondition(blalert.chochplusswing, "Bullish Swing CHOCH+", "Bullish Swing CHOCH+")
alertcondition(blalert.chochswing , "Bullish Swing CHOCH", "Bullish CHOCH")
alertcondition(blalert.swingbos , "Bullish Swing BOS", "Bullish Swing BOS")
alertcondition(blalert.equal , "EQL", "EQL")
alertcondition(blalert.fvg , "Bullish FVG", "Bullish FVG")
alertcondition(blalert.ob , "Bullish Order Block", "Bullish Order Block")
alertcondition(blalert.swingob , "Bullish Swing Order Block", "Bullish Swing Order Block")
alertcondition(blalert.zone , "Accumulation Zone", "Accumulation Zone")
alertcondition(bralert.bos , "Bearish BOS", "Bearish BOS")
alertcondition(bralert.choch , "Bearish CHOCH", "Bearish CHOCH")
alertcondition(bralert.chochplus , "Bearish CHOCH+", "Bearish CHOCH+")
alertcondition(bralert.chochplusswing, "Bearish Swing CHOCH+", "Bearish Swing CHOCH+")
alertcondition(bralert.chochswing , "Bearish Swing CHOCH", "Bearish CHOCH")
alertcondition(bralert.swingbos , "Bearish Swing BOS", "Bearish Swing BOS")
alertcondition(bralert.equal , "EQH", "EQH")
alertcondition(bralert.fvg , "Bearish FVG", "Bearish FVG")
alertcondition(bralert.ob , "Bearish Order Block", "Bearish Order Block")
alertcondition(bralert.swingob , "Bearish Swing Order Block", "Bearish Swing Order Block")
alertcondition(bralert.zone , "Distribution Zone", "Distribution Zone")
if barstate.isfirst
var table errorBox = table.new(position.bottom_right, 1, 1, bgcolor = color.new(#363a45, 100))
table.cell(errorBox, 0, 0, "© Stratify", text_color = color.gray, text_halign = text.align_center, text_size = size.normal)
|
AI Moving Average (Expo) | https://www.tradingview.com/script/zgEx7k4v-AI-Moving-Average-Expo/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 1,125 | 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/
//@version=5
indicator("AI Moving Average (Expo)", overlay=true)
// ~~ ToolTips {
t1 ="Number of neighbors used in the KNN algorithm. Increasing 'k' can make the prediction more resilient to noise but may decrease sensitivity to local variations.\n\nNumber of data points considered in the AI analysis. This affects how the AI interprets patterns in the price data."
t2 ="Type of moving average to be applied. Various options allow for different smoothing techniques which can emphasize or dampen certain aspects of the price movement. \n\nLength of the moving average. A greater length will create a smoother curve but might lag behind recent price changes."
t3 ="Source data used to classify price as bullish or bearish. Can be adjusted to consider different aspects of the price information."
t4 ="Source data used to calculate the moving average for comparison. Different selections may emphasize different aspects of price movement."
t5 ="Toggle to show or hide the AI-generated moving average line."
t6 ="Toggle to show or hide the AI-calculated slope of the trend."
t7 ="Option to remove or retain historical boxes."
t8 ="Smoothing period for the initial moving average in the AI(2) algorithm."
t9 ="Toggle to remove all boxes from the chart."
t10 ="Toggle to remove all lines from the chart."
t11 = "Number of closest values used for the calculation of AI(2) Moving Averages. A higher number may provide a smoother but less sensitive curve."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
//
aiMa = input.bool(false, title="Show AI(1) Moving Average", group="AI(1) Average", tooltip=t5)
aiSlope = input.bool(true, title="Show AI(1) Slope", group="AI(1) Average", tooltip=t6)
maType = input.string("SMA", title="Select MA", options=["SMA", "EMA", "WMA", "RMA", "HMA", "VWMA"], inline="MA", group="AI(1) Average")
length = input.int(50, title="", minval=1, inline="MA", group="AI(1) Average",tooltip=t2)
// ~~ Input settings for K and N values
k = input.int(5, title="Neighbors", minval=1, maxval=100, inline="AI", group="AI(1) Settings")
n_ = input.int(10, title="DataPoints", minval=1, maxval=100, inline="AI", group="AI(1) Settings",tooltip=t1)
n = math.max(k, n_)
aiMa_2 = input.bool(false, title="Show AI(2) Moving Average 1", group="AI(2) Average", tooltip=t5)
aiMa_3 = input.bool(true, title="Show AI(2) Moving Average 2", group="AI(2) Average", tooltip=t6)
// Input parameters for the KNN Moving Average
numberOfClosestValues = input.int(15, "Number of Closest Values", 2, 200, inline="AI2", group="AI(2) Settings", tooltip=t11)
smoothingPeriod = input.int(20, "Smoothing Period", 2, 500, inline="aiMa_2", group="AI(2) Settings", tooltip=t8)
windowSize = math.max(numberOfClosestValues, 30)
dataToClassify = input.source(close, title= "Data To Classify", group="AI(1) Settings",tooltip=t3)
dataForMovingAverage = input.source(close, title= "Data For Moving Average (DataForComparison)", group="AI(1) Settings",tooltip=t4)
negBox_col = input.color(color.new(color.red,75),title="", group="Style", inline="box")
posBox_col = input.color(color.new(color.lime,75),title="", group="Style", inline="box")
line_col = input.color(color.rgb(255, 169, 39),title="", group="Style", inline="box")
line_width = input.int(2, title="",group="Style", inline="box", tooltip="Box & Line coloring")
del = input.bool(false, title="Remove Historical Boxes", group="Style", tooltip=t7)
del_boxes = input.bool(true, title="Remove All Boxes", group="Style", tooltip=t9)
del_line = input.bool(true,title="Remove All Line", group="Style", tooltip=t10)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Calculate the selected type of moving average based on the user's choice
ma = switch maType
"SMA" => ta.sma(dataForMovingAverage, length)
"EMA" => ta.ema(dataForMovingAverage, length)
"WMA" => ta.wma(dataForMovingAverage, length)
"RMA" => ta.rma(dataForMovingAverage, length)
"HMA" => ta.hma(dataForMovingAverage, length)
"VWMA" => ta.vwma(dataForMovingAverage,length)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Collect data points and their corresponding labels
labels = array.new_float(n)
data = array.new_float(n)
for i = 0 to n - 1
data.set(i, ma[i])
label_i = dataToClassify[i] > ma[i] ? 1 : 0
label_j = ma[i] > ma[i+1] ? 1 : 0
lab = int(math.avg(label_i,label_j))
labels.set(i,lab)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define the weighted k-nearest neighbors (KNN) function
knn_weighted(data, labels, k, x) =>
n1 = data.size()
distances = array.new_float(n1)
indices = array.new_int(n1)
// Compute distances from the current point to all other points
for i = 0 to n1 - 1
x_i = data.get(i)
dist = math.abs(x-x_i)
distances.set(i, dist)
indices.set(i, i)
// Sort distances and corresponding indices in ascending order
// Bubble sort method
for i = 0 to n1 - 2
for j = 0 to n1 - i - 2
if distances.get(j) > distances.get(j + 1)
tempDist = distances.get(j)
distances.set(j, distances.get(j + 1))
distances.set(j + 1, tempDist)
tempIndex = indices.get(j)
indices.set(j, indices.get(j + 1))
indices.set(j + 1, tempIndex)
// Compute weighted sum of labels of the k nearest neighbors
weighted_sum = 0.
total_weight = 0.
for i = 0 to k - 1
index = indices.get(i)
label_i = labels.get(index)
weight_i = 1 / (distances.get(i) + 1e-6)
weighted_sum += weight_i * label_i
total_weight += weight_i
weighted_sum / total_weight
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Classify the current data point
label_ = knn_weighted(data, labels, k, ma)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ kNN Classifier {
meanOfKClosest(value_in_,target_) =>
closestDistances = array.new_float(numberOfClosestValues, 1e10)
closestValues = array.new_float(numberOfClosestValues, 0.0)
for i = 1 to windowSize
value = value_in_[i]
distance = math.abs(target_ - value)
maxDistIndex = 0
maxDistValue = closestDistances.get(0)
for j = 1 to numberOfClosestValues - 1
if closestDistances.get(j) > maxDistValue
maxDistIndex := j
maxDistValue := closestDistances.get(j)
if distance < maxDistValue
closestDistances.set(maxDistIndex, distance)
closestValues.set(maxDistIndex, value)
closestValues.sum() / numberOfClosestValues
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// Initializes the KNN Moving Average.
ma_ = ta.sma(close,smoothingPeriod)
knnMA_price_ma = meanOfKClosest(close,ma_)
KnnMA_ma_ma = meanOfKClosest(ma_,ma_)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Box Conditions
red = label_ == 0
green = label_ == 1
blue = not red and not green
prevRed = red[1]
prevGreen = green[1]
prevBlue = blue[1]
switchdown = (prevBlue or prevGreen) and red
switchup = (prevBlue or prevRed) and green
redtoblue = prevRed and blue
greentoblue= prevGreen and blue
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Slope
// ~~ Declare variables to hold the values for x and y
var float[] x_values = array.new_float(0)
var float[] y_values = array.new_float(0)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Clear x and y values when switching trends
if switchdown or switchup
x_values.clear()
y_values.clear()
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Collect x and y values
x_values.push(bar_index)
y_values.push(ma)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Perform linear regression if enough values are collected
float slope = na
float intercept = na
if x_values.size() > 1
float sum_x = x_values.sum()
float sum_y = y_values.sum()
float sum_xy = 0.
float sum_x2 = 0.
int count = x_values.size()
for int i = 0 to count - 1
float x = x_values.get(i)
float y = y_values.get(i)
sum_xy := sum_xy + x * y
sum_x2 := sum_x2 + x * x
slope := (count * sum_xy - sum_x * sum_y) / (count * sum_x2 - sum_x * sum_x)
intercept := (sum_y - slope * sum_x) / count
line_eq = na(slope) ? na : slope * bar_index + intercept
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plot Box
var bo = box(na)
var li = line(na)
var maxHi = float(na)
var minLo = float(na)
highPoint = ta.highest(high,20)
lowPoint = ta.lowest(low,20)
if switchdown or switchup
if del
bo.delete()
maxHi := na(highPoint) ? high : math.max(highPoint, high)
minLo := na(lowPoint) ? low : math.min(lowPoint, low)
bo := box.new(bar_index,maxHi,bar_index+1,minLo,na,
bgcolor=label_>0?posBox_col:negBox_col)
mid = chart.point.now(math.avg(maxHi,minLo))
li := line.new(mid,mid,color=line_col,style=line.style_dotted,width=line_width)
maxHi := math.max(maxHi,high)
minLo := math.min(minLo,low)
bo.set_top(maxHi)
bo.set_rightbottom(bar_index,minLo)
li.set_y1(math.avg(maxHi,minLo))
li.set_xy2(bar_index,math.avg(maxHi,minLo))
if del_boxes
bo.delete()
if del_line
li.delete()
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plots
plot(aiMa?ma:na, title="AI(1) Bullish Trend",color=label_ == 1 ? color.lime : na, linewidth = 2)
plot(aiMa?ma:na, title="AI(1) Bearish Trend",color=label_ == 0 ? color.red : na, linewidth = 2)
plot(aiMa?ma:na, title="AI(1) Moving Average",color=label_ == 1 ? na : label_ == 0 ? na: color.rgb(0, 136, 255))
plot(aiSlope?line_eq:na,title="AI(1) Box Slope", color=slope > 0 ? color.lime : color.red, linewidth=1)
plot(aiMa_2?ta.wma(knnMA_price_ma,5):na, color=color.rgb(31, 199, 255), title="AI(2) Moving Average 1")
plot(aiMa_3?ta.wma(KnnMA_ma_ma,5):na, color=color.yellow, title="AI(2) Moving Average 2")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
Support and Resistance Levels and Zones [Quantigenics] | https://www.tradingview.com/script/qFgBi7oT-Support-and-Resistance-Levels-and-Zones-Quantigenics/ | Quantigenics | https://www.tradingview.com/u/Quantigenics/ | 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/
// © Quantigenics
//@version=5
indicator("Support and Resistance Levels and Zones [Quantigenics]",overlay = true,max_labels_count = 500,max_boxes_count = 500)
/////////////////
//Inputs////////
///////////////
hoursOffsetInput = input.float(0.0, "Timezone offset (in hours)", minval = -12.0, maxval = 14.0, step = 0.5)
PivotCalcType = input.string( "Classic pivots",title = "Pivot Calc Type" , options = ["Classic pivots","Traditional pivots","Camarilla pivots"], tooltip = "Pivot Calculation Type.")
PivotInterval = input.string( "Daily",title = "Pivot Interval", options = ["Daily","Weekly","Monthly","Quarterly","Yearly"], tooltip = "Choose Interval.")
SR2LevelsCalcTime = input(defval = "00:00",title = "SR2 Levels Calc Time")
PlotZones = input.bool(defval = true,title = "Plot Zones")
ShowGrayLines = input.bool(defval = false,title = "Show Gray Lines")
FTPLevels = input.bool(defval = false,title = "Show FTP Levels")
SR2Levels = input.bool(defval = false,title = "SR2 Levels")
AdjustTheLabels = input.string("Left","Adjust Labels",["Left","Center","Right"])
bool ShowPivotLabels = input( defval = true,title = "Show Pivot Labels", tooltip = "Enter 1 to show text labels for the pivot levels. Enter 0 to not show text labels." )
bool ShowCurrentPeriodLabelsOnly = input( defval = true,title = "Show Current Period Labels Only", tooltip = "Enter 1 to show text labels for the current period only. Enter 0 to show text labels for all pivot levels.")
bool ShowPriceLevelsInLabels = input( defval = true,title = "Show Price Levels In Labels", tooltip = "Enter 1 to include the pivot price values in the text labels. Enter 0 to not include pivot price values." )
bool ShowPivotIntervalInLabels = input( defval = true,title = "Show Pivot Interval In Labels",tooltip = "Enter 1 to show the pivot interval in the text labels. Enter 0 to not show the pivot interval." )
float PercentTransparency = input( defval = 0,title = "Percent Transparency", tooltip = "Percentage Transparency. Enter the desired percentage transparency of the text labels (0 = solid, 100 = clear)." )
R5Color = input( defval = color.red, title = "R5 Color", tooltip = "Enter the color to use for the R5 pivot plot and associated text label." )
R4Color = input( defval = color.rgb(255, 123, 0), title = "R4 Color", tooltip = "Enter the color to use for the R4 pivot plot and associated text label.")
R3Color = input( defval = color.rgb(255, 99, 71), title = "R3 Color", tooltip = "Enter the color to use for the R3 pivot plot and associated text label.")
R2Color = input( defval = color.rgb(189, 105, 66), title = "R2 Color", tooltip = "Enter the color to use for the R2 pivot plot and associated text label.")
R1Color = input( defval = color.rgb(255, 123, 0), title = "R1 Color", tooltip = "Enter the color to use for the R1 pivot plot and associated text label.")
PivotColor = input( defval = color.rgb(30, 144, 255), title = "Pivot Color", tooltip = "Enter the color to use for the pivot point plot and associated text label." )
S1Color = input( defval = color.rgb(85, 107, 47), title = "S1 Color", tooltip = "Enter the color to use for the S1 pivot plot and associated text label.")
S2Color = input( defval = color.rgb(128, 128, 0), title = "S2 Color", tooltip = "Enter the color to use for the S2 pivot plot and associated text label.")
S3Color = input( defval = color.rgb(107, 142, 35), title = "S3 Color", tooltip = "Enter the color to use for the S3 pivot plot and associated text label.")
S4Color = input( defval = color.rgb(55,79,47), title = "S4 Color", tooltip = "Enter the color to use for the S4 pivot plot and associated text label.")
S5Color = input( defval = color.rgb(0, 128, 128), title = "S5 Color", tooltip = "Enter the color to use for the S5 pivot plot and associated text label.")
bool ShowR5 = input( defval = true, title = "Show R5", tooltip = "Enter 1 to plot the R5 pivot level and draw the associated text label (if text labels are set to show) enter 0 to not plot the pivot value.")
bool ShowR4 = input( defval = true, title = "Show R4", tooltip = "Enter 1 to plot the R4 pivot level and draw the associated text label (if text labels are set to show) enter 0 to not plot the pivot value.")
bool ShowR3 = input( defval = true, title = "Show R3", tooltip = "Enter 1 to plot the R3 pivot level and draw the associated text label (if text labels are set to show) enter 0 to not plot the pivot value.")
bool ShowR2 = input( defval = true, title = "Show R2", tooltip = "Enter 1 to plot the R2 pivot level and draw the associated text label (if text labels are set to show) enter 0 to not plot the pivot value.")
bool ShowR1 = input( defval = true, title = "Show R1", tooltip = "Enter 1 to plot the R1 pivot level and draw the associated text label (if text labels are set to show) enter 0 to not plot the pivot value.")
bool ShowPP = input( defval = true, title = "Show Main Pivot", tooltip = "Enter 1 to plot the pivot point level and draw the associated text label (if text labels are set to show) enter 0 to not plot the pivot value.")
bool ShowS1 = input( defval = true, title = "Show S1", tooltip = "Enter 1 to plot the S1 pivot level and draw the associated text label (if text labels are set to show) enter 0 to not plot the pivot value.")
bool ShowS2 = input( defval = true, title = "Show S2", tooltip = "Enter 1 to plot the S2 pivot level and draw the associated text label (if text labels are set to show) enter 0 to not plot the pivot value.")
bool ShowS3 = input( defval = true, title = "Show S3", tooltip = "Enter 1 to plot the S3 pivot level and draw the associated text label (if text labels are set to show) enter 0 to not plot the pivot value.")
bool ShowS4 = input( defval = true, title = "Show S4", tooltip = "Enter 1 to plot the S4 pivot level and draw the associated text label (if text labels are set to show) enter 0 to not plot the pivot value.")
bool ShowS5 = input( defval = true, title = "Show S5", tooltip = "Enter 1 to plot the S5 pivot level and draw the associated text label (if text labels are set to show) enter 0 to not plot the pivot value.")
float TextLabelFontSize = input(defval = 8.0,title = "Text Label Font Size", tooltip = "Enter the font size for the text labels on the lines")
var isdaily = (PivotInterval=="Daily")
///////////////////
//Used Variables//
/////////////////
var TRENDLINE_LEVEL_KEY = "TLLevel"
var TRENDLINE_COLOR_KEY = "TLColor"
var R5_KEY = "R5"
var R4_KEY = "R4"
var R3_KEY = "R3"
var R2_KEY = "R2"
var R1_KEY = "R1"
var PP_KEY = "MP"
var S1_KEY = "S1"
var S2_KEY = "S2"
var S3_KEY = "S3"
var S4_KEY = "S4"
var S5_KEY = "S5"
var DATA_LOAD_FAIL_const = "Required data failed to load."
type Times
int Year
int Month
type psarr
Times Time
float High
float Low
float Close
type PriceSeriesProvider
int Count
array<psarr> ps
// TokenList TokenListOfLevels = NULL
// Vector CurrentTextLabelVector = NULL
// Vector AllTextLabelsVector = NULL
// Vector TrendlineVector = NULL
// Vector TomorrowTextLabelVector = NULL
// Dictionary DOColorDict = NULL
// Dictionary PlotColorDict = NULL
type Bar
float H
float C
float L
float T
var PivotsPSP = PriceSeriesProvider.new(0,array.new<psarr>(0))
var customPSP = PriceSeriesProvider.new(0,array.new<psarr>(0))
// QuotesProvider QP1 = NULL
// ChartingHost ChartingHost1 = NULL
var localtimezone = "GMT+"+str.tostring(hoursOffsetInput)
bool InputsAreOkay = true
bool RealTime = false
bool InAChart = true //todo
bool AllowTransparentPlots = true
int DecimalPlaces = 0
int BT = 0
bool OkToCalc = false
int PSPIndexOffset = 0
string PivotIntervalString = ""
bool PivotsPSPIsLoaded = false
type colors
color PPPlotColor
color S1PlotColor
color S2PlotColor
color S3PlotColor
color S4PlotColor
color S5PlotColor
color R1PlotColor
color R2PlotColor
color R3PlotColor
color R4PlotColor
color R5PlotColor
type Boxes
box PPBox
box S1Box
box S2Box
box S3Box
box R1Box
box R2Box
box R3Box
type Lines
line PPLine
line S1Line
line S2Line
line S3Line
line R1Line
line R2Line
line R3Line
colors PSPColor = colors.new(PivotColor,S1Color,S2Color,S3Color,S4Color,S5Color,R1Color,R2Color,R3Color,R4Color,R5Color)
colors CustomColor = colors.new(PivotColor,S1Color,S2Color,S3Color,S4Color,S5Color,R1Color,R2Color,R3Color,R4Color,R5Color)
getColor(color cl, int tr = 70)=>
color.rgb(color.r(cl),color.g(cl),color.b(cl),transp = tr)
var ZoneColor = colors.new(getColor(PivotColor),getColor(S1Color),getColor(S2Color),getColor(S3Color),getColor(S4Color),getColor(S5Color),getColor(R1Color),getColor(R2Color),getColor(R3Color),getColor(R4Color),getColor(R5Color))
var Box = Boxes.new(na,na,na,na,na,na,na)
var Line = Lines.new(na,na,na,na,na,na,na)
var LabelS1 = label.new(0,0,"")
var LabelS2 = label.new(0,0,"")
var LabelS3 = label.new(0,0,"")
var LabelS4 = label.new(0,0,"")
var LabelS5 = label.new(0,0,"")
var LabelR1 = label.new(0,0,"")
var LabelR2 = label.new(0,0,"")
var LabelR3 = label.new(0,0,"")
var LabelR4 = label.new(0,0,"")
var LabelR5 = label.new(0,0,"")
var LabelPP = label.new(0,0,"")
type Pivots
float S1
float S2
float S3
float S4
float S5
float R1
float R2
float R3
float R4
float R5
float PP
type Tom
float S1Tom
float S2Tom
float S3Tom
float S4Tom
float S5Tom
float R1Tom
float R2Tom
float R3Tom
float R4Tom
float R5Tom
float PPTom
var tom = Tom.new( 0,0,0,0,0,0,0,0,0,0,0)
var customtom = Tom.new( 0,0,0,0,0,0,0,0,0,0,0)
var pivs = Pivots.new( 0,0,0,0,0,0,0,0,0,0,0)
var customPiv = Pivots.new( 0,0,0,0,0,0,0,0,0,0,0)
int TransparencyValue = 255
int ReuseIndex = 0
bool TomorrowsPivotsShowing = true
/////////////////
//Pivot Calcs///
///////////////
GetQuarterForDateTime(Times tim)=>
int ReturnQuarter = 0
if(time("M")<4)
ReturnQuarter := 1
else if(time("M")<7)
ReturnQuarter:= 2
else if(time("M")< 10)
ReturnQuarter:= 3
else
ReturnQuarter:= 4
ReturnQuarter
CalcQuarterlyPivots( PriceSeriesProvider PSP, int iYear,int iQuarter )=>
float PeriodHigh = -1
float PeriodLow = 10000000
float PeriodClose = -1
int LastMonth = -1
int NumMonthsFound = 0
for Counter = 0 to PSP.Count - 1
if (array.get(PSP.ps,PSP.Count - 1-Counter).Time.Year == iYear and GetQuarterForDateTime( array.get(PSP.ps,PSP.Count - 1 - Counter).Time ) == iQuarter)
NumMonthsFound += 1
if (array.get(PSP.ps,PSP.Count - 1-Counter).High > PeriodHigh)
PeriodHigh := array.get(PSP.ps,PSP.Count - 1-Counter).High
if (array.get(PSP.ps,PSP.Count - 1-Counter).Low < PeriodLow)
PeriodLow := array.get(PSP.ps,PSP.Count - 1-Counter).Low
if (array.get(PSP.ps,PSP.Count - 1-Counter).Time.Month > LastMonth )
PeriodClose := array.get(PSP.ps,PSP.Count - 1-Counter).Close
LastMonth := array.get(PSP.ps,PSP.Count - 1-Counter).Time.Month
bool ret = (PeriodClose != 0 and PeriodHigh != -1 and PeriodLow != 10000000 and NumMonthsFound == 3)
ret
CalcYearlyPivots( PriceSeriesProvider PSP, int tempYear )=>
float PeriodHigh = -1
float PeriodLow = 10000000
float PeriodClose = 0
int NumMonthsFound = 0
for Counter = 0 to PSP.Count - 1
if (array.get(PSP.ps,PSP.Count - 1-Counter).Time.Year == tempYear )
NumMonthsFound += 1
if (array.get(PSP.ps,PSP.Count - 1-Counter).High > PeriodHigh)
PeriodHigh := array.get(PSP.ps,PSP.Count - 1-Counter).High
if (array.get(PSP.ps,PSP.Count - 1-Counter).Low < PeriodLow)
PeriodLow := array.get(PSP.ps,PSP.Count - 1-Counter).Low
if (array.get(PSP.ps,PSP.Count - 1-Counter).Time.Month == 12 )
PeriodClose := array.get(PSP.ps,PSP.Count - 1-Counter).Close
else if (array.get(PSP.ps,PSP.Count - 1-Counter).Time.Year == tempYear - 1)
break
PeriodClose != 0 and PeriodHigh != -1 and PeriodLow != 10000000 and NumMonthsFound == 12
CalcPivotLevels(float iHigh,float iLow,float iClose, Pivots piv_)=>
if (not (iHigh == 0 or iLow == 0 or iClose == 0) )
switch ( PivotCalcType )
"Traditional pivots"=>
piv_.PP := ( iHigh + iLow + iClose ) / 3
piv_.R1 := piv_.PP * 2 - iLow
piv_.R2 := piv_.PP + iHigh - iLow
piv_.R3 := piv_.PP * 2 + ( iHigh - 2 * iLow )
piv_.R4 := piv_.PP * 3 + ( iHigh - 3 * iLow )
piv_.R5 := piv_.PP * 4 + ( iHigh - 4 * iLow )
piv_.S1 := piv_.PP * 2 - iHigh
piv_.S2 := piv_.PP - iHigh + iLow
piv_.S3 := piv_.PP * 2 - ( 2 * iHigh - iLow )
piv_.S4 := piv_.PP * 3 - ( 3 * iHigh - iLow )
piv_.S5 := piv_.PP * 4 - ( 4 * iHigh - iLow )
"Camarilla pivots"=>
piv_.PP := ( iHigh + iLow + iClose ) / 3
piv_.R1 := iClose + ( iHigh - iLow ) * 1.1 / 12
piv_.R2 := iClose + ( iHigh - iLow ) * 1.1 / 6
piv_.R3 := iClose + ( iHigh - iLow ) * 1.1 / 4
piv_.R4 := iClose + ( iHigh - iLow ) * 1.1 / 2
piv_.S1 := iClose - ( iHigh - iLow ) * 1.1 / 12
piv_.S2 := iClose - ( iHigh - iLow ) * 1.1 / 6
piv_.S3 := iClose - ( iHigh - iLow ) * 1.1 / 4
piv_.S4 := iClose - ( iHigh - iLow ) * 1.1 / 2
=>
piv_.PP := ( iHigh + iLow + iClose ) / 3
piv_.R1 := piv_.PP * 2 - iLow
piv_.R2 := piv_.PP + iHigh - iLow
piv_.R3 := piv_.R2 + iHigh - iLow
piv_.S1 := piv_.PP * 2 - iHigh
piv_.S2 := piv_.PP - iHigh + iLow
piv_.S3 := piv_.S2 - iHigh + iLow
CalculateLevels()=>
// if(PivotInterval == "Quarterly")
// if (GetQuarterForDateTime(Times.new(year,month)) == 1)
// iy = year - 1
// CalcQuarterlyPivots( PivotsPSP, iy, 4 )
// else
// gqf = GetQuarterForDateTime(Times.new(year,month) ) - 1
// CalcQuarterlyPivots( PivotsPSP, year, gqf)
// else if(PivotInterval == "Yearly")
// CalcYearlyPivots( PivotsPSP, year - 1 )
// else
CalcPivotLevels( array.get(PivotsPSP.ps,PivotsPSP.Count - 1-PSPIndexOffset).High, array.get(PivotsPSP.ps,PivotsPSP.Count - 1-PSPIndexOffset).Low, array.get(PivotsPSP.ps,PivotsPSP.Count - 1-PSPIndexOffset).Close,pivs)
//
//pivot calcs for next period
CalcPivotLevelsForTomorrow(float iHigh, float iLow, float iClose, Tom tm )=>
if (not (iHigh == 0 or iLow == 0 or iClose == 0))
switch ( PivotCalcType )
"Traditional pivots"=>
tm.PPTom := ( iHigh + iLow + iClose ) / 3
tm.R1Tom := tm.PPTom * 2 - iLow
tm.R2Tom := tm.PPTom + iHigh - iLow
tm.R3Tom := tm.PPTom * 2 + ( iHigh - 2 * iLow )
tm.R4Tom := tm.PPTom * 3 + ( iHigh - 3 * iLow )
tm.R5Tom := tm.PPTom * 4 + ( iHigh - 4 * iLow )
tm.S1Tom := tm.PPTom * 2 - iHigh
tm.S2Tom := tm.PPTom - iHigh + iLow
tm.S3Tom := tm.PPTom * 2 - ( 2 * iHigh - iLow )
tm.S4Tom := tm.PPTom * 3 - ( 3 * iHigh - iLow )
tm.S5Tom := tm.PPTom * 4 - ( 4 * iHigh - iLow )
"Camarilla pivots"=>
tm.PPTom := ( iHigh + iLow + iClose ) / 3
tm.R1Tom := iClose + ( iHigh - iLow ) * 1.1 / 12
tm.R2Tom := iClose + ( iHigh - iLow ) * 1.1 / 6
tm.R3Tom := iClose + ( iHigh - iLow ) * 1.1 / 4
tm.R4Tom := iClose + ( iHigh - iLow ) * 1.1 / 2
tm.S1Tom := iClose - ( iHigh - iLow ) * 1.1 / 12
tm.S2Tom := iClose - ( iHigh - iLow ) * 1.1 / 6
tm.S3Tom := iClose - ( iHigh - iLow ) * 1.1 / 4
tm.S4Tom := iClose - ( iHigh - iLow ) * 1.1 / 2
=>
tm.PPTom := ( iHigh + iLow + iClose ) / 3
tm.R1Tom := tm.PPTom * 2 - iLow
tm.R2Tom := tm.PPTom + iHigh - iLow
tm.R3Tom := tm.R2Tom + iHigh - iLow
tm.S1Tom := tm.PPTom * 2 - iHigh
tm.S2Tom := tm.PPTom - iHigh + iLow
tm.S3Tom := tm.S2Tom - iHigh + iLow
CalcQuarterlyPivotsForTomorrow( PriceSeriesProvider PSP, int iYear, int iQuarter )=>
float PeriodHigh = 10000000
float PeriodLow = 10000000
float PeriodClose = -1
int LastMonth = -1
int NumMonthsFound = 0
for Counter = 0 to PSP.Count - 1
if (array.get(PSP.ps,PSP.Count - 1-Counter).Time.Year == iYear and true)// GetQuarterForDateTime( array.get(PSP.ps,PSP.Count - 1-Counter).Time ) == iQuarter)
NumMonthsFound += 1
if (array.get(PSP.ps,PSP.Count - 1-Counter).High > PeriodHigh)
PeriodHigh := array.get(PSP.ps,PSP.Count - 1-Counter).High
if (array.get(PSP.ps,PSP.Count - 1-Counter).Low < PeriodLow )
PeriodLow := array.get(PSP.ps,PSP.Count - 1-Counter).Low
if (array.get(PSP.ps,PSP.Count - 1-Counter).Time.Month > LastMonth)
PeriodClose := array.get(PSP.ps,PSP.Count - 1-Counter).Close
LastMonth := array.get(PSP.ps,PSP.Count - 1-Counter).Time.Month
CalcPivotLevelsForTomorrow( PeriodHigh, PeriodLow, PeriodClose,tom )
PeriodClose != 0 and PeriodHigh != -1 and PeriodLow != 10000000 and NumMonthsFound == 3
CalcYearlyPivotsForTomorrow( PriceSeriesProvider PSP, int iYear )=>
float PeriodHigh = -1
float PeriodLow = 10000000
float PeriodClose = 0
int NumMonthsFound = 0
for Counter = 0 to PSP.Count - 1
if (array.get(PSP.ps,PSP.Count - 1-Counter).Time.Year == iYear)
NumMonthsFound += 1
if (array.get(PSP.ps,PSP.Count - 1-Counter).High > PeriodHigh)
PeriodHigh := array.get(PSP.ps,PSP.Count - 1-Counter).High
if (array.get(PSP.ps,PSP.Count - 1-Counter).Low < PeriodLow)
PeriodLow := array.get(PSP.ps,PSP.Count - 1-Counter).Low
if (array.get(PSP.ps,PSP.Count - 1-Counter).Time.Month == 12)
PeriodClose := array.get(PSP.ps,PSP.Count - 1-Counter).Close
else if (array.get(PSP.ps,PSP.Count - 1-Counter).Time.Year == iYear - 1)
break
CalcPivotLevelsForTomorrow( PeriodHigh, PeriodLow, PeriodClose,tom )
PeriodClose != 0 and PeriodHigh != -1 and PeriodLow != 10000000 and NumMonthsFound == 12
CalculateLevelsForTomorrow()=>
// if(PivotInterval == "Quarterly")
// if (GetQuarterForDateTime(Times.new(year,month) ) == 1)
// CalcQuarterlyPivotsForTomorrow( PivotsPSP, year - 1, 4 )
// else
// CalcQuarterlyPivotsForTomorrow( PivotsPSP, year, GetQuarterForDateTime(Times.new(year,month) ) - 1 )
// else if(PivotInterval == "Yearly")
// CalcYearlyPivotsForTomorrow( PivotsPSP, year - 1 )
// else
CalcPivotLevelsForTomorrow( array.get(PivotsPSP.ps,PivotsPSP.Count - 1).High, array.get(PivotsPSP.ps,PivotsPSP.Count - 1).Low, array.get(PivotsPSP.ps,PivotsPSP.Count - 1).Close,tom )
/////////////////
//Helpers misc//
///////////////
ShowPivotLevel( string pPivotLevel )=>
ShowLevel = false
switch ( pPivotLevel )
R5_KEY=>
ShowLevel := ShowR5 and PivotCalcType == "Traditional pivots"
R4_KEY=>
ShowLevel := ShowR4 and PivotCalcType != "Classic pivots"
R3_KEY=>
ShowLevel := ShowR3
R2_KEY=>
ShowLevel := ShowR2
R1_KEY=>
ShowLevel := ShowR1
PP_KEY=>
ShowLevel := PivotCalcType != "Camarilla pivots" and ShowPP
S1_KEY=>
ShowLevel := ShowS1
S2_KEY=>
ShowLevel := ShowS2
S3_KEY=>
ShowLevel := ShowS3
S4_KEY=>
ShowLevel := ShowS4 and PivotCalcType != "Classic pivots"
S5_KEY=>
ShowLevel := ShowS5 and PivotCalcType == "Traditional pivots"
=>
ShowLevel := false
ShowLevel
setUpBox(box b, float x, float y, color cl)=>
box.set_right(b, right = bar_index)
box.set_bottom(b, bottom = math.min(x,y))
box.set_top(b,top = math.max(x,y))
box.set_bgcolor(b,getColor(cl))
setTransparency(colors cc)=>
cc.PPPlotColor := color.rgb(255, 255, 255, 100)
cc.S1PlotColor := color.rgb(255, 255, 255, 100)
cc.S2PlotColor := color.rgb(255, 255, 255, 100)
cc.S3PlotColor := color.rgb(255, 255, 255, 100)
cc.S4PlotColor := color.rgb(255, 255, 255, 100)
cc.S5PlotColor := color.rgb(255, 255, 255, 100)
cc.R1PlotColor := color.rgb(255, 255, 255, 100)
cc.R2PlotColor := color.rgb(255, 255, 255, 100)
cc.R3PlotColor := color.rgb(255, 255, 255, 100)
cc.R4PlotColor := color.rgb(255, 255, 255, 100)
cc.R5PlotColor := color.rgb(255, 255, 255, 100)
////////////////
//Main Code////
//////////////
// Function to extract hours and minutes from a time string
getHoursAndMinutes(_str) =>
// Split the string into an array using ":" as the separator
time_array = str.split(_str, ":")
// Extract the hours and minutes from the array
hours = str.tonumber(array.get(time_array,0))
minutes = str.tonumber(array.get(time_array,1))
// Return the extracted values
[hours, minutes]
// Extract hours and minutes from the sample string
[extracted_hours, extracted_minutes] = getHoursAndMinutes(SR2LevelsCalcTime)
Bar dailyBar=Bar.new(request.security(syminfo.tickerid,"D",high[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"D",close[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"D",low[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"D",time[1],barmerge.gaps_off,barmerge.lookahead_on))
Bar weaklyBar=Bar.new(request.security(syminfo.tickerid,"W",high[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"W",close[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"W",low[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"W",time[1],barmerge.gaps_off,barmerge.lookahead_on))
Bar monthlyBar=Bar.new(request.security(syminfo.tickerid,"M",high[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"M",close[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"M",low[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"M",time[1],barmerge.gaps_off,barmerge.lookahead_on))
Bar quorterlyBar=Bar.new(request.security(syminfo.tickerid,"3M",high[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"3M",close[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"3M",low[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"3M",time[1],barmerge.gaps_off,barmerge.lookahead_on))
Bar yearlyBar=Bar.new(request.security(syminfo.tickerid,"12M",high[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"12M",close[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"12M",low[1],barmerge.gaps_off,barmerge.lookahead_on),request.security(syminfo.tickerid,"12M",time[1],barmerge.gaps_off,barmerge.lookahead_on))
color dgray = color.gray
if(hour(time,localtimezone)==extracted_hours and minute(time,localtimezone)==extracted_minutes)
dgray := color.rgb(255, 255, 255, 100)
Init(PriceSeriesProvider PSP, PriceSeriesProvider CPSP)=>
var changed = false
switch(PivotInterval)
"Daily"=>
if(dailyBar.T!=dailyBar.T[1])
array.push(PSP.ps,psarr.new(Times.new(year,month),dailyBar.H,dailyBar.L,dailyBar.C))
PSP.Count+= 1
else if(PSP.Count-1>0)
pp = psarr.new(Times.new(year,month),dailyBar.H,dailyBar.L,dailyBar.C)
array.set(PSP.ps,PSP.Count-1,pp)
if(hour(time,localtimezone)==extracted_hours and minute(time,localtimezone)==extracted_minutes)
array.push(CPSP.ps,psarr.new(Times.new(year,month),high ,low,dailyBar.C))
CPSP.Count+= 1
setTransparency(CustomColor)
else if(CPSP.Count-1>0)
hg = array.get(CPSP.ps,CPSP.Count-1).High
lg = array.get(CPSP.ps,CPSP.Count-1).Low
pp = psarr.new(Times.new(year,month),high>hg?high:hg,lg<low?lg:low,close)
array.set(CPSP.ps,CPSP.Count-1,pp)
"Weekly"=>
if(weaklyBar.T!=weaklyBar.T[1] )
array.push(PSP.ps,psarr.new(Times.new(year,month),weaklyBar.H,weaklyBar.L,weaklyBar.C))
PSP.Count+= 1
else if(PSP.Count-1>0)
pp = psarr.new(Times.new(year,month),weaklyBar.H,weaklyBar.L,weaklyBar.C)
array.set(PSP.ps,PSP.Count-1,pp)
"Monthly"=>
if(monthlyBar.T!=monthlyBar.T[1])
array.push(PSP.ps,psarr.new(Times.new(year,month),monthlyBar.H,monthlyBar.L,monthlyBar.C))
PSP.Count+= 1
else if(PSP.Count-1>0)
pp = psarr.new(Times.new(year,month),monthlyBar.H,monthlyBar.L,monthlyBar.C)
array.set(PSP.ps,PSP.Count-1,pp)
"Quarterly"=>
if(quorterlyBar.T!=quorterlyBar.T[1])
array.push(PSP.ps,psarr.new(Times.new(year,month),quorterlyBar.H,quorterlyBar.L,quorterlyBar.C))
PSP.Count+= 1
else if(PSP.Count-1>0)
pp = psarr.new(Times.new(year,month),quorterlyBar.H,quorterlyBar.L,quorterlyBar.C)
array.set(PSP.ps,PSP.Count-1,pp)
"Yearly"=>
if(yearlyBar.T!=yearlyBar.T[1])
array.push(PSP.ps,psarr.new(Times.new(year,month),yearlyBar.H,yearlyBar.L,yearlyBar.C))
PSP.Count+= 1
else if(PSP.Count-1>0)
pp = psarr.new(Times.new(year,month),yearlyBar.H,yearlyBar.L,yearlyBar.C)
array.set(PSP.ps,PSP.Count-1,pp)
true
customCalc(float PC,float PH,float PL,Tom tm)=>
tm.PPTom := ( PC + PH + PL ) / 3
tm.R1Tom := 2 * tm.PPTom - PL
tm.R2Tom := tm.PPTom + PH - PL
tm.R3Tom := tm.R2Tom + PH - PL
tm.S1Tom := 2 * tm.PPTom - PH
tm.S2Tom := tm.PPTom - PH + PL
tm.S3Tom := tm.S2Tom - PH + PL
Init(PivotsPSP,customPSP)
if(isdaily and PlotZones and dailyBar.T!=dailyBar.T[1] )
bgc=color.red
Box := Boxes.new(box.new(bar_index,dailyBar.H,bar_index,dailyBar.L,bgcolor = bgc,border_width = 0), box.new(bar_index,dailyBar.H,bar_index,dailyBar.L,bgcolor = bgc,border_width = 0),box.new(bar_index,dailyBar.H,bar_index,dailyBar.L,bgcolor = bgc,border_width = 0),box.new(bar_index,dailyBar.H,bar_index,dailyBar.L,bgcolor = bgc,border_width = 0),box.new(bar_index,dailyBar.H,bar_index,dailyBar.L,bgcolor = bgc,border_width = 0), box.new(bar_index,dailyBar.H,bar_index,dailyBar.L,bgcolor = bgc,border_width = 0),box.new(bar_index,dailyBar.H,bar_index,dailyBar.L,bgcolor = bgc,border_width = 0))
Line:= Lines.new(line.new(bar_index,0,bar_index,0),line.new(bar_index,0,bar_index,0),line.new(bar_index,0,bar_index,0),line.new(bar_index,0,bar_index,0),line.new(bar_index,0,bar_index,0),line.new(bar_index,0,bar_index,0),line.new(bar_index,0,bar_index,0))
if true//(BarDateTime > PivotsPSP.Time[0])//todo
PSPIndexOffset := 0
else
PSPIndexOffset := 1
// if (not OkToCalc)
// switch (PivotInterval)
// "Quarterly"=>
// OkToCalc := PivotsPSP.Count > 3
// "Yearly"=>
// OkToCalc := PivotsPSP.Count > 12
// =>
// OkToCalc := PivotsPSP.Count > 1
if (PivotsPSP.Count > 1)
CalculateLevels()
CalculateLevelsForTomorrow()
if(isdaily and customPSP.Count>1)
customCalc(array.get(customPSP.ps,customPSP.Count-2).Close,array.get(customPSP.ps,customPSP.Count-2).High,array.get(customPSP.ps,customPSP.Count-2).Low,customtom)
// when new pivot levels are calculated, we need to create text labels for the new
// pivot levels and set plot colors to transparent to eliminate connector lines
// from the prior pivot levels to the new pivot levels
setUpLine(line l,float y,color cl)=>
line.set_color(l,cl)
line.set_x2(l,bar_index)
line.set_y1(l,y)
line.set_y2(l,y)
makest(string st,float pr)=>
string s = st
if(ShowPivotIntervalInLabels)
s+=" ("
s+= str.substring(PivotInterval,0,1)
s+=") "
if(ShowPriceLevelsInLabels)
s+=str.tostring(pr,".##")
s
var labelStartPlace = 0
var label_exist = false
if (InAChart and pivs.PP != 0 and ( pivs.PP != pivs.PP[1] or pivs.R1 != pivs.R1[1] or pivs.S1 != pivs.S1[1] ))
setTransparency(PSPColor)
if (ShowPivotLabels)
if(ShowCurrentPeriodLabelsOnly)
label.delete(LabelS1 )
label.delete(LabelS2 )
label.delete(LabelS3 )
label.delete(LabelS4 )
label.delete(LabelS5 )
label.delete(LabelR1 )
label.delete(LabelR2 )
label.delete(LabelR3 )
label.delete(LabelR4 )
label.delete(LabelR5 )
label.delete(LabelPP )
labelStartPlace := bar_index
label_exist := true
if(ShowPivotLevel( S1_KEY ))
LabelS1 := label.new(bar_index,tom.S1Tom,makest("S1",tom.S1Tom),textcolor = color.white,color = S1Color)
if(ShowPivotLevel( S2_KEY ))
LabelS2 := label.new(bar_index,tom.S2Tom,makest("S2",tom.S2Tom),textcolor = color.white,color = S2Color)
if(ShowPivotLevel( S3_KEY ))
LabelS3 := label.new(bar_index,tom.S3Tom,makest("S3",tom.S3Tom),textcolor = color.white,color = S3Color)
if(ShowPivotLevel( S4_KEY ))
LabelS4 := label.new(bar_index,tom.S4Tom,makest("S4",tom.S4Tom),textcolor = color.white,color = S4Color)
if(ShowPivotLevel( S5_KEY ))
LabelS5 := label.new(bar_index,tom.S5Tom,makest("S5",tom.S5Tom),textcolor = color.white,color = S5Color)
if(ShowPivotLevel( R1_KEY ))
LabelR1 := label.new(bar_index,tom.R1Tom,makest("R1",tom.R1Tom),textcolor = color.white,color = R1Color)
if(ShowPivotLevel( R2_KEY ))
LabelR2 := label.new(bar_index,tom.R2Tom,makest("R2",tom.R2Tom),textcolor = color.white,color = R2Color)
if(ShowPivotLevel( R3_KEY ))
LabelR3 := label.new(bar_index,tom.R3Tom,makest("R3",tom.R3Tom),textcolor = color.white,color = R3Color)
if(ShowPivotLevel( R4_KEY ))
LabelR4 := label.new(bar_index,tom.R4Tom,makest("R4",tom.R4Tom),textcolor = color.white,color = R4Color)
if(ShowPivotLevel( R5_KEY ))
LabelR5 := label.new(bar_index,tom.R5Tom,makest("R5",tom.R5Tom),textcolor = color.white,color = R5Color)
if(ShowPivotLevel( PP_KEY ))
LabelPP := label.new(bar_index,tom.PPTom,makest("MP",tom.PPTom),textcolor = color.white,color = PivotColor)
var label_x = bar_index
switch(AdjustTheLabels)
"Left" =>
label_x := labelStartPlace
"Center"=>
label_x := (labelStartPlace+bar_index)/2
"Right" =>
label_x := bar_index
if (label_exist)
if(ShowPivotLevel( S1_KEY ))
label.set_x(LabelS1,label_x)
if(ShowPivotLevel( S2_KEY ))
label.set_x(LabelS2,label_x)
if(ShowPivotLevel( S3_KEY ))
label.set_x(LabelS3,label_x)
if(ShowPivotLevel( S4_KEY ))
label.set_x(LabelS4,label_x)
if(ShowPivotLevel( S5_KEY ))
label.set_x(LabelS5,label_x)
if(ShowPivotLevel( R1_KEY ))
label.set_x(LabelR1,label_x)
if(ShowPivotLevel( R2_KEY ))
label.set_x(LabelR2,label_x)
if(ShowPivotLevel( R3_KEY ))
label.set_x(LabelR3,label_x)
if(ShowPivotLevel( R4_KEY ))
label.set_x(LabelR4,label_x)
if(ShowPivotLevel( R5_KEY ))
label.set_x(LabelR5,label_x)
if(ShowPivotLevel( PP_KEY ))
label.set_x(LabelPP,label_x)
if(isdaily and PlotZones)
if(ShowPivotLevel( R1_KEY ))
setUpBox(Box.R1Box,tom.R1Tom,customtom.R1Tom,ZoneColor.R1PlotColor)
setUpLine(Line.R1Line,(tom.R1Tom+customtom.R1Tom)/2,R1Color)
if(ShowPivotLevel( R2_KEY ))
setUpBox(Box.R2Box,tom.R2Tom,customtom.R2Tom,ZoneColor.R2PlotColor)
setUpLine(Line.R2Line,(tom.R2Tom+customtom.R2Tom)/2,R2Color)
if(ShowPivotLevel( R3_KEY ))
setUpBox(Box.R3Box,tom.R3Tom,customtom.R3Tom,ZoneColor.R3PlotColor)
setUpLine(Line.R3Line,(tom.R3Tom+customtom.R3Tom)/2,R3Color)
if(ShowPivotLevel( S1_KEY ))
setUpBox(Box.S1Box,tom.S1Tom,customtom.S1Tom,ZoneColor.S1PlotColor)
setUpLine(Line.S1Line,(tom.S1Tom+customtom.S1Tom)/2,S1Color)
if(ShowPivotLevel( S2_KEY ))
setUpBox(Box.S2Box,tom.S2Tom,customtom.S2Tom,ZoneColor.S2PlotColor)
setUpLine(Line.S2Line,(tom.S2Tom+customtom.S2Tom)/2,S2Color)
if(ShowPivotLevel( S3_KEY ))
setUpBox(Box.S3Box,tom.S3Tom,customtom.S3Tom,ZoneColor.S3PlotColor)
setUpLine(Line.S3Line,(tom.S3Tom+customtom.S3Tom)/2,S3Color)
if(ShowPivotLevel( PP_KEY ))
setUpBox(Box.PPBox,tom.PPTom,customtom.PPTom,ZoneColor.PPPlotColor)
setUpLine(Line.PPLine,(tom.PPTom+customtom.PPTom)/2,PivotColor)
plot(ShowPivotLevel( R5_KEY ) and tom.PPTom!=0 and FTPLevels ? tom.R5Tom:na, title = R5_KEY , color = PSPColor.R5PlotColor )
plot(ShowPivotLevel( R4_KEY ) and tom.PPTom!=0 and FTPLevels ? tom.R4Tom:na, title = R4_KEY , color = PSPColor.R4PlotColor )
plot(ShowPivotLevel( R3_KEY ) and tom.PPTom!=0 and FTPLevels ? tom.R3Tom:na, title = R3_KEY , color = PSPColor.R3PlotColor )
plot(ShowPivotLevel( R2_KEY ) and tom.PPTom!=0 and FTPLevels ? tom.R2Tom:na, title = R2_KEY , color = PSPColor.R2PlotColor )
plot(ShowPivotLevel( R1_KEY ) and tom.PPTom!=0 and FTPLevels ? tom.R1Tom:na, title = R1_KEY , color = PSPColor.R1PlotColor )
plot(ShowPivotLevel( PP_KEY ) and tom.PPTom!=0 and FTPLevels ? tom.PPTom:na, title = PP_KEY , color = PSPColor.PPPlotColor )
plot(ShowPivotLevel( S1_KEY ) and tom.PPTom!=0 and FTPLevels ? tom.S1Tom:na, title = S1_KEY , color = PSPColor.S1PlotColor )
plot(ShowPivotLevel( S2_KEY ) and tom.PPTom!=0 and FTPLevels ? tom.S2Tom:na, title = S2_KEY , color = PSPColor.S2PlotColor )
plot(ShowPivotLevel( S3_KEY ) and tom.PPTom!=0 and FTPLevels ? tom.S3Tom:na, title = S3_KEY , color = PSPColor.S3PlotColor )
plot(ShowPivotLevel( S4_KEY ) and tom.PPTom!=0 and FTPLevels ? tom.S4Tom:na, title = S4_KEY , color = PSPColor.S4PlotColor )
plot(ShowPivotLevel( S5_KEY ) and tom.PPTom!=0 and FTPLevels ? tom.S5Tom:na, title = S5_KEY , color = PSPColor.S5PlotColor )
plot(ShowPivotLevel( R3_KEY ) and customtom.PPTom!=0 and SR2Levels and isdaily ? customtom.R3Tom:na, title = R3_KEY +"C" , color = CustomColor.R3PlotColor )
plot(ShowPivotLevel( R2_KEY ) and customtom.PPTom!=0 and SR2Levels and isdaily ? customtom.R2Tom:na, title = R2_KEY +"C" , color = CustomColor.R2PlotColor )
plot(ShowPivotLevel( R1_KEY ) and customtom.PPTom!=0 and SR2Levels and isdaily ? customtom.R1Tom:na, title = R1_KEY +"C" , color = CustomColor.R1PlotColor )
plot(ShowPivotLevel( PP_KEY ) and customtom.PPTom!=0 and SR2Levels and isdaily ? customtom.PPTom:na, title = PP_KEY +"C" , color = CustomColor.PPPlotColor )
plot(ShowPivotLevel( S1_KEY ) and customtom.PPTom!=0 and SR2Levels and isdaily ? customtom.S1Tom:na, title = S1_KEY +"C" , color = CustomColor.S1PlotColor )
plot(ShowPivotLevel( S2_KEY ) and customtom.PPTom!=0 and SR2Levels and isdaily ? customtom.S2Tom:na, title = S2_KEY +"C" , color = CustomColor.S2PlotColor )
plot(ShowPivotLevel( S3_KEY ) and customtom.PPTom!=0 and SR2Levels and isdaily ? customtom.S3Tom:na, title = S3_KEY +"C" , color = CustomColor.S3PlotColor )
plot(ShowPivotLevel( R3_KEY ) and customtom.PPTom!=0 and PlotZones and isdaily ? line.get_y1(Line.R3Line):na, title = R3_KEY +"MID" , color = getColor(R3Color,100) )
plot(ShowPivotLevel( R2_KEY ) and customtom.PPTom!=0 and PlotZones and isdaily ? line.get_y1(Line.R2Line):na, title = R2_KEY +"MID" , color = getColor(R2Color,100) )
plot(ShowPivotLevel( R1_KEY ) and customtom.PPTom!=0 and PlotZones and isdaily ? line.get_y1(Line.R1Line):na, title = R1_KEY +"MID" , color = getColor(R1Color,100) )
plot(ShowPivotLevel( PP_KEY ) and customtom.PPTom!=0 and PlotZones and isdaily ? line.get_y1(Line.PPLine):na, title = PP_KEY +"MID" , color = getColor(PivotColor,100) )
plot(ShowPivotLevel( S1_KEY ) and customtom.PPTom!=0 and PlotZones and isdaily ? line.get_y1(Line.S1Line):na, title = S1_KEY +"MID" , color = getColor(S1Color,100) )
plot(ShowPivotLevel( S2_KEY ) and customtom.PPTom!=0 and PlotZones and isdaily ? line.get_y1(Line.S2Line):na, title = S2_KEY +"MID" , color = getColor(S2Color,100) )
plot(ShowPivotLevel( S3_KEY ) and customtom.PPTom!=0 and PlotZones and isdaily ? line.get_y1(Line.S3Line):na, title = S3_KEY +"MID" , color = getColor(S3Color,100) )
Dist_S3_S2 = customtom.S3Tom-(customtom.S3Tom - customtom.S2Tom)/2
Dist_S2_S1 = customtom.S2Tom-(customtom.S2Tom - customtom.S1Tom)/2
Dist_S1_PP = customtom.S1Tom-(customtom.S1Tom - customtom.PPTom)/2
Dist_PP_R1 = customtom.PPTom-(customtom.PPTom - customtom.R1Tom)/2
Dist_R1_R2 = customtom.R1Tom-(customtom.R1Tom - customtom.R2Tom)/2
Dist_R2_R3 = customtom.R2Tom-(customtom.R2Tom - customtom.R3Tom)/2
plot(ShowPivotLevel( R3_KEY ) and customtom.PPTom!=0 and isdaily and ShowGrayLines ? Dist_S3_S2:na, title = "Dist_S3_S2" , color = dgray )
plot(ShowPivotLevel( R2_KEY ) and customtom.PPTom!=0 and isdaily and ShowGrayLines ? Dist_S2_S1:na, title = "Dist_S2_S1" , color = dgray )
plot(ShowPivotLevel( R1_KEY ) and customtom.PPTom!=0 and isdaily and ShowGrayLines ? Dist_S1_PP:na, title = "Dist_S1_PP" , color = dgray )
plot(ShowPivotLevel( PP_KEY ) and customtom.PPTom!=0 and isdaily and ShowGrayLines ? Dist_PP_R1:na, title = "Dist_PP_R1" , color = dgray )
plot(ShowPivotLevel( S1_KEY ) and customtom.PPTom!=0 and isdaily and ShowGrayLines ? Dist_R1_R2:na, title = "Dist_R1_R2" , color = dgray )
plot(ShowPivotLevel( S2_KEY ) and customtom.PPTom!=0 and isdaily and ShowGrayLines ? Dist_R2_R3:na, title = "Dist_R2_R3" , color = dgray )
|
Expansion/Contraction Indicator (ECI) [Angel Algo] | https://www.tradingview.com/script/lp7RoKnM-Expansion-Contraction-Indicator-ECI-Angel-Algo/ | AngelAlgo | https://www.tradingview.com/u/AngelAlgo/ | 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/
//@version=5
indicator("Expansion/Contraction Indicator (ECI) [Angel Algo]", shorttitle = "ECI [Angel Algo]", overlay=false)
// User-defined input for the indicator period
Period = input.int(14, title="Period", minval=1, maxval=200)
// Calculate the range between open and close of each bar
ocRange = math.abs(close - open)
// Calculate the exponential moving average (EMA) of the range
emaRange = ta.ema(ocRange, Period)
// Calculate the ECI value
ocroValue = ocRange / emaRange
// Create and plot the threshold lines for identifying contractions/expansions
// User-defined input for the upper and lower threshold levels
upperThreshold = input(3.0, title="Upper Threshold")
lowerThreshold = input(0.5, title="Lower Threshold")
// Plot upper, lower and middle threshold levels
mL = hline(1.0, title="Middle Line", linestyle=hline.style_dashed, color=color.green)
uT = hline(upperThreshold, title="Upper Threshold", linestyle=hline.style_dotted,
color=color.green)
lT = hline(lowerThreshold, title="Lower Threshold", linestyle=hline.style_dotted,
color=color.green)
// Plot zero level
zero = hline(0.0, title="Zero Line", linestyle=hline.style_dotted, color=color.gray)
// Fill areas between the thresholds for better visualization
fill(uT, mL, color=color.rgb(41, 179, 73, 70), title="Expansion Area 1")
fill(mL, lT, color= color.rgb(41, 179, 73, 90), title="Expansion Area 2")
// Define the conditional coloring for the ECI dots
ECI_dots_color = ocroValue < lowerThreshold ? color.red : color.green
// Plot the OCRO as a line
plot(ocroValue, title="ECI", color= color.gray, linewidth=2)
plot( ocroValue, title="ECI dots",
color = ECI_dots_color,
style = plot.style_circles,
linewidth = 3 )
// Alert conditions for breakouts and contractions
alertcondition(ta.crossover(ocroValue, upperThreshold), title="Expansion",
message="ECI is above the upper threshold, indicating an expansion.")
alertcondition(ta.crossunder(ocroValue, lowerThreshold), title="Contraction",
message="ECI is below the lower threshold, indicating a contraction.")
|
Momentum Probability Oscillator [SS] | https://www.tradingview.com/script/l2bbfb1G-Momentum-Probability-Oscillator-SS/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 188 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// /$$$$$$ /$$ /$$
// /$$__ $$ | $$ | $$
//| $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$
//| $$$$$$|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$__ $$ /$$_____/|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$_____/
// \____ $$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$ \__/| $$$$$$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$$$$$
// /$$ \ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/| $$ \____ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/ \____ $$
//| $$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$| $$ /$$$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$ /$$$$$$$/
// \______/ \___/ \_______/ \_/ \_______/|__/ |_______/ \___/ \_______/ \_/ \_______/|_______/
// ___________________
// / \
// / _____ _____ \
// / / \ / \ \
// __/__/ \____/ \__\_____
//| ___________ ____|
// \_________/ \_________/
// \ /////// /
// \/////////
// © Steversteves
//@version=5
indicator("Momentum Probability Oscillator [SS]", shorttitle = "Probability Oscillator [SS]", max_bars_back = 500)
len = input.int(500, "Length")
timeframe = input.timeframe("", "Timeframe")
smoothe = input.bool(false, "Smoothing")
showtbl = input.bool(false, "Show Table")
showlbl = input.bool(true, "Show Labels")
[rsi1, rsi] = request.security(syminfo.ticker, timeframe, [ta.rsi(close,14)[1], ta.rsi(close, 14)], lookahead = barmerge.lookahead_on)
[hitoop, optolo] = request.security(syminfo.ticker, timeframe, [(high[1] - open[1]), (open[1] - low[1])], lookahead = barmerge.lookahead_on)
[sto1, sto] = request.security(syminfo.ticker, timeframe, [ta.stoch(close, high, low, 14)[1], ta.stoch(close, high, low, 14)], lookahead = barmerge.lookahead_on)
[mfi1, mfi] = request.security(syminfo.ticker, timeframe, [ta.mfi(close, 14)[1], ta.mfi(close,14)], lookahead = barmerge.lookahead_on)
op = request.security(syminfo.ticker, timeframe, open, lookahead = barmerge.lookahead_on)
// Bullish vs bearish
bullishday = hitoop > optolo
bearishday = optolo > hitoop
bullish_mfi_array = array.new_float()
bullish_rsi_array = array.new_float()
bullish_sto_array = array.new_float()
hitoop_array = array.new_float()
bearish_mfi_array = array.new_float()
bearish_rsi_array = array.new_float()
bearish_sto_array = array.new_float()
lotoop_array = array.new_float()
for i = 0 to len
if bullishday[i]
array.push(bullish_mfi_array, mfi1[i])
array.push(bullish_rsi_array, rsi1[i])
array.push(bullish_sto_array, sto1[i])
array.push(hitoop_array, hitoop[i])
if bearishday[i]
array.push(bearish_mfi_array, mfi1[i])
array.push(bearish_rsi_array, rsi1[i])
array.push(bearish_sto_array, sto1[i])
array.push(lotoop_array, optolo[i])
// Bullish avg
hitoop_avg = array.avg(hitoop_array)
lotoop_avg = array.avg(lotoop_array)
rsi_bull_avg = array.avg(bullish_rsi_array)
rsi_bull_max = array.max(bullish_rsi_array)
rsi_bull_min = array.min(bullish_rsi_array)
sto_bull_avg = array.avg(bullish_sto_array)
sto_bull_max = array.max(bullish_sto_array)
sto_bull_min = array.min(bullish_sto_array)
mfi_bull_avg = array.avg(bullish_mfi_array)
mfi_bull_max = array.max(bullish_mfi_array)
mfi_bull_min = array.min(bullish_mfi_array)
rsi_bear_avg = array.avg(bearish_rsi_array)
rsi_bear_max = array.max(bearish_rsi_array)
rsi_bear_min = array.min(bearish_rsi_array)
sto_bear_avg = array.avg(bearish_sto_array)
sto_bear_max = array.max(bearish_sto_array)
sto_bear_min = array.min(bearish_sto_array)
mfi_bear_avg = array.avg(bearish_mfi_array)
mfi_bear_max = array.max(bearish_mfi_array)
mfi_bear_min = array.min(bearish_mfi_array)
// EM
em_hitoop = op + hitoop_avg
em_lotoop = op - lotoop_avg
// Colours
color black = color.rgb(0, 0, 0)
color white = color.white
color bearfill = color.new(color.red, 85)
color bullfill = color.new(color.lime, 85)
color bearfill2 = color.new(color.red, 70)
color bullfill2 = color.new(color.lime, 70)
color grayfill = color.new(color.gray, 65)
color transp = color.new(color.white, 100)
var table datatable = table.new(position.middle_right, 10, 10, bgcolor = color.black)
if showtbl
table.cell(datatable, 1, 1, text = "Technicals", bgcolor = black, text_color = white)
table.cell(datatable, 1, 2, text = "RSI", bgcolor = black, text_color = white)
table.cell(datatable, 1, 3, text = "Stochastics", bgcolor = black, text_color = white)
table.cell(datatable, 1, 4, text = "MFI", bgcolor = black, text_color = white)
table.cell(datatable, 2, 1, text = "Bullish", bgcolor = black, text_color = white)
table.cell(datatable, 3, 1, text = "Bullish Max", bgcolor = black, text_color = white)
table.cell(datatable, 4, 1, text = "Bullish Min", bgcolor = black, text_color = white)
table.cell(datatable, 5, 1, text = "Bearish", bgcolor = black, text_color = white)
table.cell(datatable, 6, 1, text = "Bearish Max", bgcolor = black, text_color = white)
table.cell(datatable, 7, 1, text = "Bearish Min", bgcolor = black, text_color = white)
table.cell(datatable, 2, 2, text = str.tostring(math.round(rsi_bull_avg, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 2, 3, text = str.tostring(math.round(sto_bull_avg, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 2, 4, text = str.tostring(math.round(mfi_bull_avg, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 3, 2, text = str.tostring(math.round(rsi_bull_max, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 3, 3, text = str.tostring(math.round(sto_bull_max, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 3, 4, text = str.tostring(math.round(mfi_bull_max, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 4, 2, text = str.tostring(math.round(rsi_bull_min, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 4, 3, text = str.tostring(math.round(sto_bull_min, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 4, 4, text = str.tostring(math.round(mfi_bull_min, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 5, 2, text = str.tostring(math.round(rsi_bear_avg, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 5, 3, text = str.tostring(math.round(sto_bear_avg, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 5, 4, text = str.tostring(math.round(mfi_bear_avg, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 6, 2, text = str.tostring(math.round(rsi_bear_max, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 6, 3, text = str.tostring(math.round(sto_bear_max, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 6, 4, text = str.tostring(math.round(mfi_bear_max, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 7, 2, text = str.tostring(math.round(rsi_bear_min, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 7, 3, text = str.tostring(math.round(sto_bear_min, 2)), bgcolor = black, text_color = white)
table.cell(datatable, 7, 4, text = str.tostring(math.round(mfi_bear_min, 2)), bgcolor = black, text_color = white)
bullish_average = math.avg(rsi_bull_avg, sto_bull_avg, mfi_bull_avg)
bullish_max_average = math.avg(rsi_bull_max, sto_bull_max, mfi_bull_max)
bearish_average = math.avg(rsi_bear_avg, sto_bear_avg, mfi_bear_avg)
bearish_min_average = math.avg(rsi_bear_min, sto_bear_min, mfi_bear_min)
current_average = math.avg(mfi, sto, rsi)
bull_bear_avg = math.avg(bullish_average, bearish_average)
var float current_average_plot = 0.0
if smoothe
current_average_plot := ta.sma(current_average, 14)
else
current_average_plot := current_average
bull_mid = math.avg(bullish_average, bullish_max_average)
bear_mid = math.avg(bearish_average, bearish_min_average)
e = plot(bear_mid, color=bearfill)
f = plot(bull_mid, color=bullfill)
plot(bull_bear_avg, color=color.yellow)
plot(current_average_plot, color=color.purple, linewidth=3)
c = plot(bullish_max_average, color=bullfill2)
d = plot(bearish_min_average, color=bearfill2)
a = plot(bullish_average, color=grayfill)
b = plot(bearish_average, color=grayfill)
fill(a, b, color=grayfill)
fill(b, e, color=bearfill)
fill(f, a, color = bullfill)
fill(e, d, color=bearfill2)
fill(f, c, color=bullfill2)
// Candle distribution
bool neut = current_average >= bearish_average and current_average <= bullish_average
bool bull_upper = current_average > bull_mid and current_average <= bullish_max_average
bool bull_lower = current_average > bullish_average and current_average <= bull_mid
bool bear_upper = current_average < bearish_average and current_average >= bear_mid
bool bear_lower = current_average < bear_mid and current_average >= bearish_min_average
int neut_count = 0
int bull_count = 0
int bull_overbought_count = 0
int bear_count = 0
int bear_overbought_count = 0
for i = 0 to len
if neut[i] and barstate.islast
neut_count := neut_count + 1
if bull_lower[i] and barstate.islast
bull_count := bull_count + 1
if bull_upper[i] and barstate.islast
bull_overbought_count := bull_overbought_count + 1
if bear_upper[i] and barstate.islast
bear_count := bear_count + 1
if bear_lower[i] and barstate.islast
bear_overbought_count := bear_overbought_count + 1
f_perc(count, lookback) =>
count / lookback * 100
neut_perc = f_perc(neut_count, len)
bull_perc = f_perc(bull_count, len)
bear_perc = f_perc(bear_count, len)
bull_o_perc = f_perc(bull_overbought_count, len)
bear_o_perc = f_perc(bear_overbought_count, len)
var label neut_lbl = na
var label bull_lbl = na
var label bull_o_lbl = na
var label bear_lbl = na
var label bear_o_lbl = na
var label hi_lbl = na
var label lo_lbl = na
if barstate.islast and showlbl
label.delete(neut_lbl)
label.delete(bull_lbl)
label.delete(bull_o_lbl)
label.delete(bear_lbl)
label.delete(bear_o_lbl)
label.delete(hi_lbl)
label.delete(lo_lbl)
bull_lbl := label.new(bar_index - 10, y = bullish_average, text = str.tostring(math.round(bull_perc,2)) + "%", color=transp, textcolor = white)
bull_o_lbl := label.new(bar_index - 10, y = bull_mid, text = str.tostring(math.round(bull_o_perc,2)) + "%", color=transp, textcolor = white)
neut_lbl := label.new(bar_index + 10, y = bull_bear_avg, text = str.tostring(math.round(neut_perc,2)) + "%", style=label.style_label_right, color = transp, textcolor = white)
bear_lbl := label.new(bar_index - 10, y = bearish_average, text = str.tostring(math.round(bear_perc,2)) + "%", style=label.style_label_up, color = transp, textcolor = white)
bear_o_lbl := label.new(bar_index - 10, y = bear_mid, text = str.tostring(math.round(bear_o_perc,2)) + "%", style=label.style_label_up, color = transp, textcolor = white)
hi_lbl := label.new(bar_index + 5, y = bull_mid, text = str.tostring(math.round(em_hitoop,2)), style=label.style_label_right, color = transp, textcolor = white)
lo_lbl := label.new(bar_index + 5, y = bear_mid, text = str.tostring(math.round(em_lotoop,2)), style=label.style_label_right, color = transp, textcolor = white) |
Moving Average Continuity [QuantVue] | https://www.tradingview.com/script/UqHC9TlS-Moving-Average-Continuity-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 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/
// © QuantVue
//@version=5
indicator('Moving Average Continuity [QuantVue]', overlay = true)
tt = 'Please select a chart time frame lower than or equal to your lowest selected moving average time frame'
// inputs
tf1 = input.timeframe('D', 'Time Frame 1', tooltip = tt)
tf2 = input.timeframe('240', 'Time Frame 2', tooltip = tt)
tf3 = input.timeframe('60', 'Time Frame 3', tooltip = tt)
fastMaLen = input.int(8, 'Fast MA', inline = '2')
slowMaLen = input.int(21, 'Slow MA', inline = '3')
slowMaType = input.string(defval = 'EMA', title = 'MA Type', options = ['EMA', 'SMA', 'HMA', 'WMA', 'VWMA'], inline = '2')
fastMaType = input.string(defval = 'EMA', title = 'MA Type', options = ['EMA', 'SMA', 'HMA', 'WMA', 'VWMA'], inline = '3')
yPos = input.string('Top', 'Table Position', options = ['Top', 'Middle', 'Bottom'], inline = '1')
xPos = input.string('Right', ' ', options = ['Right','Center', 'Left'], inline = '1')
//runtime error
if timeframe.in_seconds() > timeframe.in_seconds(tf1) or timeframe.in_seconds() > timeframe.in_seconds(tf2) or timeframe.in_seconds() > timeframe.in_seconds(tf3)
runtime.error(tt)
//create labels
var table maLabels = table.new(str.lower(yPos) + '_' + str.lower(xPos), 3, 2, color.new(color.white,100), color.new(color.white,100), 2 , color.new(color.white,100), 2)
// get moving average data
fastMa = switch fastMaType
'EMA' => ta.ema(close, fastMaLen)
'SMA' => ta.sma(close, fastMaLen)
'HMA' => ta.hma(close, fastMaLen)
'WMA' => ta.wma(close, fastMaLen)
'VWMA' => ta.vwma(close, fastMaLen)
slowMa = switch slowMaType
'EMA' => ta.ema(close, slowMaLen)
'SMA' => ta.sma(close, slowMaLen)
'HMA' => ta.hma(close, slowMaLen)
'WMA' => ta.wma(close, slowMaLen)
'VWMA' => ta.vwma(close, slowMaLen)
tf1FastMa = request.security(syminfo.tickerid, tf1, fastMa)
tf1SlowMa = request.security(syminfo.tickerid, tf1, slowMa)
tf2FastMa = request.security(syminfo.tickerid, tf2, fastMa)
tf2SlowMa = request.security(syminfo.tickerid, tf2, slowMa)
tf3FastMa = request.security(syminfo.tickerid, tf3, fastMa)
tf3SlowMa = request.security(syminfo.tickerid, tf3, slowMa)
// table variables
cell1Text = timeframe.in_seconds(tf1) < timeframe.in_seconds('D') ? str.tostring(tf1) + 'm : ' + str.tostring(fastMaLen) + ':' + str.tostring(slowMaLen) :
str.tostring(tf1) + ' : ' + str.tostring(fastMaLen) + ':' + str.tostring(slowMaLen)
cell2Text = timeframe.in_seconds(tf2) < timeframe.in_seconds('D') ? str.tostring(tf2) + 'm : ' + str.tostring(fastMaLen) + ':' + str.tostring(slowMaLen) :
str.tostring(tf2) + ' : ' + str.tostring(fastMaLen) + ':' + str.tostring(slowMaLen)
cell3Text = timeframe.in_seconds(tf3) < timeframe.in_seconds('D') ? str.tostring(tf3) + 'm : ' + str.tostring(fastMaLen) + ':' + str.tostring(slowMaLen) :
str.tostring(tf3) + ' : ' + str.tostring(fastMaLen) + ':' + str.tostring(slowMaLen)
tf1CellColor = tf1FastMa > tf1SlowMa ? color.green : color.red
tf2CellColor = tf2FastMa > tf2SlowMa ? color.green : color.red
tf3CellColor = tf3FastMa > tf3SlowMa ? color.green : color.red
// plot the data
if barstate.islast
maLabels.cell(0,0, ' ')
maLabels.merge_cells(0,0,2,0)
maLabels.cell(0,1, cell1Text, bgcolor = tf1CellColor)
maLabels.cell(1,1, cell2Text, bgcolor = tf2CellColor)
maLabels.cell(2,1, cell3Text, bgcolor = tf3CellColor)
//alerts
bullish = tf1FastMa > tf1SlowMa and tf2FastMa > tf2SlowMa and tf3FastMa > tf3SlowMa
bearish = tf1FastMa < tf1SlowMa and tf2FastMa < tf2SlowMa and tf3FastMa < tf3SlowMa
alertcondition((not bullish and bullish[1]) or (not bearish and bearish[1]), 'Mixed Moving Averages', 'Moving Averages No Longer Aligned')
alertcondition(bearish and not bearish[1], 'Bearish Moving Averages', 'Moving Averages on All Time Frames Aligned Bearish')
if bullish and not bullish[1]
alert('Moving Averages on All Time Frames Aligned Bullish', alert.freq_once_per_bar_close)
if (not bearish and bearish[1]) or (not bullish and bullish[1])
alert('Moving Averages No Longer Aligned', alert.freq_once_per_bar_close)
if bearish and not bearish[1]
alert('Moving Averages on All Time Frames Aligned Bearish', alert.freq_once_per_bar_close) |
Z-Score Weighted Moving Averages | https://www.tradingview.com/script/QeroyX1e-Z-Score-Weighted-Moving-Averages/ | federalTacos5392b | https://www.tradingview.com/u/federalTacos5392b/ | 26 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © federalTacos5392b
//@version=5
indicator("Z-Score Weighted Moving Averages", overlay = true)
// Input parameters
lookback_period = input(14, title = "Lookback Period")
smoothing_period = input(14, title = "Smoothing Period")
src = input(close, title = "Source")
// Choose which plot to display
plot_wma_smoothed = input(true, title = "Display Smoothed WMA")
plot_wma_dynamic = input(true, title = "Display Dynamic WMA")
// Calulate Mean absolute devaition around median
median = ta.median(src, lookback_period)
deviation = math.abs(src - median)
MAD = ta.sma(deviation, lookback_period)
// Calculate z-scores
z_scores = (src - ta.sma(src, lookback_period)) / (MAD*1.2533)
// Calculate weights based on absolute value of inverse of z-scores
weights = 1 / (1 + math.abs(z_scores))
// Calculate z_score weighted moving average
wma_sum = 0.0
sum_weights = 0.0
for i = 0 to smoothing_period - 1
wma_sum := wma_sum + src[i] * weights[i]
sum_weights := sum_weights + weights[i]
wma_smoothed = wma_sum / sum_weights
// Calculate weights based on absolute value of z-scores
weight_dynamic = math.abs(z_scores)
// Calculate weighted moving average
wma_sum1 = 0.0
sum_weights1 = 0.0
for i = 0 to smoothing_period - 1
wma_sum1 := wma_sum1 + src[i] * weight_dynamic[i]
sum_weights1 := sum_weights1 + weight_dynamic[i]
wma_dynamic = wma_sum1 / sum_weights1
// Determine trend direction of smoothed WMA and dynamic WMA
var float prev_wma_smoothed = na
var float prev_wma_dynamic = na
wma_smoothed_trend = 0
if not na(prev_wma_smoothed)
wma_smoothed_trend := wma_smoothed > prev_wma_smoothed ? 1 : wma_smoothed < prev_wma_smoothed ? -1 : 0
wma_dynamic_trend = 0
if not na(prev_wma_dynamic)
wma_dynamic_trend := wma_dynamic > prev_wma_dynamic ? 1 : wma_dynamic < prev_wma_dynamic ? -1 : 0
prev_wma_smoothed := wma_smoothed
prev_wma_dynamic := wma_dynamic
// Plot the chosen plots with customized colors
plot(plot_wma_smoothed ? wma_smoothed : na, color = wma_smoothed_trend > 0 ? color.green : color.red, title = "Smoothed Weighted Moving Average")
plot(plot_wma_dynamic ? wma_dynamic : na, color = wma_dynamic_trend > 0 ? color.blue : color.orange, title = "Dynamic Weighted Moving Average")
|
Engulfing Box & Lines | https://www.tradingview.com/script/SoXHpA6P-Engulfing-Box-Lines/ | AleSaira | https://www.tradingview.com/u/AleSaira/ | 46 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AleSaira
//@version=5
indicator(title="Engulfing Box & Lines", shorttitle="Engulfing Box&Lines", overlay=true)
ema200 = ta.ema (close, length=200)
bodySize = math.abs (close - open)
bodySizePrev = math.abs (close[1] - open[1])
Linelenght = input.int (40, "Line length")
lineColorBull = input.color (color.green, "Line color Engufing bullish")
lineColorBear = input.color (color.red, "Line color Engufing bullish")
BoxColorBull = input.color (color.green, "Box color Engufing bullish")
BoxColorBear = input.color (color.rgb(175, 76, 76), "Box color Engufing bearish")
StyleOption = input.string ("dotted (┈)", title="Line Style",
options = ["solid (─)", "dotted (┈)", "dashed (╌)"], group="Display")
// STEP 2. Convert the input to a proper line style value
lineStyle2 = StyleOption == "dotted (┈)" ? line.style_dotted : StyleOption == "dashed (╌)" ? line.style_dashed : line.style_solid
engulfingBullish = close > high[1] and open < open[1] and bodySize > bodySizePrev
engulfingBearish = close < low[1] and open > open[1] and bodySize > bodySizePrev
lineStyle = engulfingBullish ? lineStyle2 : engulfingBearish ? lineStyle2 : lineStyle2
lineColor = engulfingBullish ? lineColorBull : engulfingBearish ? lineColorBear : na
var line[] linesBullish = array.new_line()
var line[] linesBearish = array.new_line()
// Store the history of Engulfing patterns
var box[] boxesBullish = array.new_box()
var box[] boxesBearish = array.new_box()
if engulfingBullish and close > ema200
// Create and store the new bullish box
var line aiji = na
// Lines for engulfing
aiji := line.new(x1 = bar_index[1], y1 = high, x2 = bar_index + Linelenght, y2 = high, color = lineColor, width = 2, style = lineStyle)
array.push(linesBullish, aiji)
if engulfingBearish and close < ema200
// Create and store the new bullish box
var line aiji2 = na
// Lines for engulfing
aiji2 := line.new(x1 = bar_index[1], y1 = low, x2 = bar_index + Linelenght, y2 = low, color = lineColor, width = 2, style = lineStyle)
array.push(linesBullish, aiji2)
// Draw rectangles using box.new for Engulfing bars
if engulfingBullish and close > ema200
// Create and store the new bullish box
var box boxObj = na
boxObj := box.new(left = bar_index[1], right = bar_index, top = high, bottom = low, bgcolor=BoxColorBull, border_width=1, border_color=color.black)
array.push(boxesBullish, boxObj)
// Add a label
label.new(x = bar_index, y = high, text = "HiE", textcolor = color.black, color = color.rgb(243, 240, 240), style = label.style_label_center, textalign = text.align_center, size = size.tiny)
// Remove the oldest box if there are more than 10 bullish boxes in the array
if array.size(boxesBullish) > 10
box.delete(array.shift(boxesBullish))
if engulfingBearish and close < ema200
// Create and store the new bearish box
var box boxObj = na
boxObj := box.new(left = bar_index[1], right = bar_index, top = high, bottom = low, bgcolor=BoxColorBear, border_width=1, border_color=color.black)
array.push(boxesBearish, boxObj)
label.new(x = bar_index, y = low, text = "LoE", textcolor = color.black, color = color.rgb(243, 240, 240), style = label.style_label_center, textalign = text.align_center, size = size.tiny)
// Remove the oldest box if there are more than 10 bearish boxes in the array
if array.size(boxesBearish) > 10
box.delete(array.shift(boxesBearish))
|
McClellan Indicators (Oscillator, Summation Index w/ RSI & MACD) | https://www.tradingview.com/script/i6LNu8wO-McClellan-Indicators-Oscillator-Summation-Index-w-RSI-MACD/ | crutchie | https://www.tradingview.com/u/crutchie/ | 162 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © crutchie
//@version=5
indicator("McClellan Indicators", shorttitle = "Mkt Internals")
// Inputs
exchange = input.string("NYSE", options = ["NYSE", "Nasdaq"])
Indicator = input.string('Oscillator', 'Indicator', options = ['Oscillator', 'Summation Index (MSI)', 'MSI RSI', 'MSI MACD'])
MSI_EMA_Length = input(10, "MSI EMA Length")
// Data
adv = exchange == "NYSE" ? request.security("ADVN", timeframe.period, close) : request.security("ADVQ", timeframe.period,close)
dec = exchange == "NYSE" ? request.security("DECN", timeframe.period, close) : request.security("DECQ", timeframe.period,close)
// Osc calc
netadv = 1000 * (adv-dec)/(adv+dec)
ema1 = ta.ema(netadv,19)
ema2 = ta.ema(netadv,39)
osc = ema1-ema2
// MSI calc
msi = ta.cum(osc)
msiema = ta.ema(msi,MSI_EMA_Length)
// MSI RSI calc
msirsi = ta.rsi(msi,14)
rsihi = ta.highest(msirsi,5)
rsilo = ta.lowest(msirsi,5)
// MSI MACD calc
fast = ta.ema(msi,12)
slow = ta.ema(msi,26)
macd = fast-slow
avg = ta.ema(macd,9)
diff = macd-avg
// Osc plots
osccolor = osc > 0 ? color.green : color.red
plot(Indicator == 'Oscillator' ? osc : na, title = "Osc", color = osccolor)
hline(Indicator == 'Oscillator' ? 0 : na, title = "Osc Zero Line", color = color.black, linestyle=hline.style_dashed)
// MSI plots
plot(Indicator == 'Summation Index (MSI)' ? msi : na, title = "MSI", color = color.black)
plot(Indicator == 'Summation Index (MSI)' ? msiema : na, title = "MSI EMA", color = color.red)
msisignal = msi > msiema ? color.rgb(76, 175, 79, 90) : color.rgb(255, 82, 82, 92)
bgcolor(Indicator == 'Summation Index (MSI)' ? msisignal : na, title = "MSI Signal Shading")
msiup = ta.crossover(msi,msiema) ? msi : na
plotshape(Indicator == 'Summation Index (MSI)' ? msiup : na, title="MSI Cross Up", location = location.absolute, color=color.green, style=shape.xcross, size=size.tiny)
msidown = ta.crossunder(msi,msiema) ? msi : na
plotshape(Indicator == 'Summation Index (MSI)' ? msidown : na, title="MSI Cross Down", location = location.absolute, color=color.red, style=shape.xcross, size=size.tiny)
// MSI RSI plots
msirsicolor = msirsi < rsihi and msirsi > 70 ? color.red : msirsi > rsilo and msirsi < 30 ? color.green : color.black
plot(Indicator == 'MSI RSI' ? msirsi : na, "MSI RSI", color = msirsicolor)
hline(Indicator == 'MSI RSI' ? 70 : na,"RSI Overbought", linestyle = hline.style_solid, color = color.red)
hline(Indicator == 'MSI RSI' ? 30 : na,"RSI Oversold", linestyle = hline.style_solid, color = color.green)
hookdown = msirsi < rsihi and msirsi < msirsi[1] and msirsi > 70 or ta.crossunder(msirsi,70) ? msirsi+5 : na
plotshape(Indicator == 'MSI RSI' ? hookdown : na, title="RSI Hook Down", location = location.absolute, color=color.red, style=shape.triangleup, size=size.tiny)
hookup = msirsi > rsilo and msirsi > msirsi[1] and msirsi < 30 or ta.crossover(msirsi,30) ? msirsi-5 : na
plotshape(Indicator == 'MSI RSI' ? hookup : na, title="RSI Hook Up", location = location.absolute, color=color.green, style=shape.triangledown, size=size.tiny)
// MSI MACD plots
diffcolor = diff > 0 and diff > diff[1]? color.green : diff > 0 ? color.rgb(76, 175, 79, 47) : diff < 0 and diff < diff[1] ? color.red : color.rgb(255, 82, 82, 51)
plot(Indicator == 'MSI MACD' ? macd : na, "MACD", color = color.black)
plot(Indicator == 'MSI MACD' ? avg : na, "MACD Signal Line", color = color.red)
plot(Indicator == 'MSI MACD' ? diff : na, "MACD Histogram", style = plot.style_histogram, linewidth=4, color = diffcolor)
MACDsignal = macd > avg ? color.rgb(76, 175, 79, 90): color.rgb(255, 82, 82, 92)
bgcolor(Indicator == 'MSI MACD' ? MACDsignal : na, title = "MACD Signal Shading")
MACDup = ta.crossover(macd,avg) ? macd : na
plotshape(Indicator == 'MSI MACD' ? MACDup : na, title="MACD Cross Up", location = location.absolute, color=color.green, style=shape.xcross, size=size.tiny)
MACDdown = ta.crossunder(macd,avg) ? macd : na
plotshape(Indicator == 'MSI MACD' ? MACDdown : na, title="MACD Cross Down", location = location.absolute, color=color.red, style=shape.xcross, size=size.tiny) |
Key Levels (Daily Percentages) | https://www.tradingview.com/script/ngtQPxWS-Key-Levels-Daily-Percentages/ | liquid-trader | https://www.tradingview.com/u/liquid-trader/ | 108 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © liquid-trader
// This indicator automatically identifies and progressively draws daily percentage levels, normalized to
// the first market bar. Percentages are one of the most common ways to measure price action (outside price itself).
// Being able to visually reference these levels helps contextualize price action.
// More here: https://www.tradingview.com/script/ngtQPxWS-Key-Levels-Daily-Percentages/
//@version=5
indicator("Key Levels (Daily Percentages)", "Key Levels • Daily %", overlay = true, max_bars_back=1440, max_lines_count=500, max_boxes_count = 500, max_labels_count=500), max_bars_back(time, 1440)
// ---------------------------------------------------- SETTINGS --------------------------------------------------- //
// Base Colors
none = color.new(color.black, 100), clr1 = color.gray, clr2 = color.new(color.aqua, 50), clr3 = color.new(color.maroon, 25)
// Group Labels
g1 = "Auto Levels", g2 = "Static Zones", g3 = "General Settings", g4 = "Price Proximity", g5 = "Market Hours"
// Normalized Level Settings
zeroColor = input.color(color.new(clr1, 75), "Normalized Zero ", tooltip="Color, width, and style of the normalization level (aka. the \"zero\").", group=g1, inline="zero", display=display.none)
zeroWidth = input.int(4, "", 1, group=g1, inline="zero", display=display.none)
zeroStyle = input.string("Solid", "", ["Solid", "Dashed", "Dotted"], group=g1, inline="zero", display=display.none)
// Whole Value Settings
wholeColor = input.color(color.new(clr1, 50), "Whole Percentages ", "Color, width, and style of each 1 % increment.", group=g1, inline="whole", display=display.none)
wholeWidth = input.int(4, "", 1, group=g1, inline="whole", display=display.none)
wholeStyle = input.string("Solid", "", ["Solid", "Dashed", "Dotted"], group=g1, inline="whole", display=display.none)
// Fractional Value Settings
f1 = "Eighths", f2 = "Quarters", f3 = "Halves"
frac = input.bool(true, "", group=g1, inline="frac")
fracType = input.string(f2, "", [f1, f2, f3], group=g1, inline="frac", display=display.none)
fracColor = input.color(color.new(clr1, 50), "", "Color, width, and style of fractional increments.", group=g1, inline="frac", display=display.none)
fracWidth = input.int(2, "", 1, group=g1, inline="frac", display=display.none)
fracStyle = input.string("Solid", "", ["Solid", "Dashed", "Dotted"], group=g1, inline="frac", display=display.none)
// Intra Value Settings
intra = input.bool(false, "Intra Levels ", "Color, width, and style of smaller values between the other levels.\n\nThese will not have labels or display historically.", group=g1, inline="intra", display=display.none)
intraColor = input.color(color.new(clr1, 75), "", group=g1, inline="intra", display=display.none)
intraWidth = input.int(2, "", 1, group=g1, inline="intra", display=display.none)
intraStyle = input.string("Dotted", "", ["Solid", "Dashed", "Dotted"], group=g1, inline="intra", display=display.none)
// Custom Settings
custom = input.bool(true, "Custom Range", "Line color, background color, and percentages of a custom range. The larger percentage will not display until price crosses the smaller percentage.", group=g2, inline="custom", display=display.none)
customColor = input.color(clr2, "", group=g2, inline="custom", display=display.none)
customBgColor = input.color(color.new(clr2, 95), "", group=g2, inline="custom", display=display.none)
customWidth = wholeWidth
customStyle = wholeStyle
customLower = input.float(0.25, "", 0, group=g2, inline="custom", display=display.none), var Not_Showing_LOWER_Range = false
customUpper = input.float(0.5, "", 0.001, group=g2, inline="custom", display=display.none), var Not_Showing_UPPER_Range = false
// Anomalous Settings
anomalous = input.bool(true, "Ext. Anomalies", "Color and percentage. This will change the color of levels exceeding the percentage.\n\nThis is intended to be set wherever you consider price to be extended, or an anomaly . For context, and broadly speaking, 70% of days will have 0-1% moves, 20% of days will have 1-2% moves, and 10% of days will have moves exceeding 3%.", group=g2, inline="anomalous", display=display.none)
anomalousColor = input.color(clr3, "", group=g2, inline="anomalous", display=display.none)
anomalousRange = input.float(1, "", 0, group=g2, inline="anomalous", display=display.none)
// Source Settings
td = "Todays Open", yd = "Yesterdays Close", O = "open", H = "high", L = "low", C = "close", HL2 = "hl2", HLC3 = "hlc3", OHLC4 = "ohlc4", HLCC4 = "hlcc4"
srcBar = input.string(td, "Norm. Source ", [td, yd], "The value used to normalize the percent levels.\n\n\"Todays Open\" uses the first market bar of the current session.\n\n\"Yesterdays Close\" uses the last market bar of the previous session.\n\nPremarket levels inherit the current normalized source.", inline="source", group=g3), today = srcBar == td, yesterday = srcBar == yd
source = input.string(HLCC4, "", [O, H, L, C, HL2, HLC3, OHLC4, HLCC4], inline="source", group=g3, display=display.none)
// Label Settings
d1 = "Percentage ( % )", d2 = "Basis Points ( ‱ )", d3 = "Value Delta ( Δ )"
showLabel = input.bool(true, "Labels as","Label text value, and background / text colors.", inline="labels", group=g3, display=display.none)
delta = input.string(d1, "", [d1, d2, d3], inline="labels", group=g3, display=display.none)
lblClr = input.color(none, "", inline="labels", group=g3, display=display.none)
txtClr = input.color(clr1, "", inline="labels", group=g3, display=display.none)
incPrc = input.bool(false, "Include Price", inline="labels", group=g3, display=display.none)
showOldLevels = input.bool(true, "Show older levels", inline="old", group=g3, display=display.none)
oldColor = input.color(clr1, "", inline="old", group=g3, display=display.none)
// Line Settings
truncate = input.bool(false, "Max line length ", "Truncates the lines so they do not stretch back to the first market bar.", inline="max line length", group=g3, display=display.none)
truncLen = input.int(15, "", 0, inline="max line length", group=g3, display=display.none)
// Price Proximity Settings
prxRng = input.float(0.025, "Range of Proximity ( % )", 0, tooltip="How close price needs to be for an enabled proximity setting to take effect. This is a percentage (not monetary) value.", group=g4, display=display.none)
extend = input.bool(false, "Line Length Override", "Extends the line back to the first market bar when price is proximal to a given line and \"Max Line Length\" is enabled.", inline="extend", group=g4, display=display.none)
showProx = input.bool(false, "Toggle Visibility", "Hides levels by default, and only shows a level when price is proximal to a given line.", inline="prox vis", group=g4, display=display.none)
atrZone = input.bool(false, "ATR Zones", "This will show a 5 bar ATR zone around the level when price is proximal to a given line. Half the ATR is above the line, and half the ATR is below the line.", group=g4, display=display.none)
// Market Hours Settings
mktHrs = input.session("0930-1600", "Start / End Time ", tooltip = "A 24 hour format, where 0930 is 9:30 AM, 1600 is 4:00 PM, etc.\n\nDisabling \"Mkt Hrs Only\" will extend the previous sessions percentages into the premarket of the next session.", group=g5, inline="mkt", display=display.none)
mktHrsOnly = input.bool(false, "Mkt Hrs Only", group=g5, inline="mkt", display=display.none)
zone = input.string("America/New_York", "Time Zone ", tooltip="Any IANA time zone ID. Ex: America/New_York\n\nYou can also use \"syminfo.timezone\", which inherits the time zone of the exchange of the chart.", group=g5, inline="zone", display=display.none)
timezone = zone == "syminfo.timezone" ? syminfo.timezone : zone
// ----------------------------------------------------- CORE ------------------------------------------------------ //
// Set common variables.
o = open, h = high, l = low, c = close, barIndex = bar_index, var scaleBarIndex = bar_index
// Set the percentage scale source, based on trader selection.
price = switch source
O => open
H => high
L => low
C => close
HL2 => hl2
HLC3 => hlc3
OHLC4 => ohlc4
HLCC4 => hlcc4
// Initialize the daily normalized zero level.
var zero = 0.0
var normalizedZero = zero
// Initialize percent increment.
increment = frac ? fracType == f1 ? 0.125 : fracType == f2 ? 0.25 : 0.5 : 1
// Initialize color, and width arrays.
colors = array.from(zeroColor, wholeColor, fracColor, intraColor, customColor, anomalousColor)
width = array.from(zeroWidth, wholeWidth, fracWidth, intraWidth, customWidth)
// Initialize style array.
var style = array.from(zeroStyle, wholeStyle, fracStyle, intraStyle, customStyle), var Style_Arr_Not_Initialized = true
if Style_Arr_Not_Initialized
for i = 0 to style.size() - 1
s = switch style.get(i)
"Solid" => line.style_solid
"Dashed" => line.style_dashed
"Dotted" => line.style_dotted
style.set(i, s)
Style_Arr_Not_Initialized := false
// Initialize arrays used to manage objects.
var percent = array.new_float(na), var level = array.new_float(na), var lines = array.new_line(na), var labels = array.new_label(na), var atrBox = array.new_box(na), var intraLevel = array.new_float(na), var intraLines = array.new_line(na), var crLevel = array.new_float(na), var crBox = array.new_box(na), var signal = array.new_float(4, na)
// Set relative direction of price action.
dir = price >= normalizedZero ? 1 : -1
// --------------------------------------------------- TIME LOGIC -------------------------------------------------- //
// Define session segments.
minutesInDay = "1440"
market = time(minutesInDay, mktHrs, timezone)
newSession = session.isfirstbar
firstMarketBar = market and (not market[1] or newSession)
lastMarketBar = market[1] and (not market or newSession)
// -------------------------------------------- OBJECT UPDATE FUNCTIONS -------------------------------------------- //
convertToLevel(a) =>
math.round_to_mintick(normalizedZero + (normalizedZero * a) / 100)
labelString(pct, lvl) =>
float value = pct
symbol = " %"
prefix = pct > 0 ? " + " : pct < 0 ? " - " : " "
suffix = incPrc ? " • " + str.tostring(lvl) + " " : " "
switch delta
d2 => value *= 100, symbol := " ‱"
d3 => value := level.get(0) - lvl, symbol := " Δ"
prefix + str.tostring(math.abs(value)) + symbol + suffix
setSignal(pct) =>
if pct == 0
signal.set(0, math.avg(math.avg(convertToLevel(increment), normalizedZero), normalizedZero))
signal.set(1, increment)
signal.set(2, math.avg(math.avg(convertToLevel(-1 * increment), normalizedZero), normalizedZero))
signal.set(3, -1 * increment)
else
currLevel = convertToLevel(pct)
p = dir * (math.abs(pct) + increment)
signal.set(p > 0 ? 0 : 2, math.avg(math.avg(convertToLevel(p), currLevel), currLevel))
signal.set(p > 0 ? 1 : 3, p)
getIndexAndColor(pct, lvl) =>
decimal = pct - math.floor(pct)
decInc = (decimal / increment) - math.floor(decimal / increment)
n = decimal == 0 ? 1 : decInc == 0 ? 2 : 3
i = crLevel.includes(lvl) ? 4 : pct != 0 ? n : 0
clr = anomalous and math.abs(pct) >= anomalousRange ? anomalousColor : colors.get(i)
[i, clr]
addLevel(pct) =>
lvl = convertToLevel(pct)
[i, linClr] = getIndexAndColor(pct, lvl)
if (i < 2 or frac or crLevel.includes(lvl)) and not level.includes(lvl)
percent.push(pct)
level.push(lvl)
lines.push(line.new(scaleBarIndex, lvl, scaleBarIndex + 1, lvl, color=linClr, style=style.get(i), width=width.get(i), extend=extend.none))
if atrZone
atrBox.push(box.new(scaleBarIndex, lvl, scaleBarIndex + 1, lvl, color.new(linClr, 80), 1, bgcolor=color.new(linClr, 90)))
if showLabel and i != 3
labels.push(label.new(barIndex, lvl, labelString(pct, lvl), color=lblClr, textcolor=txtClr, style=label.style_label_left))
addIntraLevels(pct) =>
a = math.abs(pct)
b = math.abs(pct) - increment
for i = 1 to 3
lvl = convertToLevel((a - ((a - b) / 4) * i) * dir)
[j, linClr] = getIndexAndColor(b, lvl)
intraLevel.push(lvl)
intraLines.push(line.new(scaleBarIndex, intraLevel.last(), scaleBarIndex + 1, intraLevel.last(), color=linClr, style=style.get(3), width=width.get(3), extend=extend.none))
nextLevel(next) =>
addLevel(next)
if intra and not showProx
addIntraLevels(percent.last())
addIntraLevels(next)
setSignal(next)
showCustomRange(a, b) =>
if not level.includes(a)
addLevel(customLower * dir)
if not level.includes(b)
addLevel(customUpper * dir)
if not showProx
avg = math.round_to_mintick(math.avg(a, b))
intraLines.push(line.new(lines.get(0).get_x1(), avg, lines.get(0).get_x2(), avg, color=colors.get(4), style=line.style_dotted, width=2, extend=extend.none))
crBox.push(box.new(lines.get(0).get_x1(), a, lines.get(0).get_x2(), b, customBgColor, 1, bgcolor=customBgColor))
if atrZone
atrBox.push(box.new(lines.get(0).get_x1(), level.last(), lines.get(0).get_x2(), level.last(), none, 1, bgcolor=none))
// ------------------------------------------------- SESSION LOGIC ------------------------------------------------- //
deleteArray(arr) =>
for object in arr
object.delete()
setNewZero = ((today and firstMarketBar) or (yesterday and lastMarketBar)) and barstate.isconfirmed
terminateScale = (today and firstMarketBar) or (yesterday and newSession) or (mktHrsOnly and lastMarketBar)
createNewScale = ((today and firstMarketBar) or (yesterday and ((not mktHrsOnly and newSession) or (mktHrsOnly and firstMarketBar)))) and barstate.isconfirmed
// When it's time to terminate the old scale…
if terminateScale
// Delete old custom range lines, intra lines, and ATR zones.
deleteArray(intraLines), deleteArray(atrBox)
// If the trader wants levels from the previous day to remain visible…
if showOldLevels
// Reformat lines.
for [i, lineObject] in lines
[j, linClr] = getIndexAndColor(percent.get(i), level.get(i))
lineObject.set_x1(scaleBarIndex)
lineObject.set_x2(barIndex[1])
lineObject.set_width(1)
lineObject.set_color(color.new(linClr, 50))
lineObject.set_style(style.get(j))
// Reformat labels.
for labelObject in labels
labelObject.set_x(barIndex[1])
labelObject.set_color(none)
labelObject.set_textcolor(oldColor)
labelObject.set_style(label.style_label_lower_right)
// Reformat custom ranges.
for boxObject in crBox
boxObject.set_left(scaleBarIndex)
boxObject.set_right(barIndex[1])
else
// Otherwise, delete the old stuff.
deleteArray(lines), deleteArray(labels), deleteArray(crBox)
// Remove objects from the management arrays.
percent.clear(), level.clear(), lines.clear(), labels.clear(), atrBox.clear(), intraLevel.clear(), intraLines.clear(), crLevel.clear(), crBox.clear()
// Set the normalized zero value.
if setNewZero
zero := today ? price : price[1]
if createNewScale
// Set scale bar metrics.
scaleBarIndex := barIndex
normalizedZero := zero
dir := price >= normalizedZero ? 1 : -1
// If the custom range is enabled…
if custom
// Reset custom range switches.
Not_Showing_UPPER_Range := custom
Not_Showing_LOWER_Range := custom
// Set custom range.
crLevel := array.from(customLower, customUpper)
for i = 0 to crLevel.size() - 1
p = crLevel.shift()
crLevel.push(convertToLevel(p))
crLevel.push(convertToLevel(-1 * p))
// Reset the daily percent scale.
addLevel(0), setSignal(0)
// ----------------------------------------------- BAR BY BAR LOGIC ------------------------------------------------ //
if not mktHrsOnly or (market and mktHrsOnly)
// Show the next meaningful level.
if price > signal.get(0)
nextLevel(signal.get(1))
if price < signal.get(2)
nextLevel(signal.get(3))
// Show the custom range.
if custom
if price > crLevel.max(1) and Not_Showing_UPPER_Range
showCustomRange(crLevel.max(1), crLevel.max())
Not_Showing_UPPER_Range := false
if price < crLevel.min(1) and Not_Showing_LOWER_Range
showCustomRange(crLevel.min(1), crLevel.min())
Not_Showing_LOWER_Range := false
// Adjust labels.
for labelObject in labels
labelObject.set_x(barIndex + 10)
// Adjust percentage lines.
for lineObject in lines
lineObject.set_x2(barIndex + 10)
if truncate
lineObject.set_x1(barIndex - 15)
// Adjust intra lines.
for lineObject in intraLines
lvl = lineObject.get_y1()
avg1 = math.round_to_mintick(math.avg(crLevel.max(), crLevel.max(1)))
avg2 = math.round_to_mintick(math.avg(crLevel.min(), crLevel.min(1)))
n = lvl == avg1 or lvl == avg2 ? 0 : 5
lineObject.set_x2(lines.get(0).get_x2() - n)
if truncate
lineObject.set_x1(lines.get(0).get_x1() + n)
// Adjust custom range box.
for boxObject in crBox
boxObject.set_right(barIndex + 10)
if truncate
boxObject.set_left(barIndex - 15)
// ----------------------------------------- PRICE & LEVEL PROXIMITY LOGIC ----------------------------------------- //
// Proximity functions.
getLevelRange(lineObject) =>
lvl = lineObject.get_price(barIndex)
lvlRng = lvl * (prxRng / 100)
lvlRngHi = lvl + lvlRng
lvlRngLo = lvl - lvlRng
[lvl, lvlRng, lvlRngHi, lvlRngLo]
priceWithinLevelProximity(lvlRngHi, lvlRngLo) =>
(h < lvlRngHi and h > lvlRngLo)
or (l < lvlRngHi and l > lvlRngLo)
or (h > lvlRngHi and l < lvlRngLo)
or (h[1] < lvlRngHi and h[1] > lvlRngLo)
or (l[1] < lvlRngHi and l[1] > lvlRngLo)
or (h[1] > lvlRngHi and l[1] < lvlRngLo)
proximal(lineObject) =>
[lvl, lvlRng, lvlRngHi, lvlRngLo] = getLevelRange(lineObject)
proximal = priceWithinLevelProximity(lvlRngHi, lvlRngLo)
// If proximity settings are enabled…
if (truncate and extend) or showProx or atrZone
// Proximity specific variables.
prxAtr = ta.atr(5) / 2
for [i, lineObject] in lines
if proximal(lineObject)
if truncate and extend
// Override truncated line length.
lineObject.set_x1(scaleBarIndex)
if showProx
// Show level and label.
[j, linClr] = getIndexAndColor(percent.get(i), level.get(i))
lineObject.set_color(linClr)
if showLabel
labels.get(i).set_color(lblClr)
labels.get(i).set_textcolor(txtClr)
if atrZone
// // Show average true range zone around level.
[lvl, lvlRng, lvlRngHi, lvlRngLo] = getLevelRange(lineObject)
[j, clr] = getIndexAndColor(percent.get(i), level.get(i))
atrBox.get(i).set_lefttop(lineObject.get_x1(), lvl + prxAtr)
atrBox.get(i).set_rightbottom(lineObject.get_x2(), lvl - prxAtr)
atrBox.get(i).set_bgcolor(color.new(clr, 90))
atrBox.get(i).set_border_color(color.new(clr, 80))
else
if truncate and extend
// Re-truncate lines.
lineObject.set_x1(barIndex - truncLen)
if showProx
// Hide level and label.
lineObject.set_color(none)
if showLabel
labels.get(i).set_color(none)
labels.get(i).set_textcolor(none)
if atrZone
// Hide ATR zone.
atrBox.get(i).set_lefttop(lineObject.get_x1(), lineObject.get_y1())
atrBox.get(i).set_rightbottom(lineObject.get_x2(), lineObject.get_y2())
atrBox.get(i).set_bgcolor(none)
atrBox.get(i).set_border_color(none) |
Exchange Net Highs-Lows | https://www.tradingview.com/script/T5ypw8Mk-Exchange-Net-Highs-Lows/ | crutchie | https://www.tradingview.com/u/crutchie/ | 35 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © crutchie
//@version=5
indicator(title="Exchange Net Highs-Lows", shorttitle="Net Highs-Lows")
//Inputs
exchange = input.string("NYSE", options = ["NYSE", "Nasdaq"])
MA_length = input(50, "MA Length")
// Data
NetHL = exchange == "NYSE" ? request.security("MAHN", timeframe.period, close)-request.security("MALN",timeframe.period,close) : request.security("MAHQ", timeframe.period, close)-request.security("MALQ",timeframe.period,close)
// Determine color of bars
bar_color = NetHL >= 0 ? color.green : color.red
// Plots
plot(NetHL, "Net HL", style=plot.style_histogram, color=bar_color, linewidth=4)
Average = ta.sma(NetHL,MA_length)
plot(Average,"SMA", color = color.black)
hline(0, "Zero line",linestyle=hline.style_solid, color = color.black)
//Signal shading
signalcolor = NetHL > Average ? color.rgb(76, 175, 79, 90) : color.rgb(255, 82, 82, 92)
bgcolor(signalcolor, title = "Signal shading") |
[SS] Linear Modeler | https://www.tradingview.com/script/fLeTgfxW-SS-Linear-Modeler/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 282 | study | 5 | MPL-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
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Quick Info //
// This indicator calculates linear regression models and correlations between a chosen data source and time. //
// It performs these calculations over different time intervals (e.g., 10, 20, ..., 100 candles) and It displays the results of //
//these calculations in a table format on the chart, showing regression results, correlation values, and backtesting pass rates. //
// The table's rows represent different time intervals, and the columns show various results and metrics, including: //
// 1. Regression results //
// 2. Upper and lower range bounds //
// 3. Backtesting pass rate (percentage of times the data fell within the range) //
// 4. Correlation values //
// 5. Trend assessments //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//@version=5
indicator("[SS] Linear Modeler", overlay=true)
// Groups //
g1 = "Display Settings"
g2 = "Modelling Parameters"
g3 = "Backtest Results"
// Tooltips //
t1 = "Determines the length of regression assessment. Reccomended to select a length with the strongest correlation assessment."
t2 = "Performs back-test results on the inputed number of candles. Default is a 300 candle lookback period."
t3 = "Determines the source of the assessment. Select the desired variable you want to model (i.e. the High Price, Close price or Low price)."
t4 = "Plots a demographic label at the end of the plotted range."
// user inputs //
len = input.int(50, "Assessment Length", tooltip = t1, group=g2)
pos = input.string("Bottom Right", "Table Position", ["Bottom Right", "Middle Right", "Centre", "Bottom Left", "Middle Left"], group = g1)
dispchart = input.bool(true, "Display Chart", group=g1)
dispbt = input.bool(true, "Display Backtest Results", group=g1)
dispcor = input.bool(true, "Display Correlation", group=g1)
distrend = input.bool(true, "Display Trend Result", group = g1)
lookback = input.int(300, "Backtest Range", tooltip = t2, group=g3)
src = input.source(close, "Source", tooltip=t3, group=g2)
labels = input.bool(false, "Plot Labels", tooltip = t4, group=g1)
prjplot = input.string("None", "Projection Plots", ["None", "10 Candles", "20 Candles", "30 Candles", "40 Candles", "50 Candles", "60 Candles", "70 Candles", "80 Candles", "90 Candles", "100 Candles"], group=g1)
// Pull Source Data //
src_data = request.security(syminfo.ticker, "", src, lookahead = barmerge.lookahead_on)
src_data_time = request.security(syminfo.ticker, "", time, lookahead = barmerge.lookahead_on)
// Colours //
color black = color.rgb(0, 0, 0)
color white = color.white
color transp = color.new(color.white, 100)
color purple = color.purple
color orange = color.orange
color green = color.lime
color red = color.red
// Fundamental Functions //
f_cor(len) =>
ta.correlation(src_data, src_data_time, len)
f_color_cor(variable) =>
variable >= 0.5 or variable <= -0.5 ? green : red
f_color_perc(variable) =>
variable >= 51 ? green : red
f_regression(float independent, float dependent, int len, float variable) =>
y_array = array.new_float()
y_sq_array = array.new_float()
x_array = array.new_float()
x_sq_array = array.new_float()
xy_array = array.new_float()
// Loop functions
for i = 0 to len
array.push(y_array, dependent[i])
array.push(y_sq_array, dependent[i] * dependent[i])
array.push(x_array, independent[i])
array.push(x_sq_array, independent[i] * independent[i])
array.push(xy_array, independent[i] * dependent[i])
// Regression Calculations
y = array.sum(y_array)
y2 = array.sum(y_sq_array)
x = array.sum(x_array)
x2 = array.sum(x_sq_array)
xy = array.sum(xy_array)
b1 = xy - (x * y) / len
bbb2 = x2 - (math.pow(x, 2) / len)
slope = (b1 / bbb2)
abc = y - (slope * x)
abc1 = abc / len
result = (variable * slope) + abc1
f_standard_error(float result, float dependent, int len) =>
se_residuals = array.new_float()
for i = 0 to len
array.push(se_residuals, (result[i] - dependent[i]) * (result[i] - dependent[i]))
se_add = array.sum(se_residuals)
rk = se_add / (len - 2)
se= math.sqrt(rk)
// Forecast Model //
change = ta.change(src_data_time)
q10 = f_regression(src_data_time[10], src_data, len, (time + (change * 10)))
q20 = f_regression(src_data_time[20], src_data, len, (time + (change * 20)))
q30 = f_regression(src_data_time[30], src_data, len, (time + (change * 30)))
q40 = f_regression(src_data_time[40], src_data, len, (time + (change * 40)))
q50 = f_regression(src_data_time[50], src_data, len, (time + (change * 50)))
q60 = f_regression(src_data_time[60], src_data, len, (time + (change * 60)))
q70 = f_regression(src_data_time[70], src_data, len, (time + (change * 70)))
q80 = f_regression(src_data_time[80], src_data, len, (time + (change * 80)))
q90 = f_regression(src_data_time[90], src_data, len, (time + (change * 90)))
q100 = f_regression(src_data_time[100], src_data, len, (time + (change * 100)))
// Correlations //
q10_cor = f_cor(10)
q20_cor = f_cor(20)
q30_cor = f_cor(30)
q40_cor = f_cor(40)
q50_cor = f_cor(50)
q60_cor = f_cor(60)
q70_cor = f_cor(70)
q80_cor = f_cor(80)
q90_cor = f_cor(90)
q100_cor = f_cor(100)
// Range Determination //
se_q10 = f_standard_error(q10[10], src_data, len)
q10_ucl = se_q10 + q10
q10_lcl = q10 - se_q10
se_q20 = f_standard_error(q20[20], src_data, len)
q20_ucl = q20 + se_q20
q20_lcl = q20 - se_q20
se_q30 = f_standard_error(q30[30], src_data, len)
q30_ucl = q30 + se_q30
q30_lcl = q30 - se_q30
se_q40 = f_standard_error(q40[40], src_data, len)
q40_ucl = q40 + se_q40
q40_lcl = q40 - se_q40
se_q50 = f_standard_error(q50[50], src_data, len)
q50_ucl = q50 + se_q50
q50_lcl = q50 - se_q50
se_q60 = f_standard_error(q60[60], src_data, len)
q60_ucl = q60 + se_q60
q60_lcl = q60 - se_q60
se_q70 = f_standard_error(q70[70], src_data, len)
q70_ucl = q70 + se_q70
q70_lcl = q70 - se_q70
se_q80 = f_standard_error(q80[80], src_data, len)
q80_ucl = q80 + se_q80
q80_lcl = q80 - se_q80
se_q90 = f_standard_error(q90[90], src_data, len)
q90_ucl = q90 + se_q90
q90_lcl = q90 - se_q90
se_q100 = f_standard_error(q100[100], src_data, len)
q100_ucl = q100 + se_q100
q100_lcl = q100 - se_q100
// Plot above functions //
tableposition = pos == "Bottom Right" ? position.bottom_right : pos == "Bottom Left" ? position.bottom_left : pos == "Centre" ? position.middle_center : pos == "Bottom Right" ? position.bottom_right : pos == "Middle Left" ? position.middle_left : position.bottom_right
var data = table.new(tableposition, 9, 12, bgcolor = black, frame_color = white, frame_width = 3)
if dispchart
table.cell(data, 1, 1, text = "Time \n by Candle", bgcolor=black, text_color=white)
table.cell(data, 2, 1, text = "Result", bgcolor=black, text_color=white)
table.cell(data, 4, 1, text = "Upper Range", bgcolor=black, text_color=white)
table.cell(data, 5, 1, text = "Lower Range", bgcolor=black, text_color=white)
if dispchart and dispbt
table.cell(data, 6, 1, text = "% Within Range", bgcolor=black, text_color=white)
table.cell(data, 3, 1, text = "% Result Achieved", bgcolor=black, text_color=white)
if dispchart and dispcor
table.cell(data, 7, 1, text = "Correlation", bgcolor=black, text_color=white)
if dispchart
table.cell(data, 1, 2, text = "10", bgcolor=black, text_color=white)
table.cell(data, 1, 3, text = "20", bgcolor=black, text_color=white)
table.cell(data, 1, 4, text = "30", bgcolor=black, text_color=white)
table.cell(data, 1, 5, text = "40", bgcolor=black, text_color=white)
table.cell(data, 1, 6, text = "50", bgcolor=black, text_color=white)
table.cell(data, 1, 7, text = "60", bgcolor=black, text_color=white)
table.cell(data, 1, 8, text = "70", bgcolor=black, text_color=white)
table.cell(data, 1, 9, text = "80", bgcolor=black, text_color=white)
table.cell(data, 1, 10, text = "90", bgcolor=black, text_color=white)
table.cell(data, 1, 11, text = "100", bgcolor=black, text_color=white)
table.cell(data, 2, 2, text = str.tostring(math.round(q10,2)), bgcolor=black, text_color=white)
table.cell(data, 2, 3, text = str.tostring(math.round(q20,2)), bgcolor=black, text_color=white)
table.cell(data, 2, 4, text = str.tostring(math.round(q30,2)), bgcolor=black, text_color=white)
table.cell(data, 2, 5, text = str.tostring(math.round(q40,2)), bgcolor=black, text_color=white)
table.cell(data, 2, 6, text = str.tostring(math.round(q50,2)), bgcolor=black, text_color=white)
table.cell(data, 2, 7, text = str.tostring(math.round(q60,2)), bgcolor=black, text_color=white)
table.cell(data, 2, 8, text = str.tostring(math.round(q70,2)), bgcolor=black, text_color=white)
table.cell(data, 2, 9, text = str.tostring(math.round(q80, 2)), bgcolor=black, text_color=white)
table.cell(data, 2, 10, text = str.tostring(math.round(q90,2)), bgcolor=black, text_color=white)
table.cell(data, 2, 11, text = str.tostring(math.round(q100, 2)), bgcolor=black, text_color=white)
// error
table.cell(data, 4, 2, text = str.tostring(math.round(q10_ucl,2)), bgcolor=black, text_color=white)
table.cell(data, 4, 3, text = str.tostring(math.round(q20_ucl,2)), bgcolor=black, text_color=white)
table.cell(data, 4, 4, text = str.tostring(math.round(q30_ucl,2)), bgcolor=black, text_color=white)
table.cell(data, 4, 5, text = str.tostring(math.round(q40_ucl,2)), bgcolor=black, text_color=white)
table.cell(data, 4, 6, text = str.tostring(math.round(q50_ucl,2)), bgcolor=black, text_color=white)
table.cell(data, 4, 7, text = str.tostring(math.round(q60_ucl,2)), bgcolor=black, text_color=white)
table.cell(data, 4, 8, text = str.tostring(math.round(q70_ucl,2)), bgcolor=black, text_color=white)
table.cell(data, 4, 9, text = str.tostring(math.round(q80_ucl, 2)), bgcolor=black, text_color=white)
table.cell(data, 4, 10, text = str.tostring(math.round(q90_ucl,2)), bgcolor=black, text_color=white)
table.cell(data, 4, 11, text = str.tostring(math.round(q100_ucl, 2)), bgcolor=black, text_color=white)
table.cell(data, 5, 2, text = str.tostring(math.round(q10_lcl,2)), bgcolor=black, text_color=white)
table.cell(data, 5, 3, text = str.tostring(math.round(q20_lcl,2)), bgcolor=black, text_color=white)
table.cell(data, 5, 4, text = str.tostring(math.round(q30_lcl,2)), bgcolor=black, text_color=white)
table.cell(data, 5, 5, text = str.tostring(math.round(q40_lcl,2)), bgcolor=black, text_color=white)
table.cell(data, 5, 6, text = str.tostring(math.round(q50_lcl,2)), bgcolor=black, text_color=white)
table.cell(data, 5, 7, text = str.tostring(math.round(q60_lcl,2)), bgcolor=black, text_color=white)
table.cell(data, 5, 8, text = str.tostring(math.round(q70_lcl,2)), bgcolor=black, text_color=white)
table.cell(data, 5, 9, text = str.tostring(math.round(q80_lcl, 2)), bgcolor=black, text_color=white)
table.cell(data, 5, 10, text = str.tostring(math.round(q90_lcl,2)), bgcolor=black, text_color=white)
table.cell(data, 5, 11, text = str.tostring(math.round(q100_lcl, 2)), bgcolor=black, text_color=white)
//correlation
if dispcor and dispchart
table.cell(data, 7, 2, text = str.tostring(math.round(q10_cor,2)), bgcolor=black, text_color=f_color_cor(q10_cor))
table.cell(data, 7, 3, text = str.tostring(math.round(q20_cor,2)), bgcolor=black, text_color=f_color_cor(q20_cor))
table.cell(data, 7, 4, text = str.tostring(math.round(q30_cor,2)), bgcolor=black, text_color=f_color_cor(q30_cor))
table.cell(data, 7, 5, text = str.tostring(math.round(q40_cor,2)), bgcolor=black, text_color=f_color_cor(q40_cor))
table.cell(data, 7, 6, text = str.tostring(math.round(q50_cor,2)), bgcolor=black, text_color=f_color_cor(q50_cor))
table.cell(data, 7, 7, text = str.tostring(math.round(q60_cor,2)), bgcolor=black, text_color=f_color_cor(q60_cor))
table.cell(data, 7, 8, text = str.tostring(math.round(q70_cor,2)), bgcolor=black, text_color=f_color_cor(q70_cor))
table.cell(data, 7, 9, text = str.tostring(math.round(q80_cor, 2)), bgcolor=black, text_color=f_color_cor(q80_cor))
table.cell(data, 7, 10, text = str.tostring(math.round(q90_cor,2)), bgcolor=black, text_color=f_color_cor(q90_cor))
table.cell(data, 7, 11, text = str.tostring(math.round(q100_cor, 2)), bgcolor=black, text_color=f_color_cor(q100_cor))
// Range Backtest //
int q10_pass = 0
int q10_fail = 0
int q20_pass = 0
int q20_fail = 0
int q30_pass = 0
int q30_fail = 0
int q40_pass = 0
int q40_fail = 0
int q50_pass = 0
int q50_fail = 0
int q60_pass = 0
int q60_fail = 0
int q70_pass = 0
int q70_fail = 0
int q80_pass = 0
int q80_fail = 0
int q90_pass = 0
int q90_fail = 0
int q100_pass = 0
int q100_fail = 0
bool q10_rng_bt = src_data >= q10_lcl[10] and src_data <= q10_ucl[10]
bool q20_rng_bt = src_data >= q20_lcl[20] and src_data <= q20_ucl[20]
bool q30_rng_bt = src_data >= q30_lcl[30] and src_data <= q30_ucl[30]
bool q40_rng_bt = src_data >= q40_lcl[40] and src_data <= q40_ucl[40]
bool q50_rng_bt = src_data >= q50_lcl[50] and src_data <= q50_ucl[50]
bool q60_rng_bt = src_data >= q60_lcl[60] and src_data <= q50_ucl[60]
bool q70_rng_bt = src_data >= q70_lcl[70] and src_data <= q70_ucl[70]
bool q80_rng_bt = src_data >= q80_lcl[80] and src_data <= q80_ucl[80]
bool q90_rng_bt = src_data >= q90_lcl[90] and src_data <= q90_ucl[90]
bool q100_rng_bt = src_data >= q100_lcl[100] and src_data <= q100_ucl[100]
for i = 0 to lookback
if q10_rng_bt[i] and barstate.islast
q10_pass := q10_pass + 1
else
q10_fail := q10_fail + 1
if q20_rng_bt[i] and barstate.islast
q20_pass := q20_pass + 1
else
q20_fail := q20_fail + 1
if q30_rng_bt[i] and barstate.islast
q30_pass := q30_pass + 1
else
q30_fail := q30_fail + 1
if q40_rng_bt[i] and barstate.islast
q40_pass := q40_pass + 1
else
q40_fail := q40_fail + 1
if q50_rng_bt[i] and barstate.islast
q50_pass := q50_pass + 1
else
q50_fail := q50_fail + 1
if q60_rng_bt[i] and barstate.islast
q60_pass := q60_pass + 1
else
q60_fail := q60_fail + 1
if q70_rng_bt[i] and barstate.islast
q70_pass := q70_pass + 1
else
q70_fail := q70_fail + 1
if q80_rng_bt[i] and barstate.islast
q80_pass := q80_pass + 1
else
q80_fail := q80_fail + 1
if q90_rng_bt[i] and barstate.islast
q90_pass := q90_pass + 1
else
q90_fail := q90_fail + 1
if q100_rng_bt[i] and barstate.islast
q100_pass := q100_pass + 1
else
q100_fail := q100_fail + 1
f_perc(pass, fail) =>
pass / (pass + fail) * 100
q10_pass_res = (q10_pass / (q10_pass + q10_fail)) * 100
q20_pass_res = (q20_pass / (q20_pass + q20_fail)) * 100
q30_pass_res = (q30_pass / (q30_pass + q30_fail)) * 100
q40_pass_res = (q40_pass / (q40_pass + q40_fail)) * 100
q50_pass_res = (q50_pass / (q50_pass + q50_fail)) * 100
q60_pass_res = (q60_pass / (q60_pass + q60_fail)) * 100
q70_pass_res = f_perc(q70_pass, q70_fail)
q80_pass_res = f_perc(q80_pass, q80_fail)
q90_pass_res = f_perc(q90_pass, q90_fail)
q100_pass_res = f_perc(q100_pass, q100_fail)
// Result Backtest //
highest10 = ta.highest(high, 10)
lowest10 = ta.lowest(low, 10)
highest20 = ta.highest(high, 20)
lowest20 = ta.lowest(low, 20)
highest30 = ta.highest(high, 30)
lowest30 = ta.lowest(low, 30)
highest40 = ta.highest(high, 40)
lowest40 = ta.lowest(low, 40)
highest50 = ta.highest(high, 50)
lowest50 = ta.lowest(low, 50)
highest60 = ta.highest(high, 60)
lowest60 = ta.lowest(low, 60)
highest70 = ta.highest(high, 70)
lowest70 = ta.lowest(low, 70)
highest80 = ta.highest(high, 80)
lowest80 = ta.lowest(low, 80)
highest90 = ta.highest(high, 90)
lowest90 = ta.lowest(low, 90)
highest100 = ta.highest(high, 100)
lowest100 = ta.lowest(low, 100)
int q10_res_pass = 0
int q10_res_fail = 0
int q20_res_pass = 0
int q20_res_fail = 0
int q30_res_pass = 0
int q30_res_fail = 0
int q40_res_pass = 0
int q40_res_fail = 0
int q50_res_pass = 0
int q50_res_fail = 0
int q60_res_pass = 0
int q60_res_fail = 0
int q70_res_pass = 0
int q70_res_fail = 0
int q80_res_pass = 0
int q80_res_fail = 0
int q90_res_pass = 0
int q90_res_fail = 0
int q100_res_pass = 0
int q100_res_fail = 0
bool q10_bt = q10[10] <= highest10 and q10[10] >= lowest10
bool q20_bt = q20[20] <= highest20 and q20[20] >= lowest20
bool q30_bt = q30[30] <= highest30 and q30[30] >= lowest30
bool q40_bt = q40[40] <= highest40 and q40[40] >= lowest40
bool q50_bt = q50[50] <= highest50 and q50[50] >= lowest50
bool q60_bt = q60[60] <= highest60 and q60[60] >= lowest60
bool q70_bt = q70[70] <= highest70 and q70[70] >= lowest70
bool q80_bt = q80[80] <= highest80 and q80[80] >= lowest80
bool q90_bt = q90[90] <= highest90 and q90[90] >= lowest90
bool q100_bt = q100[100] <= highest100 and q100[100] >= lowest100
for i = 0 to lookback
if q10_bt[i] and barstate.islast
q10_res_pass := q10_res_pass + 1
else
q10_res_fail := q10_res_fail + 1
if q20_bt[i] and barstate.islast
q20_res_pass := q20_res_pass + 1
else
q20_res_fail := q20_res_fail + 1
if q30_bt[i] and barstate.islast
q30_res_pass := q30_res_pass + 1
else
q30_res_fail := q30_res_fail + 1
if q40_bt[i] and barstate.islast
q40_res_pass := q40_res_pass + 1
else
q40_res_fail := q40_res_fail + 1
if q50_bt[i] and barstate.islast
q50_res_pass := q50_res_pass + 1
else
q50_res_fail := q50_res_fail + 1
if q60_bt[i] and barstate.islast
q60_res_pass := q60_res_pass + 1
else
q60_res_fail := q60_res_fail + 1
if q70_bt[i] and barstate.islast
q70_res_pass := q70_res_pass + 1
else
q70_res_fail := q70_res_fail + 1
if q80_bt[i] and barstate.islast
q80_res_pass := q80_res_pass + 1
else
q80_res_fail := q80_res_fail + 1
if q90_bt[i] and barstate.islast
q90_res_pass := q90_res_pass + 1
else
q90_res_fail := q90_res_fail + 1
if q100_bt[i] and barstate.islast
q100_res_pass := q100_res_pass + 1
else
q100_res_fail := q100_res_fail + 1
q10_perc = f_perc(q10_res_pass, q10_res_fail)
q20_perc = f_perc(q20_res_pass, q20_res_fail)
q30_perc = f_perc(q30_res_pass, q30_res_fail)
q40_perc = f_perc(q40_res_pass, q40_res_fail)
q50_perc = f_perc(q50_res_pass, q50_res_fail)
q60_perc = f_perc(q60_res_pass, q60_res_fail)
q70_perc = f_perc(q70_res_pass, q70_res_fail)
q80_perc = f_perc(q80_res_pass, q80_res_fail)
q90_perc = f_perc(q90_res_pass, q90_res_fail)
q100_perc = f_perc(q100_res_pass, q100_res_fail)
// Plot above functions //
if dispbt and dispchart
table.cell(data, 6, 2, text = str.tostring(math.round(q10_pass_res, 2)) + "%", bgcolor = black, text_color = f_color_perc(q10_pass_res))
table.cell(data, 6, 3, text = str.tostring(math.round(q20_pass_res, 2)) + "%", bgcolor = black, text_color = f_color_perc(q20_pass_res))
table.cell(data, 6, 4, text = str.tostring(math.round(q30_pass_res, 2)) + "%", bgcolor = black, text_color = f_color_perc(q30_pass_res))
table.cell(data, 6, 5, text = str.tostring(math.round(q40_pass_res, 2)) + "%", bgcolor = black, text_color = f_color_perc(q40_pass_res))
table.cell(data, 6, 6, text = str.tostring(math.round(q50_pass_res, 2)) + "%", bgcolor = black, text_color = f_color_perc(q50_pass_res))
table.cell(data, 6, 7, text = str.tostring(math.round(q60_pass_res, 2)) + "%", bgcolor = black, text_color = f_color_perc(q60_pass_res))
table.cell(data, 6, 8, text = str.tostring(math.round(q70_pass_res, 2)) + "%", bgcolor = black, text_color = f_color_perc(q70_pass_res))
table.cell(data, 6, 9, text = str.tostring(math.round(q80_pass_res, 2)) + "%", bgcolor = black, text_color = f_color_perc(q80_pass_res))
table.cell(data, 6, 10, text = str.tostring(math.round(q90_pass_res, 2)) + "%", bgcolor = black, text_color = f_color_perc(q90_pass_res))
table.cell(data, 6, 11, text = str.tostring(math.round(q100_pass_res, 2)) + "%", bgcolor = black, text_color = f_color_perc(q100_pass_res))
table.cell(data, 3, 2, text = str.tostring(math.round(q10_perc, 2)) + "%", bgcolor = black, text_color = f_color_perc(q10_perc))
table.cell(data, 3, 3, text = str.tostring(math.round(q20_perc, 2)) + "%", bgcolor = black, text_color = f_color_perc(q20_perc))
table.cell(data, 3, 4, text = str.tostring(math.round(q30_perc, 2)) + "%", bgcolor = black, text_color = f_color_perc(q30_perc))
table.cell(data, 3, 5, text = str.tostring(math.round(q40_perc, 2)) + "%", bgcolor = black, text_color = f_color_perc(q40_perc))
table.cell(data, 3, 6, text = str.tostring(math.round(q50_perc, 2)) + "%", bgcolor = black, text_color = f_color_perc(q50_perc))
table.cell(data, 3, 7, text = str.tostring(math.round(q60_perc, 2)) + "%", bgcolor = black, text_color = f_color_perc(q60_perc))
table.cell(data, 3, 8, text = str.tostring(math.round(q70_perc, 2)) + "%", bgcolor = black, text_color = f_color_perc(q70_perc))
table.cell(data, 3, 9, text = str.tostring(math.round(q80_perc, 2)) + "%", bgcolor = black, text_color = f_color_perc(q80_perc))
table.cell(data, 3, 10, text = str.tostring(math.round(q90_perc, 2)) + "%", bgcolor = black, text_color = f_color_perc(q90_perc))
table.cell(data, 3, 11, text = str.tostring(math.round(q100_perc, 2)) + "%", bgcolor = black, text_color = f_color_perc(q100_perc))
// Range Plotting Functions //
var float plot_input = 0.0
var float plot_input_ucl = 0.0
var float plot_input_lcl = 0.0
var int offset_int = 0
if prjplot == "10 Candles"
plot_input := q10
plot_input_ucl := q10_ucl
plot_input_lcl := q10_lcl
offset_int := 10
if prjplot == "20 Candles"
plot_input := q20
plot_input_ucl := q20_ucl
plot_input_lcl := q20_lcl
offset_int := 20
if prjplot == "30 Candles"
plot_input := q30
plot_input_ucl := q30_ucl
plot_input_lcl := q30_lcl
offset_int := 30
if prjplot == "40 Candles"
plot_input := q40
plot_input_ucl := q40_ucl
plot_input_lcl := q40_lcl
offset_int := 40
if prjplot == "50 Candles"
plot_input := q50
plot_input_ucl := q50_ucl
plot_input_lcl := q50_lcl
offset_int := 50
if prjplot == "60 Candles"
plot_input := q60
plot_input_ucl := q60_ucl
plot_input_lcl := q60_lcl
offset_int := 60
if prjplot == "70 Candles"
plot_input := q70
plot_input_ucl := q70_ucl
plot_input_lcl := q70_lcl
offset_int := 70
if prjplot == "80 Candles"
plot_input := q80
plot_input_ucl := q80_ucl
plot_input_lcl := q80_lcl
offset_int := 80
if prjplot == "90 Candles"
plot_input := q90
plot_input_ucl := q90_ucl
plot_input_lcl := q90_lcl
offset_int := 90
if prjplot == "100 Candles"
plot_input := q100
plot_input_ucl := q100_ucl
plot_input_lcl := q100_lcl
offset_int := 100
plot(plot_input, color=purple, linewidth=3, offset = offset_int)
plot(plot_input_lcl, color = orange, linewidth=3, offset = offset_int)
plot(plot_input_ucl, color = orange, linewidth=3, offset = offset_int)
// Plot labels //
var label q10_label = na
var label q20_label = na
var label q30_label = na
var label q40_label = na
var label q50_label = na
var label q60_label = na
var label q70_label = na
var label q80_label = na
var label q90_label = na
var label q100_label = na
if labels and barstate.islast
label.delete(q10_label)
label.delete(q20_label)
label.delete(q30_label)
label.delete(q40_label)
label.delete(q50_label)
label.delete(q60_label)
label.delete(q70_label)
label.delete(q80_label)
label.delete(q90_label)
label.delete(q100_label)
if prjplot == "10 Candles"
q10_label := label.new(bar_index + 10, y=plot_input, text = "Projection at 10 Candles \n Range: $" + str.tostring(math.round(q10_lcl,2)) + " to $" + str.tostring(math.round(q10_ucl,2)) + "\n Correlation: " + str.tostring(math.round(q10_cor,2)) + "\n Reliability: " + str.tostring(math.round(q10_pass_res,2)) + "%", style = label.style_label_left, textcolor = purple, color = transp, size = size.large)
if prjplot == "20 Candles"
q20_label := label.new(bar_index + 20, y=plot_input, text = "Projection at 20 Candles \n Range: $" + str.tostring(math.round(q20_lcl,2)) + " to $" + str.tostring(math.round(q20_ucl,2)) + "\n Correlation: " + str.tostring(math.round(q20_cor,2)) + "\n Reliability: " + str.tostring(math.round(q20_pass_res,2)) + "%", style = label.style_label_left, textcolor = purple, color = transp, size = size.large)
if prjplot == "30 Candles"
q30_label := label.new(bar_index + 30, y=plot_input, text = "Projection at 30 Candles \n Range: $" + str.tostring(math.round(q30_lcl,2)) + " to $" + str.tostring(math.round(q30_ucl,2)) + "\n Correlation: " + str.tostring(math.round(q30_cor,2)) + "\n Reliability: " + str.tostring(math.round(q30_pass_res,2)) + "%", style = label.style_label_left, textcolor = purple, color = transp, size = size.large)
if prjplot == "40 Candles"
q40_label := label.new(bar_index + 40, y=plot_input, text = "Projection at 40 Candles \n Range: $" + str.tostring(math.round(q40_lcl,2)) + " to $" + str.tostring(math.round(q40_ucl,2)) + "\n Correlation: " + str.tostring(math.round(q40_cor,2)) + "\n Reliability: " + str.tostring(math.round(q40_pass_res,2)) + "%", style = label.style_label_left, textcolor = purple, color = transp, size = size.large)
if prjplot == "50 Candles"
q50_label := label.new(bar_index + 50, y=plot_input, text = "Projection at 50 Candles \n Range: $" + str.tostring(math.round(q50_lcl,2)) + " to $" + str.tostring(math.round(q50_ucl,2)) + "\n Correlation: " + str.tostring(math.round(q50_cor,2)) + "\n Reliability: " + str.tostring(math.round(q50_pass_res,2)) + "%", style = label.style_label_left, textcolor = purple, color = transp, size = size.large)
if prjplot == "60 Candles"
q60_label := label.new(bar_index + 60, y=plot_input, text = "Projection at 60 Candles \n Range: $" + str.tostring(math.round(q60_lcl,2)) + " to $" + str.tostring(math.round(q60_ucl,2)) + "\n Correlation: " + str.tostring(math.round(q60_cor,2)) + "\n Reliability: " + str.tostring(math.round(q60_pass_res,2)) + "%", style = label.style_label_left, textcolor = purple, color = transp, size = size.large)
if prjplot == "70 Candles"
q70_label := label.new(bar_index + 70, y=plot_input, text = "Projection at 70 Candles \n Range: $" + str.tostring(math.round(q70_lcl,2)) + " to $" + str.tostring(math.round(q70_ucl,2)) + "\n Correlation: " + str.tostring(math.round(q70_cor,2)) + "\n Reliability: " + str.tostring(math.round(q70_pass_res,2)) + "%", style = label.style_label_left, textcolor = purple, color = transp, size = size.large)
if prjplot == "80 Candles"
q80_label := label.new(bar_index + 80, y=plot_input, text = "Projection at 80 Candles \n Range: $" + str.tostring(math.round(q80_lcl,2)) + " to $" + str.tostring(math.round(q80_ucl,2)) + "\n Correlation: " + str.tostring(math.round(q80_cor,2)) + "\n Reliability: " + str.tostring(math.round(q80_pass_res,2)) + "%", style = label.style_label_left, textcolor = purple, color = transp, size = size.large)
if prjplot == "90 Candles"
q90_label := label.new(bar_index + 90, y=plot_input, text = "Projection at 90 Candles \n Range: $" + str.tostring(math.round(q90_lcl,2)) + " to $" + str.tostring(math.round(q90_ucl,2)) + "\n Correlation: " + str.tostring(math.round(q90_cor,2)) + "\n Reliability: " + str.tostring(math.round(q90_pass_res,2)) + "%", style = label.style_label_left, textcolor = purple, color = transp, size = size.large)
if prjplot == "100 Candles"
q100_label := label.new(bar_index + 100, y=plot_input, text = "Projection at 100 Candles \n Range: $" + str.tostring(math.round(q100_lcl,2)) + " to $" + str.tostring(math.round(q100_ucl,2)) + "\n Correlation: " + str.tostring(math.round(q100_cor,2)) + "\n Reliability: " + str.tostring(math.round(q100_pass_res,2)) + "%", style = label.style_label_left, textcolor = purple, color = transp, size = size.large)
f_trend(cor) =>
string res = na
if cor >= 0.5 and cor <= 0.7
res := "Moderate Uptrend"
else if cor > 0.7
res := "Strong Uptrend"
else if cor <= -0.5 and cor >= -0.7
res := "Moderate Downtrend"
else if cor < -0.7
res := "Strong Downtrend"
else
res := "No Clear Trend"
trend_color(cor) =>
if cor >= 0.5 and cor <= 0.7
color.lime
else if cor > 0.7
color.lime
else if cor <= -0.5 and cor >= -0.7
color.red
else if cor < -0.7
color.red
else
color.orange
s_10 = f_trend(q10_cor)
s_20 = f_trend(q20_cor)
s_30 = f_trend(q30_cor)
s_40 = f_trend(q40_cor)
s_50 = f_trend(q50_cor)
s_60 = f_trend(q60_cor)
s_70 = f_trend(q70_cor)
s_80 = f_trend(q80_cor)
s_90 = f_trend(q90_cor)
s_100 = f_trend(q100_cor)
// Trend Table
if distrend and dispchart
table.cell(data, 8, 1, text = "Trend", bgcolor = black, text_color = white)
table.cell(data, 8, 2, text = str.tostring(s_10), bgcolor = black, text_color = trend_color(q10_cor))
table.cell(data, 8, 3, text = str.tostring(s_20), bgcolor = black, text_color = trend_color(q20_cor))
table.cell(data, 8, 4, text = str.tostring(s_30), bgcolor = black, text_color = trend_color(q30_cor))
table.cell(data, 8, 5, text = str.tostring(s_40), bgcolor = black, text_color = trend_color(q40_cor))
table.cell(data, 8, 6, text = str.tostring(s_50), bgcolor = black, text_color = trend_color(q50_cor))
table.cell(data, 8, 7, text = str.tostring(s_60), bgcolor = black, text_color = trend_color(q60_cor))
table.cell(data, 8, 8, text = str.tostring(s_70), bgcolor = black, text_color = trend_color(q70_cor))
table.cell(data, 8, 9, text = str.tostring(s_80), bgcolor = black, text_color = trend_color(q80_cor))
table.cell(data, 8, 10, text = str.tostring(s_90), bgcolor = black, text_color = trend_color(q90_cor))
table.cell(data, 8, 11, text = str.tostring(s_100), bgcolor = black, text_color = trend_color(q100_cor))
|
Hurst Exponent (Dubuc's variation method) | https://www.tradingview.com/script/v7SnbHhU-Hurst-Exponent-Dubuc-s-variation-method/ | and_then_it_CRASHED | https://www.tradingview.com/u/and_then_it_CRASHED/ | 15 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Copyright ©2022 and_then_it_CRASHED.
// This is an implementation of Dubuc's variation method for estimating the Hurst exponent.
// Dubuc B, Quiniou JF, Roques-Carmes C, Tricot C. Evaluating the fractal dimension of profiles. Physical Review A. 1989;39(3):1500-1512. DOI: 10.1103/PhysRevA.39.1500
// https://www.intechopen.com/chapters/64463
//@version=5
library("Hurst")
import lejmer/OrdinaryLeastSquares/2
// @function Estimate the Hurst Exponent using Dubuc's variation method
// @param length The length of the history window to use. Large values do not cause lag.
// @param samples The number of scale samples to take within the window. These samples are then used for regression. The minimum value is 2 but 3+ is recommended. Large values give more accurate results but suffer from a performance penalty.
// @param hi The high value of the series to analyze.
// @param lo The low value of the series to analyze.
export hurst(int length=100, int samples = 5, float hi=high, float lo=low) =>
if length < 2
runtime.error('Dubuc.hurst() window length must be at least 2.')
if samples < 2
runtime.error('Dubuc.hurst() must have at least two samples.')
var x = matrix.new<float>(samples, 2, 1) // the second column is full of 1's for the intercept
var y = array.new<float>(samples)
min_iep = math.exp(-1) // inverse epsilon
max_iep = math.exp(-length)
float base_count = na
string msg = ''
for s = 0 to samples-1
iep = math.log(length) * s / (samples-1)
ep = int(math.exp(iep))
t = ta.highest(hi, 2*ep+1) // neighborhood top
b = ta.lowest(lo, 2*ep+1) // neighborhood bottom
count = 0
area = 0.
for i = 0 to length
if not na(t) and not na(b)
count += 1
area += t - b
if na(base_count) // this will be set on the first window, the smallest, which will have the highest count
base_count := count
area *= base_count / count // normalize areas due to different sample sizes
msg := str.format('{0} {1}=>{2}*{3}/{4}',msg,ep,area,count,base_count)
matrix.set(x, s, 0, math.log(1/ep)) // x value
array.set(y, s, math.log(area/ep/ep))
fit = OrdinaryLeastSquares.solve(x,y)
slope = array.get(fit, 0)
hurst = slope - 1
hurst
length = input.int(100, 'Length', minval = 2, tooltip = 'The window size for analysis. Using a large window does not cause lag and is not detrimental to getting a good measurement.')
samples = input.int(5, 'Samples', minval = 2, tooltip = 'Within the window, this many samples of different "scales" are used for regression. Higher numbers give more accurate results but cause performance delays. At least 3 samples are recommended.')
ind = hurst(length, samples=samples)
plot(ind)
hline(0.5, color=color.new(color.white,70))
|
MACD Bands - Multi Timeframe [TradeMaster Lite] | https://www.tradingview.com/script/gfh8aIiA-MACD-Bands-Multi-Timeframe-TradeMaster-Lite/ | trademasterindicator | https://www.tradingview.com/u/trademasterindicator/ | 352 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Copyright (c) 2023 trademasterindicator. All rights reserved.
// The Pinescript source code ("MACD Bands - Multi Timeframe [TradeMaster Lite]") is exclusively licensed to trademasterindicator TradingView account. No other use is permitted without written consent from trademasterindicator.
// By accessing or using the script, you agree to the following terms:
// Grant of License: You are granted a non-transferable license to use the script for personal, non-commercial purposes related to technical analysis and trading on TradingView.
// Ownership and Intellectual Property: trademasterindicator retains all ownership and intellectual property rights to the script. You may not modify, reverse engineer, or distribute the script.
// Disclaimer of Warranty: The source code is provided as-is, without warranties. trademasterindicator shall not be liable for any damages arising from its use.
// Termination: This license is valid until terminated.
//@version=5
indicator("MACD Bands - Multi Timeframe [TradeMaster Lite]", 'MACD Bands - MTF [TradeMaster Lite]', precision = 3)
// INPUTS \\
i_src = input.source (close, 'Source' , inline = 'src')
i_tf = input.timeframe('' , 'Timeframe', inline = 'src', tooltip = 'Only timeframes higher than the chart timeframe is supported currently. Might get updated in the future.')
i_maType = input.string ('EMA', 'MA Type' , inline = 'ma' , options = ['SMA','SMMA','EMA','DEMA','TEMA','LSMA','HMA','VWMA','WMA'], tooltip = 'Moving average calculation that is used across the script.\n\nThe choices available in our system include:\n● SMA (Simple Moving Average): This calculates the average of a selected range of prices, typically closing prices, by the number of periods in that range.\n● SMMA (Smoothed Moving Average): This takes into account all data available and assigns equal weighting to the prices.\n● EMA (Exponential Moving Average): This places a greater weight and significance on the most recent data points.\n● DEMA (Double Exponential Moving Average): This is a faster-moving average that uses a proprietary calculation to reduce the lag in data points.\n● TEMA (Triple Exponential Moving Average): This is even quicker than the DEMA, helping traders respond more quickly to changes in trend.\n● LSMA (Least Squares Moving Average): This moving average applies least squares regression method to determine the future direction of the trend.\n● HMA (Hull Moving Average): This moving average is designed to reduce lag and improve smoothness, providing quicker signals for short-term market movements. \n● VWMA (Volume Weighted Moving Average): This assigns more weight to candles with a high volume, reflecting the true average price more accurately in high volume periods.\n● WMA (Weighted Moving Average): This assigns more weight to the latest data, but not as much as the EMA.\n\nEach type of moving average offers a unique perspective and can be used in different scenarios to identify market trends.')
i_bbMult = input.float (1 , 'Band mult', inline = 'ma' , minval = 0.1, maxval = 100, step = 0.1)
i_fast = input.int (12 , '' , inline = 'len')
i_slow = input.int (26 , '' , inline = 'len')
i_sign = input.int (9 , '' , inline = 'len')
// OBJECT BLUEPRINT \\
type Macd
float line = na
float sign = na
float hist = na
float top = na
float bot = na
// FUNCTIONS \\
get_sec(tf , exp) => request.security('', tf, exp[1], barmerge.gaps_off, barmerge.lookahead_on)
dema (src, len) => ema = ta.ema(src, len), 2 * ema - ta.ema(ema,len)
tema (src, len) => ema = ta.ema(src, len), ema2 = ta.ema(ema, len), 3 * (ema - ema2) + ta.ema(ema2, len)
get_ma(src, len) =>
switch i_maType
'SMA' => ta.sma (src, len)
'SMMA' => ta.rma (src, len)
'EMA' => ta.ema (src, len)
'DEMA' => dema (src, len)
'TEMA' => tema (src, len)
'LSMA' => ta.linreg(src, len, 0)
'HMA' => ta.hma (src, len)
'VWMA' => ta.vwma (src, len)
'WMA' => ta.wma (src, len)
get_macd() =>
macd = get_ma (i_src, i_fast) - get_ma(i_src, i_slow)
sign = get_ma (macd , i_sign)
deviation = ta.stdev(sign , i_sign) * i_bbMult
Macd.new(macd, sign, macd - sign, sign + deviation, sign - deviation)
// CALCULATION \\ exclued ltf for now, irrelevant and noisy anyways
var color clrHist = na
var isMtf = not na(i_tf) and timeframe.in_seconds(i_tf) > timeframe.in_seconds()
tf_change = isMtf ? timeframe.change(i_tf) : true
macd = get_macd()
macd := isMtf ? get_sec(i_tf, macd) : macd
clrHist := macd.hist > macd.hist[1] ? #00897b83 : macd.hist < macd.hist[1] ? #ff990080 : clrHist
// PLOTS \\
isBull = macd.line > macd.sign
macdline = plot(tf_change ? macd.line : na, 'macdLine', isBull ? #4caf50 : #ff5252)
plot(tf_change ? macd.sign : na, 'signalLine', #ffeb3b)
plot(macd.hist, 'histogram ', clrHist, style = plot.style_columns)
plot(ta.cross(macd.line, macd.sign) ? macd.line : na, 'cross', isBull ? #00897b : #ff9800, 4, plot.style_circles)
bTop = plot(tf_change ? macd.top : na, 'band top', #2196f31a)
bBot = plot(tf_change ? macd.bot : na, 'band bot', #2196f31a)
// FILLS \\
fill(bTop , bBot, #2196f31a , 'Fill band', fillgaps = true)
fill(macdline, bTop, macd.line > macd.top ? #4caf4f7d : na, 'Fill bull', fillgaps = true)
fill(macdline, bBot, macd.line < macd.bot ? #ff525288 : na, 'Fill bear', fillgaps = true)
// a zero line :) \\
hline(0, '0 Line', linestyle = hline.style_dotted, color = color.gray, editable = false) |
NetLiquidityLibrary | https://www.tradingview.com/script/Ev9ue1cv-NetLiquidityLibrary/ | calebsandfort | https://www.tradingview.com/u/calebsandfort/ | 60 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © calebsandfort
//@version=5
// @description The Net Liquidity Library provides daily values for net liquidity. Net liquidity is measured as Fed Balance Sheet - Treasury General Account - Reverse Repo. Time series for each individual component included too.
library("NetLiquidityLibrary", overlay = true)
get_net_liquidity_0(simple string component = "", int ts = 0) =>
float val = switch ts
1624320000000 => component == "fed" ? 8064257000000.0 : component == "tga" ? 744249000000.0 : component == "rrp" ? 791605000000.0 : 6528403000000.0
1624406400000 => component == "fed" ? 8064257000000.0 : component == "tga" ? 744249000000.0 : component == "rrp" ? 813650000000.0 : 6544046000000.0
1624492800000 => component == "fed" ? 8101945000000.0 : component == "tga" ? 733877000000.0 : component == "rrp" ? 813048000000.0 : 6555020000000.0
1624579200000 => component == "fed" ? 8101945000000.0 : component == "tga" ? 723946000000.0 : component == "rrp" ? 770830000000.0 : 6607169000000.0
1624838400000 => component == "fed" ? 8101945000000.0 : component == "tga" ? 733226000000.0 : component == "rrp" ? 803019000000.0 : 6565700000000.0
1624924800000 => component == "fed" ? 8101945000000.0 : component == "tga" ? 734915000000.0 : component == "rrp" ? 841246000000.0 : 6525784000000.0
1625011200000 => component == "fed" ? 8101945000000.0 : component == "tga" ? 711267000000.0 : component == "rrp" ? 991939000000.0 : 6375338000000.0
1625097600000 => component == "fed" ? 8078544000000.0 : component == "tga" ? 851929000000.0 : component == "rrp" ? 742647000000.0 : 6483968000000.0
1625184000000 => component == "fed" ? 8078544000000.0 : component == "tga" ? 784035000000.0 : component == "rrp" ? 731504000000.0 : 6563005000000.0
1625529600000 => component == "fed" ? 8078544000000.0 : component == "tga" ? 757682000000.0 : component == "rrp" ? 772581000000.0 : 6548281000000.0
1625616000000 => component == "fed" ? 8078544000000.0 : component == "tga" ? 733889000000.0 : component == "rrp" ? 785720000000.0 : 6578164000000.0
1625702400000 => component == "fed" ? 8097773000000.0 : component == "tga" ? 724898000000.0 : component == "rrp" ? 793399000000.0 : 6579476000000.0
1625788800000 => component == "fed" ? 8097773000000.0 : component == "tga" ? 727336000000.0 : component == "rrp" ? 780596000000.0 : 6589841000000.0
1626048000000 => component == "fed" ? 8097773000000.0 : component == "tga" ? 718092000000.0 : component == "rrp" ? 776472000000.0 : 6603209000000.0
1626134400000 => component == "fed" ? 8097773000000.0 : component == "tga" ? 718474000000.0 : component == "rrp" ? 798267000000.0 : 6581032000000.0
1626220800000 => component == "fed" ? 8097773000000.0 : component == "tga" ? 676800000000.0 : component == "rrp" ? 859975000000.0 : 6664876000000.0
1626307200000 => component == "fed" ? 8201651000000.0 : component == "tga" ? 657542000000.0 : component == "rrp" ? 776261000000.0 : 6767848000000.0
1626393600000 => component == "fed" ? 8201651000000.0 : component == "tga" ? 690107000000.0 : component == "rrp" ? 817566000000.0 : 6693978000000.0
1626652800000 => component == "fed" ? 8201651000000.0 : component == "tga" ? 697581000000.0 : component == "rrp" ? 860468000000.0 : 6643602000000.0
1626739200000 => component == "fed" ? 8201651000000.0 : component == "tga" ? 700041000000.0 : component == "rrp" ? 848102000000.0 : 6653508000000.0
1626825600000 => component == "fed" ? 8201651000000.0 : component == "tga" ? 647533000000.0 : component == "rrp" ? 886206000000.0 : 6706791000000.0
1626912000000 => component == "fed" ? 8240530000000.0 : component == "tga" ? 616294000000.0 : component == "rrp" ? 898197000000.0 : 6726039000000.0
1626998400000 => component == "fed" ? 8240530000000.0 : component == "tga" ? 590042000000.0 : component == "rrp" ? 877251000000.0 : 6773237000000.0
1627257600000 => component == "fed" ? 8240530000000.0 : component == "tga" ? 588083000000.0 : component == "rrp" ? 891203000000.0 : 6761244000000.0
1627344000000 => component == "fed" ? 8240530000000.0 : component == "tga" ? 591368000000.0 : component == "rrp" ? 927419000000.0 : 6721743000000.0
1627430400000 => component == "fed" ? 8240530000000.0 : component == "tga" ? 564799000000.0 : component == "rrp" ? 965189000000.0 : 6691485000000.0
1627516800000 => component == "fed" ? 8221473000000.0 : component == "tga" ? 536966000000.0 : component == "rrp" ? 987283000000.0 : 6697224000000.0
1627603200000 => component == "fed" ? 8221473000000.0 : component == "tga" ? 501179000000.0 : component == "rrp" ? 1039394000000.0 : 6680900000000.0
1627862400000 => component == "fed" ? 8221473000000.0 : component == "tga" ? 459402000000.0 : component == "rrp" ? 921317000000.0 : 6840754000000.0
1627948800000 => component == "fed" ? 8221473000000.0 : component == "tga" ? 555569000000.0 : component == "rrp" ? 909442000000.0 : 6756462000000.0
1628035200000 => component == "fed" ? 8221473000000.0 : component == "tga" ? 507848000000.0 : component == "rrp" ? 931755000000.0 : 6795470000000.0
1628121600000 => component == "fed" ? 8235073000000.0 : component == "tga" ? 505871000000.0 : component == "rrp" ? 944335000000.0 : 6784867000000.0
1628208000000 => component == "fed" ? 8235073000000.0 : component == "tga" ? 466601000000.0 : component == "rrp" ? 952134000000.0 : 6816338000000.0
1628467200000 => component == "fed" ? 8235073000000.0 : component == "tga" ? 442557000000.0 : component == "rrp" ? 981765000000.0 : 6810751000000.0
1628553600000 => component == "fed" ? 8235073000000.0 : component == "tga" ? 444212000000.0 : component == "rrp" ? 998654000000.0 : 6792207000000.0
1628640000000 => component == "fed" ? 8235073000000.0 : component == "tga" ? 416199000000.0 : component == "rrp" ? 1000460000000.0 : 6840500000000.0
1628726400000 => component == "fed" ? 8257159000000.0 : component == "tga" ? 389747000000.0 : component == "rrp" ? 1087342000000.0 : 6780070000000.0
1628812800000 => component == "fed" ? 8257159000000.0 : component == "tga" ? 351572000000.0 : component == "rrp" ? 1050941000000.0 : 6854646000000.0
1629072000000 => component == "fed" ? 8257159000000.0 : component == "tga" ? 335190000000.0 : component == "rrp" ? 1036418000000.0 : 6885551000000.0
1629158400000 => component == "fed" ? 8257159000000.0 : component == "tga" ? 362012000000.0 : component == "rrp" ? 1053454000000.0 : 6841693000000.0
1629244800000 => component == "fed" ? 8257159000000.0 : component == "tga" ? 338853000000.0 : component == "rrp" ? 1115656000000.0 : 6888089000000.0
1629331200000 => component == "fed" ? 8342598000000.0 : component == "tga" ? 313651000000.0 : component == "rrp" ? 1109938000000.0 : 6919009000000.0
1629417600000 => component == "fed" ? 8342598000000.0 : component == "tga" ? 321137000000.0 : component == "rrp" ? 1111905000000.0 : 6909556000000.0
1629676800000 => component == "fed" ? 8342598000000.0 : component == "tga" ? 309820000000.0 : component == "rrp" ? 1135697000000.0 : 6897081000000.0
1629763200000 => component == "fed" ? 8342598000000.0 : component == "tga" ? 317103000000.0 : component == "rrp" ? 1129737000000.0 : 6895758000000.0
1629849600000 => component == "fed" ? 8342598000000.0 : component == "tga" ? 284110000000.0 : component == "rrp" ? 1147089000000.0 : 6901544000000.0
1629936000000 => component == "fed" ? 8332743000000.0 : component == "tga" ? 258200000000.0 : component == "rrp" ? 1091792000000.0 : 6982751000000.0
1630022400000 => component == "fed" ? 8332743000000.0 : component == "tga" ? 239304000000.0 : component == "rrp" ? 1120015000000.0 : 6973424000000.0
1630281600000 => component == "fed" ? 8332743000000.0 : component == "tga" ? 262811000000.0 : component == "rrp" ? 1140711000000.0 : 6929221000000.0
1630368000000 => component == "fed" ? 8332743000000.0 : component == "tga" ? 262895000000.0 : component == "rrp" ? 1189616000000.0 : 6880232000000.0
1630454400000 => component == "fed" ? 8332743000000.0 : component == "tga" ? 355984000000.0 : component == "rrp" ? 1084115000000.0 : 6909074000000.0
1630540800000 => component == "fed" ? 8349173000000.0 : component == "tga" ? 296934000000.0 : component == "rrp" ? 1066987000000.0 : 6985252000000.0
1630627200000 => component == "fed" ? 8349173000000.0 : component == "tga" ? 292163000000.0 : component == "rrp" ? 1074707000000.0 : 6982303000000.0
1630972800000 => component == "fed" ? 8349173000000.0 : component == "tga" ? 262488000000.0 : component == "rrp" ? 1079945000000.0 : 7006740000000.0
1631059200000 => component == "fed" ? 8349173000000.0 : component == "tga" ? 231654000000.0 : component == "rrp" ? 1115229000000.0 : 7010431000000.0
1631145600000 => component == "fed" ? 8357314000000.0 : component == "tga" ? 200702000000.0 : component == "rrp" ? 1107659000000.0 : 7048953000000.0
1631232000000 => component == "fed" ? 8357314000000.0 : component == "tga" ? 207218000000.0 : component == "rrp" ? 1099323000000.0 : 7050773000000.0
1631491200000 => component == "fed" ? 8357314000000.0 : component == "tga" ? 208035000000.0 : component == "rrp" ? 1087108000000.0 : 7062171000000.0
1631577600000 => component == "fed" ? 8357314000000.0 : component == "tga" ? 225075000000.0 : component == "rrp" ? 1169280000000.0 : 6962959000000.0
1631664000000 => component == "fed" ? 8357314000000.0 : component == "tga" ? 211227000000.0 : component == "rrp" ? 1081342000000.0 : 7156201000000.0
1631750400000 => component == "fed" ? 8448770000000.0 : component == "tga" ? 344668000000.0 : component == "rrp" ? 1147494000000.0 : 6956608000000.0
1631836800000 => component == "fed" ? 8448770000000.0 : component == "tga" ? 317970000000.0 : component == "rrp" ? 1218303000000.0 : 6912497000000.0
1632096000000 => component == "fed" ? 8448770000000.0 : component == "tga" ? 315003000000.0 : component == "rrp" ? 1224289000000.0 : 6909478000000.0
1632182400000 => component == "fed" ? 8448770000000.0 : component == "tga" ? 324877000000.0 : component == "rrp" ? 1240494000000.0 : 6883399000000.0
1632268800000 => component == "fed" ? 8448770000000.0 : component == "tga" ? 295620000000.0 : component == "rrp" ? 1283281000000.0 : 6910923000000.0
1632355200000 => component == "fed" ? 8489824000000.0 : component == "tga" ? 272679000000.0 : component == "rrp" ? 1352483000000.0 : 6864662000000.0
1632441600000 => component == "fed" ? 8489824000000.0 : component == "tga" ? 173922000000.0 : component == "rrp" ? 1313657000000.0 : 7002245000000.0
1632700800000 => component == "fed" ? 8489824000000.0 : component == "tga" ? 215533000000.0 : component == "rrp" ? 1297050000000.0 : 6977241000000.0
1632787200000 => component == "fed" ? 8489824000000.0 : component == "tga" ? 217019000000.0 : component == "rrp" ? 1365185000000.0 : 6907620000000.0
1632873600000 => component == "fed" ? 8489824000000.0 : component == "tga" ? 172920000000.0 : component == "rrp" ? 1415840000000.0 : 6859221000000.0
1632960000000 => component == "fed" ? 8447981000000.0 : component == "tga" ? 173745000000.0 : component == "rrp" ? 1604881000000.0 : 6669355000000.0
1633046400000 => component == "fed" ? 8447981000000.0 : component == "tga" ? 215160000000.0 : component == "rrp" ? 1385991000000.0 : 6846830000000.0
1633305600000 => component == "fed" ? 8447981000000.0 : component == "tga" ? 132452000000.0 : component == "rrp" ? 1399173000000.0 : 6916356000000.0
1633392000000 => component == "fed" ? 8447981000000.0 : component == "tga" ? 141318000000.0 : component == "rrp" ? 1431180000000.0 : 6875483000000.0
1633478400000 => component == "fed" ? 8447981000000.0 : component == "tga" ? 99385000000.0 : component == "rrp" ? 1451175000000.0 : 6913472000000.0
1633564800000 => component == "fed" ? 8464032000000.0 : component == "tga" ? 95854000000.0 : component == "rrp" ? 1375863000000.0 : 6992315000000.0
1633651200000 => component == "fed" ? 8464032000000.0 : component == "tga" ? 86339000000.0 : component == "rrp" ? 1371958000000.0 : 7005735000000.0
1633910400000 => component == "fed" ? 8464032000000.0 : component == "tga" ? 81803000000.0 : component == "rrp" ? 1371958000000.0 : 7010271000000.0
1633996800000 => component == "fed" ? 8464032000000.0 : component == "tga" ? 81803000000.0 : component == "rrp" ? 1367051000000.0 : 7015178000000.0
1634083200000 => component == "fed" ? 8464032000000.0 : component == "tga" ? 58993000000.0 : component == "rrp" ? 1364701000000.0 : 7057248000000.0
1634169600000 => component == "fed" ? 8480942000000.0 : component == "tga" ? 72460000000.0 : component == "rrp" ? 1445660000000.0 : 6962822000000.0
1634256000000 => component == "fed" ? 8480942000000.0 : component == "tga" ? 46508000000.0 : component == "rrp" ? 1462297000000.0 : 6972137000000.0
1634515200000 => component == "fed" ? 8480942000000.0 : component == "tga" ? 50846000000.0 : component == "rrp" ? 1477114000000.0 : 6952982000000.0
1634601600000 => component == "fed" ? 8480942000000.0 : component == "tga" ? 134768000000.0 : component == "rrp" ? 1470739000000.0 : 6875435000000.0
1634688000000 => component == "fed" ? 8480942000000.0 : component == "tga" ? 132525000000.0 : component == "rrp" ? 1493961000000.0 : 6938457000000.0
1634774400000 => component == "fed" ? 8564943000000.0 : component == "tga" ? 117364000000.0 : component == "rrp" ? 1458605000000.0 : 6988974000000.0
1634860800000 => component == "fed" ? 8564943000000.0 : component == "tga" ? 149154000000.0 : component == "rrp" ? 1403020000000.0 : 7012769000000.0
1635120000000 => component == "fed" ? 8564943000000.0 : component == "tga" ? 208815000000.0 : component == "rrp" ? 1413188000000.0 : 6942940000000.0
1635206400000 => component == "fed" ? 8564943000000.0 : component == "tga" ? 219868000000.0 : component == "rrp" ? 1423198000000.0 : 6921877000000.0
1635292800000 => component == "fed" ? 8564943000000.0 : component == "tga" ? 261071000000.0 : component == "rrp" ? 1433370000000.0 : 6861740000000.0
1635379200000 => component == "fed" ? 8556181000000.0 : component == "tga" ? 236495000000.0 : component == "rrp" ? 1384684000000.0 : 6935002000000.0
1635465600000 => component == "fed" ? 8556181000000.0 : component == "tga" ? 259761000000.0 : component == "rrp" ? 1502296000000.0 : 6794124000000.0
1635724800000 => component == "fed" ? 8556181000000.0 : component == "tga" ? 278023000000.0 : component == "rrp" ? 1358606000000.0 : 6919552000000.0
1635811200000 => component == "fed" ? 8556181000000.0 : component == "tga" ? 269343000000.0 : component == "rrp" ? 1329913000000.0 : 6956925000000.0
1635897600000 => component == "fed" ? 8556181000000.0 : component == "tga" ? 311302000000.0 : component == "rrp" ? 1343985000000.0 : 6919584000000.0
1635984000000 => component == "fed" ? 8574871000000.0 : component == "tga" ? 286959000000.0 : component == "rrp" ? 1348539000000.0 : 6939373000000.0
1636070400000 => component == "fed" ? 8574871000000.0 : component == "tga" ? 268350000000.0 : component == "rrp" ? 1354059000000.0 : 6952462000000.0
1636329600000 => component == "fed" ? 8574871000000.0 : component == "tga" ? 263023000000.0 : component == "rrp" ? 1354382000000.0 : 6957466000000.0
1636416000000 => component == "fed" ? 8574871000000.0 : component == "tga" ? 270273000000.0 : component == "rrp" ? 1377197000000.0 : 6927401000000.0
1636502400000 => component == "fed" ? 8574871000000.0 : component == "tga" ? 255937000000.0 : component == "rrp" ? 1448623000000.0 : 6958557000000.0
=>
float(na)
val
get_net_liquidity_1(simple string component = "", int ts = 0) =>
float val = switch ts
1636588800000 => component == "fed" ? 8663117000000.0 : component == "tga" ? 231421000000.0 : component == "rrp" ? 1448623000000.0 : 6983073000000.0
1636675200000 => component == "fed" ? 8663117000000.0 : component == "tga" ? 231421000000.0 : component == "rrp" ? 1417643000000.0 : 7014053000000.0
1636934400000 => component == "fed" ? 8663117000000.0 : component == "tga" ? 219793000000.0 : component == "rrp" ? 1391657000000.0 : 7051667000000.0
1637020800000 => component == "fed" ? 8663117000000.0 : component == "tga" ? 211700000000.0 : component == "rrp" ? 1466857000000.0 : 6984560000000.0
1637107200000 => component == "fed" ? 8663117000000.0 : component == "tga" ? 198696000000.0 : component == "rrp" ? 1520000000000.0 : 6956274000000.0
1637193600000 => component == "fed" ? 8674970000000.0 : component == "tga" ? 178972000000.0 : component == "rrp" ? 1584097000000.0 : 6911901000000.0
1637280000000 => component == "fed" ? 8674970000000.0 : component == "tga" ? 168229000000.0 : component == "rrp" ? 1575384000000.0 : 6931357000000.0
1637539200000 => component == "fed" ? 8674970000000.0 : component == "tga" ? 170311000000.0 : component == "rrp" ? 1573769000000.0 : 6930890000000.0
1637625600000 => component == "fed" ? 8674970000000.0 : component == "tga" ? 163242000000.0 : component == "rrp" ? 1571980000000.0 : 6939748000000.0
1637712000000 => component == "fed" ? 8674970000000.0 : component == "tga" ? 165160000000.0 : component == "rrp" ? 1452897000000.0 : 7063714000000.0
1637884800000 => component == "fed" ? 8681771000000.0 : component == "tga" ? 141042000000.0 : component == "rrp" ? 1451108000000.0 : 7089621000000.0
1638144000000 => component == "fed" ? 8681771000000.0 : component == "tga" ? 137091000000.0 : component == "rrp" ? 1459339000000.0 : 7085341000000.0
1638230400000 => component == "fed" ? 8681771000000.0 : component == "tga" ? 143941000000.0 : component == "rrp" ? 1517956000000.0 : 7019874000000.0
1638316800000 => component == "fed" ? 8681771000000.0 : component == "tga" ? 213153000000.0 : component == "rrp" ? 1427347000000.0 : 7009902000000.0
1638403200000 => component == "fed" ? 8650402000000.0 : component == "tga" ? 159148000000.0 : component == "rrp" ? 1448585000000.0 : 7042669000000.0
1638489600000 => component == "fed" ? 8650402000000.0 : component == "tga" ? 125195000000.0 : component == "rrp" ? 1475464000000.0 : 7049743000000.0
1638748800000 => component == "fed" ? 8650402000000.0 : component == "tga" ? 101192000000.0 : component == "rrp" ? 1487996000000.0 : 7061214000000.0
1638835200000 => component == "fed" ? 8650402000000.0 : component == "tga" ? 106980000000.0 : component == "rrp" ? 1455038000000.0 : 7088384000000.0
1638921600000 => component == "fed" ? 8650402000000.0 : component == "tga" ? 144924000000.0 : component == "rrp" ? 1484192000000.0 : 7035408000000.0
1639008000000 => component == "fed" ? 8664524000000.0 : component == "tga" ? 125144000000.0 : component == "rrp" ? 1500027000000.0 : 7039353000000.0
1639094400000 => component == "fed" ? 8664524000000.0 : component == "tga" ? 118145000000.0 : component == "rrp" ? 1507147000000.0 : 7039232000000.0
1639353600000 => component == "fed" ? 8664524000000.0 : component == "tga" ? 114680000000.0 : component == "rrp" ? 1599768000000.0 : 6950076000000.0
1639440000000 => component == "fed" ? 8664524000000.0 : component == "tga" ? 133605000000.0 : component == "rrp" ? 1584488000000.0 : 6946431000000.0
1639526400000 => component == "fed" ? 8664524000000.0 : component == "tga" ? 79505000000.0 : component == "rrp" ? 1621097000000.0 : 7056064000000.0
1639612800000 => component == "fed" ? 8756666000000.0 : component == "tga" ? 58294000000.0 : component == "rrp" ? 1657626000000.0 : 7040746000000.0
1639699200000 => component == "fed" ? 8756666000000.0 : component == "tga" ? 42111000000.0 : component == "rrp" ? 1704586000000.0 : 7009969000000.0
1639958400000 => component == "fed" ? 8756666000000.0 : component == "tga" ? 47877000000.0 : component == "rrp" ? 1758041000000.0 : 6950748000000.0
1640044800000 => component == "fed" ? 8756666000000.0 : component == "tga" ? 64905000000.0 : component == "rrp" ? 1748285000000.0 : 6943476000000.0
1640131200000 => component == "fed" ? 8756666000000.0 : component == "tga" ? 146518000000.0 : component == "rrp" ? 1699277000000.0 : 6944700000000.0
1640217600000 => component == "fed" ? 8790495000000.0 : component == "tga" ? 197516000000.0 : component == "rrp" ? 1577780000000.0 : 7015199000000.0
1640563200000 => component == "fed" ? 8790495000000.0 : component == "tga" ? 176914000000.0 : component == "rrp" ? 1580347000000.0 : 7033234000000.0
1640649600000 => component == "fed" ? 8790495000000.0 : component == "tga" ? 202813000000.0 : component == "rrp" ? 1637064000000.0 : 6950618000000.0
1640736000000 => component == "fed" ? 8790495000000.0 : component == "tga" ? 268208000000.0 : component == "rrp" ? 1642506000000.0 : 6846746000000.0
1640822400000 => component == "fed" ? 8757460000000.0 : component == "tga" ? 283995000000.0 : component == "rrp" ? 1696476000000.0 : 6776989000000.0
1640908800000 => component == "fed" ? 8757460000000.0 : component == "tga" ? 284174000000.0 : component == "rrp" ? 1904582000000.0 : 6568704000000.0
1641168000000 => component == "fed" ? 8757460000000.0 : component == "tga" ? 406108000000.0 : component == "rrp" ? 1579526000000.0 : 6771826000000.0
1641254400000 => component == "fed" ? 8757460000000.0 : component == "tga" ? 366304000000.0 : component == "rrp" ? 1495692000000.0 : 6895464000000.0
1641340800000 => component == "fed" ? 8757460000000.0 : component == "tga" ? 424696000000.0 : component == "rrp" ? 1492787000000.0 : 6848238000000.0
1641427200000 => component == "fed" ? 8765721000000.0 : component == "tga" ? 434757000000.0 : component == "rrp" ? 1510553000000.0 : 6820411000000.0
1641513600000 => component == "fed" ? 8765721000000.0 : component == "tga" ? 440561000000.0 : component == "rrp" ? 1530096000000.0 : 6795064000000.0
1641772800000 => component == "fed" ? 8765721000000.0 : component == "tga" ? 436443000000.0 : component == "rrp" ? 1560421000000.0 : 6768857000000.0
1641859200000 => component == "fed" ? 8765721000000.0 : component == "tga" ? 447887000000.0 : component == "rrp" ? 1527020000000.0 : 6790814000000.0
1641945600000 => component == "fed" ? 8765721000000.0 : component == "tga" ? 507352000000.0 : component == "rrp" ? 1536981000000.0 : 6743945000000.0
1642032000000 => component == "fed" ? 8788278000000.0 : component == "tga" ? 489679000000.0 : component == "rrp" ? 1636742000000.0 : 6661857000000.0
1642118400000 => component == "fed" ? 8788278000000.0 : component == "tga" ? 441135000000.0 : component == "rrp" ? 1598887000000.0 : 6748256000000.0
1642464000000 => component == "fed" ? 8788278000000.0 : component == "tga" ? 453239000000.0 : component == "rrp" ? 1597137000000.0 : 6737902000000.0
1642550400000 => component == "fed" ? 8788278000000.0 : component == "tga" ? 586619000000.0 : component == "rrp" ? 1656576000000.0 : 6624639000000.0
1642636800000 => component == "fed" ? 8867834000000.0 : component == "tga" ? 580171000000.0 : component == "rrp" ? 1678931000000.0 : 6608732000000.0
1642723200000 => component == "fed" ? 8867834000000.0 : component == "tga" ? 601115000000.0 : component == "rrp" ? 1706127000000.0 : 6560592000000.0
1642982400000 => component == "fed" ? 8867834000000.0 : component == "tga" ? 598929000000.0 : component == "rrp" ? 1614002000000.0 : 6654903000000.0
1643068800000 => component == "fed" ? 8867834000000.0 : component == "tga" ? 619699000000.0 : component == "rrp" ? 1599502000000.0 : 6648633000000.0
1643155200000 => component == "fed" ? 8867834000000.0 : component == "tga" ? 646920000000.0 : component == "rrp" ? 1613046000000.0 : 6600519000000.0
1643241600000 => component == "fed" ? 8860485000000.0 : component == "tga" ? 639620000000.0 : component == "rrp" ? 1583895000000.0 : 6636970000000.0
1643328000000 => component == "fed" ? 8860485000000.0 : component == "tga" ? 641597000000.0 : component == "rrp" ? 1615021000000.0 : 6603867000000.0
1643587200000 => component == "fed" ? 8860485000000.0 : component == "tga" ? 642334000000.0 : component == "rrp" ? 1654850000000.0 : 6563301000000.0
1643673600000 => component == "fed" ? 8860485000000.0 : component == "tga" ? 742843000000.0 : component == "rrp" ? 1584109000000.0 : 6533533000000.0
1643760000000 => component == "fed" ? 8860485000000.0 : component == "tga" ? 708705000000.0 : component == "rrp" ? 1626895000000.0 : 6537611000000.0
1643846400000 => component == "fed" ? 8873211000000.0 : component == "tga" ? 710267000000.0 : component == "rrp" ? 1640397000000.0 : 6522547000000.0
1643932800000 => component == "fed" ? 8873211000000.0 : component == "tga" ? 684721000000.0 : component == "rrp" ? 1642892000000.0 : 6545598000000.0
1644192000000 => component == "fed" ? 8873211000000.0 : component == "tga" ? 682002000000.0 : component == "rrp" ? 1679932000000.0 : 6511277000000.0
1644278400000 => component == "fed" ? 8873211000000.0 : component == "tga" ? 691711000000.0 : component == "rrp" ? 1674610000000.0 : 6506890000000.0
1644364800000 => component == "fed" ? 8873211000000.0 : component == "tga" ? 703228000000.0 : component == "rrp" ? 1653153000000.0 : 6521628000000.0
1644451200000 => component == "fed" ? 8878009000000.0 : component == "tga" ? 679019000000.0 : component == "rrp" ? 1634146000000.0 : 6564844000000.0
1644537600000 => component == "fed" ? 8878009000000.0 : component == "tga" ? 672004000000.0 : component == "rrp" ? 1635826000000.0 : 6570179000000.0
1644796800000 => component == "fed" ? 8878009000000.0 : component == "tga" ? 682930000000.0 : component == "rrp" ? 1666232000000.0 : 6528847000000.0
1644883200000 => component == "fed" ? 8878009000000.0 : component == "tga" ? 699135000000.0 : component == "rrp" ? 1608494000000.0 : 6570380000000.0
1644969600000 => component == "fed" ? 8878009000000.0 : component == "tga" ? 718597000000.0 : component == "rrp" ? 1644134000000.0 : 6548302000000.0
1645056000000 => component == "fed" ? 8911033000000.0 : component == "tga" ? 709261000000.0 : component == "rrp" ? 1647202000000.0 : 6554570000000.0
1645142400000 => component == "fed" ? 8911033000000.0 : component == "tga" ? 705359000000.0 : component == "rrp" ? 1674929000000.0 : 6530745000000.0
1645488000000 => component == "fed" ? 8911033000000.0 : component == "tga" ? 702252000000.0 : component == "rrp" ? 1699432000000.0 : 6509349000000.0
1645574400000 => component == "fed" ? 8911033000000.0 : component == "tga" ? 695704000000.0 : component == "rrp" ? 1738322000000.0 : 6494103000000.0
1645660800000 => component == "fed" ? 8928129000000.0 : component == "tga" ? 674797000000.0 : component == "rrp" ? 1650399000000.0 : 6602933000000.0
1645747200000 => component == "fed" ? 8928129000000.0 : component == "tga" ? 640342000000.0 : component == "rrp" ? 1603349000000.0 : 6684438000000.0
1646006400000 => component == "fed" ? 8928129000000.0 : component == "tga" ? 661184000000.0 : component == "rrp" ? 1596052000000.0 : 6670893000000.0
1646092800000 => component == "fed" ? 8928129000000.0 : component == "tga" ? 771264000000.0 : component == "rrp" ? 1552950000000.0 : 6603915000000.0
1646179200000 => component == "fed" ? 8928129000000.0 : component == "tga" ? 699674000000.0 : component == "rrp" ? 1526211000000.0 : 6678570000000.0
1646265600000 => component == "fed" ? 8904455000000.0 : component == "tga" ? 685491000000.0 : component == "rrp" ? 1533992000000.0 : 6684972000000.0
1646352000000 => component == "fed" ? 8904455000000.0 : component == "tga" ? 661486000000.0 : component == "rrp" ? 1483061000000.0 : 6759908000000.0
1646611200000 => component == "fed" ? 8904455000000.0 : component == "tga" ? 658241000000.0 : component == "rrp" ? 1461227000000.0 : 6784987000000.0
1646697600000 => component == "fed" ? 8904455000000.0 : component == "tga" ? 673387000000.0 : component == "rrp" ? 1525099000000.0 : 6705969000000.0
1646784000000 => component == "fed" ? 8904455000000.0 : component == "tga" ? 645312000000.0 : component == "rrp" ? 1542504000000.0 : 6722932000000.0
1646870400000 => component == "fed" ? 8910748000000.0 : component == "tga" ? 609369000000.0 : component == "rrp" ? 1568735000000.0 : 6732644000000.0
1646956800000 => component == "fed" ? 8910748000000.0 : component == "tga" ? 541965000000.0 : component == "rrp" ? 1557823000000.0 : 6810960000000.0
1647216000000 => component == "fed" ? 8910748000000.0 : component == "tga" ? 544592000000.0 : component == "rrp" ? 1608021000000.0 : 6758135000000.0
1647302400000 => component == "fed" ? 8910748000000.0 : component == "tga" ? 567360000000.0 : component == "rrp" ? 1583471000000.0 : 6759917000000.0
1647388800000 => component == "fed" ? 8910748000000.0 : component == "tga" ? 629614000000.0 : component == "rrp" ? 1613637000000.0 : 6711055000000.0
1647475200000 => component == "fed" ? 8954306000000.0 : component == "tga" ? 621527000000.0 : component == "rrp" ? 1659977000000.0 : 6672802000000.0
1647561600000 => component == "fed" ? 8954306000000.0 : component == "tga" ? 624216000000.0 : component == "rrp" ? 1715148000000.0 : 6614942000000.0
1647820800000 => component == "fed" ? 8954306000000.0 : component == "tga" ? 622418000000.0 : component == "rrp" ? 1728893000000.0 : 6602995000000.0
1647907200000 => component == "fed" ? 8954306000000.0 : component == "tga" ? 626636000000.0 : component == "rrp" ? 1763183000000.0 : 6564487000000.0
1647993600000 => component == "fed" ? 8954306000000.0 : component == "tga" ? 607762000000.0 : component == "rrp" ? 1803186000000.0 : 6551526000000.0
1648080000000 => component == "fed" ? 8962474000000.0 : component == "tga" ? 576442000000.0 : component == "rrp" ? 1707655000000.0 : 6678377000000.0
1648166400000 => component == "fed" ? 8962474000000.0 : component == "tga" ? 563796000000.0 : component == "rrp" ? 1676974000000.0 : 6721704000000.0
1648425600000 => component == "fed" ? 8962474000000.0 : component == "tga" ? 582578000000.0 : component == "rrp" ? 1688632000000.0 : 6691264000000.0
1648512000000 => component == "fed" ? 8962474000000.0 : component == "tga" ? 596168000000.0 : component == "rrp" ? 1718870000000.0 : 6647436000000.0
1648598400000 => component == "fed" ? 8962474000000.0 : component == "tga" ? 560968000000.0 : component == "rrp" ? 1785939000000.0 : 6590235000000.0
1648684800000 => component == "fed" ? 8937142000000.0 : component == "tga" ? 556791000000.0 : component == "rrp" ? 1871970000000.0 : 6508381000000.0
1648771200000 => component == "fed" ? 8937142000000.0 : component == "tga" ? 651523000000.0 : component == "rrp" ? 1666063000000.0 : 6619556000000.0
1649030400000 => component == "fed" ? 8937142000000.0 : component == "tga" ? 567423000000.0 : component == "rrp" ? 1692936000000.0 : 6676783000000.0
1649116800000 => component == "fed" ? 8937142000000.0 : component == "tga" ? 579607000000.0 : component == "rrp" ? 1710834000000.0 : 6646701000000.0
=>
float(na)
val
get_net_liquidity_2(simple string component = "", int ts = 0) =>
float val = switch ts
1649203200000 => component == "fed" ? 8937142000000.0 : component == "tga" ? 542176000000.0 : component == "rrp" ? 1731472000000.0 : 6663944000000.0
1649289600000 => component == "fed" ? 8937592000000.0 : component == "tga" ? 545584000000.0 : component == "rrp" ? 1734424000000.0 : 6657584000000.0
1649376000000 => component == "fed" ? 8937592000000.0 : component == "tga" ? 542946000000.0 : component == "rrp" ? 1750498000000.0 : 6644148000000.0
1649635200000 => component == "fed" ? 8937592000000.0 : component == "tga" ? 544736000000.0 : component == "rrp" ? 1758958000000.0 : 6633898000000.0
1649721600000 => component == "fed" ? 8937592000000.0 : component == "tga" ? 564856000000.0 : component == "rrp" ? 1710414000000.0 : 6662322000000.0
1649808000000 => component == "fed" ? 8937592000000.0 : component == "tga" ? 545611000000.0 : component == "rrp" ? 1815555000000.0 : 6604321000000.0
1649894400000 => component == "fed" ? 8965487000000.0 : component == "tga" ? 543536000000.0 : component == "rrp" ? 1706935000000.0 : 6715016000000.0
1650240000000 => component == "fed" ? 8965487000000.0 : component == "tga" ? 602292000000.0 : component == "rrp" ? 1738379000000.0 : 6624816000000.0
1650326400000 => component == "fed" ? 8965487000000.0 : component == "tga" ? 841253000000.0 : component == "rrp" ? 1817292000000.0 : 6306942000000.0
1650412800000 => component == "fed" ? 8965487000000.0 : component == "tga" ? 893351000000.0 : component == "rrp" ? 1866560000000.0 : 6195940000000.0
1650499200000 => component == "fed" ? 8955851000000.0 : component == "tga" ? 907526000000.0 : component == "rrp" ? 1854700000000.0 : 6193625000000.0
1650585600000 => component == "fed" ? 8955851000000.0 : component == "tga" ? 918877000000.0 : component == "rrp" ? 1765031000000.0 : 6271943000000.0
1650844800000 => component == "fed" ? 8955851000000.0 : component == "tga" ? 934238000000.0 : component == "rrp" ? 1783609000000.0 : 6238004000000.0
1650931200000 => component == "fed" ? 8955851000000.0 : component == "tga" ? 958291000000.0 : component == "rrp" ? 1819343000000.0 : 6178217000000.0
1651017600000 => component == "fed" ? 8955851000000.0 : component == "tga" ? 972993000000.0 : component == "rrp" ? 1803162000000.0 : 6163044000000.0
1651104000000 => component == "fed" ? 8939199000000.0 : component == "tga" ? 957419000000.0 : component == "rrp" ? 1818416000000.0 : 6163364000000.0
1651190400000 => component == "fed" ? 8939199000000.0 : component == "tga" ? 953933000000.0 : component == "rrp" ? 1906802000000.0 : 6078464000000.0
1651449600000 => component == "fed" ? 8939199000000.0 : component == "tga" ? 923240000000.0 : component == "rrp" ? 1796302000000.0 : 6219657000000.0
1651536000000 => component == "fed" ? 8939199000000.0 : component == "tga" ? 975018000000.0 : component == "rrp" ? 1796252000000.0 : 6167929000000.0
1651622400000 => component == "fed" ? 8939199000000.0 : component == "tga" ? 955262000000.0 : component == "rrp" ? 1815656000000.0 : 6169054000000.0
1651708800000 => component == "fed" ? 8939972000000.0 : component == "tga" ? 964412000000.0 : component == "rrp" ? 1844762000000.0 : 6130798000000.0
1651795200000 => component == "fed" ? 8939972000000.0 : component == "tga" ? 943481000000.0 : component == "rrp" ? 1861866000000.0 : 6134625000000.0
1652054400000 => component == "fed" ? 8939972000000.0 : component == "tga" ? 950700000000.0 : component == "rrp" ? 1858995000000.0 : 6130277000000.0
1652140800000 => component == "fed" ? 8939972000000.0 : component == "tga" ? 962928000000.0 : component == "rrp" ? 1864225000000.0 : 6112819000000.0
1652227200000 => component == "fed" ? 8939972000000.0 : component == "tga" ? 941766000000.0 : component == "rrp" ? 1876119000000.0 : 6124123000000.0
1652313600000 => component == "fed" ? 8942008000000.0 : component == "tga" ? 919331000000.0 : component == "rrp" ? 1900069000000.0 : 6122608000000.0
1652400000000 => component == "fed" ? 8942008000000.0 : component == "tga" ? 893803000000.0 : component == "rrp" ? 1865287000000.0 : 6182918000000.0
1652659200000 => component == "fed" ? 8942008000000.0 : component == "tga" ? 880792000000.0 : component == "rrp" ? 1833152000000.0 : 6228064000000.0
1652745600000 => component == "fed" ? 8942008000000.0 : component == "tga" ? 914571000000.0 : component == "rrp" ? 1877483000000.0 : 6149954000000.0
1652832000000 => component == "fed" ? 8942008000000.0 : component == "tga" ? 891271000000.0 : component == "rrp" ? 1973373000000.0 : 6081254000000.0
1652918400000 => component == "fed" ? 8945898000000.0 : component == "tga" ? 866726000000.0 : component == "rrp" ? 1981005000000.0 : 6098167000000.0
1653004800000 => component == "fed" ? 8945898000000.0 : component == "tga" ? 825182000000.0 : component == "rrp" ? 1987987000000.0 : 6132729000000.0
1653264000000 => component == "fed" ? 8945898000000.0 : component == "tga" ? 822339000000.0 : component == "rrp" ? 2044658000000.0 : 6078901000000.0
1653350400000 => component == "fed" ? 8945898000000.0 : component == "tga" ? 838141000000.0 : component == "rrp" ? 1987865000000.0 : 6119892000000.0
1653436800000 => component == "fed" ? 8945898000000.0 : component == "tga" ? 818688000000.0 : component == "rrp" ? 1995750000000.0 : 6099843000000.0
1653523200000 => component == "fed" ? 8914281000000.0 : component == "tga" ? 801714000000.0 : component == "rrp" ? 2007702000000.0 : 6104865000000.0
1653609600000 => component == "fed" ? 8914281000000.0 : component == "tga" ? 762674000000.0 : component == "rrp" ? 2006688000000.0 : 6144919000000.0
1653955200000 => component == "fed" ? 8914281000000.0 : component == "tga" ? 782309000000.0 : component == "rrp" ? 1978538000000.0 : 6153434000000.0
1654041600000 => component == "fed" ? 8914281000000.0 : component == "tga" ? 854240000000.0 : component == "rrp" ? 1965015000000.0 : 6095795000000.0
1654128000000 => component == "fed" ? 8915050000000.0 : component == "tga" ? 780575000000.0 : component == "rrp" ? 1985239000000.0 : 6149236000000.0
1654214400000 => component == "fed" ? 8915050000000.0 : component == "tga" ? 757559000000.0 : component == "rrp" ? 2031228000000.0 : 6126263000000.0
1654473600000 => component == "fed" ? 8915050000000.0 : component == "tga" ? 731781000000.0 : component == "rrp" ? 2040093000000.0 : 6143176000000.0
1654560000000 => component == "fed" ? 8915050000000.0 : component == "tga" ? 724554000000.0 : component == "rrp" ? 2091395000000.0 : 6099101000000.0
1654646400000 => component == "fed" ? 8915050000000.0 : component == "tga" ? 702336000000.0 : component == "rrp" ? 2140277000000.0 : 6075641000000.0
1654732800000 => component == "fed" ? 8918254000000.0 : component == "tga" ? 683892000000.0 : component == "rrp" ? 2142318000000.0 : 6092044000000.0
1654819200000 => component == "fed" ? 8918254000000.0 : component == "tga" ? 631026000000.0 : component == "rrp" ? 2162885000000.0 : 6124343000000.0
1655078400000 => component == "fed" ? 8918254000000.0 : component == "tga" ? 627393000000.0 : component == "rrp" ? 2212620000000.0 : 6078241000000.0
1655164800000 => component == "fed" ? 8918254000000.0 : component == "tga" ? 653718000000.0 : component == "rrp" ? 2223857000000.0 : 6040679000000.0
1655251200000 => component == "fed" ? 8918254000000.0 : component == "tga" ? 661227000000.0 : component == "rrp" ? 2162924000000.0 : 6108269000000.0
1655337600000 => component == "fed" ? 8932420000000.0 : component == "tga" ? 769937000000.0 : component == "rrp" ? 2178382000000.0 : 5984101000000.0
1655424000000 => component == "fed" ? 8932420000000.0 : component == "tga" ? 755888000000.0 : component == "rrp" ? 2229279000000.0 : 5947253000000.0
1655769600000 => component == "fed" ? 8932420000000.0 : component == "tga" ? 762327000000.0 : component == "rrp" ? 2188627000000.0 : 5981466000000.0
1655856000000 => component == "fed" ? 8932420000000.0 : component == "tga" ? 757733000000.0 : component == "rrp" ? 2259458000000.0 : 5917155000000.0
1655942400000 => component == "fed" ? 8934346000000.0 : component == "tga" ? 745052000000.0 : component == "rrp" ? 2285442000000.0 : 5903852000000.0
1656028800000 => component == "fed" ? 8934346000000.0 : component == "tga" ? 735139000000.0 : component == "rrp" ? 2180984000000.0 : 6018223000000.0
1656288000000 => component == "fed" ? 8934346000000.0 : component == "tga" ? 758505000000.0 : component == "rrp" ? 2155942000000.0 : 6019899000000.0
1656374400000 => component == "fed" ? 8934346000000.0 : component == "tga" ? 768652000000.0 : component == "rrp" ? 2213784000000.0 : 5951910000000.0
1656460800000 => component == "fed" ? 8934346000000.0 : component == "tga" ? 757242000000.0 : component == "rrp" ? 2226976000000.0 : 5929335000000.0
1656547200000 => component == "fed" ? 8913553000000.0 : component == "tga" ? 759845000000.0 : component == "rrp" ? 2329743000000.0 : 5823965000000.0
1656633600000 => component == "fed" ? 8913553000000.0 : component == "tga" ? 782406000000.0 : component == "rrp" ? 2167085000000.0 : 5964062000000.0
1656979200000 => component == "fed" ? 8913553000000.0 : component == "tga" ? 685842000000.0 : component == "rrp" ? 2138280000000.0 : 6089431000000.0
1657065600000 => component == "fed" ? 8913553000000.0 : component == "tga" ? 689482000000.0 : component == "rrp" ? 2168026000000.0 : 6034343000000.0
1657152000000 => component == "fed" ? 8891851000000.0 : component == "tga" ? 687943000000.0 : component == "rrp" ? 2172457000000.0 : 6031451000000.0
1657238400000 => component == "fed" ? 8891851000000.0 : component == "tga" ? 666044000000.0 : component == "rrp" ? 2144921000000.0 : 6080886000000.0
1657497600000 => component == "fed" ? 8891851000000.0 : component == "tga" ? 658096000000.0 : component == "rrp" ? 2164266000000.0 : 6069489000000.0
1657584000000 => component == "fed" ? 8891851000000.0 : component == "tga" ? 665792000000.0 : component == "rrp" ? 2146132000000.0 : 6079927000000.0
1657670400000 => component == "fed" ? 8891851000000.0 : component == "tga" ? 643141000000.0 : component == "rrp" ? 2155290000000.0 : 6097436000000.0
1657756800000 => component == "fed" ? 8895867000000.0 : component == "tga" ? 618740000000.0 : component == "rrp" ? 2207121000000.0 : 6070006000000.0
1657843200000 => component == "fed" ? 8895867000000.0 : component == "tga" ? 595272000000.0 : component == "rrp" ? 2153750000000.0 : 6146845000000.0
1658102400000 => component == "fed" ? 8895867000000.0 : component == "tga" ? 606834000000.0 : component == "rrp" ? 2190375000000.0 : 6098658000000.0
1658188800000 => component == "fed" ? 8895867000000.0 : component == "tga" ? 628659000000.0 : component == "rrp" ? 2211821000000.0 : 6055387000000.0
1658275200000 => component == "fed" ? 8895867000000.0 : component == "tga" ? 636362000000.0 : component == "rrp" ? 2240204000000.0 : 6022647000000.0
1658361600000 => component == "fed" ? 8899213000000.0 : component == "tga" ? 616348000000.0 : component == "rrp" ? 2271756000000.0 : 6011109000000.0
1658448000000 => component == "fed" ? 8899213000000.0 : component == "tga" ? 594035000000.0 : component == "rrp" ? 2228959000000.0 : 6076219000000.0
1658707200000 => component == "fed" ? 8899213000000.0 : component == "tga" ? 589322000000.0 : component == "rrp" ? 2192367000000.0 : 6117524000000.0
1658793600000 => component == "fed" ? 8899213000000.0 : component == "tga" ? 605872000000.0 : component == "rrp" ? 2189474000000.0 : 6103867000000.0
1658880000000 => component == "fed" ? 8899213000000.0 : component == "tga" ? 637228000000.0 : component == "rrp" ? 2188994000000.0 : 6063782000000.0
1658966400000 => component == "fed" ? 8890004000000.0 : component == "tga" ? 615515000000.0 : component == "rrp" ? 2239883000000.0 : 6034606000000.0
1659052800000 => component == "fed" ? 8890004000000.0 : component == "tga" ? 597017000000.0 : component == "rrp" ? 2300200000000.0 : 5992787000000.0
1659312000000 => component == "fed" ? 8890004000000.0 : component == "tga" ? 619273000000.0 : component == "rrp" ? 2161885000000.0 : 6108846000000.0
1659398400000 => component == "fed" ? 8890004000000.0 : component == "tga" ? 551023000000.0 : component == "rrp" ? 2156013000000.0 : 6182968000000.0
1659484800000 => component == "fed" ? 8890004000000.0 : component == "tga" ? 586370000000.0 : component == "rrp" ? 2182238000000.0 : 6106012000000.0
1659571200000 => component == "fed" ? 8874620000000.0 : component == "tga" ? 566577000000.0 : component == "rrp" ? 2191546000000.0 : 6116497000000.0
1659657600000 => component == "fed" ? 8874620000000.0 : component == "tga" ? 554402000000.0 : component == "rrp" ? 2194927000000.0 : 6125291000000.0
1659916800000 => component == "fed" ? 8874620000000.0 : component == "tga" ? 548849000000.0 : component == "rrp" ? 2195692000000.0 : 6130079000000.0
1660003200000 => component == "fed" ? 8874620000000.0 : component == "tga" ? 555513000000.0 : component == "rrp" ? 2186568000000.0 : 6132539000000.0
1660089600000 => component == "fed" ? 8874620000000.0 : component == "tga" ? 583255000000.0 : component == "rrp" ? 2177646000000.0 : 6118237000000.0
1660176000000 => component == "fed" ? 8879138000000.0 : component == "tga" ? 561140000000.0 : component == "rrp" ? 2199247000000.0 : 6118751000000.0
1660262400000 => component == "fed" ? 8879138000000.0 : component == "tga" ? 546978000000.0 : component == "rrp" ? 2213193000000.0 : 6118967000000.0
1660521600000 => component == "fed" ? 8879138000000.0 : component == "tga" ? 548414000000.0 : component == "rrp" ? 2175857000000.0 : 6154867000000.0
1660608000000 => component == "fed" ? 8879138000000.0 : component == "tga" ? 525921000000.0 : component == "rrp" ? 2165332000000.0 : 6187885000000.0
1660694400000 => component == "fed" ? 8879138000000.0 : component == "tga" ? 559827000000.0 : component == "rrp" ? 2199631000000.0 : 6090304000000.0
1660780800000 => component == "fed" ? 8849762000000.0 : component == "tga" ? 539278000000.0 : component == "rrp" ? 2218161000000.0 : 6092323000000.0
1660867200000 => component == "fed" ? 8849762000000.0 : component == "tga" ? 530499000000.0 : component == "rrp" ? 2221680000000.0 : 6097583000000.0
1661126400000 => component == "fed" ? 8849762000000.0 : component == "tga" ? 529281000000.0 : component == "rrp" ? 2235665000000.0 : 6084816000000.0
1661212800000 => component == "fed" ? 8849762000000.0 : component == "tga" ? 543194000000.0 : component == "rrp" ? 2250718000000.0 : 6055850000000.0
1661299200000 => component == "fed" ? 8849762000000.0 : component == "tga" ? 555139000000.0 : component == "rrp" ? 2237072000000.0 : 6059225000000.0
1661385600000 => component == "fed" ? 8851436000000.0 : component == "tga" ? 530196000000.0 : component == "rrp" ? 2187907000000.0 : 6133333000000.0
1661472000000 => component == "fed" ? 8851436000000.0 : component == "tga" ? 580033000000.0 : component == "rrp" ? 2182452000000.0 : 6088951000000.0
1661731200000 => component == "fed" ? 8851436000000.0 : component == "tga" ? 600109000000.0 : component == "rrp" ? 2205188000000.0 : 6046139000000.0
=>
float(na)
val
get_net_liquidity_3(simple string component = "", int ts = 0) =>
float val = switch ts
1661817600000 => component == "fed" ? 8851436000000.0 : component == "tga" ? 610399000000.0 : component == "rrp" ? 2188975000000.0 : 6052062000000.0
1661904000000 => component == "fed" ? 8851436000000.0 : component == "tga" ? 627082000000.0 : component == "rrp" ? 2251025000000.0 : 5947986000000.0
1661990400000 => component == "fed" ? 8826093000000.0 : component == "tga" ? 669911000000.0 : component == "rrp" ? 2173156000000.0 : 5983026000000.0
1662076800000 => component == "fed" ? 8826093000000.0 : component == "tga" ? 598859000000.0 : component == "rrp" ? 2173413000000.0 : 6053821000000.0
1662422400000 => component == "fed" ? 8826093000000.0 : component == "tga" ? 574423000000.0 : component == "rrp" ? 2188796000000.0 : 6062874000000.0
1662508800000 => component == "fed" ? 8826093000000.0 : component == "tga" ? 589596000000.0 : component == "rrp" ? 2206987000000.0 : 6025818000000.0
1662595200000 => component == "fed" ? 8822401000000.0 : component == "tga" ? 582921000000.0 : component == "rrp" ? 2210466000000.0 : 6029014000000.0
1662681600000 => component == "fed" ? 8822401000000.0 : component == "tga" ? 581785000000.0 : component == "rrp" ? 2209714000000.0 : 6030902000000.0
1662940800000 => component == "fed" ? 8822401000000.0 : component == "tga" ? 585000000000.0 : component == "rrp" ? 2218546000000.0 : 6018855000000.0
1663027200000 => component == "fed" ? 8822401000000.0 : component == "tga" ? 601944000000.0 : component == "rrp" ? 2202719000000.0 : 6017738000000.0
1663113600000 => component == "fed" ? 8822401000000.0 : component == "tga" ? 599932000000.0 : component == "rrp" ? 2225579000000.0 : 6007248000000.0
1663200000000 => component == "fed" ? 8832759000000.0 : component == "tga" ? 617997000000.0 : component == "rrp" ? 2176188000000.0 : 6038574000000.0
1663286400000 => component == "fed" ? 8832759000000.0 : component == "tga" ? 677452000000.0 : component == "rrp" ? 2186833000000.0 : 5968474000000.0
1663545600000 => component == "fed" ? 8832759000000.0 : component == "tga" ? 692971000000.0 : component == "rrp" ? 2217542000000.0 : 5922246000000.0
1663632000000 => component == "fed" ? 8832759000000.0 : component == "tga" ? 704998000000.0 : component == "rrp" ? 2238870000000.0 : 5888891000000.0
1663718400000 => component == "fed" ? 8832759000000.0 : component == "tga" ? 695823000000.0 : component == "rrp" ? 2315900000000.0 : 5805079000000.0
1663804800000 => component == "fed" ? 8816802000000.0 : component == "tga" ? 690286000000.0 : component == "rrp" ? 2359227000000.0 : 5767289000000.0
1663891200000 => component == "fed" ? 8816802000000.0 : component == "tga" ? 682027000000.0 : component == "rrp" ? 2319361000000.0 : 5815414000000.0
1664150400000 => component == "fed" ? 8816802000000.0 : component == "tga" ? 697726000000.0 : component == "rrp" ? 2299011000000.0 : 5820065000000.0
1664236800000 => component == "fed" ? 8816802000000.0 : component == "tga" ? 705918000000.0 : component == "rrp" ? 2327111000000.0 : 5783773000000.0
1664323200000 => component == "fed" ? 8816802000000.0 : component == "tga" ? 683943000000.0 : component == "rrp" ? 2366798000000.0 : 5744826000000.0
1664409600000 => component == "fed" ? 8795567000000.0 : component == "tga" ? 661920000000.0 : component == "rrp" ? 2371763000000.0 : 5761884000000.0
1664496000000 => component == "fed" ? 8795567000000.0 : component == "tga" ? 658634000000.0 : component == "rrp" ? 2425910000000.0 : 5711023000000.0
1664755200000 => component == "fed" ? 8795567000000.0 : component == "tga" ? 635994000000.0 : component == "rrp" ? 2252523000000.0 : 5907050000000.0
1664841600000 => component == "fed" ? 8795567000000.0 : component == "tga" ? 630975000000.0 : component == "rrp" ? 2233616000000.0 : 5930976000000.0
1664928000000 => component == "fed" ? 8795567000000.0 : component == "tga" ? 617850000000.0 : component == "rrp" ? 2230799000000.0 : 5910404000000.0
1665014400000 => component == "fed" ? 8759053000000.0 : component == "tga" ? 622131000000.0 : component == "rrp" ? 2232801000000.0 : 5904121000000.0
1665100800000 => component == "fed" ? 8759053000000.0 : component == "tga" ? 612400000000.0 : component == "rrp" ? 2226950000000.0 : 5919703000000.0
1665360000000 => component == "fed" ? 8759053000000.0 : component == "tga" ? 611855000000.0 : component == "rrp" ? 2226950000000.0 : 5920248000000.0
1665446400000 => component == "fed" ? 8759053000000.0 : component == "tga" ? 611855000000.0 : component == "rrp" ? 2222479000000.0 : 5924719000000.0
1665532800000 => component == "fed" ? 8759053000000.0 : component == "tga" ? 614781000000.0 : component == "rrp" ? 2247206000000.0 : 5896982000000.0
1665619200000 => component == "fed" ? 8758969000000.0 : component == "tga" ? 583513000000.0 : component == "rrp" ? 2244100000000.0 : 5931356000000.0
1665705600000 => component == "fed" ? 8758969000000.0 : component == "tga" ? 578283000000.0 : component == "rrp" ? 2222052000000.0 : 5958634000000.0
1665964800000 => component == "fed" ? 8758969000000.0 : component == "tga" ? 574982000000.0 : component == "rrp" ? 2172301000000.0 : 6011686000000.0
1666051200000 => component == "fed" ? 8758969000000.0 : component == "tga" ? 651318000000.0 : component == "rrp" ? 2226725000000.0 : 5880926000000.0
1666137600000 => component == "fed" ? 8758969000000.0 : component == "tga" ? 655230000000.0 : component == "rrp" ? 2241835000000.0 : 5846857000000.0
1666224000000 => component == "fed" ? 8743922000000.0 : component == "tga" ? 640613000000.0 : component == "rrp" ? 2234071000000.0 : 5869238000000.0
1666310400000 => component == "fed" ? 8743922000000.0 : component == "tga" ? 635492000000.0 : component == "rrp" ? 2265809000000.0 : 5842621000000.0
1666569600000 => component == "fed" ? 8743922000000.0 : component == "tga" ? 624584000000.0 : component == "rrp" ? 2242044000000.0 : 5877294000000.0
1666656000000 => component == "fed" ? 8743922000000.0 : component == "tga" ? 636785000000.0 : component == "rrp" ? 2195616000000.0 : 5911521000000.0
1666742400000 => component == "fed" ? 8743922000000.0 : component == "tga" ? 659483000000.0 : component == "rrp" ? 2186856000000.0 : 5876751000000.0
1666828800000 => component == "fed" ? 8723090000000.0 : component == "tga" ? 636327000000.0 : component == "rrp" ? 2152485000000.0 : 5934278000000.0
1666915200000 => component == "fed" ? 8723090000000.0 : component == "tga" ? 625362000000.0 : component == "rrp" ? 2183290000000.0 : 5914438000000.0
1667174400000 => component == "fed" ? 8723090000000.0 : component == "tga" ? 621627000000.0 : component == "rrp" ? 2275459000000.0 : 5826004000000.0
1667260800000 => component == "fed" ? 8723090000000.0 : component == "tga" ? 596470000000.0 : component == "rrp" ? 2200510000000.0 : 5926110000000.0
1667347200000 => component == "fed" ? 8723090000000.0 : component == "tga" ? 551009000000.0 : component == "rrp" ? 2229861000000.0 : 5896000000000.0
1667433600000 => component == "fed" ? 8676870000000.0 : component == "tga" ? 552089000000.0 : component == "rrp" ? 2219791000000.0 : 5904990000000.0
1667520000000 => component == "fed" ? 8676870000000.0 : component == "tga" ? 524883000000.0 : component == "rrp" ? 2230840000000.0 : 5921147000000.0
1667779200000 => component == "fed" ? 8676870000000.0 : component == "tga" ? 524694000000.0 : component == "rrp" ? 2241317000000.0 : 5910859000000.0
1667865600000 => component == "fed" ? 8676870000000.0 : component == "tga" ? 530764000000.0 : component == "rrp" ? 2232555000000.0 : 5913551000000.0
1667952000000 => component == "fed" ? 8676870000000.0 : component == "tga" ? 545285000000.0 : component == "rrp" ? 2237812000000.0 : 5895789000000.0
1668038400000 => component == "fed" ? 8678886000000.0 : component == "tga" ? 517340000000.0 : component == "rrp" ? 2200586000000.0 : 5960960000000.0
1668124800000 => component == "fed" ? 8678886000000.0 : component == "tga" ? 510550000000.0 : component == "rrp" ? 2200586000000.0 : 5967750000000.0
1668384000000 => component == "fed" ? 8678886000000.0 : component == "tga" ? 510550000000.0 : component == "rrp" ? 2165018000000.0 : 6003318000000.0
1668470400000 => component == "fed" ? 8678886000000.0 : component == "tga" ? 524136000000.0 : component == "rrp" ? 2086574000000.0 : 6068176000000.0
1668556800000 => component == "fed" ? 8678886000000.0 : component == "tga" ? 482354000000.0 : component == "rrp" ? 2099070000000.0 : 6044196000000.0
1668643200000 => component == "fed" ? 8625620000000.0 : component == "tga" ? 472185000000.0 : component == "rrp" ? 2114439000000.0 : 6038996000000.0
1668729600000 => component == "fed" ? 8625620000000.0 : component == "tga" ? 465368000000.0 : component == "rrp" ? 2113413000000.0 : 6046839000000.0
1668988800000 => component == "fed" ? 8625620000000.0 : component == "tga" ? 469610000000.0 : component == "rrp" ? 2125426000000.0 : 6030584000000.0
1669075200000 => component == "fed" ? 8625620000000.0 : component == "tga" ? 476764000000.0 : component == "rrp" ? 2103932000000.0 : 6044924000000.0
1669161600000 => component == "fed" ? 8625620000000.0 : component == "tga" ? 512602000000.0 : component == "rrp" ? 2069174000000.0 : 6039614000000.0
1669334400000 => component == "fed" ? 8621390000000.0 : component == "tga" ? 492754000000.0 : component == "rrp" ? 2031066000000.0 : 6097570000000.0
1669593600000 => component == "fed" ? 8621390000000.0 : component == "tga" ? 510532000000.0 : component == "rrp" ? 2054914000000.0 : 6055944000000.0
1669680000000 => component == "fed" ? 8621390000000.0 : component == "tga" ? 517125000000.0 : component == "rrp" ? 2064377000000.0 : 6039888000000.0
1669766400000 => component == "fed" ? 8621390000000.0 : component == "tga" ? 506052000000.0 : component == "rrp" ? 2115913000000.0 : 5962611000000.0
1669852800000 => component == "fed" ? 8584576000000.0 : component == "tga" ? 532791000000.0 : component == "rrp" ? 2050286000000.0 : 6001499000000.0
1669939200000 => component == "fed" ? 8584576000000.0 : component == "tga" ? 458408000000.0 : component == "rrp" ? 2049763000000.0 : 6076405000000.0
1670198400000 => component == "fed" ? 8584576000000.0 : component == "tga" ? 434939000000.0 : component == "rrp" ? 2093647000000.0 : 6055990000000.0
1670284800000 => component == "fed" ? 8584576000000.0 : component == "tga" ? 440836000000.0 : component == "rrp" ? 2111465000000.0 : 6032275000000.0
1670371200000 => component == "fed" ? 8584576000000.0 : component == "tga" ? 411431000000.0 : component == "rrp" ? 2151549000000.0 : 6019755000000.0
1670457600000 => component == "fed" ? 8582735000000.0 : component == "tga" ? 410853000000.0 : component == "rrp" ? 2175973000000.0 : 5995909000000.0
1670544000000 => component == "fed" ? 8582735000000.0 : component == "tga" ? 358794000000.0 : component == "rrp" ? 2146748000000.0 : 6077193000000.0
1670803200000 => component == "fed" ? 8582735000000.0 : component == "tga" ? 357709000000.0 : component == "rrp" ? 2158517000000.0 : 6066509000000.0
1670889600000 => component == "fed" ? 8582735000000.0 : component == "tga" ? 370897000000.0 : component == "rrp" ? 2180676000000.0 : 6031162000000.0
1670976000000 => component == "fed" ? 8582735000000.0 : component == "tga" ? 343699000000.0 : component == "rrp" ? 2192864000000.0 : 6046850000000.0
1671062400000 => component == "fed" ? 8583413000000.0 : component == "tga" ? 342104000000.0 : component == "rrp" ? 2123995000000.0 : 6117314000000.0
1671148800000 => component == "fed" ? 8583413000000.0 : component == "tga" ? 448106000000.0 : component == "rrp" ? 2126540000000.0 : 6008767000000.0
1671408000000 => component == "fed" ? 8583413000000.0 : component == "tga" ? 467544000000.0 : component == "rrp" ? 2134765000000.0 : 5981104000000.0
1671494400000 => component == "fed" ? 8583413000000.0 : component == "tga" ? 482388000000.0 : component == "rrp" ? 2159408000000.0 : 5941617000000.0
1671580800000 => component == "fed" ? 8583413000000.0 : component == "tga" ? 450413000000.0 : component == "rrp" ? 2206965000000.0 : 5907033000000.0
1671667200000 => component == "fed" ? 8564411000000.0 : component == "tga" ? 434922000000.0 : component == "rrp" ? 2222898000000.0 : 5906591000000.0
1671753600000 => component == "fed" ? 8564411000000.0 : component == "tga" ? 429684000000.0 : component == "rrp" ? 2216348000000.0 : 5918379000000.0
1672099200000 => component == "fed" ? 8564411000000.0 : component == "tga" ? 431253000000.0 : component == "rrp" ? 2221259000000.0 : 5911899000000.0
1672185600000 => component == "fed" ? 8564411000000.0 : component == "tga" ? 430977000000.0 : component == "rrp" ? 2293003000000.0 : 5827189000000.0
1672272000000 => component == "fed" ? 8551169000000.0 : component == "tga" ? 409809000000.0 : component == "rrp" ? 2308319000000.0 : 5833041000000.0
1672358400000 => component == "fed" ? 8551169000000.0 : component == "tga" ? 412900000000.0 : component == "rrp" ? 2553716000000.0 : 5584553000000.0
1672704000000 => component == "fed" ? 8551169000000.0 : component == "tga" ? 446685000000.0 : component == "rrp" ? 2188272000000.0 : 5916212000000.0
1672790400000 => component == "fed" ? 8551169000000.0 : component == "tga" ? 386114000000.0 : component == "rrp" ? 2229542000000.0 : 5891773000000.0
1672876800000 => component == "fed" ? 8507429000000.0 : component == "tga" ? 379620000000.0 : component == "rrp" ? 2242486000000.0 : 5885323000000.0
1672963200000 => component == "fed" ? 8507429000000.0 : component == "tga" ? 379653000000.0 : component == "rrp" ? 2208265000000.0 : 5919511000000.0
1673222400000 => component == "fed" ? 8507429000000.0 : component == "tga" ? 375694000000.0 : component == "rrp" ? 2199121000000.0 : 5932614000000.0
1673308800000 => component == "fed" ? 8507429000000.0 : component == "tga" ? 385220000000.0 : component == "rrp" ? 2192942000000.0 : 5929267000000.0
1673395200000 => component == "fed" ? 8507429000000.0 : component == "tga" ? 368000000000.0 : component == "rrp" ? 2199170000000.0 : 5941417000000.0
1673481600000 => component == "fed" ? 8508587000000.0 : component == "tga" ? 346426000000.0 : component == "rrp" ? 2202989000000.0 : 5959172000000.0
1673568000000 => component == "fed" ? 8508587000000.0 : component == "tga" ? 310363000000.0 : component == "rrp" ? 2179781000000.0 : 6018443000000.0
1673913600000 => component == "fed" ? 8508587000000.0 : component == "tga" ? 321572000000.0 : component == "rrp" ? 2093328000000.0 : 6093687000000.0
1674000000000 => component == "fed" ? 8508587000000.0 : component == "tga" ? 398974000000.0 : component == "rrp" ? 2131678000000.0 : 5958387000000.0
1674086400000 => component == "fed" ? 8489039000000.0 : component == "tga" ? 377500000000.0 : component == "rrp" ? 2110145000000.0 : 6001394000000.0
1674172800000 => component == "fed" ? 8489039000000.0 : component == "tga" ? 455623000000.0 : component == "rrp" ? 2090523000000.0 : 5942893000000.0
1674432000000 => component == "fed" ? 8489039000000.0 : component == "tga" ? 454615000000.0 : component == "rrp" ? 2135499000000.0 : 5898925000000.0
=>
float(na)
val
// @function Gets the Net Liquidity time series for the last 250 trading days. Dates that are not present are represented as na.
// @param component The component of the Net Liquidity function to return. Possible values: 'fed', 'tga', and 'rrp'. (`Net Liquidity` is returned if no argument is supplied).
// @returns The Net Liquidity time series or a component of the Net Liquidity function.
export get_net_liquidity(simple string component = "") =>
ts = timestamp("UTC-0", year, month, dayofmonth, 0, 0, 0)
float val = if ts >= 1624320000000 and ts <= 1636502400000
get_net_liquidity_0(component, ts)
else if ts >= 1636588800000 and ts <= 1649116800000
get_net_liquidity_1(component, ts)
else if ts >= 1649203200000 and ts <= 1661731200000
get_net_liquidity_2(component, ts)
else if ts >= 1661817600000 and ts <= 1674432000000
get_net_liquidity_3(component, ts)
else
float(na)
val
|
StringStringHashmap | https://www.tradingview.com/script/RSLPnjKN/ | gianlucac | https://www.tradingview.com/u/gianlucac/ | 0 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gianlucac
// code took and readapted from: © ramihoteit321
//@version=5
//@description A simple implementation of a key string to string value dictionary in pinescript
library('StringStringHashmap', false)
//@function Create empty string-string dictionary
//@returns the indeces and elements of the dict
export create_ss_dict() =>
indices = array.new_string(0)
elements = array.new_string(0)
[indices, elements]
//@function Add new key-value pair in the dictionary
//@param key string
//@param value string
//@param i string[] the indices of the dictionary
//@param e string[] the element of the dictionary
export add_key_value(string key, string value, string[] i, string[] e) =>
// check if key exists
if array.indexof(i, key) == -1
array.push(i, key)
array.push(e, value)
//@function Get the value of the given key
//@param key string
//@param i string[] the indices of the dictionary
//@param e string[] the element of the dictionary
//@returns return the value of the fiven key
export get_value(string key, string[] i, string[] e) =>
array.get(e, array.indexof(i, key))
//@function Change the value of the given key
//@param key string
//@param value string
//@param i string[] the indices of the dictionary
//@param e string[] the element of the dictionary
export change_value(string key, string new_value , string[] i, string[] e) =>
array.set(e, array.indexof(i, key), new_value)
|
Support & Resistance AI (K means/median) [ThinkLogicAI] | https://www.tradingview.com/script/FwB6GWPC-Support-Resistance-AI-K-means-median-ThinkLogicAI/ | ThinkLogicAI | https://www.tradingview.com/u/ThinkLogicAI/ | 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/
// © ThinkLogicAI
//@version=5
indicator("K clustering", overlay = true, max_lines_count = 10, max_labels_count = 251)
//inputs
k = input.int(3, "Number of clusters", minval = 3, maxval = 5, step = 1)
cent_meth = input.string("K means", title="Cluster Method", options=["K means", "K median"])
train_n = input.int(252,"Bars back from last bar to train on", minval = 20, maxval = 1000, step = 1)
plot_band = input.bool(true, "Show SD bands")
//variables needed
x = close
max_bars_back(x, 5000)
var clust = array.new<float>(k, 0)
var sd_clust = array.new<float>(k, 0)
var n_clust = array.new<float>(k,0)
var conv = array.new<int>(0)
var bar_lab = array.new<label>(0)
var table tab = table.new(position.top_right,2, k+1)
var line ts = na
var line k1 = na
var line k2 = na
var line k3 = na
var line k4 = na
var line k5 = na
var line k6 = na
var line sh_1 = na
var line sl_1 = na
var line sh_2 = na
var line sl_2 = na
var line sh_3 = na
var line sl_3 = na
var line sh_4 = na
var line sl_4 = na
var line sh_5 = na
var line sl_5 = na
var line sh_6 = na
var line sl_6 = na
//fuctions used
euc_dist(p,q) =>
//distance metric
//p is the close vector and q is the cluster cecnter
math.sqrt(math.pow(p-q,2))
subtract_array(a,b)=>
//subtract arrays
out = array.new<float>(array.size(a),na)
for i = 0 to array.size(a) -1
array.set(out,i, array.get(a,i) - array.get(b,i))
array.sum(out)
center_method(arry)=>
//calculate either the mean or median based on user input
float out = 0.00
if cent_meth == "K means"//k means clustering
out := array.avg(arry)
else
out := array.median((arry))//k meedian clustering
out
sd_method(arry, mu, ddof)=>
//my will either be the mean or the median based on user input
float sum_dif = 0.00
if cent_meth == "k means"
sum_dif := array.stdev(arry)
else
if arry.size() > 0
for i = 0 to arry.size() - 1
sum_dif += math.pow(array.get(arry, i) - mu,2)
sum_dif := math.sqrt(sum_dif/(array.size(arry)-ddof))
sum_dif
vector_params(k, a1, a2, a3, a4, a5, a6)=>
//calculate mean, sd, and array size
mu = array.new<float>(0)
sd = array.new<float>(0)
N = array.new<float>(0)
mean_ar1 = center_method(a1)
mean_ar2 = center_method(a2)
mean_ar3 = center_method(a3)
mean_ar4 = center_method(a4)
mean_ar5 = center_method(a5)
mean_ar6 = center_method(a6)
sd_ar1 = sd_method(a1, mean_ar1, 0)
sd_ar2 = sd_method(a2, mean_ar2, 0)
sd_ar3 = sd_method(a3, mean_ar3, 0)
sd_ar4 = sd_method(a4, mean_ar4, 0)
sd_ar5 = sd_method(a5, mean_ar5, 0)
sd_ar6 = sd_method(a6, mean_ar6, 0)
n1 = array.size(a1)
n2 = array.size(a2)
n3 = array.size(a3)
n4 = array.size(a4)
n5 = array.size(a5)
n6 = array.size(a6)
array.push(mu, mean_ar1)
array.push(mu, mean_ar2)
array.push(mu, mean_ar3)
array.push(mu, mean_ar4)
array.push(mu, mean_ar5)
array.push(mu, mean_ar6)
array.push(sd, sd_ar1)
array.push(sd, sd_ar2)
array.push(sd, sd_ar3)
array.push(sd, sd_ar4)
array.push(sd, sd_ar5)
array.push(sd, sd_ar6)
array.push(N, n1)
array.push(N, n2)
array.push(N, n3)
array.push(N, n4)
array.push(N, n5)
array.push(N, n6)
[array.slice(mu,0,k), array.slice(sd, 0, k), array.slice(N, 0, k)]
// k means/median clustering
if barstate.islast
err = 100.00
for i = 0 to array.size(clust) - 1
array.set(clust, i, i == 0 ? x[math.floor(train_n*.02)] : x[math.floor(train_n*((i/k)))])
//run while clusters keep changing
while err > .01
c1 = array.new<float>(0)
c2 = array.new<float>(0)
c3 = array.new<float>(0)
c4 = array.new<float>(0)
c5 = array.new<float>(0)
c6 = array.new<float>(0)
hold = array.new<int>(0)
for i = 1 to train_n
int idx = na
dist = 1000000.00
for j = 0 to k-1
d_temp = euc_dist(x[i], array.get(clust,j))
if d_temp < dist
dist := d_temp
idx := j
if idx == 0
array.push(c1, x[i])
array.push(hold, 0)
else if idx == 1
array.push(c2, x[i])
array.push(hold, 1)
else if idx == 2
array.push(c3, x[i])
array.push(hold, 2)
else if idx == 3
array.push(c4, x[i])
array.push(hold, 3)
else if idx == 4
array.push(c5, x[i])
array.push(hold, 4)
else if idx == 5
array.push(c6, x[i])
array.push(hold, 5)
//after looping though data
[mu, sd, n] = vector_params(k, c1, c2, c3, c4, c5, c6)
err := math.pow(subtract_array(clust, mu),2)
clust := array.copy(mu)
sd_clust := array.copy(sd)
array.push(conv,1)
conv := array.copy(hold)
n_clust := array.copy(n)
//populate table
table.cell(tab, 0, 0, "Cluster", bgcolor = color.new(color.gray, 50), text_color = color.white)
table.cell(tab, 1, 0, "Density", bgcolor = color.new(color.gray, 50), text_color = color.white)
//visuals, table update, and stats all based on user defined number of clusters
if k == 3
n1 = n_clust.get(0)
n2 = n_clust.get(1)
n3 = n_clust.get(2)
denom = n1 + n2 + n3
table.cell(tab, 1, 1, str.tostring(100*math.round(n1 / denom,3)) + "%", bgcolor = color.new(color.green,50), text_color = color.white)
table.cell(tab, 1, 2, str.tostring(100*math.round(n2 / denom,3)) + "%", bgcolor = color.new(color.red, 50), text_color = color.white)
table.cell(tab, 1, 3, str.tostring(100*math.round(n3 / denom,3)) + "%", bgcolor = color.new(color.blue,50), text_color = color.white)
table.cell(tab, 0, 1, "1", bgcolor = color.gray, text_color = color.white)
table.cell(tab, 0, 2, "2", bgcolor = color.gray, text_color = color.white)
table.cell(tab, 0, 3, "3", bgcolor = color.gray, text_color = color.white)
if n1 > 0
k1 := line.new(bar_index - 1, array.get(clust,0), bar_index, array.get(clust,0),xloc = xloc.bar_time,extend = extend.both, color = color.green, width = 2)
if plot_band
sh_1 := line.new(bar_index - 1 , array.get(clust,0) + array.get(sd_clust, 0), bar_index, array.get(clust,0) + array.get(sd_clust, 0),xloc = xloc.bar_time,extend = extend.both, color = color.white, width = 1)
sl_1 := line.new(bar_index - 1, array.get(clust,0) - array.get(sd_clust, 0), bar_index, array.get(clust,0) - array.get(sd_clust, 0),xloc = xloc.bar_time,extend = extend.both, color = color.white, width = 1)
linefill.new(sh_1, sl_1, color.new(color.green, 90))
if n2 > 0
k2 := line.new(bar_index - 1, array.get(clust,1), bar_index, array.get(clust,1),xloc = xloc.bar_time,extend = extend.both, color = color.red, width = 2)
if plot_band
sh_2 := line.new(bar_index - 1, array.get(clust,1) + array.get(sd_clust, 1), bar_index, array.get(clust,1) + array.get(sd_clust, 1),xloc = xloc.bar_time,extend = extend.both, color = color.white, width = 1)
sl_2 := line.new(bar_index - 1, array.get(clust,1) - array.get(sd_clust, 1), bar_index, array.get(clust,1) - array.get(sd_clust, 1),xloc = xloc.bar_time,extend = extend.both, color = color.white, width = 1)
linefill.new(sh_2, sl_2, color.new(color.red, 90))
if n3 > 0
k3 := line.new(bar_index - 1, array.get(clust,2), bar_index, array.get(clust,2),xloc = xloc.bar_time,extend = extend.both, color = color.blue, width = 2)
if plot_band
sh_3 := line.new(bar_index - 1, array.get(clust,2) + array.get(sd_clust, 2), bar_index, array.get(clust,2) + array.get(sd_clust, 2),xloc = xloc.bar_time,extend = extend.both, color = color.white, width = 1)
sl_3 := line.new(bar_index - 1, array.get(clust,2) - array.get(sd_clust, 2), bar_index, array.get(clust,2) - array.get(sd_clust, 2),xloc = xloc.bar_time,extend = extend.both, color = color.white, width = 1)
linefill.new(sh_3, sl_3, color.new(color.blue, 90))
else if k == 4
n1 = n_clust.get(0)
n2 = n_clust.get(1)
n3 = n_clust.get(2)
n4 = n_clust.get(3)
denom = n1 + n2 + n3 + n4
table.cell(tab, 1, 1, str.tostring(100*math.round(n1 / denom,3)) + "%", bgcolor = color.new(color.green,50), text_color = color.white)
table.cell(tab, 1, 2, str.tostring(100*math.round(n2 / denom,3)) + "%", bgcolor = color.new(color.red,50), text_color = color.white)
table.cell(tab, 1, 3, str.tostring(100*math.round(n3 / denom,3)) + "%", bgcolor = color.new(color.blue,50), text_color = color.white)
table.cell(tab, 1, 4, str.tostring(100*math.round(n4 / denom,3)) + "%", bgcolor = color.new(color.orange,50), text_color = color.white)
table.cell(tab, 0, 1, "1", bgcolor = color.gray, text_color = color.white)
table.cell(tab, 0, 2, "2", bgcolor = color.gray, text_color = color.white)
table.cell(tab, 0, 3, "3", bgcolor = color.gray, text_color = color.white)
table.cell(tab, 0, 4, "4", bgcolor = color.gray, text_color = color.white)
if n1 > 0
k1 := line.new(bar_index - 1, array.get(clust,0), bar_index, array.get(clust,0),extend = extend.both, color = color.green, width = 2)
if plot_band
sh_1 := line.new(bar_index - 1, array.get(clust,0) + array.get(sd_clust, 0), bar_index, array.get(clust,0) + array.get(sd_clust, 0),extend = extend.both, color = color.white, width = 1)
sl_1 := line.new(bar_index - 1, array.get(clust,0) - array.get(sd_clust, 0), bar_index, array.get(clust,0) - array.get(sd_clust, 0),extend = extend.both, color = color.white, width = 1)
linefill.new(sh_1, sl_1, color.new(color.green, 90))
if n2 > 0
k2 := line.new(bar_index - 1, array.get(clust,1), bar_index, array.get(clust,1),extend = extend.both, color = color.red, width = 2)
if plot_band
sh_2 := line.new(bar_index - 1, array.get(clust,1) + array.get(sd_clust, 1), bar_index, array.get(clust,1) + array.get(sd_clust, 1),extend = extend.both, color = color.white, width = 1)
sl_2 := line.new(bar_index - 1, array.get(clust,1) - array.get(sd_clust, 1), bar_index, array.get(clust,1) - array.get(sd_clust, 1),extend = extend.both, color = color.white, width = 1)
linefill.new(sh_2, sl_2, color.new(color.red, 90))
if n3 > 0
k3 := line.new(bar_index - 1, array.get(clust,2), bar_index, array.get(clust,2),extend = extend.both, color = color.blue, width = 2)
if plot_band
sh_3 := line.new(bar_index - 1, array.get(clust,2) + array.get(sd_clust, 2), bar_index, array.get(clust,2) + array.get(sd_clust, 2),extend = extend.both, color = color.white, width = 1)
sl_3 := line.new(bar_index - 1, array.get(clust,2) - array.get(sd_clust, 2), bar_index, array.get(clust,2) - array.get(sd_clust, 2),extend = extend.both, color = color.white, width = 1)
linefill.new(sh_3, sl_3, color.new(color.blue, 90))
if n4 > 0
k4 := line.new(bar_index - 1, array.get(clust,3), bar_index, array.get(clust,3),extend = extend.both, color = color.orange, width = 2)
if plot_band
sh_4 := line.new(bar_index - 1, array.get(clust,3) + array.get(sd_clust, 3), bar_index, array.get(clust,3) + array.get(sd_clust, 3),extend = extend.both, color = color.white, width = 1)
sl_4 := line.new(bar_index - 1, array.get(clust,3) - array.get(sd_clust, 3), bar_index, array.get(clust,3) - array.get(sd_clust, 3),extend = extend.both, color = color.white, width = 1)
linefill.new(sh_4, sl_4, color.new(color.orange, 90))
else if k == 5
n1 = n_clust.get(0)
n2 = n_clust.get(1)
n3 = n_clust.get(2)
n4 = n_clust.get(3)
n5 = n_clust.get(4)
denom = n1 + n2 + n3 + n4 + n5
table.cell(tab, 1, 1, str.tostring(100*math.round(n1 / denom,3)) + "%", bgcolor = color.new(color.green,50), text_color = color.white)
table.cell(tab, 1, 2, str.tostring(100*math.round(n2 / denom,3)) + "%", bgcolor = color.new(color.red,50), text_color = color.white)
table.cell(tab, 1, 3, str.tostring(100*math.round(n3 / denom,3)) + "%", bgcolor = color.new(color.blue,50), text_color = color.white)
table.cell(tab, 1, 4, str.tostring(100*math.round(n4 / denom,3)) + "%", bgcolor = color.new(color.orange,50), text_color = color.white)
table.cell(tab, 1, 5, str.tostring(100*math.round(n5 / denom,3)) + "%", bgcolor = color.new(color.yellow,50), text_color = color.white)
table.cell(tab, 0, 1, "1", bgcolor = color.gray, text_color = color.white)
table.cell(tab, 0, 2, "2", bgcolor = color.gray, text_color = color.white)
table.cell(tab, 0, 3, "3", bgcolor = color.gray, text_color = color.white)
table.cell(tab, 0, 4, "4", bgcolor = color.gray, text_color = color.white)
table.cell(tab, 0, 5, "5", bgcolor = color.gray, text_color = color.white)
if n1 > 0
k1 := line.new(bar_index - 1, array.get(clust,0), bar_index, array.get(clust,0),extend = extend.both, color = color.green, width = 2)
if plot_band
sh_1 := line.new(bar_index - 1, array.get(clust,0) + array.get(sd_clust, 0), bar_index, array.get(clust,0) + array.get(sd_clust, 0),extend = extend.both, color = color.white, width = 1)
sl_1 := line.new(bar_index - 1, array.get(clust,0) - array.get(sd_clust, 0), bar_index, array.get(clust,0) - array.get(sd_clust, 0),extend = extend.both, color = color.white, width = 1)
linefill.new(sh_1, sl_1, color.new(color.green, 90))
if n2 > 0
k2 := line.new(bar_index - 1, array.get(clust,1), bar_index, array.get(clust,1),extend = extend.both, color = color.red, width = 2)
if plot_band
sh_2 := line.new(bar_index - 1, array.get(clust,1) + array.get(sd_clust, 1), bar_index, array.get(clust,1) + array.get(sd_clust, 1),extend = extend.both, color = color.white, width = 1)
sl_2 := line.new(bar_index - 1, array.get(clust,1) - array.get(sd_clust, 1), bar_index, array.get(clust,1) - array.get(sd_clust, 1),extend = extend.both, color = color.white, width = 1)
linefill.new(sh_2, sl_2, color.new(color.red, 90))
if n3 > 0
k3 := line.new(bar_index - 1, array.get(clust,2), bar_index, array.get(clust,2),extend = extend.both, color = color.blue, width = 2)
if plot_band
sh_3 := line.new(bar_index - 1, array.get(clust,2) + array.get(sd_clust, 2), bar_index, array.get(clust,2) + array.get(sd_clust, 2),extend = extend.both, color = color.white, width = 1)
sl_3 := line.new(bar_index - 1, array.get(clust,2) - array.get(sd_clust, 2), bar_index, array.get(clust,2) - array.get(sd_clust, 2),extend = extend.both, color = color.white, width = 1)
linefill.new(sh_3, sl_3, color.new(color.blue, 90))
if n4 > 0
k4 := line.new(bar_index - 1, array.get(clust,3), bar_index, array.get(clust,3),extend = extend.both, color = color.orange, width = 2)
if plot_band
sh_4 := line.new(bar_index - 1, array.get(clust,3) + array.get(sd_clust, 3), bar_index, array.get(clust,3) + array.get(sd_clust, 3),extend = extend.both, color = color.white, width = 1)
sl_4 := line.new(bar_index - 1, array.get(clust,3) - array.get(sd_clust, 3), bar_index, array.get(clust,3) - array.get(sd_clust, 3),extend = extend.both, color = color.white, width = 1)
linefill.new(sh_4, sl_4, color.new(color.orange, 90))
if n5 > 0
k5 := line.new(bar_index - 1, array.get(clust,4), bar_index, array.get(clust,4),extend = extend.both, color = color.yellow, width = 2)
if plot_band
sh_5 := line.new(bar_index - 1, array.get(clust,4) + array.get(sd_clust, 4), bar_index, array.get(clust,4) + array.get(sd_clust, 4),extend = extend.both, color = color.white, width = 1)
sl_5 := line.new(bar_index - 1, array.get(clust,4) - array.get(sd_clust, 4), bar_index, array.get(clust,4) - array.get(sd_clust, 4),extend = extend.both, color = color.white, width = 1)
linefill.new(sh_5, sl_5, color.new(color.yellow, 90))
|
Seasonal - Trading Day of Month | https://www.tradingview.com/script/okZH3MgH/ | sammypi | https://www.tradingview.com/u/sammypi/ | 15 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sammypi
//@version=5
indicator("Seasonal", overlay = true)
i_position = input.string("bottom_right", "Position", options=["top_left", "top_center", "top_right", "middle_left", "middle_center", "middle_right", "bottom_left", "bottom_center", "bottom_right"])
position = switch i_position
"top_left" => position.top_left
"top_center" => position.top_center
"top_right" => position.top_right
"middle_left" => position.middle_left
"middle_center" => position.middle_center
"middle_right" => position.middle_right
"bottom_left" => position.bottom_left
"bottom_center" => position.bottom_center
"bottom_right" => position.bottom_right
// Default used when none of the options match
=> position.top_left
//-----timeframe
year_cal = input(2022, title="Must be the last year", tooltip = "You Should check with CLOSE Data if the first Trading Day of Month in the Matrix is the 31. of prior Month or the 1. of current Month", group = "Timeframe Input (MAX 32 Columns)")
month_start = input(5, title="Month", tooltip = "To get the first TradingDay of Month you have to set the StartPoint to 31. of the prior Month or 1. of current Month")
month_end = input(6)
day_start = input(31, title="Day", tooltip = "To get the first TradingDay of Month you have to set the StartPoint to 31. of the prior Month or 1. of current Month")
day_end = input(31)
//-----Color
gradient_upcolor_weak = input(color.rgb(0, 140, 255, 80))
gradient_upcolor_strong = input(color.rgb(0, 255, 8, 80))
gradient_downcolor_weak = input(color.rgb(255, 0, 225, 80))
gradient_downcolor_strong = input(color.rgb(246, 0, 0, 80))
gradient_upcolor_weak_bar = input(color.rgb(0, 140, 255, 40))
gradient_upcolor_strong_bar = input(color.rgb(0, 255, 8, 40))
gradient_downcolor_weak_bar = input(color.rgb(255, 0, 225, 40))
gradient_downcolor_strong_bar = input(color.rgb(246, 0, 0, 40))
channel_upcolor = input(color.rgb(57, 132, 60))
channel_upcolor_power = input(color.rgb(19, 204, 53))
channel_downcolor = input(color.rgb(169, 58, 58))
channel_downcolor_power = input(color.rgb(227, 11, 47))
channel_neutralcolor = input(color.gray)
//-----arrayinput
data_input = input.string("Percent Change", title="Data from...", options = ["Percent Change", "Close", "Close-Open"])
data_source(type) =>
switch type
"Percent Change" => (close - open) / open * 100
"Close" => close
"Close-Open" => close-open
ma = data_source(data_input)
//-----array this year
startDateTime0 = timestamp(year_cal+1, month_start, day_start, 00, 00)
endDateTime0 = timestamp(year_cal+1, month_end, day_end, 23, 59)
inDateAndTimeRange0 = (time >= startDateTime0) and (time < endDateTime0)
showClose0 = inDateAndTimeRange0 ? ma : na
//-----array last year
startDateTime1 = timestamp(year_cal, month_start, day_start, 00, 00)
endDateTime1 = timestamp(year_cal, month_end, day_end, 23, 59)
inDateAndTimeRange1 = (time >= startDateTime1) and (time < endDateTime1)
showClose1 = inDateAndTimeRange1 ? ma : na
//-----array last year-1
startDateTime2 = timestamp(year_cal-1, month_start, day_start, 00, 00)
endDateTime2 = timestamp(year_cal-1, month_end, day_end, 23, 59)
inDateAndTimeRange2 = (time >= startDateTime2) and (time < endDateTime2)
showClose2 = inDateAndTimeRange2 ? ma : na
//-----array last year-2
startDateTime3 = timestamp(year_cal-2, month_start, day_start, 00, 00)
endDateTime3 = timestamp(year_cal-2, month_end, day_end, 23, 59)
inDateAndTimeRange3 = (time >= startDateTime3) and (time < endDateTime3)
showClose3 = inDateAndTimeRange3 ? ma : na
//-----array last year-3
startDateTime4 = timestamp(year_cal-3, month_start, day_start, 00, 00)
endDateTime4 = timestamp(year_cal-3, month_end, day_end, 23, 59)
inDateAndTimeRange4 = (time >= startDateTime4) and (time < endDateTime4)
showClose4 = inDateAndTimeRange4 ? ma : na
//-----array last year-4
startDateTime5 = timestamp(year_cal-4, month_start, day_start, 00, 00)
endDateTime5 = timestamp(year_cal-4, month_end, day_end, 23, 59)
inDateAndTimeRange5 = (time >= startDateTime5) and (time < endDateTime5)
showClose5 = inDateAndTimeRange5 ? ma : na
//-----array last year-5
startDateTime6 = timestamp(year_cal-5, month_start, day_start, 00, 00)
endDateTime6 = timestamp(year_cal-5, month_end, day_end, 23, 59)
inDateAndTimeRange6 = (time >= startDateTime6) and (time < endDateTime6)
showClose6 = inDateAndTimeRange6 ? ma : na
//-----array last year-6
startDateTime7 = timestamp(year_cal-6, month_start, day_start, 00, 00)
endDateTime7 = timestamp(year_cal-6, month_end, day_end, 23, 59)
inDateAndTimeRange7 = (time >= startDateTime7) and (time < endDateTime7)
showClose7 = inDateAndTimeRange7 ? ma : na
//-----array last year-7
startDateTime8 = timestamp(year_cal-7, month_start, day_start, 00, 00)
endDateTime8 = timestamp(year_cal-7, month_end, day_end, 23, 59)
inDateAndTimeRange8 = (time >= startDateTime8) and (time < endDateTime8)
showClose8 = inDateAndTimeRange8 ? ma : na
//-----array last year-8
startDateTime9 = timestamp(year_cal-8, month_start, day_start, 00, 00)
endDateTime9 = timestamp(year_cal-8, month_end, day_end, 23, 59)
inDateAndTimeRange9 = (time >= startDateTime9) and (time < endDateTime9)
showClose9 = inDateAndTimeRange9 ? ma : na
//-----array last year-9
startDateTime10 = timestamp(year_cal-9, month_start, day_start, 00, 00)
endDateTime10 = timestamp(year_cal-9, month_end, day_end, 23, 59)
inDateAndTimeRange10 = (time >= startDateTime10) and (time < endDateTime10)
showClose10 = inDateAndTimeRange10 ? ma : na
//-----array last year-10
startDateTime11 = timestamp(year_cal-10, month_start, day_start, 00, 00)
endDateTime11 = timestamp(year_cal-10, month_end, day_end, 23, 59)
inDateAndTimeRange11 = (time >= startDateTime11) and (time < endDateTime11)
showClose11 = inDateAndTimeRange11 ? ma : na
//-----arrays variable
var float [] sumClose00 = array.new_float(0)
var float [] sumClose0 = array.new_float(0)
var float [] sumClose1 = array.new_float(0)
var float [] sumClose2 = array.new_float(0)
var float [] sumClose3 = array.new_float(0)
var float [] sumClose4 = array.new_float(0)
var float [] sumClose5 = array.new_float(0)
var float [] sumClose6 = array.new_float(0)
var float [] sumClose7 = array.new_float(0)
var float [] sumClose8 = array.new_float(0)
var float [] sumClose9 = array.new_float(0)
var float [] sumClose10 = array.new_float(0)
var float [] check = array.new_float(0)
if showClose1
array.push(check, close)
if showClose0
array.push(sumClose00, ma)
size0 = array.size(sumClose00)
if showClose1
array.push(sumClose1, ma)
size1 = array.size(sumClose1)
if showClose2
array.push(sumClose2, ma)
size2 = array.size(sumClose2)
if showClose3
array.push(sumClose3, ma)
size3 = array.size(sumClose3)
if showClose4
array.push(sumClose4, ma)
size4 = array.size(sumClose4)
if showClose5
array.push(sumClose5, ma)
size5 = array.size(sumClose5)
if showClose6
array.push(sumClose6, ma)
size6 = array.size(sumClose6)
if showClose7
array.push(sumClose7, ma)
size7 = array.size(sumClose7)
if showClose8
array.push(sumClose8, ma)
size8 = array.size(sumClose8)
if showClose9
array.push(sumClose9, ma)
size9 = array.size(sumClose9)
if showClose10
array.push(sumClose10, ma)
size10 = array.size(sumClose10)
get_index_values0 = array.new_float(0)
get_index_values1 = array.new_float(0)
get_index_values2 = array.new_float(0)
get_index_values3 = array.new_float(0)
get_index_values4 = array.new_float(0)
get_index_values5 = array.new_float(0)
get_index_values6 = array.new_float(0)
get_index_values7 = array.new_float(0)
get_index_values8 = array.new_float(0)
get_index_values9 = array.new_float(0)
get_index_values10 = array.new_float(0)
get_index_values11 = array.new_float(0)
get_index_values12 = array.new_float(0)
get_index_values13 = array.new_float(0)
get_index_values14 = array.new_float(0)
get_index_values15 = array.new_float(0)
get_index_values16 = array.new_float(0)
get_index_values17 = array.new_float(0)
get_index_values18 = array.new_float(0)
get_index_values19 = array.new_float(0)
get_index_values20 = array.new_float(0)
get_index_values21 = array.new_float(0)
get_index_values22 = array.new_float(0)
get_index_values23 = array.new_float(0)
get_index_values24 = array.new_float(0)
get_index_values25 = array.new_float(0)
get_index_values26 = array.new_float(0)
get_index_values27 = array.new_float(0)
get_index_values28 = array.new_float(0)
get_index_values29 = array.new_float(0)
get_index_values30 = array.new_float(0)
//---sumClose1 array
if array.size(sumClose1) > 0
array.push(get_index_values0, array.get(sumClose1, 0))
if array.size(sumClose1) > 1
array.push(get_index_values1, array.get(sumClose1, 1))
if array.size(sumClose1) > 2
array.push(get_index_values2, array.get(sumClose1, 2))
if array.size(sumClose1) > 3
array.push(get_index_values3, array.get(sumClose1, 3))
if array.size(sumClose1) > 4
array.push(get_index_values4, array.get(sumClose1, 4))
if array.size(sumClose1) > 5
array.push(get_index_values5, array.get(sumClose1, 5))
if array.size(sumClose1) > 6
array.push(get_index_values6, array.get(sumClose1, 6))
if array.size(sumClose1) > 7
array.push(get_index_values7, array.get(sumClose1, 7))
if array.size(sumClose1) > 8
array.push(get_index_values8, array.get(sumClose1, 8))
if array.size(sumClose1) > 9
array.push(get_index_values9, array.get(sumClose1, 9))
if array.size(sumClose1) > 10
array.push(get_index_values10, array.get(sumClose1, 10))
if array.size(sumClose1) > 11
array.push(get_index_values11, array.get(sumClose1, 11))
if array.size(sumClose1) > 12
array.push(get_index_values12, array.get(sumClose1, 12))
if array.size(sumClose1) > 13
array.push(get_index_values13, array.get(sumClose1, 13))
if array.size(sumClose1) > 14
array.push(get_index_values14, array.get(sumClose1, 14))
if array.size(sumClose1) > 15
array.push(get_index_values15, array.get(sumClose1, 15))
if array.size(sumClose1) > 16
array.push(get_index_values16, array.get(sumClose1, 16))
if array.size(sumClose1) > 17
array.push(get_index_values17, array.get(sumClose1, 17))
if array.size(sumClose1) > 18
array.push(get_index_values18, array.get(sumClose1, 18))
if array.size(sumClose1) > 19
array.push(get_index_values19, array.get(sumClose1, 19))
if array.size(sumClose1) > 20
array.push(get_index_values20, array.get(sumClose1, 20))
if array.size(sumClose1) > 21
array.push(get_index_values21, array.get(sumClose1, 21))
if array.size(sumClose1) > 22
array.push(get_index_values22, array.get(sumClose1, 22))
if array.size(sumClose1) > 23
array.push(get_index_values23, array.get(sumClose1, 23))
if array.size(sumClose1) > 24
array.push(get_index_values24, array.get(sumClose1, 24))
if array.size(sumClose1) > 25
array.push(get_index_values25, array.get(sumClose1, 25))
if array.size(sumClose1) > 26
array.push(get_index_values26, array.get(sumClose1, 26))
if array.size(sumClose1) > 27
array.push(get_index_values27, array.get(sumClose1, 27))
if array.size(sumClose1) > 28
array.push(get_index_values28, array.get(sumClose1, 28))
if array.size(sumClose1) > 29
array.push(get_index_values29, array.get(sumClose1, 29))
if array.size(sumClose1) > 30
array.push(get_index_values30, array.get(sumClose1, 30))
//---sumClose2 array
if array.size(sumClose2) > 0
array.push(get_index_values0, array.get(sumClose2, 0))
if array.size(sumClose2) > 1
array.push(get_index_values1, array.get(sumClose2, 1))
if array.size(sumClose2) > 2
array.push(get_index_values2, array.get(sumClose2, 2))
if array.size(sumClose2) > 3
array.push(get_index_values3, array.get(sumClose2, 3))
if array.size(sumClose2) > 4
array.push(get_index_values4, array.get(sumClose2, 4))
if array.size(sumClose2) > 5
array.push(get_index_values5, array.get(sumClose2, 5))
if array.size(sumClose2) > 6
array.push(get_index_values6, array.get(sumClose2, 6))
if array.size(sumClose2) > 7
array.push(get_index_values7, array.get(sumClose2, 7))
if array.size(sumClose2) > 8
array.push(get_index_values8, array.get(sumClose2, 8))
if array.size(sumClose2) > 9
array.push(get_index_values9, array.get(sumClose2, 9))
if array.size(sumClose2) > 10
array.push(get_index_values10, array.get(sumClose2, 10))
if array.size(sumClose2) > 11
array.push(get_index_values11, array.get(sumClose2, 11))
if array.size(sumClose2) > 12
array.push(get_index_values12, array.get(sumClose2, 12))
if array.size(sumClose2) > 13
array.push(get_index_values13, array.get(sumClose2, 13))
if array.size(sumClose2) > 14
array.push(get_index_values14, array.get(sumClose2, 14))
if array.size(sumClose2) > 15
array.push(get_index_values15, array.get(sumClose2, 15))
if array.size(sumClose2) > 16
array.push(get_index_values16, array.get(sumClose2, 16))
if array.size(sumClose2) > 17
array.push(get_index_values17, array.get(sumClose2, 17))
if array.size(sumClose2) > 18
array.push(get_index_values18, array.get(sumClose2, 18))
if array.size(sumClose2) > 19
array.push(get_index_values19, array.get(sumClose2, 19))
if array.size(sumClose2) > 20
array.push(get_index_values20, array.get(sumClose2, 20))
if array.size(sumClose2) > 21
array.push(get_index_values21, array.get(sumClose2, 21))
if array.size(sumClose2) > 22
array.push(get_index_values22, array.get(sumClose2, 22))
if array.size(sumClose2) > 23
array.push(get_index_values23, array.get(sumClose2, 23))
if array.size(sumClose2) > 24
array.push(get_index_values24, array.get(sumClose2, 24))
if array.size(sumClose2) > 25
array.push(get_index_values25, array.get(sumClose2, 25))
if array.size(sumClose2) > 26
array.push(get_index_values26, array.get(sumClose2, 26))
if array.size(sumClose2) > 27
array.push(get_index_values27, array.get(sumClose2, 27))
if array.size(sumClose2) > 28
array.push(get_index_values28, array.get(sumClose2, 28))
if array.size(sumClose2) > 29
array.push(get_index_values29, array.get(sumClose2, 29))
if array.size(sumClose2) > 30
array.push(get_index_values30, array.get(sumClose2, 30))
//---sumClose3 array
if array.size(sumClose3) > 0
array.push(get_index_values0, array.get(sumClose3, 0))
if array.size(sumClose3) > 1
array.push(get_index_values1, array.get(sumClose3, 1))
if array.size(sumClose3) > 2
array.push(get_index_values2, array.get(sumClose3, 2))
if array.size(sumClose3) > 3
array.push(get_index_values3, array.get(sumClose3, 3))
if array.size(sumClose3) > 4
array.push(get_index_values4, array.get(sumClose3, 4))
if array.size(sumClose3) > 5
array.push(get_index_values5, array.get(sumClose3, 5))
if array.size(sumClose3) > 6
array.push(get_index_values6, array.get(sumClose3, 6))
if array.size(sumClose3) > 7
array.push(get_index_values7, array.get(sumClose3, 7))
if array.size(sumClose3) > 8
array.push(get_index_values8, array.get(sumClose3, 8))
if array.size(sumClose3) > 9
array.push(get_index_values9, array.get(sumClose3, 9))
if array.size(sumClose3) > 10
array.push(get_index_values10, array.get(sumClose3, 10))
if array.size(sumClose3) > 11
array.push(get_index_values11, array.get(sumClose3, 11))
if array.size(sumClose3) > 12
array.push(get_index_values12, array.get(sumClose3, 12))
if array.size(sumClose3) > 13
array.push(get_index_values13, array.get(sumClose3, 13))
if array.size(sumClose3) > 14
array.push(get_index_values14, array.get(sumClose3, 14))
if array.size(sumClose3) > 15
array.push(get_index_values15, array.get(sumClose3, 15))
if array.size(sumClose3) > 16
array.push(get_index_values16, array.get(sumClose3, 16))
if array.size(sumClose3) > 17
array.push(get_index_values17, array.get(sumClose3, 17))
if array.size(sumClose3) > 18
array.push(get_index_values18, array.get(sumClose3, 18))
if array.size(sumClose3) > 19
array.push(get_index_values19, array.get(sumClose3, 19))
if array.size(sumClose3) > 20
array.push(get_index_values20, array.get(sumClose3, 20))
if array.size(sumClose3) > 21
array.push(get_index_values21, array.get(sumClose3, 21))
if array.size(sumClose3) > 22
array.push(get_index_values22, array.get(sumClose3, 22))
if array.size(sumClose3) > 23
array.push(get_index_values23, array.get(sumClose3, 23))
if array.size(sumClose3) > 24
array.push(get_index_values24, array.get(sumClose3, 24))
if array.size(sumClose3) > 25
array.push(get_index_values25, array.get(sumClose3, 25))
if array.size(sumClose3) > 26
array.push(get_index_values26, array.get(sumClose3, 26))
if array.size(sumClose3) > 27
array.push(get_index_values27, array.get(sumClose3, 27))
if array.size(sumClose3) > 28
array.push(get_index_values28, array.get(sumClose3, 28))
if array.size(sumClose3) > 29
array.push(get_index_values29, array.get(sumClose3, 29))
if array.size(sumClose3) > 30
array.push(get_index_values30, array.get(sumClose3, 30))
//---sumClose4 array
if array.size(sumClose4) > 0
array.push(get_index_values0, array.get(sumClose4, 0))
if array.size(sumClose4) > 1
array.push(get_index_values1, array.get(sumClose4, 1))
if array.size(sumClose4) > 2
array.push(get_index_values2, array.get(sumClose4, 2))
if array.size(sumClose4) > 3
array.push(get_index_values3, array.get(sumClose4, 3))
if array.size(sumClose4) > 4
array.push(get_index_values4, array.get(sumClose4, 4))
if array.size(sumClose4) > 5
array.push(get_index_values5, array.get(sumClose4, 5))
if array.size(sumClose4) > 6
array.push(get_index_values6, array.get(sumClose4, 6))
if array.size(sumClose4) > 7
array.push(get_index_values7, array.get(sumClose4, 7))
if array.size(sumClose4) > 8
array.push(get_index_values8, array.get(sumClose4, 8))
if array.size(sumClose4) > 9
array.push(get_index_values9, array.get(sumClose4, 9))
if array.size(sumClose4) > 10
array.push(get_index_values10, array.get(sumClose4, 10))
if array.size(sumClose4) > 11
array.push(get_index_values11, array.get(sumClose4, 11))
if array.size(sumClose4) > 12
array.push(get_index_values12, array.get(sumClose4, 12))
if array.size(sumClose4) > 13
array.push(get_index_values13, array.get(sumClose4, 13))
if array.size(sumClose4) > 14
array.push(get_index_values14, array.get(sumClose4, 14))
if array.size(sumClose4) > 15
array.push(get_index_values15, array.get(sumClose4, 15))
if array.size(sumClose4) > 16
array.push(get_index_values16, array.get(sumClose4, 16))
if array.size(sumClose4) > 17
array.push(get_index_values17, array.get(sumClose4, 17))
if array.size(sumClose4) > 18
array.push(get_index_values18, array.get(sumClose4, 18))
if array.size(sumClose4) > 19
array.push(get_index_values19, array.get(sumClose4, 19))
if array.size(sumClose4) > 20
array.push(get_index_values20, array.get(sumClose4, 20))
if array.size(sumClose4) > 21
array.push(get_index_values21, array.get(sumClose4, 21))
if array.size(sumClose4) > 22
array.push(get_index_values22, array.get(sumClose4, 22))
if array.size(sumClose4) > 23
array.push(get_index_values23, array.get(sumClose4, 23))
if array.size(sumClose4) > 24
array.push(get_index_values24, array.get(sumClose4, 24))
if array.size(sumClose4) > 25
array.push(get_index_values25, array.get(sumClose4, 25))
if array.size(sumClose4) > 26
array.push(get_index_values26, array.get(sumClose4, 26))
if array.size(sumClose4) > 27
array.push(get_index_values27, array.get(sumClose4, 27))
if array.size(sumClose4) > 28
array.push(get_index_values28, array.get(sumClose4, 28))
if array.size(sumClose4) > 29
array.push(get_index_values29, array.get(sumClose4, 29))
if array.size(sumClose4) > 30
array.push(get_index_values30, array.get(sumClose4, 30))
//---sumClose5 array
if array.size(sumClose5) > 0
array.push(get_index_values0, array.get(sumClose5, 0))
if array.size(sumClose5) > 1
array.push(get_index_values1, array.get(sumClose5, 1))
if array.size(sumClose5) > 2
array.push(get_index_values2, array.get(sumClose5, 2))
if array.size(sumClose5) > 3
array.push(get_index_values3, array.get(sumClose5, 3))
if array.size(sumClose5) > 4
array.push(get_index_values4, array.get(sumClose5, 4))
if array.size(sumClose5) > 5
array.push(get_index_values5, array.get(sumClose5, 5))
if array.size(sumClose5) > 6
array.push(get_index_values6, array.get(sumClose5, 6))
if array.size(sumClose5) > 7
array.push(get_index_values7, array.get(sumClose5, 7))
if array.size(sumClose5) > 8
array.push(get_index_values8, array.get(sumClose5, 8))
if array.size(sumClose5) > 9
array.push(get_index_values9, array.get(sumClose5, 9))
if array.size(sumClose5) > 10
array.push(get_index_values10, array.get(sumClose5, 10))
if array.size(sumClose5) > 11
array.push(get_index_values11, array.get(sumClose5, 11))
if array.size(sumClose5) > 12
array.push(get_index_values12, array.get(sumClose5, 12))
if array.size(sumClose5) > 13
array.push(get_index_values13, array.get(sumClose5, 13))
if array.size(sumClose5) > 14
array.push(get_index_values14, array.get(sumClose5, 14))
if array.size(sumClose5) > 15
array.push(get_index_values15, array.get(sumClose5, 15))
if array.size(sumClose5) > 16
array.push(get_index_values16, array.get(sumClose5, 16))
if array.size(sumClose5) > 17
array.push(get_index_values17, array.get(sumClose5, 17))
if array.size(sumClose5) > 18
array.push(get_index_values18, array.get(sumClose5, 18))
if array.size(sumClose5) > 19
array.push(get_index_values19, array.get(sumClose5, 19))
if array.size(sumClose5) > 20
array.push(get_index_values20, array.get(sumClose5, 20))
if array.size(sumClose5) > 21
array.push(get_index_values21, array.get(sumClose5, 21))
if array.size(sumClose5) > 22
array.push(get_index_values22, array.get(sumClose5, 22))
if array.size(sumClose5) > 23
array.push(get_index_values23, array.get(sumClose5, 23))
if array.size(sumClose5) > 24
array.push(get_index_values24, array.get(sumClose5, 24))
if array.size(sumClose5) > 25
array.push(get_index_values25, array.get(sumClose5, 25))
if array.size(sumClose5) > 26
array.push(get_index_values26, array.get(sumClose5, 26))
if array.size(sumClose5) > 27
array.push(get_index_values27, array.get(sumClose5, 27))
if array.size(sumClose5) > 28
array.push(get_index_values28, array.get(sumClose5, 28))
if array.size(sumClose5) > 29
array.push(get_index_values29, array.get(sumClose5, 29))
if array.size(sumClose5) > 30
array.push(get_index_values30, array.get(sumClose5, 30))
//---sumClose6 array
if array.size(sumClose6) > 0
array.push(get_index_values0, array.get(sumClose6, 0))
if array.size(sumClose6) > 1
array.push(get_index_values1, array.get(sumClose6, 1))
if array.size(sumClose6) > 2
array.push(get_index_values2, array.get(sumClose6, 2))
if array.size(sumClose6) > 3
array.push(get_index_values3, array.get(sumClose6, 3))
if array.size(sumClose6) > 4
array.push(get_index_values4, array.get(sumClose6, 4))
if array.size(sumClose6) > 5
array.push(get_index_values5, array.get(sumClose6, 5))
if array.size(sumClose6) > 6
array.push(get_index_values6, array.get(sumClose6, 6))
if array.size(sumClose6) > 7
array.push(get_index_values7, array.get(sumClose6, 7))
if array.size(sumClose6) > 8
array.push(get_index_values8, array.get(sumClose6, 8))
if array.size(sumClose6) > 9
array.push(get_index_values9, array.get(sumClose6, 9))
if array.size(sumClose6) > 10
array.push(get_index_values10, array.get(sumClose6, 10))
if array.size(sumClose6) > 11
array.push(get_index_values11, array.get(sumClose6, 11))
if array.size(sumClose6) > 12
array.push(get_index_values12, array.get(sumClose6, 12))
if array.size(sumClose6) > 13
array.push(get_index_values13, array.get(sumClose6, 13))
if array.size(sumClose6) > 14
array.push(get_index_values14, array.get(sumClose6, 14))
if array.size(sumClose6) > 15
array.push(get_index_values15, array.get(sumClose6, 15))
if array.size(sumClose6) > 16
array.push(get_index_values16, array.get(sumClose6, 16))
if array.size(sumClose6) > 17
array.push(get_index_values17, array.get(sumClose6, 17))
if array.size(sumClose6) > 18
array.push(get_index_values18, array.get(sumClose6, 18))
if array.size(sumClose6) > 19
array.push(get_index_values19, array.get(sumClose6, 19))
if array.size(sumClose6) > 20
array.push(get_index_values20, array.get(sumClose6, 20))
if array.size(sumClose6) > 21
array.push(get_index_values21, array.get(sumClose6, 21))
if array.size(sumClose6) > 22
array.push(get_index_values22, array.get(sumClose6, 22))
if array.size(sumClose6) > 23
array.push(get_index_values23, array.get(sumClose6, 23))
if array.size(sumClose6) > 24
array.push(get_index_values24, array.get(sumClose6, 24))
if array.size(sumClose6) > 25
array.push(get_index_values25, array.get(sumClose6, 25))
if array.size(sumClose6) > 26
array.push(get_index_values26, array.get(sumClose6, 26))
if array.size(sumClose6) > 27
array.push(get_index_values27, array.get(sumClose6, 27))
if array.size(sumClose6) > 28
array.push(get_index_values28, array.get(sumClose6, 28))
if array.size(sumClose6) > 29
array.push(get_index_values29, array.get(sumClose6, 29))
if array.size(sumClose6) > 30
array.push(get_index_values30, array.get(sumClose6, 30))
//---sumClose7 array
if array.size(sumClose7) > 0
array.push(get_index_values0, array.get(sumClose7, 0))
if array.size(sumClose7) > 1
array.push(get_index_values1, array.get(sumClose7, 1))
if array.size(sumClose7) > 2
array.push(get_index_values2, array.get(sumClose7, 2))
if array.size(sumClose7) > 3
array.push(get_index_values3, array.get(sumClose7, 3))
if array.size(sumClose7) > 4
array.push(get_index_values4, array.get(sumClose7, 4))
if array.size(sumClose7) > 5
array.push(get_index_values5, array.get(sumClose7, 5))
if array.size(sumClose7) > 6
array.push(get_index_values6, array.get(sumClose7, 6))
if array.size(sumClose7) > 7
array.push(get_index_values7, array.get(sumClose7, 7))
if array.size(sumClose7) > 8
array.push(get_index_values8, array.get(sumClose7, 8))
if array.size(sumClose7) > 9
array.push(get_index_values9, array.get(sumClose7, 9))
if array.size(sumClose7) > 10
array.push(get_index_values10, array.get(sumClose7, 10))
if array.size(sumClose7) > 11
array.push(get_index_values11, array.get(sumClose7, 11))
if array.size(sumClose7) > 12
array.push(get_index_values12, array.get(sumClose7, 12))
if array.size(sumClose7) > 13
array.push(get_index_values13, array.get(sumClose7, 13))
if array.size(sumClose7) > 14
array.push(get_index_values14, array.get(sumClose7, 14))
if array.size(sumClose7) > 15
array.push(get_index_values15, array.get(sumClose7, 15))
if array.size(sumClose7) > 16
array.push(get_index_values16, array.get(sumClose7, 16))
if array.size(sumClose7) > 17
array.push(get_index_values17, array.get(sumClose7, 17))
if array.size(sumClose7) > 18
array.push(get_index_values18, array.get(sumClose7, 18))
if array.size(sumClose7) > 19
array.push(get_index_values19, array.get(sumClose7, 19))
if array.size(sumClose7) > 20
array.push(get_index_values20, array.get(sumClose7, 20))
if array.size(sumClose7) > 21
array.push(get_index_values21, array.get(sumClose7, 21))
if array.size(sumClose7) > 22
array.push(get_index_values22, array.get(sumClose7, 22))
if array.size(sumClose7) > 23
array.push(get_index_values23, array.get(sumClose7, 23))
if array.size(sumClose7) > 24
array.push(get_index_values24, array.get(sumClose7, 24))
if array.size(sumClose7) > 25
array.push(get_index_values25, array.get(sumClose7, 25))
if array.size(sumClose7) > 26
array.push(get_index_values26, array.get(sumClose7, 26))
if array.size(sumClose7) > 27
array.push(get_index_values27, array.get(sumClose7, 27))
if array.size(sumClose7) > 28
array.push(get_index_values28, array.get(sumClose7, 28))
if array.size(sumClose7) > 29
array.push(get_index_values29, array.get(sumClose7, 29))
if array.size(sumClose7) > 30
array.push(get_index_values30, array.get(sumClose7, 30))
//---sumClose8 array
if array.size(sumClose8) > 0
array.push(get_index_values0, array.get(sumClose8, 0))
if array.size(sumClose8) > 1
array.push(get_index_values1, array.get(sumClose8, 1))
if array.size(sumClose8) > 2
array.push(get_index_values2, array.get(sumClose8, 2))
if array.size(sumClose8) > 3
array.push(get_index_values3, array.get(sumClose8, 3))
if array.size(sumClose8) > 4
array.push(get_index_values4, array.get(sumClose8, 4))
if array.size(sumClose8) > 5
array.push(get_index_values5, array.get(sumClose8, 5))
if array.size(sumClose8) > 6
array.push(get_index_values6, array.get(sumClose8, 6))
if array.size(sumClose8) > 7
array.push(get_index_values7, array.get(sumClose8, 7))
if array.size(sumClose8) > 8
array.push(get_index_values8, array.get(sumClose8, 8))
if array.size(sumClose8) > 9
array.push(get_index_values9, array.get(sumClose8, 9))
if array.size(sumClose8) > 10
array.push(get_index_values10, array.get(sumClose8, 10))
if array.size(sumClose8) > 11
array.push(get_index_values11, array.get(sumClose8, 11))
if array.size(sumClose8) > 12
array.push(get_index_values12, array.get(sumClose8, 12))
if array.size(sumClose8) > 13
array.push(get_index_values13, array.get(sumClose8, 13))
if array.size(sumClose8) > 14
array.push(get_index_values14, array.get(sumClose8, 14))
if array.size(sumClose8) > 15
array.push(get_index_values15, array.get(sumClose8, 15))
if array.size(sumClose8) > 16
array.push(get_index_values16, array.get(sumClose8, 16))
if array.size(sumClose8) > 17
array.push(get_index_values17, array.get(sumClose8, 17))
if array.size(sumClose8) > 18
array.push(get_index_values18, array.get(sumClose8, 18))
if array.size(sumClose8) > 19
array.push(get_index_values19, array.get(sumClose8, 19))
if array.size(sumClose8) > 20
array.push(get_index_values20, array.get(sumClose8, 20))
if array.size(sumClose8) > 21
array.push(get_index_values21, array.get(sumClose8, 21))
if array.size(sumClose8) > 22
array.push(get_index_values22, array.get(sumClose8, 22))
if array.size(sumClose8) > 23
array.push(get_index_values23, array.get(sumClose8, 23))
if array.size(sumClose8) > 24
array.push(get_index_values24, array.get(sumClose8, 24))
if array.size(sumClose8) > 25
array.push(get_index_values25, array.get(sumClose8, 25))
if array.size(sumClose8) > 26
array.push(get_index_values26, array.get(sumClose8, 26))
if array.size(sumClose8) > 27
array.push(get_index_values27, array.get(sumClose8, 27))
if array.size(sumClose8) > 28
array.push(get_index_values28, array.get(sumClose8, 28))
if array.size(sumClose8) > 29
array.push(get_index_values29, array.get(sumClose8, 29))
if array.size(sumClose8) > 30
array.push(get_index_values30, array.get(sumClose8, 30))
//---sumClose9 array
if array.size(sumClose9) > 0
array.push(get_index_values0, array.get(sumClose9, 0))
if array.size(sumClose9) > 1
array.push(get_index_values1, array.get(sumClose9, 1))
if array.size(sumClose9) > 2
array.push(get_index_values2, array.get(sumClose9, 2))
if array.size(sumClose9) > 3
array.push(get_index_values3, array.get(sumClose9, 3))
if array.size(sumClose9) > 4
array.push(get_index_values4, array.get(sumClose9, 4))
if array.size(sumClose9) > 5
array.push(get_index_values5, array.get(sumClose9, 5))
if array.size(sumClose9) > 6
array.push(get_index_values6, array.get(sumClose9, 6))
if array.size(sumClose9) > 7
array.push(get_index_values7, array.get(sumClose9, 7))
if array.size(sumClose9) > 8
array.push(get_index_values8, array.get(sumClose9, 8))
if array.size(sumClose9) > 9
array.push(get_index_values9, array.get(sumClose9, 9))
if array.size(sumClose9) > 10
array.push(get_index_values10, array.get(sumClose9, 10))
if array.size(sumClose9) > 11
array.push(get_index_values11, array.get(sumClose9, 11))
if array.size(sumClose9) > 12
array.push(get_index_values12, array.get(sumClose9, 12))
if array.size(sumClose9) > 13
array.push(get_index_values13, array.get(sumClose9, 13))
if array.size(sumClose9) > 14
array.push(get_index_values14, array.get(sumClose9, 14))
if array.size(sumClose9) > 15
array.push(get_index_values15, array.get(sumClose9, 15))
if array.size(sumClose9) > 16
array.push(get_index_values16, array.get(sumClose9, 16))
if array.size(sumClose9) > 17
array.push(get_index_values17, array.get(sumClose9, 17))
if array.size(sumClose9) > 18
array.push(get_index_values18, array.get(sumClose9, 18))
if array.size(sumClose9) > 19
array.push(get_index_values19, array.get(sumClose9, 19))
if array.size(sumClose9) > 20
array.push(get_index_values20, array.get(sumClose9, 20))
if array.size(sumClose9) > 21
array.push(get_index_values21, array.get(sumClose9, 21))
if array.size(sumClose9) > 22
array.push(get_index_values22, array.get(sumClose9, 22))
if array.size(sumClose9) > 23
array.push(get_index_values23, array.get(sumClose9, 23))
if array.size(sumClose9) > 24
array.push(get_index_values24, array.get(sumClose9, 24))
if array.size(sumClose9) > 25
array.push(get_index_values25, array.get(sumClose9, 25))
if array.size(sumClose9) > 26
array.push(get_index_values26, array.get(sumClose9, 26))
if array.size(sumClose9) > 27
array.push(get_index_values27, array.get(sumClose9, 27))
if array.size(sumClose9) > 28
array.push(get_index_values28, array.get(sumClose9, 28))
if array.size(sumClose9) > 29
array.push(get_index_values29, array.get(sumClose9, 29))
if array.size(sumClose9) > 30
array.push(get_index_values30, array.get(sumClose9, 30))
//---sumClose10 array
if array.size(sumClose10) > 0
array.push(get_index_values0, array.get(sumClose10, 0))
if array.size(sumClose10) > 1
array.push(get_index_values1, array.get(sumClose10, 1))
if array.size(sumClose10) > 2
array.push(get_index_values2, array.get(sumClose10, 2))
if array.size(sumClose10) > 3
array.push(get_index_values3, array.get(sumClose10, 3))
if array.size(sumClose10) > 4
array.push(get_index_values4, array.get(sumClose10, 4))
if array.size(sumClose10) > 5
array.push(get_index_values5, array.get(sumClose10, 5))
if array.size(sumClose10) > 6
array.push(get_index_values6, array.get(sumClose10, 6))
if array.size(sumClose10) > 7
array.push(get_index_values7, array.get(sumClose10, 7))
if array.size(sumClose10) > 8
array.push(get_index_values8, array.get(sumClose10, 8))
if array.size(sumClose10) > 9
array.push(get_index_values9, array.get(sumClose10, 9))
if array.size(sumClose10) > 10
array.push(get_index_values10, array.get(sumClose10, 10))
if array.size(sumClose10) > 11
array.push(get_index_values11, array.get(sumClose10, 11))
if array.size(sumClose10) > 12
array.push(get_index_values12, array.get(sumClose10, 12))
if array.size(sumClose10) > 13
array.push(get_index_values13, array.get(sumClose10, 13))
if array.size(sumClose10) > 14
array.push(get_index_values14, array.get(sumClose10, 14))
if array.size(sumClose10) > 15
array.push(get_index_values15, array.get(sumClose10, 15))
if array.size(sumClose10) > 16
array.push(get_index_values16, array.get(sumClose10, 16))
if array.size(sumClose10) > 17
array.push(get_index_values17, array.get(sumClose10, 17))
if array.size(sumClose10) > 18
array.push(get_index_values18, array.get(sumClose10, 18))
if array.size(sumClose10) > 19
array.push(get_index_values19, array.get(sumClose10, 19))
if array.size(sumClose10) > 20
array.push(get_index_values20, array.get(sumClose10, 20))
if array.size(sumClose10) > 21
array.push(get_index_values21, array.get(sumClose10, 21))
if array.size(sumClose10) > 22
array.push(get_index_values22, array.get(sumClose10, 22))
if array.size(sumClose10) > 23
array.push(get_index_values23, array.get(sumClose10, 23))
if array.size(sumClose10) > 24
array.push(get_index_values24, array.get(sumClose10, 24))
if array.size(sumClose10) > 25
array.push(get_index_values25, array.get(sumClose10, 25))
if array.size(sumClose10) > 26
array.push(get_index_values26, array.get(sumClose10, 26))
if array.size(sumClose10) > 27
array.push(get_index_values27, array.get(sumClose10, 27))
if array.size(sumClose10) > 28
array.push(get_index_values28, array.get(sumClose10, 28))
if array.size(sumClose10) > 29
array.push(get_index_values29, array.get(sumClose10, 29))
if array.size(sumClose10) > 30
array.push(get_index_values30, array.get(sumClose10, 30))
//----summa summarium
index_0_avg = array.avg(get_index_values0)
index_1_avg = array.avg(get_index_values1)
index_2_avg = array.avg(get_index_values2)
index_3_avg = array.avg(get_index_values3)
index_4_avg = array.avg(get_index_values4)
index_5_avg = array.avg(get_index_values5)
index_6_avg = array.avg(get_index_values6)
index_7_avg = array.avg(get_index_values7)
index_8_avg = array.avg(get_index_values8)
index_9_avg = array.avg(get_index_values9)
index_10_avg = array.avg(get_index_values10)
index_11_avg = array.avg(get_index_values11)
index_12_avg = array.avg(get_index_values12)
index_13_avg = array.avg(get_index_values13)
index_14_avg = array.avg(get_index_values14)
index_15_avg = array.avg(get_index_values15)
index_16_avg = array.avg(get_index_values16)
index_17_avg = array.avg(get_index_values17)
index_18_avg = array.avg(get_index_values18)
index_19_avg = array.avg(get_index_values19)
index_20_avg = array.avg(get_index_values20)
index_21_avg = array.avg(get_index_values21)
index_22_avg = array.avg(get_index_values22)
index_23_avg = array.avg(get_index_values23)
index_24_avg = array.avg(get_index_values24)
index_25_avg = array.avg(get_index_values25)
index_26_avg = array.avg(get_index_values26)
index_27_avg = array.avg(get_index_values27)
index_28_avg = array.avg(get_index_values28)
index_29_avg = array.avg(get_index_values29)
index_30_avg = array.avg(get_index_values30)
index_avg = array.from(index_0_avg, index_1_avg, index_2_avg, index_3_avg, index_4_avg, index_5_avg, index_6_avg, index_7_avg, index_8_avg, index_9_avg, index_10_avg, index_11_avg, index_12_avg, index_13_avg, index_14_avg, index_15_avg, index_16_avg, index_17_avg, index_18_avg, index_19_avg, index_20_avg, index_21_avg, index_22_avg, index_23_avg, index_24_avg, index_25_avg, index_26_avg, index_27_avg, index_28_avg, index_29_avg, index_30_avg)
//die durchschnitte der finalen Zusammenfassungen
avg_value = array.avg(index_avg)
size_avg = array.size(index_avg)
//calculate the tradingdays in the array
tradingdays = -1
for j = 0 to size1
tradingdays += 1
tradingDayOf_TimeRange = 0
if startDateTime0 and ta.change(dayofmonth(time)) != 0
tradingDayOf_TimeRange += 1
//zusammenfassung der array durchscnittswerte
sumClose = close-open
LongTermAVG = input(25)
r_avg_value = ta.sma(ma, LongTermAVG)
ShortTermAVG = input(1)
r_avg_value1 = ta.sma(ma, ShortTermAVG )
//bull and bear conditions
bull_or_bear = r_avg_value > avg_value ? "BullL" : r_avg_value < avg_value ? "BearL" : "--"
bull_or_bear_color = r_avg_value > avg_value ? channel_upcolor : r_avg_value < avg_value ? channel_downcolor :
r_avg_value > array.max(index_avg) ? channel_upcolor_power : r_avg_value < array.min(index_avg) ? channel_downcolor : channel_neutralcolor
bull_or_bear1 = r_avg_value1 > avg_value ? "BullS" : r_avg_value1 < avg_value ? "BearS" : "--"
bull_or_bear_color1 = r_avg_value1 > avg_value ? channel_upcolor : r_avg_value1 < avg_value ? channel_downcolor :
r_avg_value1 > array.max(index_avg) ? channel_upcolor_power : r_avg_value1 < array.min(index_avg) ? channel_downcolor : channel_neutralcolor
//-----matrix size of spalten
matrix_columns = 250
var m = matrix.new<float>(10, matrix_columns, 0)
var table table_ = na
if size1 > 0
str = ""
for i = 0 to size1 - 1
str += str.tostring(i) + ": " + str.tostring(array.get(sumClose1, i))
if size2 > 0
str = ""
for i = 0 to size2 - 1
str += str.tostring(i) + ": " + str.tostring(array.get(sumClose2, i))
if size3 > 0
str = ""
for i = 0 to size3 - 1
str += str.tostring(i) + ": " + str.tostring(array.get(sumClose3, i))
if size4 > 0
str = ""
for i = 0 to size4 - 1
str += str.tostring(i) + ": " + str.tostring(array.get(sumClose4, i))
if size5 > 0
str = ""
for i = 0 to size5 - 1
str += str.tostring(i) + ": " + str.tostring(array.get(sumClose5, i))
if size6 > 0
str = ""
for i = 0 to size6 - 1
str += str.tostring(i) + ": " + str.tostring(array.get(sumClose6, i))
if size7 > 0
str = ""
for i = 0 to size7 - 1
str += str.tostring(i) + ": " + str.tostring(array.get(sumClose7, i))
if size8 > 0
str = ""
for i = 0 to size8 - 1
str += str.tostring(i) + ": " + str.tostring(array.get(sumClose8, i))
if size9 > 0
str = ""
for i = 0 to size9 - 1
str += str.tostring(i) + ": " + str.tostring(array.get(sumClose9, i))
if size10 > 0
str = ""
for i = 0 to size10 - 1
str += str.tostring(i) + ": " + str.tostring(array.get(sumClose10, i))
if size_avg > 0
str = ""
for i = 0 to size_avg - 1
str += str.tostring(i) + ": " + str.tostring(array.get(index_avg, i))
//----------------------------
var table = table.new(position = i_position, columns = 34, rows = 14, bgcolor = color.rgb(0, 0, 0), frame_color=color.rgb(87, 38, 38), frame_width = 1, border_color = color.rgb(61, 28, 28), border_width = 1)
if barstate.islast
table.cell(table_id = table, column = 1, row = 0, text = "TDOM", text_font_family = font.family_monospace, text_color = color.silver, text_size = size.small)
for i = 0 to size1 -1
table.cell(table_id = table, column = 2+i, row = 0, text = str.tostring(1+i), text_font_family = font.family_monospace, text_color = color.silver, text_size = size.small)
for i = 0 to 9
table.cell(table_id = table, column = 1, row = 1+i, text = str.tostring(1+i), text_font_family = font.family_monospace, text_color = color.silver, text_size = size.small)
table.cell(table_id = table, column = 1, row = 11, text = "AVG", text_font_family = font.family_monospace, text_color = color.silver, text_size = size.small)
table.cell(table_id = table, column = 1, row = 12, text = "AVGnow", text_font_family = font.family_monospace, text_color = color.silver, text_size = size.small)
table.cell(table_id = table, column = 2, row = 13, text = "" + str.tostring(sumClose), text_font_family = font.family_monospace, text_color = color.silver, text_size = size.small, bgcolor = color.new(#414b70, 10))
for i = 0 to size10 -1
table.cell(table, 2+i, 1, str.tostring(array.get(sumClose10, i), "##.##") , bgcolor = color.new(#222020, 10), text_color = color.white, text_size = size.small)
for i = 0 to size9 -1
table.cell(table, 2+i, 2, str.tostring(array.get(sumClose9, i), "##.##") , bgcolor = color.new(#222020, 10), text_color = color.white, text_size = size.small)
for i = 0 to size8 -1
table.cell(table, 2+i, 3, str.tostring(array.get(sumClose8, i), "##.##") , bgcolor = color.new(#222020, 10), text_color = color.white, text_size = size.small)
for i = 0 to size7 -1
table.cell(table, 2+i, 4, str.tostring(array.get(sumClose7, i), "##.##") , bgcolor = color.new(#222020, 10), text_color = color.white, text_size = size.small)
for i = 0 to size6 -1
table.cell(table, 2+i, 5, str.tostring(array.get(sumClose6, i), "##.##") , bgcolor = color.new(#222020, 10), text_color = color.white, text_size = size.small)
for i = 0 to size5 -1
table.cell(table, 2+i, 6, str.tostring(array.get(sumClose5, i), "##.##") , bgcolor = color.new(#222020, 10), text_color = color.white, text_size = size.small)
for i = 0 to size4 -1
table.cell(table, 2+i, 7, str.tostring(array.get(sumClose4, i), "##.##") , bgcolor = color.new(#222020, 10), text_color = color.white, text_size = size.small)
for i = 0 to size3 -1
table.cell(table, 2+i, 8, str.tostring(array.get(sumClose3, i), "##.##") , bgcolor = color.new(#222020, 10), text_color = color.white, text_size = size.small)
for i = 0 to size2 -1
table.cell(table, 2+i, 9, str.tostring(array.get(sumClose2, i), "##.##") , bgcolor = color.new(#222020, 10), text_color = color.white, text_size = size.small)
for i = 0 to size1 -1
table.cell(table, 2+i, 10, str.tostring(array.get(sumClose1, i), "##.##") , bgcolor = color.new(#222020, 10), text_color = color.white, text_size = size.small)
for i = 0 to size_avg - 1
table.cell(table, 2+i, 11, str.tostring(nz(array.get(index_avg , i)), "##.##") , bgcolor = color.new(#457041, 10), text_color = color.white, text_size = size.small)
for i = 0 to size0 - 1
table.cell(table, 2+i, 12, str.tostring(array.get(sumClose00, i), "##.##") , bgcolor = color.new(#414b70, 10), text_color = color.white, text_size = size.small)
//"TradingPeriode from first to last >> "
table.cell(table, 1, 13, text="Cons", text_color = color.white, text_size = size.small)
//"Open-Close Price Change >> "
table.cell(table, 3, 13, text="Trend" , bgcolor = color.new(#414b70, 10), text_color = color.white, text_size = size.small)
//"Open-Close Avg. Change in % of Length LongTerm >> "
table.cell(table, 4, 13, str.tostring(r_avg_value, "LT ##.##") , bgcolor = color.new(#414b70, 10), text_color = color.white, text_size = size.small)
//"Open-Close Avg. Change in % of Length ShortTerm >> "
table.cell(table, 5, 13, str.tostring(r_avg_value1, "ST ##.##") , bgcolor = color.new(#414b70, 10), text_color = color.white, text_size = size.small)
//"This Year is over or under Avg of last 10 Year LongTerm >> "
table.cell(table, 6, 13, str.tostring(bull_or_bear) , bgcolor = color.new(#414b70, 10), text_color = bull_or_bear_color1, text_size = size.small)
//"This Year is over or under Avg of last 10 Year ShortTerm >> "
table.cell(table, 7, 13, str.tostring(bull_or_bear1) , bgcolor = color.new(#414b70, 10), text_color = bull_or_bear_color1, text_size = size.small)
//"MAX
table.cell(table, 9, 13, text="MAX", bgcolor = color.new(#457041, 10), text_color = color.white, text_size = size.small)
table.cell(table, 10, 13, str.tostring(array.max(index_avg), "##.##") , bgcolor = color.new(#457041, 10), text_color = color.white, text_size = size.small)
//"MIN
table.cell(table, 11, 13, text="MIN" , bgcolor = color.new(#457041, 10), text_color = color.white, text_size = size.small)
table.cell(table, 12, 13, str.tostring(array.min(index_avg), "##.##") , bgcolor = color.new(#457041, 10), text_color = color.white, text_size = size.small)
//"AVG
table.cell(table, 13, 13, text="AVG" , bgcolor = color.new(#457041, 10), text_color = color.white, text_size = size.small)
table.cell(table, 14, 13, str.tostring(avg_value, "##.##") , bgcolor = color.new(#457041, 10), text_color = color.white, text_size = size.small)
table.cell(table, 16, 13, text="C.1/10", bgcolor = color.new(#723f35, 10), text_color = color.white, text_size = size.small)
table.cell(table, 17, 13, str.tostring(array.get(check, 0), "##.##") , bgcolor = color.new(#723f35, 10), text_color = color.white, text_size = size.small)
max_0 = array.max(index_avg)
min_0 = array.min(index_avg)
avg_0 = avg_value
//barcolor 1 candle average is > or < than arrays average
gradientl1 = color.from_gradient(r_avg_value1, avg_0, max_0, gradient_upcolor_weak_bar , gradient_upcolor_strong_bar)
gradients1 = color.from_gradient(r_avg_value1, min_0, avg_0, gradient_downcolor_strong_bar, gradient_downcolor_weak_bar)
gradient1 = r_avg_value1 > avg_0 ? gradientl1 : gradients1
barcolor(gradient1, title="Candle is > or < than arrays average")
//bull and bear conditions
gradientl = color.from_gradient(r_avg_value, avg_0, max_0, gradient_upcolor_weak , gradient_upcolor_strong)
gradients = color.from_gradient(r_avg_value, min_0, avg_0, gradient_downcolor_strong, gradient_downcolor_weak)
gradient = r_avg_value > avg_0 ? gradientl : gradients
max_min_calculation_to_add_to_MidBand = input(5, title = "MIN & MAX Band", tooltip = "This will calculate the upper and lower Band. That means its added to the MidBand, which is an SMA of Close with the length of 21, to add the average Change of the time chosen Array")
max = ta.sma(close, max_min_calculation_to_add_to_MidBand) * (1 + max_0 / 100)
min = ta.sma(close, max_min_calculation_to_add_to_MidBand ) * (1 + min_0 / 100)
band = input(21, title = "MIN; MAX; MID Band Length")
min_band = ta.sma(min, band)
mid_band = ta.sma(close, band)
max_band = ta.sma(max, band)
channel_8 = ta.sma(low, 8)
channel_10 = ta.sma(high, 10)
channel_col = channel_8 > mid_band ? color.rgb(11, 82, 139, 80) : channel_10 < mid_band ? color.rgb(136, 20, 123, 80) : color.rgb(81, 77, 81, 70)
plot(min_band, color=gradient, linewidth = 2, title = "MIN AVG - Lower Band")
plot(mid_band, color=gradient, linewidth = 2, title = "AVG - Mid Band")
plot(max_band, color=gradient, linewidth = 2, title = "MAX AVG - Upper Band")
p6 = plot(channel_8, color=channel_col, title = "SMA 8 low Band")
p7 = plot(channel_10, color=channel_col, title = "SMA 10 high Band")
fill(p7, p6, channel_col, title = "Channel Color Filling", display = display.none)
month_begin = ta.change(month)
bgcolor(month_begin ? color.rgb(120, 123, 134, 91) : na, display = display.none) |
Market Structure | https://www.tradingview.com/script/MfVtpaOZ-Market-Structure/ | cryptonnnite | https://www.tradingview.com/u/cryptonnnite/ | 89 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © cryptonnnite
//@version=5
indicator( "Market Structure", overlay = true, max_bars_back = 5000, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
//#region[Inputs]
_showST = input.bool(true, title = "Short Term", inline = "1")
_stColor = input.color(color.black, "", inline = "1")
_showIT = input.bool(true, title = "Intermediate Term", inline = "2")
_itColor = input.color(color.orange, "", inline = "2")
_showLT = input.bool(true, title = "Long Term", inline = "3")
_ltColor = input.color(color.green, "", inline = "3")
//#endregion
//#region[Functions and Methods]
method oldSwing(array<label> a, type) =>
if type == "high"
label.get_y(a.get(a.size()-1)) < label.get_y(a.get(a.size()-2)) and
label.get_y(a.get(a.size()-2)) > label.get_y(a.get(a.size()-3))
else if type == 'low'
label.get_y(a.get(a.size()-1)) > label.get_y(a.get(a.size()-2)) and
label.get_y(a.get(a.size()-2)) < label.get_y(a.get(a.size()-3))
ict_SwingStructure(array<label> stA, bool showST,
array<label> itA, bool showIT,
array<label> ltA, bool showLT,
type) =>
color cNONE = color.new(color.white, 100)
int swing = na
float price = na
string lbl = na
string _yloc = na
string lblText = ""
if type == "high"
swing := ta.highestbars(3)
price := high[1]
lbl := label.style_label_down
lblText := "▼"
_yloc := yloc.price
else if type == "low"
swing := ta.lowestbars(3)
price := low[1],
lblText := "▲"
lbl := label.style_label_up
_yloc := yloc.price
if swing == -1
stA.push(label.new(bar_index-1, price, lblText, color = cNONE, style = lbl, yloc = _yloc, textcolor = showST ? _stColor : na, size= size.normal))
if stA.size() > 2
if stA.oldSwing(type)
it = label.copy(stA.get(stA.size()-2))
label.set_textcolor(it, showIT ? _itColor : na)
if not(itA.size() > 0)
itA.push(it)
else if label.get_y(itA.get(itA.size()-1)) != label.get_y(it)
itA.push(it)
if itA.size() > 2
if itA.oldSwing(type)
lt = label.copy(itA.get(itA.size()-2))
label.set_textcolor(lt, showLT ? _ltColor : na)
if not(ltA.size() > 0)
ltA.push(lt)
else if label.get_y(ltA.get(ltA.size()-1)) != label.get_y(lt)
ltA.push(lt)
ict_SimpleMarketStructure(array<label> stH, array<label> stL, bool showST,
array<label> itH, array<label> itL, bool showIT,
array<label> ltH, array<label> ltL, bool showLT) =>
ict_SwingStructure(stH, showST,
itH, showIT,
ltH, showLT,
"high")
ict_SwingStructure(stL, showST,
itL, showIT,
ltL, showLT,
"low")
//#endregion
//#region[Logic]
var label[] stHigh = array.new<label>()
var label[] itHigh = array.new<label>()
var label[] ltHigh = array.new<label>()
var label[] stLow = array.new<label>()
var label[] itLow = array.new<label>()
var label[] ltLow = array.new<label>()
ict_SimpleMarketStructure(stHigh, stLow, _showST,
itHigh, itLow, _showIT,
ltHigh, ltLow, _showLT)
//#endregion |
Volume SuperTrend AI (Expo) | https://www.tradingview.com/script/eTgP2ymK-Volume-SuperTrend-AI-Expo/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 2,430 | 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/
// © Zeiierman
//@version=5
indicator("Volume SuperTrend AI (Expo)", overlay=true)
// ~~ ToolTips {
t1="Number of nearest neighbors in KNN algorithm (k): Increase to consider more neighbors, providing a more balanced view but possibly smoothing out local patterns. Decrease for fewer neighbors to make the algorithm more responsive to recent changes. \n\nNumber of data points to consider (n): Increase for more historical data, providing a broader context but possibly diluting recent trends. Decrease for less historical data to focus more on recent behavior."
t2="Length of weighted moving average for price (KNN_PriceLen): Higher values create a smoother price line, influencing the KNN algorithm to be more stable but less sensitive to short-term price movements. Lower values enhance responsiveness in KNN predictions to recent price changes but may lead to more noise. \n\nLength of weighted moving average for SuperTrend (KNN_STLen): Higher values lead to a smoother SuperTrend line, affecting the KNN algorithm to emphasize long-term trends. Lower values make KNN predictions more sensitive to recent SuperTrend changes but may result in more volatility."
t3="Length of the SuperTrend (len): Increase for a smoother trend line, ideal for identifying long-term trends but possibly ignoring short-term fluctuations. Decrease for more responsiveness to recent changes but risk of more false signals. \n\nMultiplier for ATR in SuperTrend calculation (factor): Increase for wider bands, capturing larger price movements but possibly missing subtle changes. Decrease for narrower bands, more sensitive to small shifts but risk of more noise."
t4="Type of moving average for SuperTrend calculation (maSrc): Choose based on desired characteristics. SMA is simple and clear, EMA emphasizes recent prices, WMA gives more weight to recent data, RMA is less sensitive to recent changes, and VWMA considers volume."
t5="Color for bullish trend (upCol): Select to visually identify upward trends. \n\nColor for bearish trend (dnCol): Select to visually identify downward trends.\n\nColor for neutral trend (neCol): Select to visually identify neutral trends."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Input settings for K and N values
k = input.int(3, title = "Neighbors", minval=1, maxval=100,inline="AI", group="AI Settings")
n_ = input.int(10, title ="Data", minval=1, maxval=100,inline="AI", group="AI Settings", tooltip=t1)
n = math.max(k,n_)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Input settings for prediction values
KNN_PriceLen = input.int(20, title="Price Trend", minval=2, maxval=500, step=10,inline="AITrend", group="AI Trend")
KNN_STLen = input.int(100, title="Prediction Trend", minval=2, maxval=500, step=10, inline="AITrend", group="AI Trend", tooltip=t2)
aisignals = input.bool(true,title="AI Trend Signals",inline="signal", group="AI Trend")
Bullish_col = input.color(color.lime,"",inline="signal", group="AI Trend")
Bearish_col = input.color(color.red,"",inline="signal", group="AI Trend")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define SuperTrend parameters
len = input.int(10, "Length", minval=1,inline="SuperTrend", group="Super Trend Settings")
factor = input.float(3.0,step=.1,inline="SuperTrend", group="Super Trend Settings", tooltip=t3)
maSrc = input.string("WMA","Moving Average Source",["SMA","EMA","WMA","RMA","VWMA"],inline="", group="Super Trend Settings", tooltip=t4)
upCol = input.color(color.lime,"Bullish Color",inline="col", group="Super Trend Coloring")
dnCol = input.color(color.red,"Bearish Color",inline="col", group="Super Trend Coloring")
neCol = input.color(color.blue,"Neutral Color",inline="col", group="Super Trend Coloring", tooltip=t5)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Calculate the SuperTrend based on the user's choice
vwma = switch maSrc
"SMA" => ta.sma(close*volume, len) / ta.sma(volume, len)
"EMA" => ta.ema(close*volume, len) / ta.ema(volume, len)
"WMA" => ta.wma(close*volume, len) / ta.wma(volume, len)
"RMA" => ta.rma(close*volume, len) / ta.rma(volume, len)
"VWMA" => ta.vwma(close*volume, len) / ta.vwma(volume, len)
atr = ta.atr(len)
upperBand = vwma + factor * atr
lowerBand = vwma - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := close > upperBand ? -1 : 1
else
direction := close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Collect data points and their corresponding labels
price = ta.wma(close,KNN_PriceLen)
sT = ta.wma(superTrend,KNN_STLen)
data = array.new_float(n)
labels = array.new_int(n)
for i = 0 to n - 1
data.set(i, superTrend[i])
label_i = price[i] > sT[i] ? 1 : 0
labels.set(i, label_i)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define a function to compute distance between two data points
distance(x1, x2) =>
math.abs(x1 - x2)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define the weighted k-nearest neighbors (KNN) function
knn_weighted(data, labels, k, x) =>
n1 = data.size()
distances = array.new_float(n1)
indices = array.new_int(n1)
// Compute distances from the current point to all other points
for i = 0 to n1 - 1
x_i = data.get(i)
dist = distance(x, x_i)
distances.set(i, dist)
indices.set(i, i)
// Sort distances and corresponding indices in ascending order
// Bubble sort method
for i = 0 to n1 - 2
for j = 0 to n1 - i - 2
if distances.get(j) > distances.get(j + 1)
tempDist = distances.get(j)
distances.set(j, distances.get(j + 1))
distances.set(j + 1, tempDist)
tempIndex = indices.get(j)
indices.set(j, indices.get(j + 1))
indices.set(j + 1, tempIndex)
// Compute weighted sum of labels of the k nearest neighbors
weighted_sum = 0.
total_weight = 0.
for i = 0 to k - 1
index = indices.get(i)
label_i = labels.get(index)
weight_i = 1 / (distances.get(i) + 1e-6)
weighted_sum += weight_i * label_i
total_weight += weight_i
weighted_sum / total_weight
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Classify the current data point
current_superTrend = superTrend
label_ = knn_weighted(data, labels, k, current_superTrend)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plot
col = label_ == 1?upCol:label_ == 0?dnCol:neCol
plot(current_superTrend, color=col, title="Volume Super Trend AI")
upTrend = plot(superTrend==lowerBand?current_superTrend:na, title="Up Volume Super Trend AI", color=col, style=plot.style_linebr)
Middle = plot((open + close) / 2, display=display.none, editable=false)
downTrend = plot(superTrend==upperBand?current_superTrend:na, title="Down Volume Super Trend AI", color=col, style=plot.style_linebr)
fill_col = color.new(col,90)
fill(Middle, upTrend, fill_col, fillgaps=false,title="Up Volume Super Trend AI")
fill(Middle, downTrend, fill_col, fillgaps=false, title="Down Volume Super Trend AI")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Ai Super Trend Signals
Start_TrendUp = col==upCol and (col[1]!=upCol or col[1]==neCol) and aisignals
Start_TrendDn = col==dnCol and (col[1]!=dnCol or col[1]==neCol) and aisignals
TrendUp = direction == -1 and direction[1] == 1 and label_ == 1 and aisignals
TrendDn = direction == 1 and direction[1] ==-1 and label_ == 0 and aisignals
plotshape(Start_TrendUp?superTrend:na, location=location.absolute, style= shape.circle, size=size.tiny, color=Bullish_col, title="AI Bullish Trend Start")
plotshape(Start_TrendDn?superTrend:na, location=location.absolute, style= shape.circle,size=size.tiny, color=Bearish_col, title="AI Bearish Trend Start")
plotshape(TrendUp?superTrend:na, location=location.absolute, style= shape.triangleup, size=size.small, color=Bullish_col, title="AI Bullish Trend Signal")
plotshape(TrendDn?superTrend:na, location=location.absolute, style= shape.triangledown,size=size.small, color=Bearish_col, title="AI Bearish Trend Signal")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Alerts {
alertcondition(Start_TrendUp, title ="1 Bullish Trend Start", message = "AI Bullish Trend Start")
alertcondition(Start_TrendDn, title ="2 Bearish Trend Start", message = "AI Bearish Trend Start")
alertcondition((Start_TrendUp or Start_TrendDn), title ="3 Any Trend Start", message="Any AI Trend Start")
alertcondition(TrendUp, title = "4 Bullish Trend Signal", message = "AI Bullish Trend Signal")
alertcondition(TrendDn, title = "5 Bearish Trend Signal", message = "AI Bearish Trend Signal")
alertcondition((TrendUp or TrendDn),title = "6 Any Trend Signal", message ="Any AI Trend Signal")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
KeitoFX Dynamic Indicator Free vers. | https://www.tradingview.com/script/YbE7gfGT-KeitoFX-Dynamic-Indicator-Free-vers/ | uniuxfu | https://www.tradingview.com/u/uniuxfu/ | 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/
// © uniuxfu
//@version=5
indicator("KeitoFX Dynamic Indicator Free vers.", overlay=true)
// Check if the current timeframe is between 1m and 5m
isAllowedTimeframe() =>
timeframe.multiplier >= 1 and timeframe.multiplier <= 5 and timeframe.isintraday
// DYNAMIC FVG
var int maruBodyHeight = 10
bool dynamic = false
bool bullDynamic = close == high and (dynamic ? open == low : true)
bool bearDynamic = close == low and (dynamic ? open == high : true)
// Engulfing Candles
// --------------- INPUTS ---------------
var bool show_H1 = true
var bool show_H4 = false
var bool show_CUR = false
var bool filter_liqudity = true
var bool filter_close = true
// --------------- function ---------------
drawing_lec() =>
bull_engulf = false
bear_engulf = false
if barstate.isnew
prior_open = open[1]
prior_close = close[1]
current_open = open
current_close = close
bull_engulf := (current_open <= prior_close) and (current_open < prior_open) and (current_close > prior_open)
bear_engulf := (current_open >= prior_close) and (current_open > prior_open) and (current_close < prior_open)
if filter_liqudity
bull_engulf := bull_engulf and low <= low[1]
bear_engulf := bear_engulf and high >= high[1]
if filter_close
bull_engulf := bull_engulf and close >= high[1]
bear_engulf := bear_engulf and close <= low[1]
[bull_engulf, bear_engulf]
[bull_engulf_H1, bear_engulf_H1] = request.security(syminfo.tickerid, "60", drawing_lec())
[bull_engulf_H4, bear_engulf_H4] = request.security(syminfo.tickerid, "240", drawing_lec())
[bull_engulf_CUR, bear_engulf_CUR] = request.security(syminfo.tickerid, timeframe.period, drawing_lec())
// Displacement settings
var bool require_fvg = true
var string disp_type = "Open to Close"
var int std_len = 100
var float std_x = 1.5
var color disp_color = input.color(#e5e0ff, "Bar Color")
float candle_range = disp_type == "Open to Close" ? math.abs(open - close) : high - low
float std = ta.stdev(candle_range, std_len) * std_x
bool fvg = close[1] > open[1] ? high[2] < low[0] : low[2] > high[0]
bool displacement = require_fvg ? candle_range[1] > std[1] and fvg : candle_range > std
barcolor(isAllowedTimeframe() and displacement ? disp_color : na, offset = require_fvg ? -1 : na) |
Bolton-Tremblay Index | https://www.tradingview.com/script/DAqco300-Bolton-Tremblay-Index/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 105 | 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/
// © QuantiLuxe
//@version=5
indicator("Bolton-Tremblay Index", "[Ʌ] - BOLTR", false)
type bar
float o = open
float h = high
float l = low
float c = close
method src(bar b, simple string src) =>
float x = switch src
'oc2' => math.avg(b.o, b.c )
'hl2' => math.avg(b.h, b.l )
'hlc3' => math.avg(b.h, b.l, b.c )
'ohlc4' => math.avg(b.o, b.h, b.l, b.c)
'hlcc4' => math.avg(b.h, b.l, b.c, b.c)
x
method null(bar b) =>
na(b) ? bar.new(0, 0, 0, 0) : b
method ha(bar b, simple bool p = true) =>
var bar x = bar.new( )
x.c := b .src('ohlc4')
x := bar.new(
na(x.o[1]) ?
b.src('oc2') : nz(x.src('oc2')[1]),
math.max(b.h, math.max(x.o, x.c)) ,
math.min(b.l, math.min(x.o, x.c)) ,
x.c )
p ? x : b
var string gb = 'Bolton-Tremblay', var string ge = 'EMAs'
idx = input.string('NYSE', "Index ", ['NYSE', 'NASDAQ', 'AMEX'], group = gb)
ma1 = input.bool (true , "EMA |", inline = '1', group = ge)
len1 = input.int (20 , "Length", inline = '1', group = ge)
ma2 = input.bool (true , "EMA |", inline = '2', group = ge)
len2 = input.int (50 , "Length", inline = '2', group = ge)
[tick_adv, tick_dec, tick_unch] = switch idx
'NYSE' => ['ADV' , 'DECL' , 'UCHG' ]
'NASDAQ' => ['ADVQ', 'DECLQ', 'UCHGQ']
'AMEX' => ['ADVA', 'DECLA', 'UCHGA']
bar adv = request.security('USI:' + tick_adv , '', bar.new()).null()
bar dec = request.security('USI:' + tick_dec , '', bar.new()).null()
bar unc = request.security('USI:' + tick_unch, '', bar.new()).null()
float r = (adv.c - dec.c) / unc.c
float a = math.sqrt(math.abs(r) )
float b = ta .cum (r > 0 ? a : -a)
bar bt = bar .new (
b[1] ,
math.max(b, b[1]),
math.min(b, b[1]),
b ).ha()
var color colup = #fff2cc
var color coldn = #6fa8dc
var color colema1 = #FFD6E8
var color colema2 = #9a9adf
color haColor = switch
bt.c > bt.o => colup
bt.c < bt.o => coldn
plotcandle(bt.o, bt.h, bt.l, bt.c,
"BOLTR", haColor, haColor, bordercolor = haColor)
plot(ma1 ? ta.ema(bt.c, len1) : na, " 𝘌𝘔𝘈 1", colema1)
plot(ma2 ? ta.ema(bt.c, len2) : na, " 𝘌𝘔𝘈 2", colema2)
//Source Construction For Indicator\Strategy Exports
plot(bt.o , "open" , editable = false, display = display.none)
plot(bt.h , "high" , editable = false, display = display.none)
plot(bt.l , "low" , editable = false, display = display.none)
plot(bt.c , "close", editable = false, display = display.none)
plot(bt.src('hl2' ), "hl2" , editable = false, display = display.none)
plot(bt.src('hlc3' ), "hlc3" , editable = false, display = display.none)
plot(bt.src('ohlc4'), "ohlc4", editable = false, display = display.none)
plot(bt.src('hlcc4'), "hlcc4", editable = false, display = display.none) |
MarketSmith Daily Market Indicators | https://www.tradingview.com/script/W08L50WQ-MarketSmith-Daily-Market-Indicators/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 314 | study | 5 | MPL-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("Marketsmith Daily Market Indicators", shorttitle = 'MSDI')
//----------inputs----------//
index = input.string('Nasdaq', 'Index for Data', options = ['Nasdaq', 'NYSE'])
dataPlots = input.string('Advance/Decline Line', 'Data to Plot', options = ['Advance/Decline Line', 'Overbought / Oversold Oscillator', '10 Day Average Up / Down Volume', '10 Day Average New Highs / Lows'])
water = input.bool(false, 'Show Watermark', inline = '1')
waterCol = input.color(color.gray, ' ', inline = '1')
var g1 = 'Data Table'
showTable = input.bool(true, 'Show Data Table', group = g1)
yPos = input.string('Top', 'Table Position ', options = ['Top', 'Middle', 'Bottom'], inline = '1', group = g1)
xPos = input.string('Left', ' ', options = ['Right','Center', 'Left'], inline = '1', group = g1)
bgCol = input.color(color.gray, 'Cell Color', inline = '2', group = g1)
txtCol = input.color(color.white,'Text Color', inline = '2', group = g1)
var g2 = 'Other Options'
showNHL = input.bool(false, 'Show Daily Net New Highs / Lows Histogram', group = g2)
showMa = input.bool(false, 'Show Advance Decline Line Moving Average', group = g2)
maLen = input.int(10, 'Moving Average', inline = '1', group = g2)
maType = input.string('SMA', ' ', ['SMA', 'EMA'], inline = '1', group = g2)
maOffset = input.int(0, 'Offset', inline = '2', group = g2)
maCol = input.color(color.red, ' ', inline = '2', group = g2)
//----------functions----------//
getInfo(sym)=>
request.security(sym, 'D', close)
adlCalc(difference)=>
ta.cum(difference > 0 ? math.sqrt(difference) : -math.sqrt(-difference))
//----------requests----------//
//----------nasdaq data----------//
advNas = getInfo('ADVN.NQ')
decNas = getInfo('DECL.NQ')
unchNas = getInfo('UNCH.NQ')
uVolNas = getInfo('UVOLQ')
dVolNas = getInfo('DVOLQ')
tVolNas = getInfo('TVOLQ')
hq = getInfo('HIGQ')
lq = getInfo('LOWQ')
//----------nyse data----------//
advNyse = getInfo('ADVN.NY')
decNyse = getInfo('DECL.NY')
unchNyse = getInfo('UNCH.NY')
uVolNyse = getInfo('UVOL')
dVolNyse = getInfo('DVOL')
tVolNyse = getInfo('TVOL')
hn = getInfo('HIGN')
ln = getInfo('LOWN')
//----------advance decline lines----------//
adlNY = request.security("(USI:ADVN.NY - USI:DECL.NY) / (USI:UNCH.NY + 1)", 'D', adlCalc(close))
adlNAS = request.security("(USI:ADVN.NQ - USI:DECL.NQ) / (USI:UNCH.NQ + 1)", 'D', adlCalc(close))
ma = index == 'Nasdaq' ? maType == 'SMA' ? ta.sma(adlNAS,maLen) : ta.ema(adlNAS, maLen) : maType == 'SMA' ? ta.sma(adlNY,maLen) : ta.ema(adlNY,maLen)
//----------overbough oversold oscillator----------//
advDecNas = advNas - decNas
advDecNyse = advNyse - decNyse
obos = index == 'Nasdaq' ? ta.sma(advDecNas,10) : ta.sma(advDecNyse,10)
//----------up and down volume----------//
upMa = index == 'Nasdaq' ? ta.sma(uVolNas,10) : ta.sma(uVolNyse,10)
dnMa = index == 'Nasdaq' ? ta.sma(dVolNas,10) : ta.sma(dVolNyse,10)
//----------new highs/lows----------//
nhMa = index == 'Nasdaq' ? ta.sma(hq,10) : ta.sma(hn,10)
nlMa = index == 'Nasdaq' ? ta.sma(lq,10) : ta.sma(ln,10)
nhl = index == 'Nasdaq' ? hq - lq : hn - ln
//----------data table----------//
var table data = table.new(str.lower(yPos) + '_' + str.lower(xPos), 2, 4, color.new(color.white,100), color.new(color.white,100), 1, color.new(color.white,100), 1)
if barstate.islast and showTable
data.cell(0,0, '')
data.merge_cells(0,0,1,0)
data.cell(0,1, index == 'Nasdaq' ? str.tostring(advNas) + ' Advanced on ' + str.tostring(uVolNas) : str.tostring(advNyse) + ' Advanced on ' + str.tostring(uVolNyse), bgcolor = bgCol, text_color = txtCol)
data.cell(0,2, index == 'Nasdaq' ? str.tostring(decNas) + ' Declined on ' + str.tostring(dVolNas) : str.tostring(decNyse) + ' Declined on ' + str.tostring(dVolNyse), bgcolor = bgCol, text_color = txtCol)
data.cell(0,3, index == 'Nasdaq' ? str.tostring(unchNas) + ' Unchanged on ' + str.tostring(tVolNas - uVolNas - dVolNas) : str.tostring(unchNyse) + ' Unchanged on ' + str.tostring(tVolNyse - uVolNyse - dVolNyse), bgcolor = bgCol, text_color = txtCol)
data.cell(1,1, index == 'Nasdaq' ? str.tostring(hq) + ' Made New Highs' : str.tostring(hn) + ' Made New Highs', bgcolor = bgCol, text_color = txtCol)
data.cell(1,2, index == 'Nasdaq' ? str.tostring(lq) + ' Made New Lows' : str.tostring(ln) + ' Made New Lows', bgcolor = bgCol, text_color = txtCol)
//----------plots----------//
plot(dataPlots == 'Advance/Decline Line' ? index == 'Nasdaq' ? adlNAS * (maOffset + 1) : adlNY * (maOffset + 1) : na, 'Advance/Decline Line', color.blue, 2)
plot(showMa and dataPlots == 'Advance/Decline Line' ? ma * (maOffset + 1) : na, 'Advance/Decline Line Moving Average', maCol)
plot(dataPlots == 'Overbought / Oversold Oscillator' ? 0 : na, 'Zero Line', color = color.red, display = display.pane)
plot(dataPlots == 'Overbought / Oversold Oscillator' ? obos : na, 'Overbought / Oversold Oscillator', color.blue, 2)
plot(dataPlots == '10 Day Average Up / Down Volume' ? upMa : na, 'Up Volume', color.blue, 2)
plot(dataPlots == '10 Day Average Up / Down Volume' ? dnMa : na, 'Down Volume', color.red, 2)
plot(dataPlots == '10 Day Average New Highs / Lows' ? nhMa : na, 'New Highs', color.blue, 2)
plot(dataPlots == '10 Day Average New Highs / Lows' ? nlMa : na, 'New Lows', color.red, 2)
plot(dataPlots == '10 Day Average New Highs / Lows' and showNHL ? nhl : na, 'Daily Net Highs / Lows', nhl > 0 ? color.green : color.red, 2, style = plot.style_histogram)
//----------watermark----------//
var table waterM = table.new(position.top_center, 1, 1, color.new(color.white,100), color.new(color.white,100), 0, color.new(color.white,100), 0)
waterTxt = dataPlots == 'Advance/Decline Line' ? 'Advance Decline Line' : dataPlots == 'Overbought / Oversold Oscillator' ? 'Overbought / Oversold Oscillator' : dataPlots == '10 Day Average Up / Down Volume' ? '10 Day Average Up / Down Volume' : '10 Day Average New Highs / Lows'
if water
waterM.cell(0, 0, waterTxt, text_color = waterCol) |
Liquidity Levels/Voids (VP) [LuxAlgo] | https://www.tradingview.com/script/3ONrWovL-Liquidity-Levels-Voids-VP-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,809 | 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 Levels/Voids (VP) [LuxAlgo]", "LuxAlgo - Liquidity Levels/Voids (VP)", true, max_bars_back = 5000, max_boxes_count = 500) // , max_labels_count = 500, max_lines_count = 500
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
mdTT = 'The mode option controls the number of visual objects presented, where\n\n- Historical, takes into account all data available to the user\n- Present, takes into account only the last X bars specified in the \'# Bars\' option\n\nPossible \'# Bars\' values [100-5000]'
mode = input.string('Present', title = 'Mode', options =['Present', 'Historical'], inline = 'MOD')
back = input.int (360, ' # Bars', minval = 100, maxval = 5000, step = 10, inline = 'MOD', tooltip = mdTT)
grpLQ = 'Liquidity Levels / Voids'
liqUC = input.color(color.new(#1848cc, 79), 'Liquidity Levels/Voids', inline = 'UFL', group = grpLQ, tooltip = 'Color customization option for Unfilled Liquidity Levels/Voids')
ppLen = input.int(47, "Detection Length", minval = 1, group = grpLQ, tooltip = 'Lookback period used for the calculation of Swing Levels\n\nMinimum value [1]')
liqT = input.int(21, 'Threshold %', minval = 1, maxval = 51, group = grpLQ, tooltip = 'Threshold used for the calculation of the Liquidity Levels & Voids\n\nPossible values [1-51]') / 100
vpLev = input.int(27, 'Sensitivity' , minval = 10, maxval = 100, step = 1, group = grpLQ, tooltip = 'Adjusts the number of levels between two swing points, as a result, the height of a level is determined and then based on the above-given threshold the level is checked if it matches the liquidity level/void conditions\n\nPossible values [10-100]')
liqFD = input.bool(false, 'Filled Liquidity Levels/Voids', inline = 'FL', group = grpLQ, tooltip = 'Toggles the visibility of the Filled Liquidity Levels/Voids and color customization option for Filled Liquidity Levels/Voids')
liqFC = input.color(color.new(#787b86, 79), '', inline = 'FL', group = grpLQ)
othGR = 'Other Features'
ppLev = input.bool(false, 'Swing Highs/Lows', inline = 'ppLS', group = othGR, tooltip = 'Toggles the visibility of the Swing Levels, where tooltips present statistical information, such as price, price change, and cumulative volume between the two swing levels detected based on the detection length specified above\n\nColoring options to customize swing low and swing high label colors and Size option to adjust the size of the labels')
ppLCB = input.color(color.new(#f23645, 0), '', inline = 'ppLS', group = othGR)
ppLCS = input.color(color.new(#089981, 0), '', inline = 'ppLS', group = othGR)
ppLS = input.string('Small', "", options=['Tiny', 'Small', 'Normal'], inline = 'ppLS', group = othGR)
//-----------------------------------------------------------------------------}
// User Defined Types
//-----------------------------------------------------------------------------{
// @type bar properties with their values
//
// @field h (float) high price of the bar
// @field l (float) low price of the bar
// @field v (float) volume of the bar
// @field i (int) index of the bar
type bar
float h = high
float l = low
float v = volume
int i = bar_index
// @type store pivot high/low and index data
//
// @field x (int) last pivot bar index
// @field x1 (int) previous pivot bar index
// @field h (float) last pivot high
// @field h1 (float) previous pivot high
// @field l (float) last pivot low
// @field l1 (float) previous pivot low
type pivotPoint
int x
int x1
float h
float h1
float l
float l1
// @type maintain liquidity data
//
// @field b (array<bool>) array maintains price levels where liquidity exists
// @field bx (array<box>) array maintains visual object of price levels where liquidity exists
type liquidity
bool [] b
box [] bx
// @type maintain volume profile data
//
// @field vs (array<float>) array maintains tolal traded volume
// @field vp (array<box>) array maintains visual object of each price level
type volumeProfile
float [] vs
box [] vp
//-----------------------------------------------------------------------------}
// Variables
//-----------------------------------------------------------------------------{
bar b = bar.new()
var pivotPoint pp = pivotPoint.new()
var liquidity[] aLIQ = array.new<liquidity> (1, liquidity.new(array.new <bool> (vpLev, false), array.new <box> (na)))
var liquidity[] dLIQ = array.new<liquidity> (1, liquidity.new(array.new <bool> (na) , array.new <box> (na)))
volumeProfile aVP = volumeProfile.new(array.new <float> (vpLev + 1, 0.), array.new <box> (na))
qBXs = 0
//-----------------------------------------------------------------------------}
// Functions/methods
//-----------------------------------------------------------------------------{
// @function calcuates highest price, lowest price and cumulative volume of the given range
//
// @param _l (int) length of the range
// @param _c (bool) check
// @param _o (int) offset
//
// @returns (float, float, float) highest, lowest and cumulative volume
f_calcHLV(_l, _c, _o) =>
if _c
l = low [_o]
h = high[_o]
v = 0.
for x = 0 to _l - 1
l := math.min(low [_o + x], l)
h := math.max(high[_o + x], h)
v += volume[_o + x]
l := math.min(low [_o + _l], l)
h := math.max(high[_o + _l], h)
[h, l, v]
//-----------------------------------------------------------------------------}
// Calculations
//-----------------------------------------------------------------------------{
per = mode == 'Present' ? last_bar_index - b.i <= back : true
nzV = nz(b.v)
ppS = switch ppLS
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
pp_h = ta.pivothigh(ppLen, ppLen)
pp_l = ta.pivotlow (ppLen, ppLen)
if not na(pp_h)
pp.h1 := pp.h
pp.h := pp_h
if not na(pp_l)
pp.l1 := pp.l
pp.l := pp_l
go = not na(pp_h) or not na(pp_l)
if go
pp.x1 := pp.x
pp.x := b.i
vpLen = pp.x - pp.x1
[pHst, pLst, tV] = f_calcHLV(vpLen, go, ppLen)
pStp = (pHst - pLst) / vpLev
if go and nzV and pStp > 0 and b.i > vpLen and vpLen > 0 and per
for bIt = vpLen to 1
l = 0
bI = bIt + ppLen
for pLev = pLst to pHst by pStp
if b.h[bI] >= pLev and b.l[bI] < pLev + pStp
aVP.vs.set(l, aVP.vs.get(l) + nzV[bI] * ((b.h[bI] - b.l[bI]) == 0 ? 1 : pStp / (b.h[bI] - b.l[bI])))
l += 1
aLIQ.unshift(liquidity.new(array.new <bool> (vpLev, false), array.new <box> (na)))
cLIQ = aLIQ.get(0)
for l = vpLev - 1 to 0
if aVP.vs.get(l) / aVP.vs.max() < liqT
cLIQ.b.set(l, true)
cLIQ.bx.unshift(box.new(b.i[ppLen], pLst + (l + 0.00) * pStp, b.i[ppLen], pLst + (l + 1.00) * pStp, border_color = color(na), bgcolor = liqUC ))
else
cLIQ.bx.unshift(box.new(na, na, na, na))
cLIQ.b.set(l, false)
for bIt = 0 to vpLen
bI = bIt + ppLen
int qBX = cLIQ.bx.size()
for bx = 0 to (qBX > 0 ? qBX - 1 : na)
if bx < cLIQ.bx.size()
if cLIQ.b.get(bx)
cBX = cLIQ.bx.get(bx)
mBX = math.avg(cBX.get_bottom(), cBX.get_top())
if math.sign(close[bI + 1] - mBX) != math.sign(low[bI] - mBX) or math.sign(close[bI + 1] - mBX) != math.sign(high[bI] - mBX) or math.sign(close[bI + 1] - mBX) != math.sign(close[bI] - mBX)
cBX.set_left(b.i[bI])
cLIQ.b.set(bx, false)
for bI = ppLen to 0
int qBX = cLIQ.bx.size()
for bx = (qBX > 0 ? qBX - 1 : na) to 0
if bx < cLIQ.bx.size()
cBX = cLIQ.bx.get(bx)
mBX = math.avg(box.get_bottom(cBX), box.get_top(cBX))
if math.sign(close[bI + 1] - mBX) != math.sign(low[bI] - mBX) or math.sign(close[bI + 1] - mBX) != math.sign(high[bI] - mBX)
if liqFD
cBX.set_bgcolor(liqFC)
else
cBX.delete()
cLIQ.bx.remove(bx)
else
cBX.set_right(b.i[bI])
for i = aLIQ.size() - 1 to 0
x = aLIQ.get(i)
int qBX = x.bx.size()
qBXs := qBXs + qBX
if qBXs > 500
aLIQ.pop()
for bx = (qBX > 0 ? qBX - 1 : na) to 0
if bx < x.bx.size()
cBX = x.bx.get(bx)
mBX = math.avg(box.get_bottom(cBX), box.get_top(cBX))
if math.sign(close[1] - mBX) != math.sign(low - mBX) or math.sign(close[1] - mBX) != math.sign(high - mBX)
//cBX.delete()
if liqFD
cBX.set_bgcolor(liqFC)
else
cBX.delete()
x.bx.remove(bx)
else
cBX.set_right(b.i)
if ppLev and (mode == 'Present' ? last_bar_index - b.i <= back * 1.318 : true)
statTip = '\n -Traded Volume : ' + str.tostring(tV, format.volume) + ' (' + str.tostring(vpLen - 1) + ' bars)\n *Average Volume/Bar : ' + str.tostring(tV / (vpLen - 1), format.volume)
if not na(pp_h)
swH = pp.h > pp.h1 ? "HH" : pp.h < pp.h1 ? "LH" : na
label.new(b.i[ppLen], pp.h, swH, xloc.bar_index, yloc.price, color(na), label.style_label_down, ppLCS, ppS, text.align_center, 'Swing High : ' + str.tostring(pp.h, format.mintick) + '\n -Price Change : %' + str.tostring((pp.h - pp.l) * 100 / pp.l, '#.##') + statTip)
if not na(pp_l)
swL = pp.l < pp.l1 ? "LL" : pp.l > pp.l1 ? "HL" : na
label.new(b.i[ppLen], pp.l ,swL, xloc.bar_index, yloc.price, color(na), label.style_label_up , ppLCB, ppS, text.align_center, 'Swing Low : ' + str.tostring(pp.l, format.mintick) + '\n -Price Change : %' + str.tostring((pp.h - pp.l) * 100 / pp.h, '#.##') + statTip)
vpLen := barstate.islast ? last_bar_index - pp.x + ppLen : 1
pHst := ta.highest(b.h, vpLen > 0 ? vpLen + 1 : 1)
pLst := ta.lowest (b.l, vpLen > 0 ? vpLen + 1 : 1)
pStp := (pHst - pLst) / vpLev
if barstate.islast and nzV and vpLen > 0 and pStp > 0
tLIQ = dLIQ.shift()
if tLIQ.bx.size() > 0
for i = 0 to tLIQ.bx.size() - 1
tLIQ.bx.shift().delete()
tLIQ.b.shift()
for bI = vpLen to 1 //1 to vpLen
l = 0
for pLev = pLst to pHst by pStp
if b.h[bI] >= pLev and b.l[bI] < pLev + pStp
aVP.vs.set(l, aVP.vs.get(l) + nzV[bI] * ((b.h[bI] - b.l[bI]) == 0 ? 1 : pStp / (b.h[bI] - b.l[bI])))
l += 1
dLIQ.unshift(liquidity.new(array.new <bool> (na), array.new <box> (na)))
cLIQ = dLIQ.get(0)
for l = 0 to vpLev - 1
if aVP.vs.get(l) / aVP.vs.max() < liqT
cLIQ.b.unshift(true)
cLIQ.bx.unshift(box.new(b.i, pLst + (l + 0.00) * pStp, b.i, pLst + (l + 1.00) * pStp, border_color = color(na), bgcolor = liqUC))
else
cLIQ.bx.unshift(box.new(na, na, na, na))
cLIQ.b.unshift(false)
for bI = 0 to vpLen
int qBX = cLIQ.bx.size()
for bx = 0 to (qBX > 0 ? qBX - 1 : na)
if bx < cLIQ.bx.size()
if cLIQ.b.get(bx)
cBX = cLIQ.bx.get(bx)
mBX = math.avg(cBX.get_bottom(), cBX.get_top())
if math.sign(close[bI + 1] - mBX) != math.sign(low[bI] - mBX) or math.sign(close[bI + 1] - mBX) != math.sign(high[bI] - mBX) or math.sign(close[bI + 1] - mBX) != math.sign(close[bI] - mBX)
cBX.set_left(b.i[bI])
cLIQ.b.set(bx, false)
//-----------------------------------------------------------------------------} |
Short Term IndeX | https://www.tradingview.com/script/2OTubMqG-Short-Term-IndeX/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 164 | 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/
// © QuantiLuxe
//@version=5
indicator("Short Term IndeX", "[Ʌ] - STIX", false)
type bar
float o = open
float h = high
float l = low
float c = close
method src(bar b, simple string src) =>
float x = switch src
'oc2' => math.avg(b.o, b.c )
'hl2' => math.avg(b.h, b.l )
'hlc3' => math.avg(b.h, b.l, b.c )
'ohlc4' => math.avg(b.o, b.h, b.l, b.c)
'hlcc4' => math.avg(b.h, b.l, b.c, b.c)
x
method null(bar b) =>
na(b) ? bar.new(0, 0, 0, 0) : b
method ha(bar b, simple bool p = true) =>
var bar x = bar.new( )
x.c := b .src('ohlc4')
x := bar.new(
na(x.o[1]) ?
b.src('oc2') : nz(x.src('oc2')[1]),
math.max(b.h, math.max(x.o, x.c)) ,
math.min(b.l, math.min(x.o, x.c)) ,
x.c )
p ? x : b
f_stix(bar a, bar d, simple int len) =>
bar x = bar.new(
ta.ema(a.o / (a.o + d.o) * 100, len),
ta.ema(a.h / (a.h + d.h) * 100, len),
ta.ema(a.l / (a.l + d.l) * 100, len),
ta.ema(a.c / (a.c + d.c) * 100, len))
x
var string gs = 'STIX', var string ge = 'EMAs'
idx = input.string('NYSE', "Index ", ['NYSE', 'NASDAQ', 'AMEX'], group = gs)
len = input.int (21 , "Length", group = gs)
ma1 = input.bool (true , "EMA |", inline = '1', group = ge)
len1 = input.int (20 , "Length", inline = '1', group = ge)
ma2 = input.bool (false , "EMA |", inline = '2', group = ge)
len2 = input.int (50 , "Length", inline = '2', group = ge)
[tick_adv, tick_dec] = switch idx
'NYSE' => ['ADV' , 'DECL' ]
'NASDAQ' => ['ADVQ', 'DECLQ']
'AMEX' => ['ADVA', 'DECLA']
bar adv = request.security('USI:' + tick_adv, '', bar.new())
bar dec = request.security('USI:' + tick_dec, '', bar.new())
bar stix = f_stix(adv.null(), dec.null(), len).ha()
var color colup = #fff2cc
var color coldn = #6fa8dc
var color colema1 = #FFD6E8
var color colema2 = #9a9adf
color haColor = switch
stix.c > stix.o => colup
stix.c < stix.o => coldn
plotcandle(stix.o, stix.h, stix.l, stix.c,
"Stix", haColor, haColor, bordercolor = haColor)
plot(ma1 ? ta.ema(stix.c, len1) : na, " 𝘌𝘔𝘈 1", colema1)
plot(ma2 ? ta.ema(stix.c, len2) : na, " 𝘌𝘔𝘈 2", colema2)
hline(50, "MidLine", #787b86ab, hline.style_dotted)
max = hline(80, display = display.none)
hh = hline(70, display = display.none)
lh = hline(60, display = display.none)
min = hline(20, display = display.none)
ll = hline(30, display = display.none)
hl = hline(40, display = display.none)
fill(lh, hh , color = #9a9adf2a)
fill(hh, max, color = #9a9adf4d)
fill(ll, hl , color = #ffd6e83b)
fill(ll, min, color = #ffd6e85e)
//Source Construction For Indicator\Strategy Exports
plot(stix.o , "open" , editable = false, display = display.none)
plot(stix.h , "high" , editable = false, display = display.none)
plot(stix.l , "low" , editable = false, display = display.none)
plot(stix.c , "close", editable = false, display = display.none)
plot(stix.src('hl2' ), "hl2" , editable = false, display = display.none)
plot(stix.src('hlc3' ), "hlc3" , editable = false, display = display.none)
plot(stix.src('ohlc4'), "ohlc4", editable = false, display = display.none)
plot(stix.src('hlcc4'), "hlcc4", editable = false, display = display.none) |
Dynamic Liquidity Map [Kioseff Trading] | https://www.tradingview.com/script/42RzVE1t-Dynamic-Liquidity-Map-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 194 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KioseffTrading
//@version=5
indicator("Vol Oi HeatMap", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
import PineCoders/Time/4 as pct
import RicardoSantos/MathOperator/2 // Thanks again Ricardo!!
import HeWhoMustNotBeNamed/arraymethods/1 // Lord V
oib = input.bool(defval = false, title = "Use OI For Heatmap")
show = input.bool(defval = true, title = "Show Delta")
extend = input.bool(defval = false, title = "Extend Unviolated Boxes")
showB = input.bool(defval = true, title = "Show Borders")
rowscol = input.int(title = "Rows x Columns", minval = 1, maxval = 22, defval = 22) - 1
fixedRange = input.bool(defval = false, title = "Use Fixed Range", group = "Fixed Range", inline = "FR")
frt = input.time(timestamp("20 Jul 2023 00:00 +0300") ,title = "Start" ,group = "Fixed Range", inline = "FR"), cond = timeframe.period == "W" or timeframe.period == "M" , TIME = float(time), TIME1 = float(time[1]), rawChange = close - close[1], var float div = 0, var int stime = 0, tf = -1.
pos = input.color(defval = #6929F2, title = "Pos. Color", inline = "Color")
neg = input.color(defval = #F24968, title = "Neg. Color", inline = "Color")
determine (a, b, c) =>
switch a
true => b
=> c
expression() =>
[volume, close, high, low, close - close[1], time]
method float(int id) =>
float(id)
if oib and syminfo.type != "crypto"
runtime.error("No Open Interest Data Available")
strMax( float ) =>
mult = timeframe.multiplier / 9
switch cond
false => str.tostring(math.max(1, math.round(timeframe.multiplier - mult * float )))
=> na
strChange() =>
switch
timeframe.period == "W" => "D"
timeframe.period == "M" => "M"
=> na
[oic, oih, oil, oio, trueOic ] = request.security_lower_tf(syminfo.ticker + "_OI", "1",
[close-close[1], high, low, open, close], true )
req() =>
cont = switch str.contains(syminfo.ticker, "T.P")
true => syminfo.ticker + "_OI"
=> str.endswith(syminfo.ticker, "USDT") ? syminfo.ticker + ".P_OI" : syminfo.ticker + "T.P_OI"
switch syminfo.type
"crypto" => cont
=> string(na)
[vol0 , clo0 , hi0 , lo0 , clocalc0 , ltf0 ] = request.security_lower_tf(syminfo.tickerid, "1", expression(), true)
[vol12, clo12, hi12, lo12, clocalc12, ltf12] = request.security_lower_tf(syminfo.tickerid, strMax (1), expression(), true)
[vol13, clo13, hi13, lo13, clocalc13, ltf13] = request.security_lower_tf(syminfo.tickerid, strMax (2), expression(), true)
[vol14, clo14, hi14, lo14, clocalc14, ltf14] = request.security_lower_tf(syminfo.tickerid, strMax (3), expression(), true)
[vol15, clo15, hi15, lo15, clocalc15, ltf15] = request.security_lower_tf(syminfo.tickerid, strMax (4), expression(), true)
[vol16, clo16, hi16, lo16, clocalc16, ltf16] = request.security_lower_tf(syminfo.tickerid, strMax (5), expression(), true)
[vol17, clo17, hi17, lo17, clocalc17, ltf17] = request.security_lower_tf(syminfo.tickerid, strMax (6), expression(), true)
[vol18, clo18, hi18, lo18, clocalc18, ltf18] = request.security_lower_tf(syminfo.tickerid, strMax (7), expression(), true)
[vol19, clo19, hi19, lo19, clocalc19, ltf19] = request.security_lower_tf(syminfo.tickerid, strMax (8), expression(), true)
[vol20, clo20, hi20, lo20, clocalc20, ltf20] = request.security_lower_tf(syminfo.tickerid, strChange(), expression(), true)
[vol21, clo21, hi21, lo21, clocalc21, ltf21] = request.security_lower_tf(syminfo.tickerid, strChange(), expression(), true)
oi0 = request.security_lower_tf(req(), "1", rawChange, true)
oi12 = request.security_lower_tf(req(), strMax (1), rawChange, true)
oi13 = request.security_lower_tf(req(), strMax (2), rawChange, true)
oi14 = request.security_lower_tf(req(), strMax (3), rawChange, true)
oi15 = request.security_lower_tf(req(), strMax (4), rawChange, true)
oi16 = request.security_lower_tf(req(), strMax (5), rawChange, true)
oi17 = request.security_lower_tf(req(), strMax (6), rawChange, true)
oi18 = request.security_lower_tf(req(), strMax (7), rawChange, true)
oi19 = request.security_lower_tf(req(), strMax (8), rawChange, true)
oi20 = request.security_lower_tf(req(), strChange(), rawChange, true)
oi21 = request.security_lower_tf(req(), strChange(), rawChange, true)
type dotValues
float [] Levels
matrix <float> TickVol
matrix <float> misc
var dotMat = dotValues.new(
array.new_float(),
matrix.new<float>(1, 4000, 0),
matrix.new<float>(3, 0)
)
method tickSet(matrix<float> id, float value, int column, int calc) =>
int = int(dotMat.misc.row(0).first())
id.set(int, column, nz(nz(id.get(int, column)) + (value / math.max(1, (calc)))))
if barstate.isfirst
dotMat.misc.add_col(dotMat.misc.columns(), array.from(0, 0, 1e8))
valArr = array.from( vol12.size(), vol13.size(),
vol14.size(), vol15.size(),
vol16.size(), vol17.size(),
vol18.size(), vol19.size(), vol0.size()
)
if fixedRange and TIME.over_equal(frt)
for i = valArr.size() - 1 to 0
if valArr.get(i).float().over(0)
tf := i
break
[VOL, CLO, HI, LO, CLOCALC, LTF] = if fixedRange and TIME.over_equal(frt) and not cond
switch
vol0.size().float().over(0) => [determine(oib, oi0 , vol0 ), clo0 , hi0 , lo0 , clocalc0 , ltf0 ]
tf.equal(0) => [determine(oib, oi12, vol12), clo12, hi12, lo12, clocalc12, ltf12]
tf.equal(1) => [determine(oib, oi13, vol13), clo13, hi13, lo13, clocalc13, ltf13]
tf.equal(2) => [determine(oib, oi14, vol14), clo14, hi14, lo14, clocalc14, ltf14]
tf.equal(3) => [determine(oib, oi15, vol15), clo15, hi15, lo15, clocalc15, ltf15]
tf.equal(4) => [determine(oib, oi16, vol16), clo16, hi16, lo16, clocalc16, ltf16]
tf.equal(5) => [determine(oib, oi17, vol17), clo17, hi17, lo17, clocalc17, ltf17]
tf.equal(6) => [determine(oib, oi18, vol18), clo18, hi18, lo18, clocalc18, ltf18]
tf.equal(7) => [determine(oib, oi19, vol19), clo19, hi19, lo19, clocalc19, ltf19]
tf.equal(-1) => [array.from(volume), array.from(close), array.from (high) , array.from(low),array.from (close - close[1]), array.from (time)]
else
switch
not cond and not fixedRange => [determine(oib, oi0, vol0 ), clo0 , hi0 , lo0 , clocalc0 , ltf0 ]
timeframe.period == "W" => [determine(oib, oi20, vol20), clo20, hi20, lo20, clocalc20, ltf20]
timeframe.period == "M" => [determine(oib, oi21, vol21), clo21, hi21, lo21, clocalc21, ltf21]
row = determine(fixedRange, dotMat.TickVol.rows(), rowscol + 1)
if fixedRange ? TIME.over_equal(frt) : VOL.size().float().over(0)
if fixedRange
var calc = last_bar_index - bar_index
if calc.float().under_equal ( rowscol + 1)
runtime.error( "Not enough bar data in the fixed range for the
requested heatmap size (" + str.tostring(rowscol) +"). Reduce the number of rows/columns
in the settings, or lengthen the fixed range period.")
dotMat.misc.set(1, 0, math.max(dotMat.misc.get(1, 0), high))
dotMat.misc.set(2, 0, math.min(dotMat.misc.get(2, 0), low ))
if stime.float().equal(0)
div := (last_bar_time - time) / (rowscol + 1), stime := time
for i = 0 to 1000
dotMat.Levels.push(close * (1 + (i/1000)))
dotMat.Levels.push(close * (1 - (i/1000)))
dotMat.Levels.sort(order.ascending)
for i = 0 to math.min(VOL.size(), CLOCALC.size()) - 1
highest = dotMat.Levels.binary_search_leftmost (HI.get(i))
lowest = dotMat.Levels.binary_search_rightmost (LO.get(i))
for x = lowest to highest
volx = switch math.sign(CLOCALC.get(i))
1 => determine(oib, VOL.get(i), VOL.get(i) )
=> determine(oib, VOL.get(i), VOL.get(i) * -1)
dotMat.TickVol.tickSet(volx , x, math.abs(highest - lowest) + 1)
for i = 0 to rowscol
if TIME.over_equal(math.round(stime + (div * (i + 1))))
if TIME1.under(math.round(stime + (div * (i + 1))))
dotMat.misc .set (0, 0, dotMat.misc.get(0, 0) + 1)
dotMat.TickVol.add_row(dotMat.TickVol.rows(), dotMat.TickVol.row(dotMat.TickVol.rows() - 1))
break
orientation = matrix.new<float>(row, row)
method double_binary_search_leftmost(array <float> id, column) =>
n = id.binary_search_leftmost (orientation.get(0, column))
n1 = id.binary_search_rightmost (orientation.get(1, column))
[n, n1]
method finSetVol(matrix <float> id, int i, int row, int start, int end) =>
for x = start to end
id.set (row, i, id.get(row, i) + dotMat.TickVol.get(i, x))
if barstate.islast
box.all.flush(), line.all.flush(), label.all.flush()
calc = (dotMat.misc.get(1, 0) - dotMat.misc.get(2, 0)) / row
grid = matrix.new<box>(row, row)
for i = 0 to row - 1
for x = 0 to row - 1
grid.set(x, i,
box.new(
math.round(stime + (div * i)),
dotMat.misc.get(2, 0) + (calc * (x + 1)),
math.round(stime + (div * (i + 1))),
dotMat.misc.get(2, 0) + calc * (x),
xloc = xloc.bar_time,
border_color = #00000000,
border_width = 1,
bgcolor = #00000000
))
for i = 0 to row - 1
orientation.set(0, i, grid.get(i, 0).get_top ())
orientation.set(1, i, grid.get(i, 0).get_bottom())
preSet = matrix.new<int>(2, 1000, 0)
for i = 0 to row - 1
[up, dn] = dotMat.Levels.double_binary_search_leftmost (i)
preSet.set(0, i, up)
preSet.set(1, i, dn)
finTick = matrix.new<float>(row, row, 0)
finTick2 = matrix.new<float> (row, 1, 0)
for i = 0 to row - 1
for x = 0 to row - 1
finTick .finSetVol(i, x, preSet.get(0, x), preSet.get(1, x))
colMat = matrix.new<color>(row, row)
for i = 0 to grid.rows() - 1
for x = 0 to grid.columns() - 1
datax = finTick .get(i, x), datamin = finTick .min(),
datamax = finTick .max()
col = color.new(color.gray, 80), bcol = color.new(color.gray, 80)
col2 = color.new(color.gray, 80), calcx = math.sign (datax)
col := switch calcx
0 => color.new(color.gray, 80)
1 => color.from_gradient(datax, 0, datamax, color.new(pos, 90), color.new(pos, 50))
-1 => color.from_gradient(datax, datamin, 0, color.new(neg , 50), color.new(neg , 90))
bcol := switch calcx
0 => color.new(color.gray, 80)
1 => #6929F2
-1 => #F24968
grid.get(i, x).set_bgcolor(col == color.new(color.gray, 80) ? col2 : col)
if showB
grid.get(i, x).set_border_color(col == color.new(color.gray, 80) ? na : bcol)
if show
if finTick.get(i, x).not_equal(0)
grid.get(i, x).set_text_color(color.white)
grid.get(i, x).set_text(str.tostring(finTick.get(i, x), format.volume))
if finTick.get(i, x).equal(0)
grid.get(i, x).set_bgcolor(#00000000)
if extend and x.float().over(0)
if finTick.get(i, x).equal(finTick.get(i, x - 1))
grid.get(i, x) .set_left(grid.get(i, x - 1).get_left())
grid.get(i, x - 1).set_bgcolor (#00000000)
grid.get(i, x - 1).set_border_color (#00000000)
grid.get(i, x - 1).set_text_color (#00000000)
if x.float().equal(grid.columns() - 1)
grid.get(i, x).set_right(pct.timeFrom("bar", 5, "chart"))
if fixedRange
line.new(frt, high, frt, low, xloc = xloc.bar_time, color = chart.fg_color, width = 2, extend = extend.both)
if not extend
if box.all.size() < math.pow(rowscol, 2)
var tab = table.new(position.top_right, 4, 4, frame_color = color.white, frame_width = 1, border_color = color.white, border_width = 1)
tab.cell(0, 0, text = "Time Gaps Detected\n True Reducing the Rows x Columns", text_color = color.white, text_size = size.small) |
PDHL levels with INTRADAY Auto FIB | https://www.tradingview.com/script/qyZJ0Stp-PDHL-levels-with-INTRADAY-Auto-FIB/ | vatsanuj | https://www.tradingview.com/u/vatsanuj/ | 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/
// © vatsanuj
//INTRADAY day AUTO Fib also includes PDHL levels + EMA20/50/200 + VWAP -- Enjoy--Dr.Vats
//@version=5
indicator(title='INTRADAY Auto FIB with PDHL levels', shorttitle='Intraday FIB', overlay=true)
plot(ta.vwap(close), color=color.fuchsia, linewidth = 2, title = "VWAP")
[EMA20, EMA50, EMA200] =request.security(syminfo.tickerid, 'D', [math.round_to_mintick(ta.ema(close,20)),math.round_to_mintick(ta.ema(close,50)), math.round_to_mintick(ta.ema(close,200))])
plot(EMA20, title = "20 DEMA", color = color.yellow, linewidth = 2, style = plot.style_circles)
plot(EMA50,title = "50 DEMA", color = color.rgb(247, 9, 9), linewidth = 2,style = plot.style_circles)
plot(EMA200,title = "200 DEMA", color = color.green, linewidth = 3,style = plot.style_cross)
[Fhigh,Fhigh1,Fhigh2,Flow,Flow1,Flow2] = request.security(syminfo.tickerid, 'D', [high[0], high[1], high[2], low[0], low[1], low[2]])
F0 = Flow
F236 = (Fhigh - Flow) * 0.236 + Flow
F382 = (Fhigh - Flow) * 0.382 + Flow
F500 = (Fhigh - Flow) * 0.500 + Flow
F618 = (Fhigh - Flow) * 0.618 + Flow
F786 = (Fhigh - Flow) * 0.786 + Flow
F1000 = (Fhigh - Flow) * 1.000 + Flow
Fcolor_PDH_Broke = Fhigh>Fhigh1 ? color.aqua : color.gray // color of the present day high line if present day price has broken Previous day high
Fcolor_PDL_Broke = Flow <Flow1 ? color.fuchsia : color.gray // color of the present day low line if present day price has broken Previous day low
bgcolor(Fhigh>Fhigh1 ? color.new(color.white,90) :na, show_last = 1, title = "PDH broken") //highlights the background of the present candle to white if PDH is already broken anytime in present day
bgcolor(Flow<Flow1 ? color.new(color.red,85) :na, show_last = 1, title= "PDL broken") //highlights the background of the present candle to red if PDL is already broken anytime in present day
plot(Fhigh1, color= color.yellow, linewidth = 2,trackprice=true, show_last=1, title='PDH')
plot(Fhigh2, color= color.yellow, linewidth = 1,trackprice=true, show_last=1, title='PDH2')
plot(Flow1, color= color.orange, linewidth = 2,trackprice=true, show_last=1, title='PDL')
plot(Flow2, color= color.orange, linewidth = 1,trackprice=true, show_last=1, title='PDL2')
plotshape(Fhigh1, style=shape.labeldown, location=location.absolute, color=color.new(color.yellow, 10), textcolor=color.new(color.fuchsia, 10), show_last=1, text='PDH', offset=-2)
plotshape(Fhigh2, style=shape.arrowup, location=location.absolute, color=color.new(color.yellow, 10), textcolor=color.new(color.yellow, 10), show_last=1, text='PDH2', offset=-4)
plotshape(Flow1, style=shape.labeldown, location=location.absolute, color=color.new(color.orange, 30), textcolor=color.new(color.white, 10), show_last=1, text='PDL', offset=-2)
plotshape(Flow2, style=shape.arrowdown, location=location.absolute, color=color.new(color.orange, 30), textcolor=color.new(color.orange, 10), show_last=1, text='PDL2', offset=-4)
plot(F0, color=Fcolor_PDL_Broke, linewidth=2, trackprice=true, show_last=1, title='0')
plot(F236, color=color.new(color.green, 0), linewidth=1, trackprice=true, show_last=1, title='0.236')
plot(F382, color=color.rgb(169, 221, 157, 16), linewidth=2, trackprice=true, show_last=1, title='61.8 RT')
plot(F500, color=color.new(color.white, 0), linewidth=2, trackprice=true, show_last=1, title='0.5')
plot(F618, color=color.rgb(250, 92, 234, 16), linewidth=2, trackprice=true, show_last=1, title='38.2 RT')
plot(F786, color=color.new(color.maroon, 0), linewidth=1, trackprice=true, show_last=1, title='0.786')
plot(F1000, color=Fcolor_PDH_Broke, linewidth=2, trackprice=true, show_last=1, title='1')
plotshape(F0, style=shape.labeldown, location=location.absolute, color=color.new(color.white, 0), textcolor=color.new(color.black, 0), show_last=1, text='%0', offset=5)
plotshape(F236, style=shape.labeldown, location=location.absolute, color=color.new(color.white, 0), textcolor=color.new(color.black, 0), show_last=1, text='%78.6', offset=6)
plotshape(F382, style=shape.labeldown, location=location.absolute, color=color.rgb(6, 167, 24), textcolor=color.new(color.black, 0), show_last=1, text='%61.8', offset=4)
plotshape(F500, style=shape.labeldown, location=location.absolute, color=color.new(color.white, 0), textcolor=color.new(color.black, 0), show_last=1, text='%50', offset=5)
plotshape(F618, style=shape.labeldown, location=location.absolute, color=color.rgb(248, 28, 28), textcolor=color.new(color.white, 0), show_last=1, text='%38.2', offset=4)
plotshape(F786, style=shape.labeldown, location=location.absolute, color=color.new(color.white, 0), textcolor=color.new(color.black, 0), show_last=1, text='%23.6', offset=6)
plotshape(F1000, style=shape.labeldown, location=location.absolute, color=color.new(color.white, 0), textcolor=color.new(color.black, 0), show_last=1, text='%100', offset=5)
|
IND-Range Box [Salar Kamjoo] | https://www.tradingview.com/script/3nybP1NZ-IND-Range-Box-Salar-Kamjoo/ | salarkamjoo | https://www.tradingview.com/u/salarkamjoo/ | 181 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © salarkamjoo
// $KMagician/*
//@version=5
indicator('IND-Range Box [Salar kamjoo]', 'Range Boxes [Salar kamjoo]', true, max_boxes_count = 500)
// Inputs ======================================================================
count_range = input.int(20, "Number of Candles", minval=1, group = "Strategy Settings")
range_percentage = input.float(0.2, "Range percentage", minval=0, step = 0.1, group = "Strategy Settings")
draw_range = input.string('close', "Calculate basis", options=['close', 'high & low'], group = "Strategy Settings")
extend_length = input.int(5, "Number of extended candles", minval=0, group = "Strategy Settings")
float source_high = na
float source_low = na
switch
draw_range == 'close' => source_high := close, source_low := close
draw_range == 'high & low' => source_high := high, source_low := low
// highest and lowest ==========================================================
hh = ta.highest(source_high, count_range)
ll = ta.lowest(source_low, count_range)
// hh and ll difference in % ===================================================
difference_percentage = (((hh - ll)/(hh + ll)) * 100) * 2
// is it in the range of user's desire =========================================
is_in_range = difference_percentage <= range_percentage
// Count Candles ===============================================================
var int candle_under = 0
var int candle_above = 0
if source_high <= hh and is_in_range
candle_under += 1
if source_low >= ll and is_in_range
candle_above += 1
if not is_in_range
candle_under := 0
candle_above := 0
// Draw range ==================================================================
_range = (candle_under == count_range) and (candle_above == count_range)
if _range
box.new(bar_index[count_range + extend_length], hh, bar_index + extend_length, ll, bgcolor=color.new(color.fuchsia, 80), border_color=color.fuchsia)
plotshape(_range, 'Range box', shape.labeldown, location.abovebar, text = 'Range', textcolor=color.white, color=color.fuchsia, size= size.tiny)
// Alerts ======================================================================
if _range
message = 'Range Box\n' + syminfo.ticker + '\n' + timeframe.period
alert(message, alert.freq_once_per_bar_close) |
Inverse FVG with Rejections [TFO] | https://www.tradingview.com/script/arQP5Q2f-Inverse-FVG-with-Rejections-TFO/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 1,801 | study | 5 | MPL-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("Inverse FVG with Rejections [TFO]", "Inverse FVG [TFO]", true)
// -------------------------------------------------- Inputs --------------------------------------------------
var g_SET = "Settings"
show_rfvg = input.bool(true, "Show Regular FVG", inline = "RFVG", group = g_SET)
show_ifvg = input.bool(true, "Show Inverse FVG", inline = "IFVG", group = g_SET)
extend_right = input.bool(true, "Extend Boxes", group = g_SET)
rfvg_color = input.color(color.new(#2962ff, 60), "", inline = "RFVG", group = g_SET)
ifvg_color = input.color(color.new(#f23645, 60), "", inline = "IFVG", group = g_SET)
tf = input.timeframe("", "Timeframe", group = g_SET)
disp_x = input.int(3, "Displacement", 1, 10, tooltip = "Larger Displacement will require larger FVGs", group = g_SET)
disp_limit = input.int(10, "Display Limit", 1, 50, tooltip = "The maximum amount of FVGs and IFVGs to display", group = g_SET)
session = input.session("0000-0000", "Session", tooltip = "FVGs will only be saved if they are created within this time period", group = g_SET)
var g_RJ = "Rejections"
ps = input.int(1, "Rejection Strength", tooltip = "Larger values will require larger fractals/swing pivots to justify as rejections", group = g_RJ)
show_rrj = input.bool(false, "Regular FVG", inline = "RRJ", tooltip = "Show rejections made within regular FVGs", group = g_RJ)
show_irj = input.bool(false, "Inverse FVG", inline = "IRJ", tooltip = "Show rejections made within inverse FVGs", group = g_RJ)
show_brj = input.bool(true, "Regular + Inverse FVG", inline = "BRJ", tooltip = "Show rejections made within both regular and inverse FVGs", group = g_RJ)
rrj_color = input.color(#2962ff, "", inline = "RRJ", group = g_RJ)
irj_color = input.color(#f23645, "", inline = "IRJ", group = g_RJ)
brj_color = input.color(color.black, "", inline = "BRJ", group = g_RJ)
// -------------------------------------------------- Inputs --------------------------------------------------
// -------------------------------------------------- Logic --------------------------------------------------
t = not na(time(tf, session, "America/New_York"))
[o, h, l, c, ti] = request.security(syminfo.tickerid, tf, [open[1], high[1], low[1], close[1], time[1]], lookahead = barmerge.lookahead_on, gaps = barmerge.gaps_off)
var tf_o = array.new_float()
var tf_h = array.new_float()
var tf_l = array.new_float()
var tf_c = array.new_float()
var tf_time = array.new_int()
var tf_t = array.new_bool()
var reg_fvg = array.new_box()
var reg_fvg_ce = array.new_line()
var reg_fvg_side = array.new_string()
var inv_fvg = array.new_box()
var inv_fvg_ce = array.new_line()
var inv_fvg_side = array.new_string()
reg_rj_bear = false
reg_rj_bull = false
inv_rj_bear = false
inv_rj_bull = false
solid_color(color x) =>
color.new(x, 0)
avg_over(float[] h, float[] l, int len) =>
sum = 0.0
for i = 0 to len
sum += (h.get(i) - l.get(i))
result = sum / len
var tf_new = false
if timeframe.change(tf) and timeframe.in_seconds(tf) >= timeframe.in_seconds(timeframe.period)
tf_o.unshift(o)
tf_h.unshift(h)
tf_l.unshift(l)
tf_c.unshift(c)
tf_t.unshift(t[1])
tf_time.unshift(ti)
tf_new := true
if tf_o.size() > 300
tf_o.pop()
tf_h.pop()
tf_l.pop()
tf_c.pop()
tf_t.pop()
tf_time.pop()
if not extend_right
if reg_fvg.size() > 0
for i = 0 to reg_fvg.size() - 1
reg_fvg.get(i).set_right(time)
reg_fvg_ce.get(i).set_x2(time)
if inv_fvg.size() > 0
for i = 0 to inv_fvg.size() - 1
inv_fvg.get(i).set_right(time)
inv_fvg_ce.get(i).set_x2(time)
if tf_o.size() > 20 and tf_new
bull = tf_c.get(1) > tf_o.get(1)
fvg = bull ? (tf_h.get(2) < tf_l.get(0) and tf_l.get(1) <= tf_h.get(2) and tf_h.get(1) >= tf_l.get(0)) : (tf_l.get(2) > tf_h.get(0) and tf_l.get(1) <= tf_h.get(0) and tf_l.get(2) <= tf_h.get(1))
fvg_len = bull ? tf_l.get(0) - tf_h.get(2) : tf_l.get(2) - tf_h.get(0)
atr_check = fvg_len > avg_over(tf_h, tf_l, 20) * disp_x / 10
if tf_t.get(2) and fvg and atr_check
top = bull ? tf_l.get(0) : tf_l.get(2)
bottom = bull ? tf_h.get(2) : tf_h.get(0)
reg_fvg.unshift(box.new(tf_time.get(1), top, time, bottom, xloc = xloc.bar_time, extend = extend_right ? extend.right : extend.none, bgcolor = show_rfvg ? rfvg_color : na, border_color = na))
reg_fvg_ce.unshift(line.new(tf_time.get(1), math.avg(top, bottom), time, math.avg(top, bottom), xloc = xloc.bar_time, extend = extend_right ? extend.right : extend.none, color = show_rfvg ? solid_color(rfvg_color) : na, style = line.style_dashed))
reg_fvg_side.unshift(bull ? 'bull' : 'bear')
tf_new := false
if reg_fvg.size() > 0
for i = reg_fvg.size() - 1 to 0
remove_bull = reg_fvg_side.get(i) == 'bull' and tf_c.get(0) < reg_fvg.get(i).get_bottom()
remove_bear = reg_fvg_side.get(i) == 'bear' and tf_c.get(0) > reg_fvg.get(i).get_top()
if remove_bull or remove_bear
inv_fvg.unshift(box.copy(reg_fvg.get(i)))
inv_fvg_ce.unshift(line.copy(reg_fvg_ce.get(i)))
inv_fvg.get(0).set_bgcolor(show_ifvg ? ifvg_color : na)
inv_fvg_ce.get(0).set_color(show_ifvg ? solid_color(ifvg_color) : na)
box.delete(reg_fvg.get(i))
line.delete(reg_fvg_ce.get(i))
reg_fvg.remove(i)
reg_fvg_ce.remove(i)
reg_fvg_side.remove(i)
if remove_bear
inv_fvg_side.unshift('inv bear')
else if remove_bull
inv_fvg_side.unshift('inv bull')
if reg_fvg.size() > disp_limit
box.delete(reg_fvg.pop())
line.delete(reg_fvg_ce.pop())
reg_fvg_side.pop()
if inv_fvg.size() > 0
for i = inv_fvg.size() - 1 to 0
remove_inv_bear = inv_fvg_side.get(i) == 'inv bear' and tf_c.get(0) < inv_fvg.get(i).get_bottom()
remove_inv_bull = inv_fvg_side.get(i) == 'inv bull' and tf_c.get(0) > inv_fvg.get(i).get_top()
if remove_inv_bear or remove_inv_bull
box.delete(inv_fvg.get(i))
line.delete(inv_fvg_ce.get(i))
inv_fvg.remove(i)
inv_fvg_ce.remove(i)
inv_fvg_side.remove(i)
if inv_fvg.size() > disp_limit
box.delete(inv_fvg.pop())
line.delete(inv_fvg_ce.pop())
inv_fvg_side.pop()
if math.min(reg_fvg.size(), inv_fvg.size()) > 0
for i = 0 to reg_fvg.size() - 1
_rrj_bear = ta.pivothigh(high, ps, ps) and high[ps] >= reg_fvg.get(i).get_bottom() and high[ps] <= reg_fvg.get(i).get_top()
_rrj_bull = ta.pivotlow(low, ps, ps) and low[ps] >= reg_fvg.get(i).get_bottom() and low[ps] <= reg_fvg.get(i).get_top()
if _rrj_bear
reg_rj_bear := true
if _rrj_bull
reg_rj_bull := true
for i = 0 to inv_fvg.size() - 1
_irj_bear = ta.pivothigh(high, ps, ps) and high[ps] >= inv_fvg.get(i).get_bottom() and high[ps] <= inv_fvg.get(i).get_top()
_irj_bull = ta.pivotlow(low, ps, ps) and low[ps] >= inv_fvg.get(i).get_bottom() and low[ps] <= inv_fvg.get(i).get_top()
if _irj_bear
inv_rj_bear := true
if _irj_bull
inv_rj_bull := true
plotshape(show_rrj and reg_rj_bear[1], color = rrj_color, size = size.small, location = location.abovebar, style = shape.triangledown)
plotshape(show_rrj and reg_rj_bull[1], color = rrj_color, size = size.small, location = location.belowbar, style = shape.triangleup)
plotshape(show_irj and inv_rj_bear[1], color = irj_color, size = size.small, location = location.abovebar, style = shape.triangledown)
plotshape(show_irj and inv_rj_bull[1], color = irj_color, size = size.small, location = location.belowbar, style = shape.triangleup)
plotshape(show_brj and reg_rj_bear[1] and inv_rj_bear[1], color = brj_color, size = size.small, location = location.abovebar, style = shape.triangledown)
plotshape(show_brj and reg_rj_bull[1] and inv_rj_bull[1], color = brj_color, size = size.small, location = location.belowbar, style = shape.triangleup)
alertcondition(show_rrj and (reg_rj_bear[1] or reg_rj_bull[1]), "Any Regular FVG Rejection")
alertcondition(show_rrj and reg_rj_bear[1], "Regular FVG Bear Rejection")
alertcondition(show_rrj and reg_rj_bull[1], "Regular FVG Bull Rejection")
alertcondition(show_irj and (inv_rj_bear[1] or inv_rj_bull[1]), "Any Inverse FVG Rejection")
alertcondition(show_irj and inv_rj_bear[1], "Inverse FVG Bear Rejection")
alertcondition(show_irj and inv_rj_bull[1], "Inverse FVG Bull Rejection")
alertcondition(show_brj and ((reg_rj_bear[1] and inv_rj_bear[1]) or (reg_rj_bull[1] and inv_rj_bull[1])), "Any FVG + IFVG Rejection")
alertcondition(show_brj and reg_rj_bear[1] and inv_rj_bear[1], "FVG + IFVG Bear Rejection")
alertcondition(show_brj and reg_rj_bull[1] and inv_rj_bull[1], "FVG + IFVG Bull Rejection")
// -------------------------------------------------- Logic -------------------------------------------------- |
Spot line | https://www.tradingview.com/script/E0vncTIR-Spot-line/ | Kerbal | https://www.tradingview.com/u/Kerbal/ | 3 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kerbal
//@version=5
indicator("Spot line", overlay = true)
source = input.source(close, "Source")
color kuCoinColor = color.purple
color coinbaseColor = color.orange
color binanceColor = color.blue
int lineWidth = 2
var string spotSymbol = syminfo.ticker
spotSymbol := str.replace_all(spotSymbol, ".PS", "")
spotSymbol := str.replace_all(spotSymbol, ".P", "")
string binanceSpotSymbol = "BINANCE:" + spotSymbol
string coinbaseSpotSymbol = "COINBASE:" + spotSymbol
string kuCoinSpotSymbol = "KUCOIN:" + spotSymbol
binanceSpotClose = request.security(binanceSpotSymbol, timeframe.period, source, ignore_invalid_symbol = true)
plot(binanceSpotClose, "Binance spot", binanceColor, lineWidth, plot.style_line)
coinbaseSpotCloseTemp = request.security(coinbaseSpotSymbol, timeframe.period, source, ignore_invalid_symbol = true)
coinbaseSpotClose = na(binanceSpotClose) ? coinbaseSpotCloseTemp : na
plot(coinbaseSpotClose, "Coinbase spot", coinbaseColor, lineWidth, plot.style_line)
kuCoinSpotCloseTemp = request.security(kuCoinSpotSymbol, timeframe.period, source, ignore_invalid_symbol = true)
kuCoinSpotClose = na(binanceSpotClose) and na(coinbaseSpotClose) ? kuCoinSpotCloseTemp : na
plot(kuCoinSpotClose, "KuCoin spot", kuCoinColor, lineWidth, plot.style_line) |
Doji Trender | https://www.tradingview.com/script/vAllG7Mo-Doji-Trender/ | Kerbal | https://www.tradingview.com/u/Kerbal/ | 29 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kerbal
//@version=5
indicator("Doji Trender", overlay = true, max_lines_count = 500, max_bars_back = 5000)
float dojiPercent = input.float(0.00025, "Doji O/C percent", minval = 0.00001, step = 0.00001)
int emaLength = input.int(10, "EMA length")
string tf1 = input.timeframe("5", "Timeframe 1")
string tf2 = input.timeframe("15", "Timeframe 2")
string tf3 = input.timeframe("60", "Timeframe 3")
string tf4 = input.timeframe("240", "Timeframe 4")
float dojiMath = math.abs(1 - close / open) <= dojiPercent ? (open + close) / 2 : na
int otherSize = 3
float dojisChart = request.security(syminfo.ticker, timeframe.period, dojiMath)
if (timeframe.period == tf1) or (timeframe.period == tf2) or (timeframe.period == tf3) or (timeframe.period == tf4)
dojisChart := na
plot(dojisChart, "Chart doji trends", color.rgb(0, 225, 255), 2, plot.style_line, display = display.pane - display.status_line)
plot(dojisChart, "Chart doji markers", color.rgb(0, 225, 255), 5, plot.style_circles, display = display.all)
dojisMaChart = ta.ema(dojisChart, emaLength)
plot(dojisMaChart, "Chart doji trends ma", color.rgb(0, 225, 255), 1, plot.style_line, display = display.pane - display.status_line)
float dojisTf4 = request.security(syminfo.ticker, tf4, dojiMath)
plot(dojisTf4, "Fourth timeframe doji trends", color.rgb(0, 255, 0), 2, plot.style_line, display = display.pane - display.status_line)
plot(dojisTf4, "Fourth timeframe doji markers", color.rgb(0, 255, 0), otherSize, plot.style_circles, display = display.all)
dojisMaTf4 = ta.ema(dojisTf4, emaLength)
plot(dojisMaTf4, "Fourth timeframe doji trends ma", color.rgb(0, 255, 0), 1, plot.style_line, display = display.pane - display.status_line)
float dojisTf3 = request.security(syminfo.ticker, tf3, dojiMath)
plot(dojisTf3, "Third timeframe doji trends", color.rgb(255, 255, 0), 2, plot.style_line, display = display.pane - display.status_line)
plot(dojisTf3, "Third timeframe doji markers", color.rgb(255, 255, 0), otherSize, plot.style_circles, display = display.all)
dojisMaTf3 = ta.ema(dojisTf3, emaLength)
plot(dojisMaTf3, "Third timeframe doji trends ma", color.rgb(255, 255, 0), 1, plot.style_line, display = display.pane - display.status_line)
float dojisTf2 = request.security(syminfo.ticker, tf2, dojiMath)
plot(dojisTf2, "Second timeframe doji trends", color.rgb(255, 128, 0), 2, plot.style_line, display = display.pane - display.status_line)
plot(dojisTf2, "Second timeframe doji markers", color.rgb(255, 128, 0), otherSize, plot.style_circles, display = display.all)
float dojisTf1 = request.security(syminfo.ticker, tf1, dojiMath)
plot(dojisTf1, "First timeframe doji trends", color.rgb(255, 0, 0), 2, plot.style_line, display = display.pane - display.status_line)
plot(dojisTf1, "First timeframe doji markers", color.rgb(255, 0, 0), otherSize, plot.style_circles, display = display.all) |
NQ 7 Index | https://www.tradingview.com/script/prlBbc92-NQ-7-Index/ | RaenonX | https://www.tradingview.com/u/RaenonX/ | 21 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RaenonX
//@version=5
indicator("NQ 7 Index", overlay = true)
divisor = input.int(1000000000, title = "Divisor")
candle_up = #26a699
candle_down = #ef5350
[aapl_o, aapl_h, aapl_l, aapl_c] = request.security(ticker.new("NASDAQ", "AAPL", session.extended), timeframe.period, [open, high, low, close])
[aapl_h_d, aapl_l_d, aapl_c_d] = request.security(ticker.new("NASDAQ", "AAPL", session.extended), "D", [high, low, close])
aapl_shares = request.financial("NASDAQ:AAPL", "TOTAL_SHARES_OUTSTANDING", "FQ")
[msft_o, msft_h, msft_l, msft_c] = request.security(ticker.new("NASDAQ", "MSFT", session.extended), timeframe.period, [open, high, low, close])
[msft_h_d, msft_l_d, msft_c_d] = request.security(ticker.new("NASDAQ", "MSFT", session.extended), "D", [high, low, close])
msft_shares = request.financial("NASDAQ:MSFT", "TOTAL_SHARES_OUTSTANDING", "FQ")
[goog_o, goog_h, goog_l, goog_c] = request.security(ticker.new("NASDAQ", "GOOG", session.extended), timeframe.period, [open, high, low, close])
[goog_h_d, goog_l_d, goog_c_d] = request.security(ticker.new("NASDAQ", "GOOG", session.extended), "D", [high, low, close])
goog_shares = request.financial("NASDAQ:GOOG", "TOTAL_SHARES_OUTSTANDING", "FQ")
[nvda_o, nvda_h, nvda_l, nvda_c] = request.security(ticker.new("NASDAQ", "NVDA", session.extended), timeframe.period, [open, high, low, close])
[nvda_h_d, nvda_l_d, nvda_c_d] = request.security(ticker.new("NASDAQ", "NVDA", session.extended), "D", [high, low, close])
nvda_shares = request.financial("NASDAQ:NVDA", "TOTAL_SHARES_OUTSTANDING", "FQ")
[tsla_o, tsla_h, tsla_l, tsla_c] = request.security(ticker.new("NASDAQ", "TSLA", session.extended), timeframe.period, [open, high, low, close])
[tsla_h_d, tsla_l_d, tsla_c_d] = request.security(ticker.new("NASDAQ", "TSLA", session.extended), "D", [high, low, close])
tsla_shares = request.financial("NASDAQ:TSLA", "TOTAL_SHARES_OUTSTANDING", "FQ")
[meta_o, meta_h, meta_l, meta_c] = request.security(ticker.new("NASDAQ", "META", session.extended), timeframe.period, [open, high, low, close])
[meta_h_d, meta_l_d, meta_c_d] = request.security(ticker.new("NASDAQ", "META", session.extended), "D", [high, low, close])
meta_shares = request.financial("NASDAQ:META", "TOTAL_SHARES_OUTSTANDING", "FQ")
[amzn_o, amzn_h, amzn_l, amzn_c] = request.security(ticker.new("NASDAQ", "AMZN", session.extended), timeframe.period, [open, high, low, close])
[amzn_h_d, amzn_l_d, amzn_c_d] = request.security(ticker.new("NASDAQ", "AMZN", session.extended), "D", [high, low, close])
amzn_shares = request.financial("NASDAQ:AMZN", "TOTAL_SHARES_OUTSTANDING", "FQ")
bar_o = (aapl_o * aapl_shares + msft_o * msft_shares + goog_o * goog_shares + nvda_o * nvda_shares + tsla_o * tsla_shares + meta_o * meta_shares + amzn_o * amzn_shares) / divisor
bar_h = (aapl_h * aapl_shares + msft_h * msft_shares + goog_h * goog_shares + nvda_h * nvda_shares + tsla_h * tsla_shares + meta_h * meta_shares + amzn_h * amzn_shares) / divisor
bar_l = (aapl_l * aapl_shares + msft_l * msft_shares + goog_l * goog_shares + nvda_l * nvda_shares + tsla_l * tsla_shares + meta_l * meta_shares + amzn_l * amzn_shares) / divisor
bar_c = (aapl_c * aapl_shares + msft_c * msft_shares + goog_c * goog_shares + nvda_c * nvda_shares + tsla_c * tsla_shares + meta_c * meta_shares + amzn_c * amzn_shares) / divisor
bar_c_prev = (aapl_c_d[1] * aapl_shares + msft_c_d[1] * msft_shares + goog_c_d[1] * goog_shares + nvda_c_d[1] * nvda_shares + tsla_c_d[1] * tsla_shares + meta_c_d[1] * meta_shares + amzn_c_d[1] * amzn_shares) / divisor
bar_color = bar_c > bar_o ? candle_up : candle_down
plotcandle(
bar_o, bar_h, bar_l, bar_c,
title = "NQ 7 Index", color = bar_color, wickcolor = bar_color, bordercolor = bar_color)
// --------------
get_text_diff_pct(diff_pct) =>
if (diff_pct > 0)
str.tostring(diff_pct, "▲ 0.00%")
else if (diff_pct < 0)
str.tostring(math.abs(diff_pct), "▼ 0.00%")
else
"- 0.00%"
var hud = table.new(position = position.bottom_right, rows = 1, columns = 2)
is_extrema = bar_c >= bar_h or bar_c <= bar_l
hud_color = bar_c > bar_c_prev ? candle_up : candle_down
hud_text_color = is_extrema ? color.white : hud_color
hud_bg_color = is_extrema ? hud_color : color.new(#000000, transp = 100)
table.cell(table_id = hud, row = 0, column = 0,
text_size = size.normal, text_color = hud_text_color, bgcolor = hud_bg_color,
text = str.tostring(bar_c, "0.00"))
table.cell(table_id = hud, row = 0, column = 1,
text_size = size.normal, text_color = hud_text_color, bgcolor = hud_bg_color,
text = get_text_diff_pct(bar_c / bar_c_prev - 1))
|
Exhaustion Signal | https://www.tradingview.com/script/VFjyDUJx-Exhaustion-Signal/ | ChartingCycles | https://www.tradingview.com/u/ChartingCycles/ | 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/
//@version=5
indicator(title='Exhaustion Signal', shorttitle='Exhaustion', overlay=true, timeframe='')
Candles = input.int(9,"Candle Count")
Candles2 = input.int(12,"Candle Count")
// // CALCS /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
buySignals = 0
buySignals := close < close[4] ? buySignals[1] == Candles ? 1 : buySignals[1] + 1 : 0
sellSignals = 0
sellSignals := close > close[4] ? sellSignals[1] == Candles ? 1 : sellSignals[1] + 1 : 0
BuyOrSell = math.max(buySignals, sellSignals)
buy = buySignals and BuyOrSell == Candles
sell = sellSignals and BuyOrSell == Candles
// // CALCS /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
buySignals2 = 0
buySignals2 := close < close[4] ? buySignals2[1] == Candles2 ? 1 : buySignals2[1] + 1 : 0
sellSignals2 = 0
sellSignals2 := close > close[4] ? sellSignals2[1] == Candles2 ? 1 : sellSignals2[1] + 1 : 0
BuyOrSell2 = math.max(buySignals2, sellSignals2)
buy2 = buySignals2 and BuyOrSell2 == Candles2
sell2 = sellSignals2 and BuyOrSell2 == Candles2
// LABELS /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
plotshape(buy, style=shape.diamond, color=color.new(#30ff85, 0), textcolor=color.new(color.white, 0), size=size.tiny, location=location.belowbar)
plotshape(sell, style=shape.diamond, color=color.new(#ff1200, 0), textcolor=color.new(color.white, 0), size=size.tiny, location=location.abovebar)
plotshape(buy2, style=shape.xcross, color=color.new(#30ff85, 0), textcolor=color.new(color.white, 0), size=size.tiny, location=location.belowbar)
plotshape(sell2, style=shape.xcross, color=color.new(#ff1200, 0), textcolor=color.new(color.white, 0), size=size.tiny, location=location.abovebar)
// ALERTS /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
alertcondition(buy, 'Buy', 'Buy') // Once per bar close
alertcondition(sell, 'Sell', 'Sell') // Once per bar close
alertcondition(buy2, 'Buy', 'Buy') // Once per bar close
alertcondition(sell2, 'Sell', 'Sell') // Once per bar close
|
AI SuperTrend Clustering Oscillator [LuxAlgo] | https://www.tradingview.com/script/y2WjAnHA-AI-SuperTrend-Clustering-Oscillator-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,315 | 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("AI SuperTrend Clustering Oscillator [LuxAlgo]", "LuxAlgo - AI SuperTrend Clustering Oscillator")
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input(10, 'ATR Length')
minMult = input.int(1, 'Factor Range', minval = 0, inline = 'factor')
maxMult = input.int(5, '', minval = 0, inline = 'factor')
step = input.float(.5, 'Step', minval = 0, step = 0.1)
smooth = input.float(1, minval = 1)
//Trigger error
if minMult > maxMult
runtime.error('Minimum factor is greater than maximum factor in the range')
//Optimization
maxIter = input.int(1000, 'Maximum Iteration Steps', minval = 0, group = 'Optimization')
maxData = input.int(10000, 'Historical Bars Calculation', minval = 0, group = 'Optimization')
//Style
bullCss = input(color.new(#5b9cf6, 50), 'Bullish', inline = 'bull', group = 'Style')
strongBullCss = input(color.new(#5b9cf6, 28), 'Strong', inline = 'bull', group = 'Style')
neutCss = input(#9598a1, 'Neutral', inline = 'neut', group = 'Style')
bearCss = input(color.new(#f77c80, 50), 'Bearish', inline = 'bear', group = 'Style')
strongBearCss = input(color.new(#f77c80, 28), 'Strong', inline = 'bear', group = 'Style')
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type supertrend
float upper = hl2
float lower = hl2
float output
int trend
type vector
array<float> out
//-----------------------------------------------------------------------------}
//Supertrend
//-----------------------------------------------------------------------------{
var holder = array.new<supertrend>(0)
var factors = array.new<float>(0)
//Populate supertrend type array
if barstate.isfirst
for i = 0 to int((maxMult - minMult) / step)
factors.push(minMult + i * step)
holder.push(supertrend.new())
atr = ta.atr(length)
//Compute Supertrend for multiple factors
k = 0
for factor in factors
get_spt = holder.get(k)
up = hl2 + atr * factor
dn = hl2 - atr * factor
get_spt.upper := close[1] < get_spt.upper ? math.min(up, get_spt.upper) : up
get_spt.lower := close[1] > get_spt.lower ? math.max(dn, get_spt.lower) : dn
get_spt.trend := close > get_spt.upper ? 1 : close < get_spt.lower ? 0 : get_spt.trend
get_spt.output := get_spt.trend == 1 ? get_spt.lower : get_spt.upper
k += 1
//-----------------------------------------------------------------------------}
//K-means clustering
//-----------------------------------------------------------------------------{
data = array.new<float>(0)
//Populate data arrays
if last_bar_index - bar_index <= maxData
for element in holder
data.push(close - element.output)
//Intitalize centroids using quartiles
centroids = array.new<float>(0)
centroids.push(data.percentile_linear_interpolation(25))
centroids.push(data.percentile_linear_interpolation(50))
centroids.push(data.percentile_linear_interpolation(75))
//Intialize clusters
var array<vector> clusters = na
if last_bar_index - bar_index <= maxData
for _ = 0 to maxIter
clusters := array.from(vector.new(array.new<float>(0)), vector.new(array.new<float>(0)), vector.new(array.new<float>(0)))
//Assign value to cluster
for value in data
dist = array.new<float>(0)
for centroid in centroids
dist.push(math.abs(value - centroid))
idx = dist.indexof(dist.min())
if idx != -1
clusters.get(idx).out.push(value)
//Update centroids
new_centroids = array.new<float>(0)
for cluster_ in clusters
new_centroids.push(cluster_.out.avg())
//Test if centroid changed
if new_centroids.get(0) == centroids.get(0) and new_centroids.get(1) == centroids.get(1) and new_centroids.get(2) == centroids.get(2)
break
centroids := new_centroids
//-----------------------------------------------------------------------------}
//Get centroids
//-----------------------------------------------------------------------------{
//Get associated supertrend
var float bull = 0
var float neut = 0
var float bear = 0
var den = 0
if not na(clusters)
bull += 2/(smooth+1) * nz(centroids.get(2) - bull)
neut += 2/(smooth+1) * nz(centroids.get(1) - neut)
bear += 2/(smooth+1) * nz(centroids.get(0) - bear)
den += 1
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot_bull = plot(math.max(bull, 0), color = na, editable = false)
plot_bull_ext = plot(math.max(bear, 0), 'Strong Bullish'
, bear > 0 ? strongBullCss : na
, style = plot.style_circles)
plot_bear = plot(math.min(bear, 0), color = na, editable = false)
plot_bear_ext = plot(math.min(bull, 0), 'Strong Bearish'
, bull < 0 ? strongBearCss : na
, style = plot.style_circles)
plot(neut, 'Consensus', neutCss)
fill(plot_bull, plot_bull_ext, bull, math.max(bear, 0), bullCss, color.new(chart.bg_color, 100))
fill(plot_bear_ext, plot_bear, math.min(bull, 0), bear, color.new(chart.bg_color, 100), bearCss)
hline(0, linestyle = hline.style_solid)
//-----------------------------------------------------------------------------} |
Exceptional Volume Spike - Potential Trend Reversal Indicator | https://www.tradingview.com/script/pT083ycf-Exceptional-Volume-Spike-Potential-Trend-Reversal-Indicator/ | Tradager | https://www.tradingview.com/u/Tradager/ | 50 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Tradager
//@version=5
indicator(title="Trend Reversal Indicator", shorttitle="TRI", overlay=true)
// Input parameters with default values
relative_volume_threshold = input(4.0, title="Relative Volume Threshold")
ema_length = input(20, title="EMA Length")
lookback_period = input(200, title="Support/Resistance Lookback Period")
// Calculate average volume over the lookback period
avg_volume = ta.sma(volume, lookback_period)
// Calculate relative volume
rel_volume = volume / avg_volume
// Identify exceptional volume spikes
is_spike = rel_volume > relative_volume_threshold
// Calculate EMA of exceptional volume spikes
ema_spikes = ta.ema(is_spike ? volume : 0, ema_length)
// Determine trend direction based on crossover of EMA of exceptional volume spikes
trend_up = ta.crossover(ema_spikes, ta.ema(is_spike ? 0 : volume, ema_length))
trend_down = ta.crossunder(ema_spikes, ta.ema(is_spike ? 0 : volume, ema_length))
// Calculate highest high and lowest low
hh = ta.highest(high, lookback_period)
ll = ta.lowest(low, lookback_period)
// Plot triangles and trend reversal markers with larger size
plotshape(series=is_spike and trend_up, style=shape.triangleup, location=location.belowbar, color=color.new(color.red, 0), size=size.small)
plotshape(series=is_spike and trend_down, style=shape.triangledown, location=location.abovebar, color=color.new(color.green, 0), size=size.small)
// Plot support and resistance levels
plot(hh, title="Potential Resistance", color=color.new(color.orange, 0), linewidth=2)
plot(ll, title="Potential Support", color=color.new(color.purple, 0), linewidth=2)
// Calculate and plot EMA of closing price
ema_close = ta.ema(close, ema_length)
plot(ema_close, title="EMA", color=ema_close > ema_close[1] ? color.new(color.green, 0) : ema_close < ema_close[1] ? color.new(color.red, 0) : color.new(color.blue, 0))
|
HTF Trend Filter - Dynamic Smoothing | https://www.tradingview.com/script/WSfUYnNA-HTF-Trend-Filter-Dynamic-Smoothing/ | Harrocop | https://www.tradingview.com/u/Harrocop/ | 122 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Harrocop
////////////////////////////////////////////////////////////////////////////////////////
// HTF Trend Filter - Dynamic Smoothing
// - Option to change high time frame settings
// - Option to choose from different moving average types
// - The Dynamic smoothing makes a sleek line, taking the ratio of minutes of the higher time frame to the current time frame
// - Color green with uptrend, color red with downtrend
// - options for notification in case of trend reversal
////////////////////////////////////////////////////////////////////////////////////////
//@version=5
indicator("HTF Trend Filter - Dynamic Smoothing", "HTF trend", overlay = true)
//////////////////////////////////////////////////////
////////// Filter Trend ////////////
//////////////////////////////////////////////////////
TREND = "Higher Time Frame Trend"
TimeFrame_Trend = input.timeframe(title='Higher Time Frame', defval='240', inline = "Trend1", group = TREND)
length = input.int(55, title="Length MA", minval=1, tooltip = "Number of bars used to measure trend on higher timeframe chart", inline = "Trend1", group = TREND)
MA_Type = input.string(defval="EMA" , options=["EMA","DEMA","TEMA","SMA","WMA", "HMA", "McGinley"], title="MA type for HTF trend", inline = "Trend2", group = TREND)
Plot_Reversal = input.bool(true, title = "Plot Reversal?", inline = "Trend2", group = TREND)
ma(type, src, length) =>
float result = 0
if type == 'TMA' // Triangular Moving Average
result := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
result
if type == 'LSMA' // Least Squares Moving Average
result := ta.linreg(src, length, 0)
result
if type == 'SMA' // Simple Moving Average
result := ta.sma(src, length)
result
if type == 'EMA' // Exponential Moving Average
result := ta.ema(src, length)
result
if type == 'DEMA' // Double Exponential Moving Average
e = ta.ema(src, length)
result := 2 * e - ta.ema(e, length)
result
if type == 'TEMA' // Triple Exponentiale
e = ta.ema(src, length)
result := 3 * (e - ta.ema(e, length)) + ta.ema(ta.ema(e, length), length)
result
if type == 'WMA' // Weighted Moving Average
result := ta.wma(src, length)
result
if type == 'HMA' // Hull Moving Average
result := ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(length)))
result
if type == 'McGinley' // McGinley Dynamic Moving Average
mg = 0.0
mg := na(mg[1]) ? ta.ema(src, length) : mg[1] + (src - mg[1]) / (length * math.pow(src / mg[1], 4))
result := mg
result
result
// Moving Average
MAtrend = ma(MA_Type, close, length)
MA_Value_HTF = request.security(syminfo.ticker, TimeFrame_Trend, MAtrend)
// Get minutes for current and higher timeframes
// Function to convert a timeframe string to its equivalent in minutes
timeframeToMinutes(tf) =>
multiplier = 1
if (str.endswith(tf, "D"))
multiplier := 1440
else if (str.endswith(tf, "W"))
multiplier := 10080
else if (str.endswith(tf, "M"))
multiplier := 43200
else if (str.endswith(tf, "H"))
multiplier := int(str.tonumber(str.replace(tf, "H", "")))
else
multiplier := int(str.tonumber(str.replace(tf, "m", "")))
multiplier
// Get minutes for current and higher timeframes
currentTFMinutes = timeframeToMinutes(timeframe.period)
higherTFMinutes = timeframeToMinutes(TimeFrame_Trend)
// Calculate the smoothing factor
dynamicSmoothing = math.round(higherTFMinutes / currentTFMinutes)
MA_Value_Smooth = ta.sma(MA_Value_HTF, dynamicSmoothing)
// Trend HTF
UP = MA_Value_Smooth > MA_Value_Smooth[1] // Use "UP" Function to use as filter in combination with other indicators
DOWN = MA_Value_Smooth < MA_Value_Smooth[1] // Use "Down" Function to use as filter in combination with other indicators
Reversal_UP = MA_Value_Smooth[1] < MA_Value_Smooth[2] and MA_Value_Smooth > MA_Value_Smooth[1] == true
Reversal_DOWN = MA_Value_Smooth[1] > MA_Value_Smooth[2] and MA_Value_Smooth < MA_Value_Smooth[1] == true
// Plot HTF Trend and Reversals
plot(MA_Value_Smooth, "HTF Trend", color = UP ? color.rgb(0, 255, 8) : color.rgb(255, 0, 0), linewidth = 2, style = plot.style_line)
plot(Plot_Reversal ? Reversal_UP ? MA_Value_Smooth : na : na, "Start of Up trend!", style = plot.style_circles, color = color.rgb(0, 255, 8), linewidth = 4)
plot(Plot_Reversal ? Reversal_DOWN ? MA_Value_Smooth : na : na, "Start of Down trend!", style = plot.style_circles, color = color.rgb(255, 0, 0), linewidth = 4)
//////////////////////////////////////////////////
/////////// Alerts ////////////////
//////////////////////////////////////////////////
// Alert conditions for Crossover
alertcondition(Reversal_UP, title="Uptrend Started", message="Uptrend Started!")
alertcondition(Reversal_DOWN, title="Downtrend started!", message="Downtrend started!") |
MACD HIstgramMA signl Crossing | https://www.tradingview.com/script/luZytJkk/ | JFX_TV | https://www.tradingview.com/u/JFX_TV/ | 9 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// jfx_1503
//@version=5
indicator("MACD")
// 値の取得
fast_length=input.int(12,"Fast Length")
slow_length=input.int(26,"Slow Length")
src=input.source(close,"Source")
signal_length=input.int(10,"Fast Length",maxval=50,minval=1,step=9)
sma_source=input.bool(false,"Simple MA(Oscillator)")
sma_signal=input.bool(false,"Simple MA(Signal Line)")
// プロットの色
col_grow_above=#cfcfcf
col_grow_below=#cfcfcf
col_fall_above=#cfcfcf
col_fall_below=#cfcfcf
col_macd=#339207
col_signal=#ff0000
col_histma=#0011ff
col_crossAbove=#001affd3
col_crossBelow=#ff7038
// 計算
fast_ma=sma_source?ta.sma(src,fast_length):ta.ema(src,fast_length)
slow_ma=sma_source?ta.sma(src,slow_length):ta.ema(src,slow_length)
macd=fast_ma-slow_ma
signal=sma_signal?ta.sma(macd,signal_length):ta.ema(macd,signal_length)
hist=macd-signal
plot(hist,title="Histogram",style=plot.style_columns,color=color.new(hist>=0?(hist[1]<hist?col_grow_above:col_fall_above):(hist[1]<hist?col_grow_below:col_fall_below),transp=0))
plot(macd,title="MACD",color=color.new(col_macd,transp=0))
plot(signal,title="Signal",color=color.new(col_signal,transp=0))
histMaLength=input(5,"Histgram MA")
histMA=ta.sma(hist,histMaLength)
crossAbove = ta.crossover(histMA, signal)
crossBelow = ta.crossunder(histMA, signal)
plot(histMA,title="Histgram MA" ,color=color.new(col_histma,transp=0))
plotshape(series = crossAbove, title = "Cross Above", style = shape.triangledown, location=location.top, color=color.new(col_crossAbove,transp=0), size="small")
plotshape(series = crossBelow, title = "Cross Below", style = shape.triangleup,location=location.bottom, color=color.new(col_crossBelow,transp=0), size="small")
|
Bollinger Band Percentile Suite | https://www.tradingview.com/script/hA1zFpuC-Bollinger-Band-Percentile-Suite/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 278 | 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/
// © QuantiLuxe
//@version=5
indicator("Bollinger Band Percent Suite", "{Ʌ} - 𝐵𝐵𝒫𝒸𝓉 𝒮𝓊𝒾𝓉𝑒", false)
f_kama(src, len, kamaf, kamas) =>
white = math.abs(src - src[1])
ama = 0.0
nsignal = math.abs(src - src[len])
nnoise = math.sum(white, len)
nefratio = nnoise != 0 ? nsignal / nnoise : 0
nsmooth = math.pow(nefratio * (kamaf - kamas) + kamas, 2)
ama := nz(ama[1]) + nsmooth * (src - nz(ama[1]))
ama
f_t3(src, len) =>
x1 = ta.ema(src, len)
x2 = ta.ema(x1, len)
x3 = ta.ema(x2, len)
x4 = ta.ema(x3, len)
x5 = ta.ema(x4, len)
x6 = ta.ema(x5, len)
b = 0.7
c1 = - math.pow(b, 3)
c2 = 3 * math.pow(b, 2) + 3 * math.pow(b, 3)
c3 = -6 * math.pow(b, 2) - 3 * b - 3 * math.pow(b, 3)
c4 = 1 + 3 * b + math.pow(b, 3) + 3 * math.pow(b, 2)
c1 * x6 + c2 * x5 + c3 * x4 + c4 * x3
f_ehma(src, length) =>
ta.ema(2 * ta.ema(src, length / 2) - ta.ema(src, length), math.round(math.sqrt(length)))
f_thma(src, length) =>
ta.wma(ta.wma(src, length / 3) * 3 - ta.wma(src, length / 2) - ta.wma(src, length), length)
f_tema(src, len) =>
x = ta.ema(src, len)
y = ta.ema(x, len)
z = ta.ema(y, len)
3 * x - 3 * y + z
f_dema(src, len) =>
x = ta.ema(src, len)
y = ta.ema(x, len)
2 * x - y
f_ma(src, len, type, kamaf, kamas, offset, sigma) =>
x = switch type
"SMA" => ta.sma(src, len)
"EMA" => ta.ema(src, len)
"HMA" => ta.hma(src, len)
"RMA" => ta.rma(src, len)
"WMA" => ta.wma(src, len)
"VWMA" => ta.vwma(src, len)
"ALMA" => ta.alma(src, len, offset, sigma)
"DEMA" => f_dema(src, len)
"TEMA" => f_tema(src, len)
"EHMA" => f_ehma(src, len)
"THMA" => f_thma(src, len)
"T3" => f_t3(src, len)
"KAMA" => f_kama(src, len, kamaf, kamas)
"LSMA" => ta.linreg(src, len, 0)
x
f_wstdev(src, len) =>
mean = ta.wma(src, len)
norm = 0.0
sum = 0.0
for i = 0 to len - 1
weight = len - i
norm := norm + weight
sum := sum + math.pow((src[i] - mean), 2) * weight
math.sqrt(sum / norm)
matype = input.string("EMA", "BaseLine", ["SMA", "EMA", "DEMA", "TEMA", "HMA", "EHMA", "THMA", "RMA", "WMA", "VWMA", "T3", "KAMA", "ALMA", "LSMA"], inline = "2", group = "BBPct")
devtype = input.string("Standard", "Deviation", ["Weighted", "Standard"], inline = "2", group = "BBPct")
src = input(close, "Source", inline = "1", group = "BBPct")
len = input.int(20, "Length", inline = "1", group = "BBPct")
mult = input.float(2.0, "Multi", step = 0.25, group = "BBPct")
hi = input.int(100, "High Threshold", 50, 200, 5, group = "Thresholds")
lo = input.int(0, "Low Threshold", -200, 50, 5, group = "Thresholds")
kamaf = input.float(0.666, "Kaufman Fast", group = "MA Settings")
kamas = input.float(0.0645, "Kaufman Slow", group = "MA Settings")
offset = input.float(0.85, "ALMA Offset", group = "MA Settings")
sigma = input.int(6, "ALMA Sigma", group = "MA Settings")
revshow = input.bool(true, "Display Reversion Bubbles", inline = "0", group = "UI Options")
colbar = input.string("None", "Bar Coloring", ["None", "Trend", "Extremities", "Reversions"], group = "UI Options")
basis = f_ma(src, len, matype, kamaf, kamas, offset, sigma)
dev = mult * (devtype == "Standard" ? ta.stdev(src, len) : f_wstdev(src, len))
upper = basis + dev
lower = basis - dev
bbpct = (src - lower) / (upper - lower) * 100
lh = plot(hi, "Overbought", #bb0010, display = display.pane)
hh = plot(hi + 15, "Overbought", #bb0010, display = display.pane)
hline(50, "Middle Band", #f5f5dc6c, hline.style_solid)
hl = plot(lo, "Oversold", #009bafc0, display = display.pane)
ll = plot(lo - 15, "Oversold", #009bafc0, display = display.pane)
b = plot(bbpct, "𝐵𝐵𝒫𝒸𝓉", chart.fg_color)
fill(lh, hh, color = #bb001031)
fill(ll, hl, color = #009baf23)
fill(hl, b, bbpct[1] < lo and not (bbpct > lo) ? #009baf7e : na)
fill(lh, b, bbpct[1] > hi and not (bbpct < hi) ? #bb0010a2 : na)
ob = ta.crossunder(bbpct, hi)
os = ta.crossover(bbpct, lo)
plotchar(ob ? hi + 25 : na, "OB", '⚬', location.absolute, #bb0010, size = size.tiny)
plotchar(os ? lo - 25 : na, "OS", '⚬', location.absolute, #009baf, size = size.tiny)
color col = switch colbar
"Trend" => bbpct > 50 ? #009baf : #bb0010
"Extremities" => bbpct > hi ? #bb0010 : bbpct < lo ? #009baf : #787b86
"Reversions" => ob ? #bb0010 : os ? #009baf : #787b86
"None" => na
barcolor(col)
|
OBV Oscillator Volume Filter | https://www.tradingview.com/script/InJFzCSt-OBV-Oscillator-Volume-Filter/ | Harrocop | https://www.tradingview.com/u/Harrocop/ | 110 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Harrocop
// ------------------------------------------------------------------------------------------------------ //
// Script Summary:
// - The indicator calculates the on balance volume (OBV) and is plotted as an Oscillater.
// - The indicator has a volume filter using a % threshold based on the highest OBV value over X number of bars back.
// - The volume filter is thus based on a rolling window (time) and can be adjusted in sensitivity and # number of bars back.
// - The OBV can be calculated with different types of MA to your liking.
// - The signals are derived from potential trend reversals (eg. for entry and exit).
// - The script automatically shows divergences (green line for bullish and red line for bearish).
// - The script automatically shows hidden devergences using dotted lines.
// - The script includes the option to turn on alerts.
// - The script uses multiple plotted offsets of the OBV to make the indicator more appealing to read / interpret.
// ------------------------------------------------------------------------------------------------------ //
//@version=5
indicator("OBV Oscillator Volume Filter", "OBV Oscillator Volume Filter", overlay=false)
// Input Parameters
OBVgroup = "On Balance Volume Settings"
src = close
Type_MA = input.string(defval="WMA" , options=["EMA","DEMA","TEMA","SMA","WMA", "HMA"], title="MA type to calc OBV", tooltip = "MA used to calculate cumulative volume (OBV)", inline = "OBV1", group = OBVgroup)
length = input.int(21, title="Length", tooltip = "number # bars to calculate the OBV", inline = "OBV1", group = OBVgroup)
apply_smoothing = input.bool(true, title="Apply Smoothing?", inline = "OBV2", group = OBVgroup)
smoothing_length = input.int(21, title="Length Smoothing", tooltip = "To reduce noise the indicator is smoothed using a SMA)", inline = "OBV2", group = OBVgroup)
LookbackBars = input.int(480, title = "Lookback # Bars", inline = "OBV3", group = OBVgroup, tooltip = "Calculates the absolute OBV over the nr of bars back to determine deadzone, this is a rolling window")
Sensitivity = input.int(50, title = "Deadzone Sensitivity", minval = 1, maxval = 100, step = 1, tooltip = "Expressed as % value (between 1 - 100) of Absolute OBV based on Lookback # Bars, the higher the % the less signals occur", inline = "OBV3", group = OBVgroup) / 100
// Calculate DEMA
fx_dema(inp_source, inp_lenght) =>
ema_01 = ta.ema(inp_source, inp_lenght)
ema_02 = ta.ema(ema_01 , inp_lenght)
output = (2 * ema_01 - ema_02)
// Calculate TEMA
fx_tema(inp_source, inp_lenght) =>
ema_01 = ta.ema(inp_source, inp_lenght)
ema_02 = ta.ema(ema_01 , inp_lenght)
ema_03 = ta.ema(ema_02 , inp_lenght)
output = (3 * (ema_01 - ema_02) + ema_03)
// Calculate HMA
fx_hma(inp_source, inp_lenght) =>
output = ta.wma(2 * ta.wma(inp_source, inp_lenght / 2) - ta.wma(inp_source, inp_lenght), math.round(math.sqrt(inp_lenght)))
// Select type of MA
fx_typeofmavg(inp_type, inp_source, inp_length) =>
_switch = (inp_type == "EMA" ) ? ta.ema(inp_source , inp_length) :
(inp_type == "DEMA") ? fx_dema(inp_source, inp_length) :
(inp_type == "TEMA") ? fx_tema(inp_source, inp_length) :
(inp_type == "SMA" ) ? ta.sma (inp_source, inp_length) :
(inp_type == "WMA" ) ? ta.wma (inp_source, inp_length) :
(inp_type == "HMA" ) ? fx_hma(inp_source, inp_length) :
0.0 // return zero in case of mistake
output = _switch
// Calculate the On Balance Volume (OBV)
obv(src) =>
os = ta.cum(ta.change(src) > 0 ? volume : ta.change(src) < 0 ? -volume : 0)
os
os = obv(src)
obv_osc = os - fx_typeofmavg(Type_MA, os, length)
// Apply smoothing
final_obv_osc = apply_smoothing ? ta.sma(obv_osc, smoothing_length) : obv_osc
// Simulating the 2 bars forward offset
var float offset_obv_osc = na
var float offset_obv_osc_1 = na
offset_obv_osc := offset_obv_osc_1
offset_obv_osc_1 := final_obv_osc
// Smaller mountains for filling area
// Simulating the 2 bars forward offset
var float offset_obv_osc_2 = na
var float offset_obv_osc_3 = na
offset_obv_osc_2 := offset_obv_osc_3
offset_obv_osc_3 := offset_obv_osc
offset_obv_osc_small = offset_obv_osc_2 * 0.85
var float offset_obv_osc_4 = na
var float offset_obv_osc_5 = na
offset_obv_osc_4 := offset_obv_osc_5
offset_obv_osc_5 := offset_obv_osc_2
offset_obv_osc_tiny = offset_obv_osc_4 * 0.7
// Calculate outlier threshold
outlier_threshold = Sensitivity * ta.highest(volume, LookbackBars)
// Long and Short conditions
LongCondition = ta.crossover(final_obv_osc, offset_obv_osc) and final_obv_osc < -outlier_threshold and barstate.isconfirmed
ShortCondition = ta.crossunder(final_obv_osc, offset_obv_osc) and final_obv_osc > outlier_threshold and barstate.isconfirmed
// Plot outlier thresholds and zero line
f1 = plot(outlier_threshold, style = plot.style_area, color=color.rgb(255, 94, 0, 75), linewidth=1, title="Positive Outlier Threshold")
f2 = plot(-outlier_threshold, style = plot.style_area, color=color.rgb(255, 69, 0, 75), linewidth=1, title="Negative Outlier Threshold")
zeroLine = plot(0, color = color.white)
// Plotting the OBV Oscillator
plot(final_obv_osc, style=plot.style_area, color = color.rgb(51, 136, 255), title="OBV-value", linewidth=2)
plot(offset_obv_osc, style=plot.style_area, color = color.rgb(0, 0, 255, 15) , title="OBV-offset", linewidth=2)
plot(offset_obv_osc_small, style=plot.style_area, color = color.rgb(31, 31, 122, 15) , title="OBV-small", linewidth=2)
plot(offset_obv_osc_tiny, style=plot.style_area, color = color.rgb(17, 17, 63, 15) , title="OBV-tiny", linewidth=2)
// plot Signals -- Draw Green and Red Dots on Intersections
plot(LongCondition ? final_obv_osc : na, "Long Condition", style = plot.style_circles, linewidth = 5, color = color.rgb(0, 255, 8))
plot(ShortCondition ? final_obv_osc : na, "Short Condition", style = plot.style_circles, linewidth = 5, color = color.rgb(255, 0, 0))
//////////////////////////////////////////////////
/////////// Divergence Settings ////////////////
//////////////////////////////////////////////////
/////////////////////
// LONG CONDITIONS //
/////////////////////
// Calculating previous OBV Oscillator, close values, and bar indices
obv_val_current_long = ta.valuewhen(LongCondition, final_obv_osc, 0)
obv_val_previous_long = ta.valuewhen(LongCondition, final_obv_osc, 1)
close_val_current_long = ta.valuewhen(LongCondition, close, 0)
close_val_previous_long = ta.valuewhen(LongCondition, close, 1)
bar_index_current_long = ta.valuewhen(LongCondition, bar_index, 0)
bar_index_previous_long = ta.valuewhen(LongCondition, bar_index, 1)
// Bullish Divergence for LongCondition[0] and LongCondition[1]
bullishDivergenceCond1_long = LongCondition and obv_val_current_long > obv_val_previous_long and close_val_current_long < close_val_previous_long
if (bullishDivergenceCond1_long)
line.new(x1=bar_index_previous_long, y1=obv_val_previous_long, x2=bar_index_current_long, y2=obv_val_current_long, color=color.rgb(0, 255, 8))
// Fetch values for LongCondition[2]
obv_val_previous2_long = ta.valuewhen(LongCondition, final_obv_osc, 2)
close_val_previous2_long = ta.valuewhen(LongCondition, close, 2)
bar_index_previous2_long = ta.valuewhen(LongCondition, bar_index, 2)
// Bullish Divergence for LongCondition[0] and LongCondition[2]
bullishDivergenceCond2_long = LongCondition and obv_val_current_long > obv_val_previous2_long and close_val_current_long < close_val_previous2_long
if (bullishDivergenceCond2_long)
line.new(x1=bar_index_previous2_long, y1=obv_val_previous2_long, x2=bar_index_current_long, y2=obv_val_current_long, color=color.rgb(0, 255, 8))
// Hidden Bullish Divergence for LongCondition[0] and LongCondition[1]
hiddenBullishDivergenceCond1_long = LongCondition and obv_val_current_long < obv_val_previous_long and close_val_current_long > close_val_previous_long
if (hiddenBullishDivergenceCond1_long)
line.new(x1=bar_index_previous_long, y1=obv_val_previous_long, x2=bar_index_current_long, y2=obv_val_current_long, color=color.rgb(0, 255, 8), width=1, style=line.style_dotted)
// Hidden Bullish Divergence for LongCondition[0] and LongCondition[2]
hiddenBullishDivergenceCond2_long = LongCondition and obv_val_current_long < obv_val_previous2_long and close_val_current_long > close_val_previous2_long
if (hiddenBullishDivergenceCond2_long)
line.new(x1=bar_index_previous2_long, y1=obv_val_previous2_long, x2=bar_index_current_long, y2=obv_val_current_long, color=color.rgb(0, 255, 8), width=1, style=line.style_dotted)
//////////////////////
// SHORT CONDITIONS //
//////////////////////
// Calculating previous OBV Oscillator, close values, and bar indices
obv_val_current_short = ta.valuewhen(ShortCondition, final_obv_osc, 0)
obv_val_previous_short = ta.valuewhen(ShortCondition, final_obv_osc, 1)
close_val_current_short = ta.valuewhen(ShortCondition, close, 0)
close_val_previous_short = ta.valuewhen(ShortCondition, close, 1)
bar_index_current_short = ta.valuewhen(ShortCondition, bar_index, 0)
bar_index_previous_short = ta.valuewhen(ShortCondition, bar_index, 1)
// Bearish Divergence for ShortCondition[0] and ShortCondition[1]
bearishDivergenceCond1_short = ShortCondition and obv_val_current_short < obv_val_previous_short and close_val_current_short > close_val_previous_short
if (bearishDivergenceCond1_short)
line.new(x1=bar_index_previous_short, y1=obv_val_previous_short, x2=bar_index_current_short, y2=obv_val_current_short, color=color.rgb(255, 0, 0))
// Fetch values for ShortCondition[2]
obv_val_previous2_short = ta.valuewhen(ShortCondition, final_obv_osc, 2)
close_val_previous2_short = ta.valuewhen(ShortCondition, close, 2)
bar_index_previous2_short = ta.valuewhen(ShortCondition, bar_index, 2)
// Bearish Divergence for ShortCondition[0] and ShortCondition[2]
bearishDivergenceCond2_short = ShortCondition and obv_val_current_short < obv_val_previous2_short and close_val_current_short > close_val_previous2_short
if (bearishDivergenceCond2_short)
line.new(x1=bar_index_previous2_short, y1=obv_val_previous2_short, x2=bar_index_current_short, y2=obv_val_current_short, color=color.rgb(255, 0, 0))
// Hidden Bearish Divergence for ShortCondition[0] and ShortCondition[1]
hiddenBearishDivergenceCond1_short = ShortCondition and obv_val_current_short > obv_val_previous_short and close_val_current_short < close_val_previous_short
if (hiddenBearishDivergenceCond1_short)
line.new(x1=bar_index_previous_short, y1=obv_val_previous_short, x2=bar_index_current_short, y2=obv_val_current_short, color=color.rgb(255, 0, 0), width=1, style=line.style_dotted)
// Hidden Bearish Divergence for ShortCondition[0] and ShortCondition[2]
hiddenBearishDivergenceCond2_short = ShortCondition and obv_val_current_short > obv_val_previous2_short and close_val_current_short < close_val_previous2_short
if (hiddenBearishDivergenceCond2_short)
line.new(x1=bar_index_previous2_short, y1=obv_val_previous2_short, x2=bar_index_current_short, y2=obv_val_current_short, color=color.rgb(255, 0, 0), width=1, style=line.style_dotted)
//////////////////////////////////////////////////
/////////// Alerts ////////////////
//////////////////////////////////////////////////
// Alert conditions for Crossover
alertcondition(LongCondition, title="Long Alert", message="Long Condition Triggered!")
alertcondition(ShortCondition, title="Short Alert", message="Short Condition Triggered!")
alertcondition(bullishDivergenceCond1_long or bullishDivergenceCond2_long, title="Bullish Divergence Alert", message="Bullish Divergence Detected!")
alertcondition(hiddenBullishDivergenceCond1_long or hiddenBullishDivergenceCond2_long, title="Hidden Bullish Divergence Alert", message="Hidden Bullish Divergence Detected!")
alertcondition(bearishDivergenceCond1_short or bearishDivergenceCond2_short, title="Bearish Divergence Alert", message="Bearish Divergence Detected!")
alertcondition(hiddenBearishDivergenceCond1_short or hiddenBearishDivergenceCond2_short, title="Hidden Bearish Divergence Alert", message="Hidden Bearish Divergence Detected!")
|
Gaussian Average Rate Oscillator | https://www.tradingview.com/script/a20Xmcfb-Gaussian-Average-Rate-Oscillator/ | DraftVenture | https://www.tradingview.com/u/DraftVenture/ | 30 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0
// © DraftVenture
//@version=5
indicator("Gaussian Average Rate Oscillator", shorttitle = "GARO", overlay=false)
// Input parameters
source = input(ohlc4, title = "Source")
windowsize = input.int(title="Gaussian Length", defval=26)
maLength = input.int(title = "Baseline Length", defval = 52)
ma_smoothing = input.int(title="Smoothing", defval=9)
// Calculate Averages
alma_value = ta.alma(source, windowsize, 0.85, 6)
ema_value = ta.ema(source, maLength)
// Calculate Smoothing
smoothalma_value = ta.ema(alma_value, ma_smoothing)
sema_value = ta.sma(ema_value, ma_smoothing)
// Calculate ROCs
roc_smoothalma = ta.roc(smoothalma_value, 1)
roc_sema = ta.roc(sema_value, 1)
// Plot ALMA ROC
color_smoothalma = roc_smoothalma > roc_sema ? color.green : roc_smoothalma < roc_sema ? color.red : color.black
color_sema = roc_sema < roc_smoothalma ? color.green : roc_sema > roc_smoothalma ? color.red : color.black
plot(roc_smoothalma, title="Gaussian Plot Area", color=color_smoothalma, linewidth = 2, style=plot.style_histogram)
plot(roc_sema, "Smooth EMA Plot Area", color_sema, linewidth = 2, style = plot.style_histogram)
hline(0, title = "Zero Rate Line", color = color.gray, linestyle = hline.style_solid)
// ______ _________
// ___ //_/__ __ \
// __ ,< __ /_/ /
// _ /| | _ ____/
// /_/ |_| /_/ |
Implied Range from Options [SS] | https://www.tradingview.com/script/mKFQ2LRS-Implied-Range-from-Options-SS/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 154 | study | 5 | MPL-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("Implied Range from Options [SS]", overlay=true)
g1 = "Call Data"
g2 = "Put Data"
g3 = "Range Analytics"
g4 = "Settings"
showirlbl = input.bool(true, "Show Implied Range Labels", group = g4)
showplts = input.bool(true, "Show Median and Midline Plots", group = g4)
offseta = input.int(0, "Offset", group=g4)
strike = input.float(100, "Strike Price", group = g1)
iv = input.float(27.20, "Implied Volatility", group=g1)
days = input.int(7, "Days to Expiry", group = g1)
strike2 = input.float(100, "Strike Price", group = g2)
iv2 = input.float(27.20, "Implied Volatility", group=g2)
days2 = input.int(7, "Days to Expiry", group = g2)
showlbl = input.bool(true, "Show Range Labels", group=g3)
len = input.int(14, "Length", group=g3, tooltip = "Determines the lookback length for the average high to open and open to low.")
timeframe = input.timeframe("D", group = g3, tooltip = "Timeframe will determine the average range based on the desired timeframe outlook.")
em1 = (strike * iv * math.sqrt(days/252)) / 100
em2 = (strike2 * iv2 * math.sqrt(days/252)) / 100
em_ucl = strike + em1
em_lcl = strike - em1
em2_ucl = strike2 + em2
em2_lcl = strike2 - em2
a = plot(em_ucl, color=color.green, offset = offseta, linewidth=3)
b = plot(em_lcl, color=color.red, offset = offseta, linewidth=3)
c = plot(em2_ucl, color=color.green, offset=offseta, linewidth=3)
d = plot(em2_lcl, color=color.red, offset=offseta, linewidth=3)
// Additional Colours and fills
color redfill = color.new(color.red, 85)
color greenfill = color.new(color.lime, 85)
color bluefill = color.new(color.blue, 85)
color white = color.white
color purple = color.purple
color transp = color.new(color.white, 100)
fill(b, d, color = redfill)
fill(a, c, color = greenfill)
// Range analytics
[op, avg_hi_to_op, prev_hi_to_op, avg_lo_to_op, prev_lo_to_op] = request.security(syminfo.ticker, timeframe, [close, ta.sma(high-open, len), (high[1] - low[1]), ta.sma(open - low, 14), (open[1] - low[1])], lookahead = barmerge.lookahead_on)
// Avg Baseline
avg_base = (em_ucl + em2_lcl) / 2
hi_mid = (em_ucl + avg_base) / 2
lo_mid = (em2_lcl + avg_base) / 2
hi_perc_dif = (em_ucl - op) / op * 100
hi_mid_perc_dif = (hi_mid - op) / op * 100
lo_mid_perc_dif = (lo_mid - op) / op * 100
lo_perc_dif = (em_lcl - op) / op * 100
hi_midmid = (em2_ucl - hi_mid) / 2
avghi_mid = (hi_mid - avg_base) / 2
lo_midmid = (lo_mid - em2_lcl) / 2
plot(showplts ? hi_mid : na, color=color.aqua, style=plot.style_cross, offset = offseta, linewidth=2)
plot(showplts ? lo_mid : na, color=color.aqua, style=plot.style_cross, offset = offseta, linewidth=2)
plot(showplts ? avg_base : na, color=purple, style=plot.style_circles, offset = offseta, linewidth=3)
var label callucl = na
var label putucl = na
var label calllcl = na
var label putlcl = na
var label hidiflbl = na
var label himidlbl = na
var label lomidlbl = na
var label lodiflbl = na
if barstate.islast and showirlbl
label.delete(callucl)
label.delete(putucl)
label.delete(calllcl)
label.delete(putlcl)
callucl := label.new(bar_index + offseta, y=em_ucl, text = "Implied High Range from Calls: " + str.tostring(math.round(em_ucl, 2)), style=label.style_label_down, color=greenfill, textcolor=white)
putucl := label.new(bar_index + offseta, y=em2_ucl, text = "Implied High Range from Puts: " + str.tostring(math.round(em2_ucl, 2)), style=label.style_label_up, color=greenfill, textcolor=white)
calllcl := label.new(bar_index + offseta, y=em_lcl, text = "Implied Low Range from Calls: " + str.tostring(math.round(em_lcl, 2)), style=label.style_label_up, color=redfill, textcolor=white)
putlcl := label.new(bar_index + offseta, y=em2_lcl, text = "Implied Low Range from Puts: " + str.tostring(math.round(em2_lcl, 2)), style=label.style_label_down, color=redfill, textcolor=white)
if barstate.islast and showlbl
label.delete(himidlbl)
label.delete(hidiflbl)
label.delete(lomidlbl)
label.delete(lodiflbl)
hidiflbl := label.new(bar_index + offseta, y = hi_mid + hi_midmid, text = str.tostring(math.round(hi_perc_dif,2)) + "% \n Average High to Open: " + str.tostring(math.round(avg_hi_to_op,2)) + "\n Previous High to Open: " + str.tostring(prev_hi_to_op), color = transp, textcolor = white)
himidlbl := label.new(bar_index + offseta, y = avg_base + avghi_mid, text = str.tostring(math.round(hi_mid_perc_dif,2)) + "%", color = transp, textcolor = white)
lomidlbl := label.new(bar_index + offseta, y = avg_base - avghi_mid, text = str.tostring(math.round(lo_mid_perc_dif,2)) + "%", color = transp, textcolor = white)
lodiflbl := label.new(bar_index + offseta, y = lo_mid - lo_midmid, text = str.tostring(math.round(lo_perc_dif,2)) + "%" + "\n Average Open to Low: " + str.tostring(math.round(avg_lo_to_op,2)) + "\n Previous Open to Low: " + str.tostring(prev_lo_to_op), color = transp, textcolor = white)
|
Random Market «NoaTrader» | https://www.tradingview.com/script/hnXsvFli-Random-Market-NoaTrader/ | NoaTrader | https://www.tradingview.com/u/NoaTrader/ | 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/
// © NoaTrader
//@version=5
indicator("Random Market «NoaTrader»",overlay = false)
var start = input.float(1000,"Start Value")
var devider_max = input.float(100,"Devider Max")
var use_random_seed = input.bool(true,"Use Random Seed?")
var random_seed = input.int(1,"Random Seed")
var o = 0.0
var h = 0.0
var l = 0.0
var c = 0.0
if o == 0.0
o := start
else
o := c[1]
devider = use_random_seed ? math.random(devider_max/2,devider_max,random_seed) : math.random(devider_max/2,devider_max)
highest_random = use_random_seed ? math.random(0,int(o/devider),random_seed+1) : math.random(0,int(o/devider))
lowest_random = use_random_seed ? math.random(-int(o/devider),0,random_seed+2) : math.random(-int(o/devider),0)
oc = use_random_seed ? math.random(lowest_random,highest_random,random_seed+3) : math.random(lowest_random,highest_random)
c := o + oc
h := o + oc + (use_random_seed ? math.random(oc,highest_random,random_seed+4) : math.random(oc,highest_random))
l := o - (use_random_seed ? math.random(-lowest_random,-oc,random_seed+5) : math.random(-lowest_random,-oc))
candle_color = o < c ? color.green : color.red
plotcandle(o,h,l,c,color = candle_color , bordercolor = candle_color,wickcolor = candle_color) |
SuperTrend AI (Clustering) [LuxAlgo] | https://www.tradingview.com/script/wP7WWjLL-SuperTrend-AI-Clustering-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 6,066 | 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("SuperTrend AI (Clustering) [LuxAlgo]", "LuxAlgo - SuperTrend AI", overlay = true, max_labels_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input(10, 'ATR Length')
minMult = input.int(1, 'Factor Range', minval = 0, inline = 'factor')
maxMult = input.int(5, '', minval = 0, inline = 'factor')
step = input.float(.5, 'Step', minval = 0, step = 0.1)
//Trigger error
if minMult > maxMult
runtime.error('Minimum factor is greater than maximum factor in the range')
perfAlpha = input.float(10, 'Performance Memory', minval = 2)
fromCluster = input.string('Best', 'From Cluster', options = ['Best', 'Average', 'Worst'])
//Optimization
maxIter = input.int(1000, 'Maximum Iteration Steps', minval = 0, group = 'Optimization')
maxData = input.int(10000, 'Historical Bars Calculation', minval = 0, group = 'Optimization')
//Style
bearCss = input(color.red, 'Trailing Stop', inline = 'ts', group = 'Style')
bullCss = input(color.teal, '', inline = 'ts', group = 'Style')
amaBearCss = input(color.new(color.red, 50), 'AMA', inline = 'ama', group = 'Style')
amaBullCss = input(color.new(color.teal, 50), '', inline = 'ama', group = 'Style')
showGradient = input(true, 'Candle Coloring', group = 'Style')
showSignals = input(true, 'Show Signals', group = 'Style')
//Dashboard
showDash = input(true, 'Show Dashboard', group = 'Dashboard')
dashLoc = input.string('Top Right', 'Location', options = ['Top Right', 'Bottom Right', 'Bottom Left'], group = 'Dashboard')
textSize = input.string('Small', 'Size' , options = ['Tiny', 'Small', 'Normal'], group = 'Dashboard')
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type supertrend
float upper = hl2
float lower = hl2
float output
float perf = 0
float factor
int trend = 0
type vector
array<float> out
//-----------------------------------------------------------------------------}
//Supertrend
//-----------------------------------------------------------------------------{
var holder = array.new<supertrend>(0)
var factors = array.new<float>(0)
//Populate supertrend type array
if barstate.isfirst
for i = 0 to int((maxMult - minMult) / step)
factors.push(minMult + i * step)
holder.push(supertrend.new())
atr = ta.atr(length)
//Compute Supertrend for multiple factors
k = 0
for factor in factors
get_spt = holder.get(k)
up = hl2 + atr * factor
dn = hl2 - atr * factor
get_spt.trend := close > get_spt.upper ? 1 : close < get_spt.lower ? 0 : get_spt.trend
get_spt.upper := close[1] < get_spt.upper ? math.min(up, get_spt.upper) : up
get_spt.lower := close[1] > get_spt.lower ? math.max(dn, get_spt.lower) : dn
diff = nz(math.sign(close[1] - get_spt.output))
get_spt.perf += 2/(perfAlpha+1) * (nz(close - close[1]) * diff - get_spt.perf)
get_spt.output := get_spt.trend == 1 ? get_spt.lower : get_spt.upper
get_spt.factor := factor
k += 1
//-----------------------------------------------------------------------------}
//K-means clustering
//-----------------------------------------------------------------------------{
factor_array = array.new<float>(0)
data = array.new<float>(0)
//Populate data arrays
if last_bar_index - bar_index <= maxData
for element in holder
data.push(element.perf)
factor_array.push(element.factor)
//Intitalize centroids using quartiles
centroids = array.new<float>(0)
centroids.push(data.percentile_linear_interpolation(25))
centroids.push(data.percentile_linear_interpolation(50))
centroids.push(data.percentile_linear_interpolation(75))
//Intialize clusters
var array<vector> factors_clusters = na
var array<vector> perfclusters = na
if last_bar_index - bar_index <= maxData
for _ = 0 to maxIter
factors_clusters := array.from(vector.new(array.new<float>(0)), vector.new(array.new<float>(0)), vector.new(array.new<float>(0)))
perfclusters := array.from(vector.new(array.new<float>(0)), vector.new(array.new<float>(0)), vector.new(array.new<float>(0)))
//Assign value to cluster
i = 0
for value in data
dist = array.new<float>(0)
for centroid in centroids
dist.push(math.abs(value - centroid))
idx = dist.indexof(dist.min())
perfclusters.get(idx).out.push(value)
factors_clusters.get(idx).out.push(factor_array.get(i))
i += 1
//Update centroids
new_centroids = array.new<float>(0)
for cluster_ in perfclusters
new_centroids.push(cluster_.out.avg())
//Test if centroid changed
if new_centroids.get(0) == centroids.get(0) and new_centroids.get(1) == centroids.get(1) and new_centroids.get(2) == centroids.get(2)
break
centroids := new_centroids
//-----------------------------------------------------------------------------}
//Signals and trailing stop
//-----------------------------------------------------------------------------{
//Get associated supertrend
var float target_factor = na
var float perf_idx = na
var float perf_ama = na
var from = switch fromCluster
'Best' => 2
'Average' => 1
'Worst' => 0
//Performance index denominator
den = ta.ema(math.abs(close - close[1]), int(perfAlpha))
if not na(perfclusters)
//Get average factors within target cluster
target_factor := nz(factors_clusters.get(from).out.avg(), target_factor)
//Get performance index of target cluster
perf_idx := math.max(nz(perfclusters.get(from).out.avg()), 0) / den
//Get new supertrend
var upper = hl2
var lower = hl2
var os = 0
up = hl2 + atr * target_factor
dn = hl2 - atr * target_factor
upper := close[1] < upper ? math.min(up, upper) : up
lower := close[1] > lower ? math.max(dn, lower) : dn
os := close > upper ? 1 : close < lower ? 0 : os
ts = os ? lower : upper
//Get trailing stop adaptive MA
if na(ts[1]) and not na(ts)
perf_ama := ts
else
perf_ama += perf_idx * (ts - perf_ama)
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
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, 4, 4
, bgcolor = #1e222d
, border_color = #373a46
, border_width = 1
, frame_color = #373a46
, frame_width = 1)
if showDash
if barstate.isfirst
tb.cell(0, 0, 'Cluster', text_color = color.white, text_size = table_size)
tb.cell(0, 1, 'Best', text_color = color.white, text_size = table_size)
tb.cell(0, 2, 'Average', text_color = color.white, text_size = table_size)
tb.cell(0, 3, 'Worst', text_color = color.white, text_size = table_size)
tb.cell(1, 0, 'Size', text_color = color.white, text_size = table_size)
tb.cell(2, 0, 'Centroid Dispersion', text_color = color.white, text_size = table_size)
tb.cell(3, 0, 'Factors', text_color = color.white, text_size = table_size)
if barstate.islast
topN = perfclusters.get(2).out.size()
midN = perfclusters.get(1).out.size()
btmN = perfclusters.get(0).out.size()
//Size
tb.cell(1, 1, str.tostring(topN), text_color = color.white, text_size = table_size)
tb.cell(1, 2, str.tostring(midN), text_color = color.white, text_size = table_size)
tb.cell(1, 3, str.tostring(btmN), text_color = color.white, text_size = table_size)
//Content
tb.cell(3, 1, str.tostring(factors_clusters.get(2).out), text_color = color.white, text_size = table_size, text_halign = text.align_left)
tb.cell(3, 2, str.tostring(factors_clusters.get(1).out), text_color = color.white, text_size = table_size, text_halign = text.align_left)
tb.cell(3, 3, str.tostring(factors_clusters.get(0).out), text_color = color.white, text_size = table_size, text_halign = text.align_left)
//Calculate dispersion around centroid
i = 0
for cluster_ in perfclusters
disp = 0.
if cluster_.out.size() > 1
for value in cluster_.out
disp += math.abs(value - centroids.get(i))
disp /= switch i
0 => btmN
1 => midN
2 => topN
i += 1
tb.cell(2, 4 - i, str.tostring(disp, '#.####'), text_color = color.white, text_size = table_size)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
css = os ? bullCss : bearCss
plot(ts, 'Trailing Stop', os != os[1] ? na : css)
plot(perf_ama, 'Trailing Stop AMA',
ta.cross(close, perf_ama) ? na
: close > perf_ama ? amaBullCss : amaBearCss)
//Candle coloring
barcolor(showGradient ? color.from_gradient(perf_idx, 0, 1, color.new(css, 80), css) : na)
//Signals
n = bar_index
if showSignals
if os > os[1]
label.new(n, ts, str.tostring(int(perf_idx * 10))
, color = bullCss
, style = label.style_label_up
, textcolor = color.white
, size = size.tiny)
if os < os[1]
label.new(n, ts, str.tostring(int(perf_idx * 10))
, color = bearCss
, style = label.style_label_down
, textcolor = color.white
, size = size.tiny)
//-----------------------------------------------------------------------------} |
Monday Session High/Low | https://www.tradingview.com/script/e3hAIRsL-Monday-Session-High-Low/ | rahaidar | https://www.tradingview.com/u/rahaidar/ | 26 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rahaidar
//@version=5
indicator("[2023] Monday Session High/Low", max_lines_count=500, max_labels_count=500, overlay=true, max_bars_back=5000,max_boxes_count = 500)
type MONDAY
int [] uid
line [] highline
line [] lowline
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
//----------------------------------------}
//Previous day/week high/low
//----------------------------------------{
//Monday
show_pmonhl = input(true, 'Monday', inline = 'monday', group = 'Highs & Lows MTF')
pmonhl_style = input.string('⎯⎯⎯', '', options = ['⎯⎯⎯', '----', '····'], inline = 'monday', group = 'Highs & Lows MTF')
pmonhl_css = input(color.yellow, '', inline = 'monday', group = 'Highs & Lows MTF')
showhighlightmonday = input(true, 'Highlight Monday Session', inline = '2', group = 'Highs & Lows MTF')
highlightmonday_css = input(#ace5dc, '', inline = '2', group = 'Highs & Lows MTF')
highlightmonday_trans = input.int(75, 'Transparency', options = [0,25,50,75], inline = '2', group = 'Highs & Lows MTF')
history = input(10, title = 'Max History', group = 'Highs & Lows MTF', tooltip = 'Maximum number of historical lines to draw')
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
get_line_style(style) =>
out = switch style
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted
method in_out(MONDAY aMonday, x1, x2, hy, ly, col, styl) =>
aMonday.uid.unshift(x1), aMonday.uid.pop()
aMonday.highline.unshift(line.new(x1, hy, x2, hy, color= col,style=get_line_style(styl),xloc=xloc.bar_time)), aMonday.highline.pop().delete()
aMonday.lowline.unshift(line.new(x1, ly, x2, ly, color= col,style=get_line_style(styl),xloc=xloc.bar_time)), aMonday.lowline.pop().delete()
//function which is called by plot to establish day of the week is monday return true or false
isMonday() => dayofweek(time) == 2 ? 1 : 0
//HL Output function
hl() => [high, low]
//-----------------------------------------------------------------------------}
//Main
//-----------------------------------------------------------------------------{
var MONDAY aMonday = MONDAY.new(array.new < int >(), array.new < line >(),array.new < line >())
if barstate.isfirst
for i= 0 to history-1
aMonday.uid.unshift(0)
aMonday.highline.unshift(line.new(na, na, na, na))
aMonday.lowline.unshift(line.new(na, na, na, na))
// Get the start time and end time for the week
[weekStart, weekEnd] = request.security(syminfo.tickerid, 'W', [time, time_close], lookahead = barmerge.lookahead_on)
// Monday high/low
[pmonh, pmonl] = request.security(syminfo.tickerid, 'D', hl(), lookahead = barmerge.lookahead_on)
if show_pmonhl and isMonday() and aMonday.uid.indexof(weekStart) == -1
aMonday.in_out(weekStart,weekEnd, pmonh, pmonl, pmonhl_css, pmonhl_style)
// Highlight Monday Session
bgcolor(showhighlightmonday and isMonday() ? color.new(highlightmonday_css, highlightmonday_trans) : color(na))
|
Subsets and Splits