Buyer Seller Volume Balance between two Pivots - pine-script-v5

The following code shows the pivot points with tool tip showing the traded volume between two pivots. Another part of code contains select start date and end date to see the buyer and seller volume in number and in percentage. I want to display the buyer volume and seller volume in between two pivots with percentage. Please help me to correct the code., and display message when both buyer and seller volume equals 50:50.
like so
``
//#version=5
//https://www.tradingview.com/pine-script-docs/en/v5/concepts/Lines_and_boxes.html#modifying-lines
//Code taken from above url and added DGT Pivot code to filter pivot point code
indicator("Only DGT Pivots", "Only DGT Pivots", true)
//New
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Pivot Points High Low - build-in, slight presentation changes
group_tools = 'Tool Add-Ons'
group_indicators = 'Indicator Add-Ons'
tooltip_pvt = 'The Pivot Points High Low indicator aims to predict and determine price changes and potential reversals in the market'
addons = input.bool(true, '|----------|  Add-Ons On/Off  |----------|', group='Add-Ons')
msmHOffset = input.int(-23, '  Offset : Horizontal', inline='MSM', group=group_tools)
msmVOffset = input.int(0, 'Vertical', inline='MSM', group=group_tools) / 10
atrLength = input.int(14 , '  ATR : Length', inline='ATR', group=group_tools)
atrRange = input.float(2. , 'Mult', step=.1, inline='ATR', group=group_tools)
prmHOffset = input.int(-13, '  Offset : Horizontal', inline='PRM', group=group_tools) * ta.change(time)
prmVOffset = input.int(-7, 'Vertical', inline='PRM', group=group_tools) / 10
//isLabel = input.bool(true, 'Statistical Panel', inline='STAT', group=group_tools, tooltip=tooltip_panel)
//pLabel = input.int(0 , '', inline='STAT', group=group_tools)
i_textSize = input.string('Small', '', options=['Tiny', 'Small', 'Normal', 'Large'], inline='STAT', group=group_tools)
statPos = input.string('Top Right', '', options=['Top Left', 'Top Center', 'Top Right', 'Middle Right', 'Bottom Left', 'Bottom Center'], inline='STAT', group=group_tools)
dispPVT = input.bool(true , 'Pivot Points High Low  ------------------|', group=group_indicators, tooltip=tooltip_pvt)
pvtLength = input.int(20, "  Pivot Points High Low : Left/Right Length", minval=1, group=group_indicators)
pvtPrice = input(true, "Pivot Points High Low : Display Pivot High/Low Price", group=group_indicators)
pvtChange = input(true, "Pivot Points High Low : Display Pivot High/Low Price Change", group=group_indicators)
pvtVolume = input(true, "Pivot Points High Low : Display Cumulative Volume", group=group_indicators)
pvtText = input.string('Small', "  Pivot Points High Low : Text Size", options=['Tiny', 'Small', 'Normal'], group=group_indicators)
pvtTextSize = pvtText == 'Small' ? size.small : pvtText == 'Normal' ? size.normal : size.tiny
vwcbLen = input.int(21 , '  VWCB : Volume MA Length', minval=1, group=group_indicators)
vwcbUpper = input.float(1.618, '  VWCB : Upper Theshold', minval=0.1, step=.1, group=group_indicators)
vwcbLower = input.float(.618 , '  VWCB : Lower Theshold', minval=0.1, step=.1, group=group_indicators)
tooltip_vwap = 'Volume Weighted Average Price (VWAP) is a technical analysis tool used to measure the average price weighted by volume. VWAP is typically used with intraday charts as a way to determine the general direction of intraday prices. It\'s similar to a moving average in that when price is above VWAP, prices are rising and when price is below VWAP, prices are falling. VWAP is primarily used by technical analysts to identify market trend'
vwapPlot = input.bool(true, 'Volume Weighted Average Price (VWAP)  -------|', group=group_indicators, tooltip=tooltip_vwap)
//hideonDWM = input.bool(false, title='⮩ VWAP : Hide VWAP on 1D or Above', group=group_indicators)
//var anchor = input.string(defval='Session', title='  ⮩ VWAP : Anchor Period', options=['Session', 'Week', 'Month', 'Quarter', 'Year', 'Decade', 'Century'], group=group_indicators)
src = input.source(title='  VWAP : Source', defval=hlc3, group=group_indicators)
offset = input.int(0, title='  VWAP : Offset', group=group_indicators)
pll = input.int(987, 'Indicator and Historical Pivots', group='Ploting Length')
pvtHigh = ta.pivothigh(pvtLength, pvtLength)
pvtLow = ta.pivotlow (pvtLength, pvtLength)
proceed = not na(pvtHigh) or not na(pvtLow)
//pvtLength = input.int(20, "  Pivot Points High Low : Left/Right Length", minval=1, group=group_indicators)
pvtLengthTemp = 1
pvtHighTemp = ta.pivothigh(pvtLengthTemp, pvtLengthTemp)
pvtLowTemp = ta.pivotlow (pvtLengthTemp, pvtLengthTemp)
proceedTemp = not na(pvtHighTemp) or not na(pvtLowTemp)
var x1 = 0
var x2 = 0
var x2Temp = 0
var pvtHigh1 = 0.
var pvtLow1 = 0.
var pvtHigh1Temp = 0.
var pvtLow1Temp = 0.
//var pvtLast = ''
if proceed
x1 := x2
x2 := bar_index
if proceedTemp
x2Temp := bar_index
profileLength = x2 - x1
profileLengthTemp = x2Temp - pvtLengthTemp - x2 + pvtLength
//------------------------------------------------------------------------------
//f_get Tradevolume Erro
//------------------------------------------------------------------------------
// line/label/alert functions
f_drawLineX(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) =>
var id = line.new(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width)
if _y1 > 0 and _y2 > 0
line.set_xy1(id, _x1, _y1)
line.set_xy2(id, _x2, _y2)
line.set_color(id, _color)
else
line.set_xy1(id, _x1, close)
line.set_xy2(id, _x2, close)
line.set_color(id, #ffffff00)
f_drawOnlyLabelX(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) =>
label.new(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip)
f_drawLabelX(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) =>
var id = label.new(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip)
label.set_text(id, _text)
label.set_tooltip(id, _tooltip)
if _y > 0
label.set_xy(id, _x, _y)
label.set_textcolor(id, _textcolor)
else
label.set_xy(id, _x, close)
label.set_textcolor(id, #00000000)
f_crossingLevelX(_price, _level) =>
(_level > _price and _level < _price[1]) or (_level < _price and _level > _price[1])
f_processPivotLevelX(_show, _x1, _y, _x2, _c, _s, _w, _lb, pivot, _levels, _pos) =>
if _show
f_drawLineX(_x1, _y, _x2, _y, xloc.bar_time, extend.none, _c, _s, _w)
if _levels != 'None' and _lb != ''
f_drawLabelX(_pos == 'Last Bar' ? timenow : _x2, _y, (_levels == 'Levels' ? _lb : _lb + ' (' + str.tostring(_y, format.mintick) + ')') + (_pos == 'Last Bar' ? '\n\n' : ''), xloc.bar_time, yloc.price, #00000000, label.style_label_left, _c, size.normal, text.align_left, pivot + ' ' + _lb + ' (' + str.tostring(_y, format.mintick) + ')')
if f_crossingLevelX(close, _y) and _show
alert(pivot + ' (PVTvX) : ' + syminfo.ticker + ' crossing ' + pivot + ' level ' + _lb + ' level, price ' + str.tostring(_y, format.mintick))
f_getStyle(_style) =>
_style == 'Solid' ? line.style_solid : _style == 'Dotted' ? line.style_dotted : line.style_dashed
f_getTradedVolume(_len, _calc, _offset) =>
if _calc
vol = 0.
for x = 0 to _len - 1
vol += volume[_offset + x]
vol
//f_get tradevolume erro end
//------------------------------------------------------------------------------
// Volume Weighted Colored Bars by Kıvanç ÖZBİLGİÇ
nzVolume = nz(volume)
volMA = ta.sma(nzVolume, vwcbLen)
B = nzVolume * (close - low) / (high - low)
S = nzVolume * (high - close) / (high - low)
//------------------------------------------------------------------------------
// Pivot Points High Low
var label tempHigh = na
var label tempLow = na
//pvtLength = input.int(20, "  Pivot Points High Low : Left/Right Length", minval=1, group=group_indicators)
//dispPVT = input.bool(true , 'Pivot Points High Low  ------------------|', group=group_indicators, tooltip=tooltip_pvt)
if addons and dispPVT
if not na(pvtHigh)
tradedVolume = f_getTradedVolume(profileLength, proceed, pvtLength)
f_drawOnlyLabelX(bar_index[pvtLength], pvtHigh, (pvtPrice ? str.tostring(pvtHigh, format.mintick) : '') + (pvtChange ? (pvtPrice ? ' ↑ %' : '↑ %') + str.tostring((pvtHigh - pvtLow1) * 100 / pvtLow1 , '#.##') : '') + (pvtVolume and nzVolume ? (pvtPrice or pvtChange ? '\n' : '') + str.tostring(tradedVolume, format.volume) : ''), xloc.bar_index, yloc.price, chart.fg_color, label.style_label_down, chart.bg_color, (not pvtPrice and not pvtChange and not pvtVolume ? size.tiny : pvtTextSize), text.align_center, 'Pivot High : ' + str.tostring(pvtHigh, format.mintick) + '\n -Price Change : ↑ %' + str.tostring((pvtHigh - pvtLow1) * 100 / pvtLow1 , '#.##') + (nzVolume ? '\n -Traded Volume : ' + str.tostring(tradedVolume, format.volume) + ' (' + str.tostring(profileLength - 1) + ' bars)\n *Average Volume/Bar : ' + str.tostring(tradedVolume / (profileLength - 1), format.volume) : '') + '\n\nNumber of bars : ' + str.tostring(profileLength) )
pvtHigh1 := pvtHigh
//pvtLast := 'H'
label.delete(tempHigh[1])
if x2 - pvtLength > x2Temp - pvtLengthTemp
label.delete(tempLow[1])
if not na(pvtLow)
tradedVolume = f_getTradedVolume(profileLength, proceed, pvtLength)
f_drawOnlyLabelX(bar_index[pvtLength], pvtLow , (pvtPrice ? str.tostring(pvtLow , format.mintick) : '') + (pvtChange ? (pvtPrice ? ' ↓ %' : '↓ %') + str.tostring((pvtHigh1 - pvtLow) * 100 / pvtHigh1, '#.##') : '') + (pvtVolume and nzVolume ? (pvtPrice or pvtChange ? '\n' : '') + str.tostring(tradedVolume, format.volume) : ''), xloc.bar_index, yloc.price, chart.fg_color, label.style_label_up , chart.bg_color, (not pvtPrice and not pvtChange and not pvtVolume ? size.tiny : pvtTextSize), text.align_center, 'Pivot Low : ' + str.tostring(pvtLow , format.mintick) + '\n -Price Change : ↓ %' + str.tostring((pvtHigh1 - pvtLow) * 100 / pvtHigh1, '#.##') + (nzVolume ? '\n -Traded Volume : ' + str.tostring(tradedVolume, format.volume) + ' (' + str.tostring(profileLength - 1) + ' bars)\n *Average Volume/Bar : ' + str.tostring(tradedVolume / (profileLength - 1), format.volume) : '') + '\n\nNumber of bars : ' + str.tostring(profileLength) )
pvtLow1 := pvtLow
//pvtLast := 'L'
label.delete(tempLow[1])
if x2 - pvtLength > x2Temp - pvtLengthTemp// ???
label.delete(tempHigh[1])
if not na(pvtHighTemp) //and pvtLast == 'L'
if pvtHighTemp > pvtHigh1Temp// or pvtHighTemp > pvtHigh1
label.delete(tempHigh[1])
tradedVolume = f_getTradedVolume(profileLengthTemp, proceedTemp, pvtLengthTemp)
tempHigh := label.new(bar_index[pvtLengthTemp], pvtHighTemp, '* ' + (pvtPrice ? str.tostring(pvtHighTemp, format.mintick) : '') + (pvtChange ? (pvtPrice ? ' ↑ %' : '↑ %') + str.tostring((pvtHighTemp - pvtLow1) * 100 / pvtLow1 , '#.##') : '') + (pvtVolume and nzVolume ? (pvtPrice or pvtChange ? '\n' : '') + str.tostring(tradedVolume, format.volume) : ''), xloc.bar_index, yloc.price, #284aa9, label.style_label_down, color.white, (not pvtPrice and not pvtChange and not pvtVolume ? size.tiny : pvtTextSize), text.align_center, 'Temporary Pivot High : ' + str.tostring(pvtHighTemp, format.mintick) + '\n -Price Change : ↑ %' + str.tostring((pvtHighTemp - pvtLow1) * 100 / pvtLow1 , '#.##') + (nzVolume ? '\n -Traded Volume : ' + str.tostring(tradedVolume, format.volume) + ' (' + str.tostring(profileLengthTemp - 1) + ' bars)\n *Average Volume/Bar : ' + str.tostring(tradedVolume / (profileLengthTemp - 1), format.volume) : '') + '\n\nNumber of bars\n since last confirmed Pivot High/Low : ' + str.tostring(profileLengthTemp) + '\n\nWarning : subject to repaint, not a confirmed Pivot Level or Signal' )
pvtHigh1Temp := pvtHighTemp
if high > pvtHigh1Temp
label.delete(tempHigh[1])
if not na(pvtLowTemp) //and pvtLast == 'H'
if pvtLowTemp < pvtLow1Temp// or pvtLowTemp < pvtLow1
tradedVolume = f_getTradedVolume(profileLengthTemp, proceedTemp, pvtLengthTemp)
label.delete(tempLow[1])
tempLow := label.new(bar_index[pvtLengthTemp], pvtLowTemp, '* ' + (pvtPrice ? str.tostring(pvtLowTemp, format.mintick) : '') + (pvtChange ? (pvtPrice ? ' ↓ %' : '↓ %') + str.tostring((pvtHigh1 - pvtLowTemp) * 100 / pvtLowTemp , '#.##') : '') + (pvtVolume and nzVolume ? (pvtPrice or pvtChange ? '\n' : '') + str.tostring(tradedVolume, format.volume) : ''), xloc.bar_index, yloc.price, #284aa9, label.style_label_up, color.white, (not pvtPrice and not pvtChange and not pvtVolume ? size.tiny : pvtTextSize), text.align_center, 'Temporary Pivot Low : ' + str.tostring(pvtLowTemp, format.mintick) + '\n -Price Change : ↓ %' + str.tostring((pvtHigh1 - pvtLowTemp) * 100 / pvtHigh1 , '#.##') + (nzVolume ? '\n -Traded Volume : ' + str.tostring(tradedVolume, format.volume) + ' (' + str.tostring(profileLengthTemp - 1) + ' bars)\n *Average Volume/Bar : ' + str.tostring(tradedVolume / (profileLengthTemp - 1), format.volume) : '') + '\n\nNumber of bars\n since last confirmed Pivot High/Low : ' + str.tostring(profileLengthTemp) + '\n\nWarning : subject to repaint, not a confirmed Pivot Level or Signal')
pvtLow1Temp := pvtLowTemp
if low < pvtLow1Temp
label.delete(tempLow[1])
//*******Start Buying Selling Volume v3 ceevee12312
// Inputs
onlyIntraday = input.bool(true, title='Only show intraday', tooltip='Checking this will make the table disappear on timeframes >= 1D')
showYesterday = input.bool(false, title='Show yesterday\'s volume')
showAvg = input.bool(false, title='Show average')
avgPeriod = input.int(30, title='Average period', minval=0, tooltip='Number of days to consider for average volume')
textColor = input.color(color.white, title='Text Color')
backColor = input.color(color.black, title='Table Color')
//colour customization
BVol = input(title=' BVol Text color', defval=#177245)
//BVol = input(title=' BVol Text color', defval=#ecf018)
SVol = input(title=' SVol Text color', defval=#8B0000)
//SVol = input(title=' SVol Text color', defval=#d6d6d2)
TVol = input(title=' TVol Text color', defval=#FF8C00)
//TVol = input(title=' TVol Text color', defval=#e29aed)
// BUYING VOLUME AND SELLING VOLUME //
BV = high == low ? 0 : volume * (close - low) / (high - low)
SV = high == low ? 0 : volume * (high - close) / (high - low)
DayBuyVolumePercent = 100 * BV / (BV + SV)
DaySellVolumePercent = 100 * SV / (BV + SV)
vi = input(false, title='Volume Index')
vol = volume > 0 ? volume : 1
TP = BV + SV
// RAW Pressure Volume Calculations
BPV = BV / TP * vol
SPV = SV / TP * vol
TPV = BPV + SPV
// Karthik Marar's Pressure Volume Normalized Version (XeL-MOD.)
VN = vol / ta.ema(vol, 20)
BPN = BV / ta.ema(BV, 20) * VN * 100
SPN = SV / ta.ema(SV, 20) * VN * 100
TPN = BPN + SPN
// Conditional Selectors for RAW/Norm
BPc1 = BPV > SPV ? BPV : -math.abs(BPV)
BPc2 = BPN > SPN ? BPN : -math.abs(BPN)
SPc1 = SPV > BPV ? SPV : -math.abs(SPV)
SPc2 = SPN > BPN ? SPN : -math.abs(SPN)
BPcon = vi ? BPc2 : BPc1
SPcon = vi ? SPc2 : SPc1
////////////////////////////////////////////////////////////
// Functions
nocolor=color.new(color.white, transp=100)
f_rows(I) =>
O = true ? 1 : 0
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Calculations
rowNum = 1 + f_rows(showYesterday) + f_rows(showAvg)
var table dvDisplay = table.new(position=position.top_right, columns=1, rows=rowNum)
dVol = request.security(syminfo.tickerid, timeframe='D', expression=str.tostring(volume, format.volume))
ydVol = request.security(syminfo.tickerid, timeframe='D', expression=str.tostring(volume[1], format.volume))
avgVol = request.security(syminfo.tickerid, timeframe='D', expression=str.tostring(ta.sma(volume, avgPeriod)[1], format.volume))
// Calculations
i_startTime = input.time(defval=timestamp('01 DEC 2022 03:45 +0000'), title='Start Time')
i_endTime = input.time(defval=timestamp('10 Dec 2022 09:45 +0000'), title='End Time')
timeCond = time >= i_startTime and time < i_endTime
isPeriod = timeCond
var buyvol = 0.0
var sellvol = 0.0
var candle = 0
if isPeriod
buyvol += math.abs(nz(BPcon, 0))
sellvol += math.abs(nz(SPcon, 0))
candle += 1
candle
string i_positionr = position.top_center
SwingBuyVolumePercent=100*buyvol/(buyvol+sellvol)
SwingSellVolumePercent=100*sellvol/(buyvol+sellvol)
//string i_positionr = position.top_right
var tblr = table.new(i_positionr, 19, 141, frame_color=#151715, frame_width=1, border_width=2, border_color=color.new(color.white, 100))
if barstate.islast
table.cell(tblr, 0, 1, 'Buy Volume', text_halign=text.align_center, bgcolor=color.green, text_color=color.white, text_size=size.small)
table.cell(tblr, 1, 1, 'Sell Volume', text_halign=text.align_center, bgcolor=color.red, text_color=color.white, text_size=size.small)
table.cell(tblr, 0, 2, str.tostring(buyvol, format.volume), text_halign=text.align_center, bgcolor=color.green, text_color=color.white, text_size=size.small)
table.cell(tblr, 1, 2, str.tostring(sellvol, format.volume), text_halign=text.align_center, bgcolor=color.red, text_color=color.white, text_size=size.small)
//*******End Buying Selling Volume v3 ceevee12312
//Placing two tables
string i_positioner = position.top_right
var twotable = table.new(i_positionr, 48, 159,frame_color=#151715, frame_width=0, border_width=2, border_color=color.new(color.white, 100))
//var table twotable = table.new(position.bottom_center,columns=1, rows=2)
if barstate.islast
// table.cell(twotable, 0, 10, 'BVol→ ' + f_get_volume_string(BuyVol) + '(' + f_get_volume_string(BuyVolumePercent) + '%' + ')', text_color=BVol, bgcolor=color.new(#00FF00, 100))
//table.cell(twotable, 0, 20, 'ydVol→ ' + f_get_volume_string(BuyVol) + '(' + f_get_volume_string(BuyVolumePercent) + '%' + ')', text_color=BVol, bgcolor=color.new(#00FF00, 100))
table.cell(twotable, 1, 40, 'ToDay Vol: ' + dVol, text_halign=text.align_center, bgcolor=color.black, text_color=color.white)
table.cell(twotable, 1, 50, 'Yesterday: ' + ydVol, text_halign=text.align_center, bgcolor=color.black, text_color=color.white)
table.cell(twotable, 1, 60, 'Avg Vol: ' + avgVol, text_halign=text.align_center, bgcolor=color.black, text_color=color.white)
table.cell(twotable, 0, 70, "SwingBuy Vol", text_halign=text.align_center, bgcolor=color.rgb(7, 165, 42), text_color=color.white, text_size=size.small)
//table.cell(twotable, Here value 30 moves Buy Vol text to x axis 30 pixels, creating blank space.When it is 0 then x axis start from no space)
//Say if Buy Vol is 0, 15 then 0 column and 15 rows down. So text won't struck in top row.
table.cell(twotable, 0, 71, str.tostring(buyvol, format.volume), text_halign=text.align_center, bgcolor=color.rgb(7, 165, 42), text_color=color.white, text_size=size.small)
// 0, 71 means 0 th column and 71 row
table.cell(twotable, 1, 70, "SwingSell Vol", text_halign=text.align_center, bgcolor=color.red, text_color=color.white, text_size=size.small)
table.cell(twotable, 1, 71, str.tostring(sellvol, format.volume), text_halign=text.align_center, bgcolor=color.red, text_color=color.white, text_size=size.small)
// table.cell(twotable, 0, 72, 'DBuy Perc', text_halign = text.align_center, bgcolor = color.black, text_color = color.white, text_size = size.small)
//table.cell(twotable, 0, 73, str.tostring(DayBuyVolumePercent,format.volume ) , text_halign = text.align_center, bgcolor = color.black, text_color = color.white, text_size = size.small)
//table.cell(twotable, 2, 72, 'DSell Perc', text_halign = text.align_center, bgcolor = color.black, text_color = color.white, text_size = size.small)
//table.cell(twotable, 2, 73, str.tostring(DaySellVolumePercent,format.volume ) , text_halign = text.align_center, bgcolor = color.black, text_color = color.white, text_size = size.small)
//Display Swing Percentges:
table.cell(twotable, 1, 74, 'SwingBuy Perc', text_halign = text.align_center, bgcolor = color.black, text_color = color.white, text_size = size.small)
table.cell(twotable, 2, 74, str.tostring(SwingBuyVolumePercent,format.volume ) , text_halign = text.align_center, bgcolor = color.black, text_color = color.white, text_size = size.small)
table.cell(twotable, 1, 75, 'SwingSell Perc', text_halign = text.align_center, bgcolor = color.black, text_color = color.white, text_size = size.small)
table.cell(twotable, 2, 75, str.tostring(SwingSellVolumePercent,format.volume ) , text_halign = text.align_center, bgcolor = color.black, text_color = color.white, text_size = size.small)
//***********End Daily Volume
//------------------------------------------------------------------------------
//End
`like so`

Related

draw line and color the area above in indicator in Trading View with Pine Script

I want to draw a horizontal line at fixed value 30.000 and color the area above in light green in the DMI Indicator. How is this possible?
Thanks
//#version=5
indicator(title="Directional Movement Index", shorttitle="DMI", format=format.price, precision=4, timeframe="", timeframe_gaps=true)
lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50)
len = input.int(14, minval=1, title="DI Length")
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / trur)
minus = fixnan(100 * ta.rma(minusDM, len) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig)
plot(adx, color=#F50057, title="ADX")
plot(plus, color=#2962FF, title="+DI")
plot(minus, color=#FF6D00, title="-DI")
You can use the hline and fill functions
https://www.tradingview.com/pine-script-reference/v5/#fun_fill
https://www.tradingview.com/pine-script-reference/v5/#fun_hline
hline(30, title = "30 Line", color=color.blue, linestyle=hline.style_solid, linewidth=2)
fill(30, 100, color = color.new(color.green, 90))

increasing the displayed indicator value by a percentage

i'm trying to find a way to make a indicator like rsi or stochastic but be able to adjust the output by a percentage. For example RSI signal that is increased by a percentage of what i would output by default. So it normally show 70 but is increased to 80 e.g.
Is there a way to do this? I've been scrolling through the manual for hours but couldnt find it.
Any help is appreciated
//#version=4
study(title="RSI", shorttitle="RSI", format=format.price, precision=2, resolution="")
len = input(14, minval=1, title="Length")
src = input(close, "Source", type = input.source)
rsiValue = rsi(src, len)
i_perc = input(10, title = "Percentage", type = input.float) * 0.01
up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsi_increase_conditon = rsiValue >= rsiValue[1] * (1 + i_perc)
rsi_decrease_conditon = rsiValue <= rsiValue[1] * (1 - i_perc)
plot(rsi, "RSI", color=color.white)
hline(70, "OBBand", color=color.red, linestyle=hline.style_solid)
hline(20, "XOSBand", color=color.blue, linestyle=hline.style_solid)
hline(50, "Mid", color=color.gray, linestyle=hline.style_solid)
hline(80, "XOBBand", color=color.blue, linestyle=hline.style_solid)
hline(30, "OSBand", color=color.red, linestyle=hline.style_solid)
i_perc = input(10, title = "Percentage", type = input.float) * 0.01
...
rsi_increase_conditon = rsiValue >= rsiValue[1] * (1 + i_perc)
rsi_decrease_conditon = rsiValue <= rsiValue[1] * (1 - i_perc)
plotshape(rsi_increase_conditon and not rsi_increase_conditon[1], title = "RSI Increase %", style = shape.triangleup, location = location.belowbar, size = size.normal)
plotshape(rsi_decrease_conditon and not rsi_decrease_conditon[1], title = "RSI Decrease %", style = shape.triangledown, location = location.abovebar, size = size.normal)

Setting A Multiple Ticker Alert On Barstate.islast in Pine Script

Good Day! I am trying to emulate a script I created that provides alerts on multiple tickers for the various conditions I have set up. This works as it should and have been happy with it. Although it is not pretty, it is the first section of code posted below. The end of the code is where I input the action_alerts for the multiple tickers.
The new code I am trying to create deals with a label that shows if the relative strength reach a new high over a 28 day span. I am looking to create an alert of that new high on the same tickers as the first code to tell me once that new high is reached. That is the second code below. I also added a picture showing that label.new is a tiny green circle every time the new high is reached.
Any help with this will be greatly appreciated!
First Code (working)
indicator('Daily Screener #1', overlay=true)
//Backtest start date with inputs
startDate = input.int(title='Start Date', defval=1, minval=1, maxval=31)
startMonth = input.int(title='Start Month', defval=5, minval=1, maxval=12)
startYear = input.int(title='Start Year', defval=2021, minval=2000, maxval=2100)
//See if the bar's time happened on/after start date
afterStartDate = time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)
//Inputs
ts_bars = input.int(10, minval=1, title='Tenkan-Sen Bars')
ks_bars = input.int(20, minval=1, title='Kijun-Sen Bars')
ssb_bars = input.int(50, minval=1, title='Senkou-Span B Bars')
sma_bars = input.int(50, minval=1, title='SMA Bars')
sec_sma_bars = input.int(5, minval=1, title='Second SMA Bars')
cs_offset = input.int(20, minval=1, title='Chikou-Span Offset')
ss_offset = input.int(20, minval=1, title='Senkou-Span Offset')
long_entry = input(true, title='Long Entry')
short_entry = input(true, title='Short Entry')
wait_for_cloud = input(true, title='Wait for Cloud Confirmation')
//values
avgvalue = input(defval=20, title='Avg Vol Period')
avgvolfac = input(defval=2, title='Rvol Factor')
maxvol = input(defval=5, title='Max Vol')
minvol = input(defval=10000, title='Required Min Vol')
color bo = color.white
color suy = color.black
avgvola = ta.sma(volume, avgvalue)
volcheck = volume > avgvola * avgvolfac and volume > minvol and volume > volume[1] * .75
maxvolcheck = volume > avgvola * maxvol and volume > minvol and volume > volume[1] * .75
// RSI Inputs
use_rsi_tp = input(false, title='Use RSI for Take Profit')
use_rsi_entry = input(false, title='Use RSI for Entry')
seq_rsi = input(defval=1, title='Alert TP after X Sequential bars past RSI')
rsi_period = input(defval=7, title='RSI Period')
overbought_rsi = input(defval=80, title='RSI Overbought Level')
oversold_rsi = input(defval=20, title='RSI Oversold Level')
middle(len) =>
ta.sma(close, len)
//Stoch RSI Inputs
smoothK = input.int(3, 'K', minval=1)
smoothD = input.int(3, 'D', minval=1)
lengthRSI = input.int(14, 'RSI Length', minval=1)
lengthStoch = input.int(14, 'Stochastic Length', minval=1)
src = input(close, title='RSI Source')
//Stoch RSI Components
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
//MACD Inputs
fast_length = input(title='Fast Length', defval=12)
slow_length = input(title='Slow Length', defval=26)
src2 = input(title='Source', defval=close)
signal_length = input.int(title='Signal Smoothing', minval=1, maxval=50, defval=9)
sma_source = input(title='Simple MA (Oscillator)', defval=false)
sma_signal = input(title='Simple MA (Signal Line)', defval=false)
//MACD Components
fast_ma = sma_source ? ta.sma(src2, fast_length) : ta.ema(src2, fast_length)
slow_ma = sma_source ? ta.sma(src2, slow_length) : ta.ema(src2, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
// Ichimoku Components
tenkan = middle(ts_bars)
kijun = middle(ks_bars)
mid_sma = middle(sma_bars)
sec_sma = middle(sec_sma_bars)
senkouA = math.avg(tenkan, kijun)
senkouB = middle(ssb_bars)
// Plot Ichimoku Kinko Hyo
plot(tenkan, color=color.new(#0496ff, 0), title='Tenkan-Sen')
plot(kijun, color=color.new(#991515, 0), title='Kijun-Sen')
plot(mid_sma, color=color.new(color.white, 0), title='50 SMA')
plot(sec_sma, color=color.new(color.orange, 0), title='5 SMA')
plot(close, offset=-cs_offset + 1, color=color.new(color.gray, 0), title='Chikou-Span')
sa = plot(senkouA, offset=ss_offset - 1, color=color.new(color.green, 0), title='Senkou-Span A')
sb = plot(senkouB, offset=ss_offset - 1, color=color.new(color.red, 0), title='Senkou-Span B')
fill(sa, sb, color=senkouA > senkouB ? color.green : color.red, title='Cloud color', transp=90)
ss_high = math.max(senkouA[ss_offset - 1], senkouB[ss_offset - 1])
ss_low = math.min(senkouA[ss_offset - 1], senkouB[ss_offset - 1])
// Entry/Exit Signals
tk_cross_bull = tenkan > kijun
tk_cross_bear = tenkan < kijun
cs_cross_bull = ta.mom(close, cs_offset - 1) > 0
cs_cross_bear = ta.mom(close, cs_offset - 1) < 0
price_above_kumo = close > ss_high
price_below_kumo = close < ss_low
price_between_kumo = close < ss_high and close > ss_low
senkou_green = senkouA > senkouB ? true : false
rsi_value = ta.rsi(close, rsi_period)
trend_midentry_T = close < tenkan or open < tenkan
trend_midentry_K = close > kijun or open > kijun
pp_t = close > tenkan or open > tenkan
pp_k = close < kijun or open < kijun
open_trend_reentry_T = open < tenkan
open_trend_reentry_K = open > kijun
close_trend_reentry_T = close < tenkan
close_trend_reentry_K = close > kijun
kumo_open_trend_reentry_T = open > tenkan
kumo_open_trend_reentry_K = open < kijun
kumo_close_trend_reentry_T = close > tenkan
kumo_close_trend_reentry_K = close < kijun
rsi_positive = k > d
rsi_negative = d > k
rsi_cross = ta.crossover(k, d)
macd_positive = macd > signal and macd > 0
macd_exit = ta.crossover(signal, macd)
macd_entry = ta.crossover(macd, signal)
hist_positive = hist >= 0
higherOrSameClose = close >= close[1]
two_day_higherOrSameClose = close >= close[1] and close[1] >= close[2]
five_day_lowerOrSameClose = close < close[7]
macd_greater_zero = fast_ma > 0
first_exit = ta.crossover(tenkan, close)
avgVol = ta.ema(volume, 50)
support = ta.lowest(close, 25)
five_ten_cross = ta.crossunder(sec_sma, tenkan)
bullish = tk_cross_bull and cs_cross_bull and price_above_kumo
bearish = tk_cross_bear and cs_cross_bear and price_below_kumo
if wait_for_cloud
bullish := bullish and senkou_green
bearish := bearish and not senkou_green
bearish
if use_rsi_entry
bullish := bullish and rsi_value < overbought_rsi
bearish := bearish and rsi_value > oversold_rsi
bearish
in_long = false
in_long := in_long[1]
open_long = bullish and long_entry and not in_long
open_short = bearish and short_entry and in_long
ish_long_entry = tk_cross_bull and cs_cross_bull and price_below_kumo
ish_2nd_long_entry = price_above_kumo and trend_midentry_T and trend_midentry_K
ish_sell_in_trend = price_above_kumo and ta.crossunder(tenkan, kijun)
ish_buy_in_trend = price_above_kumo and ta.crossover(tenkan, kijun) and higherOrSameClose
early_exit_bear = price_below_kumo and ta.crossunder(tenkan, kijun) or first_exit and price_below_kumo
best_entry = rsi_positive and macd_positive and ish_long_entry or ish_buy_in_trend and rsi_positive and macd_positive
best_exit = macd_exit and rsi_negative and ish_2nd_long_entry or first_exit and price_above_kumo
trend_reentry = price_above_kumo and (open_trend_reentry_T or close_trend_reentry_T) and (open_trend_reentry_K or close_trend_reentry_K) and rsi_positive and higherOrSameClose and macd_entry
in_kumo_trend_reentry = price_between_kumo and (kumo_open_trend_reentry_T or kumo_close_trend_reentry_T) and (kumo_open_trend_reentry_K or kumo_close_trend_reentry_K) and rsi_positive and higherOrSameClose and macd_entry
better_entry = price_above_kumo and rsi_cross and macd_greater_zero and higherOrSameClose
in_kumo_trend_reentry1 = price_between_kumo and kumo_open_trend_reentry_T and kumo_open_trend_reentry_K and rsi_positive and higherOrSameClose and macd_entry
in_kumo_trend_reentry2 = price_between_kumo and kumo_close_trend_reentry_T and kumo_close_trend_reentry_K and rsi_positive and higherOrSameClose and macd_entry
better_entry_pos = price_above_kumo and rsi_cross and macd_positive and higherOrSameClose
pre_party = price_below_kumo and (trend_midentry_T and trend_midentry_K or pp_t and pp_k) and two_day_higherOrSameClose and not five_day_lowerOrSameClose and cs_cross_bull
test = cs_cross_bull and price_below_kumo and two_day_higherOrSameClose
trend_breakout_close = not price_below_kumo and ta.crossover(close, tenkan) and rsi_positive and close > open[3]
quick_test = not price_above_kumo and close > tenkan and rsi_positive and higherOrSameClose and close[1] > close[2] and close > close[1] * 1.05
//reversal = price_below_kumo and close > close[1] and close[1] > close[2] and close > support and macd_entry
sell_off = open_short or ish_sell_in_trend
buy_up = open_long or (trend_breakout_close and ish_buy_in_trend) or (better_entry_pos and trend_breakout_close) or (trend_reentry and trend_breakout_close) or (trend_reentry and better_entry_pos) or (in_kumo_trend_reentry and trend_breakout_close) or (pre_party and test) or (quick_test and test)
sell_all = sell_off and volcheck
buy_all = buy_up and volcheck
voliskey = higherOrSameClose and maxvolcheck
all_volcheck = higherOrSameClose and volcheck and open>mid_sma
fifty_bo = trend_breakout_close and volcheck and ta.crossover(close,mid_sma)
show_me = ((ta.crossover(close,tenkan) and ta.crossover(close,kijun)) or (ta.crossover(close,sec_sma) and ta.crossover(close,tenkan))) and close<mid_sma and sec_sma>=tenkan*.99 and (volume > avgvola*.5)
bull_trend = price_above_kumo and close > sec_sma and tenkan>sec_sma and sec_sma>kijun and close>close[1] and close[1] >close[2]
chikcross = ta.crossover(close,mid_sma[20]) and open>mid_sma
ten_chikcross = ta.crossover(close,tenkan[20]) and volume > (avgvola * .75)
upside = low<low[1] and close>close[1] and ((close-low)/(high-low))>.55 and volume>avgvola*1.33 and sec_sma>tenkan
grab_it = voliskey
dump_it = sell_all
ybbo = (trend_breakout_close and better_entry_pos)
olretrace = (open_long and ish_buy_in_trend)
hvretrace = (volcheck and ish_buy_in_trend)
earbuy = quick_test
below_earbuy = (quick_test and test)
sbreak= fifty_bo
ebreak = (trend_breakout_close and quick_test)
olyb = better_entry_pos
if open_long
in_long := true
in_long
if open_short
in_long := false
in_long
rsi_count = 0
arm_tp = false
if use_rsi_tp
rsi_count := rsi_count[1]
if in_long and rsi_value > overbought_rsi or not in_long and rsi_value < oversold_rsi
rsi_count += 1
rsi_count
else
rsi_count := 0
rsi_count
if rsi_count >= seq_rsi
arm_tp := true
arm_tp
//Function Definition
action_alert(_ticker) =>
agrab_it = voliskey
adump_it = sell_all
aybbo = better_entry_pos
aearbuy = quick_test
asbreak= fifty_bo
awatch = show_me
[_grab_it, _ybbo, _earbuy, _sbreak, good_vol, _watch, _bull_trend,_ten_chikcross, _upside] = request.security(_ticker, timeframe.period, [ agrab_it, aybbo, aearbuy, asbreak, all_volcheck, awatch, bull_trend,ten_chikcross, upside])
_msg = _ticker + ',' + timeframe.period + ': '
if _grab_it
_msg += 'Big Volume Buy'
alert(_msg, alert.freq_once_per_bar)
if _ybbo
_msg += 'Yellow Buy'
alert(_msg, alert.freq_once_per_bar_close)
if _earbuy
_msg += 'Early Buy'
alert(_msg, alert.freq_once_per_bar_close)
if _sbreak
_msg += 'Super Breakout'
alert(_msg, alert.freq_once_per_bar_close)
if _bull_trend
_msg += 'Trend'
alert(_msg, alert.freq_once_per_bar_close)
if good_vol
_msg += 'Good Vol'
alert(_msg, alert.freq_once_per_bar_close)
if chikcross
_msg += 'Chikou Cross'
alert(_msg, alert.freq_once_per_bar_close)
if _ten_chikcross
_msg += '10 Chikou Cross'
alert(_msg, alert.freq_once_per_bar_close)
if _upside
_msg += 'Upside Reversal'
alert(_msg, alert.freq_once_per_bar_close)
barcolor(sell_all ? bo : na, editable=false)
barcolor(buy_all ? suy : na, editable=false)
barcolor(voliskey ? color.yellow : na, editable=false)
barcolor(all_volcheck ? suy : na, editable=false)
//Alert Plots
plotshape(open_short, text='Open Short', style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.red, 0))
plotshape(better_entry_pos, text='Buy', style=shape.arrowup, location=location.belowbar, color=color.new(#FFC803, 0), textcolor=color.new(#FFC803, 0))
plotshape(bull_trend, text='Trend', style=shape.arrowup, location=location.belowbar, color=color.new(#00BFFF, 0), textcolor=color.new(#00BFFF, 0))
plotshape(quick_test, text='Early Buy', style=shape.arrowup, location=location.belowbar, color=color.new(color.orange, 0), textcolor=color.new(color.orange, 0))
plotshape(chikcross, text='Chikou Cross', style=shape.arrowup, location=location.belowbar, color=color.new(#00FFFF, 0), textcolor=color.new(#00FFFF, 0))
plotshape(voliskey, text= "Big Vol", style=shape.arrowup, location=location.belowbar, color=color.new(color.yellow, 0), textcolor=color.new(color.yellow, 0))
plotshape(fifty_bo, text= "Super Breakot", style=shape.arrowup, location=location.belowbar, color=color.new(color.white, 0), textcolor=color.new(color.white, 0))
plotshape(ybbo, text='Good Buy Breakout', style=shape.arrowup, location=location.belowbar, color=color.new(#66FF00, 0), textcolor=color.new(#66FF00, 0))
plotshape(all_volcheck, text='Good Volume', style=shape.arrowup, location=location.belowbar, color=color.new(color.lime, 0), textcolor=color.new(color.lime, 0))
plotshape(hvretrace, text="Retrace", style=shape.arrowup, location=location.belowbar, color=color.new(color.aqua, 0), textcolor=color.new(color.aqua, 0))
plotshape(ten_chikcross, text='10 Chikou Cross', style=shape.arrowup, location=location.belowbar, color=color.new(#00BFFF, 0), textcolor=color.new(#00BFFF, 0))
plotshape(upside, text='Upside Reversal', style=shape.arrowup, location=location.belowbar, color=color.new(#C3CDE6, 0), textcolor=color.new(#C3CDE6, 0))
//Position Alert
action_alert("AMEX:DRIP")
action_alert("AMEX:DUG")
action_alert("AMEX:EQX")
action_alert("AMEX:ERY")
action_alert("AMEX:NGD")
action_alert("AMEX:TZA")
Second Code (not working)
//#version=5
indicator("Ish's Relative Strength")
length = 20
five_sma=ta.sma(close,5)
var prevRatio = 0.0
//Save each ratio so we can look for RS line new high
var array=array.new_float(0)
// RS - IBD
ThreeMonthRS = 0.4 * (close / close[13])
SixMonthRS = 0.2 * (close / (close[26] * 2))
NineMonthRS = 0.2 * (close / (close[39] * 3))
TwelveMonthRS = 0.2 * (close / (close[52] * 4))
RatingRS = (ThreeMonthRS + SixMonthRS + NineMonthRS + TwelveMonthRS) * 100
rsText = "RS Rating \n" + str.tostring(RatingRS, "0.00")
//Gather Compared Index/Stock
comparedSymbol = input.symbol(title="Benchmark RS Line", defval="QQQ", group="Relative Strength")
comparedClose = request.security(comparedSymbol, timeframe.period, close)
cThreeMonthRS = 0.4 * (comparedClose / comparedClose[13])
cSixMonthRS = 0.2 * (comparedClose / (comparedClose[26] * 2))
cNineMonthRS = 0.2 * (comparedClose / (comparedClose[39] * 3))
cTwelveMonthRS = 0.2 * (comparedClose / (comparedClose[52] * 4))
cRatingRS = (cThreeMonthRS + cSixMonthRS + cNineMonthRS + cTwelveMonthRS) * 100
crsText = "Comp RS \n" + str.tostring(cRatingRS, "0.00")
compratio = "RS Ratio \n" + str.tostring(RatingRS/cRatingRS, "0.00")
compratioNUM = RatingRS/cRatingRS
posslope= (compratioNUM-compratioNUM[2])/2
posfive=five_sma-five_sma[1]
slope=ta.sma(compratioNUM,5)
getin=ta.crossover(compratioNUM,slope) and posslope>0 and posfive>0
//Color of line to show up or down
ColorUp = color.new(color.green,0)
ColorDown = color.new(color.red,0)
linecolor = (posslope>.02 and posfive>.02)? ColorUp: ColorDown
//plot(RatingRS, color=color.new(color.white, 0), title='50 SMA')
//plot(cRatingRS, color=color.new(color.white, 0), title='Test')
plot(compratioNUM, color=linecolor, linewidth=2, title="Got It")
//plot(slope, color=color.new(color.lime,0),title="Please Work")
//plotshape(getin, title="Get In", style=shape.arrowup, location=location.belowbar, color=color.new(#C3CDE6,0), textcolor=color.new(#C3CDE6,0))
//Show high dot based on time
if (barstate.islast)
newHigh=true
for i=0 to 27
if(array.get(array, i)>compratioNUM)
newHigh:=false
break
if (newHigh)
label.new(bar_index, compratioNUM, color=color.new(color.green,40), style=label.style_circle, size=size.tiny)
if (barstate.islast)
newLow=true
for i=0 to 27
if(array.get(array, i)<compratioNUM)
newLow:=false
break
if (newLow)
label.new(bar_index, compratioNUM, color=color.new(color.red, 40), style=label.style_circle, size=size.tiny)
prevRatio:=compratioNUM
array.unshift(array, compratioNUM)
action_alert(_ticker) =>
test= newHigh
[_test] = request.security(_ticker, timeframe.period, [newHigh])
_msg = _ticker + ',' + timeframe.period + ': '
if _test
_msg += 'New High'
alert(_msg, alert.freq_once_per_bar)
//Position Alert
action_alert("AMEX:DRIP")
action_alert("AMEX:DUG")
action_alert("AMEX:EQX")
action_alert("AMEX:ERY")
action_alert("AMEX:NGD")
action_alert("AMEX:TZA")
Green dot showing new high value of relative strength reached over the last 28 days

Max Drawdown in my Table is wrong, not same as in Overview (Tradingview)

Can you help me fix Drawdown in this table ? Is not the same as in Overview (Tradingview)
It shows a few percent difference and cannot figure a solution.
To measure an order’s drawdown, we take the difference between the entry price and worst price. Then multiply with the order’s size and increase the outcome with commission costs.
That price difference is for long orders the distance between the entry price and lowest price while the order was open. For short orders, it’s the distance between the entry price and the highest price during the order.
var balance = strategy.initial_capital
var totalTrades = strategy.closedtrades
var totalWins = strategy.wintrades
var totalLosses = strategy.losstrades
var maxDrawdown = 0.0
var maxBalance = 0.0
var drawdown = 0.0
var winsInRow = 0
var maxWinsInRow = 0
var lossesInRow = 0
var maxLossesInRow = 0
if strategy.wintrades > strategy.wintrades[1]
balance := strategy.initial_capital + strategy.netprofit
// totalWins := totalWins + 1 < not necessary as we're just using strategy.wintrades now
if balance > maxBalance
maxBalance := balance
winsInRow := winsInRow + 1
if winsInRow > maxWinsInRow
maxWinsInRow := winsInRow
lossesInRow := 0 // reset loss counter as we've just taken a win
if strategy.losstrades > strategy.losstrades[1]
balance := strategy.initial_capital + strategy.netprofit
// totalLosses := totalLosses same as above
drawdown := (maxBalance - balance) / maxBalance // I've changed this, but left your original here > (balance / maxBalance) - 1
if drawdown > maxDrawdown // drawdown will now hold, as a decimal, the max % drop from maxBalance
maxDrawdown := drawdown
lossesInRow := lossesInRow + 1
if lossesInRow > maxLossesInRow
maxLossesInRow := lossesInRow
winsInRow := 0 // reset the win counter as we've just taken a loss
var table testTable = table.new(position.bottom_right, 2, 4 , border_width=1, border_color=color.white, frame_color=color.white, frame_width=1)
fillCell(table, column, row, title, value, bgcolor, txtcolor) =>
cellText = title + "\n" + value
table.cell(table, column, row, cellText, bgcolor=bgcolor, text_color=txtcolor)
var bgcolor = color.new(color.blue,50)
green = color.new(color.green,50)
red = color.new(color.red,50)
if barstate.islastconfirmedhistory
dollarReturn = strategy.netprofit
fillCell(testTable, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
fillCell(testTable, 1, 0, "Win Rate:", str.tostring(math.round((strategy.wintrades/strategy.closedtrades)*100,2))+"%", strategy.wintrades/strategy.closedtrades >= 0.5 ? green : red, color.white)
fillCell(testTable, 0, 1, "Starting:", "$" + str.tostring(strategy.initial_capital), bgcolor, color.white)
fillCell(testTable, 1, 1, "Ending:", "$" + str.tostring(math.round(balance, 2)),strategy.netprofit > 0 ? green :red, color.white)
fillCell(testTable, 0, 3, "Wins In Row", str.tostring(maxWinsInRow), maxWinsInRow > maxLossesInRow ? green : red , color.white)
fillCell(testTable, 1, 3, "Losses In Row", str.tostring(maxLossesInRow), maxWinsInRow > maxLossesInRow ? green : red, color.white)
fillCell(testTable, 1, 2, "Max Drawdown", str.tostring(math.round(maxDrawdown * 100, 2))+"%", strategy.netprofit > maxDrawdown ? green : red, color.white)
fillCell(testTable, 0, 2, "Net Profit", str.tostring(math.round(strategy.netprofit/strategy.initial_capital*100,2))+"%", strategy.netprofit/strategy.initial_capital *100 > 0 ? green : red, color.white)```

How do I plot a buy alert on an array anytime a bar reaches 100 upon close of that bar? I am using the "Supertrend Oscillator" in pinescript

I've been at this for hours and I just can't figure it out. I've tried searching all over and watching videos. Here's code to the script I am working with. it's called Supertrend Oscillator by LuxAlgo on tradingview.
atr = ta.atr(osclength) * mult
up = hl2 + atr
dn = hl2 - atr
upper := src[1] < upper[1] ? math.min(up, upper[1]) : up
lower := src[1] > lower[1] ? math.max(dn, lower[1]) : dn
trend := src > upper[1] ? 1 : src < lower[1] ? 0 : trend[1]
Spt = trend * lower + (1 - trend) * upper
//----
ama = 0.
osc = math.max(math.min((src - Spt) / (upper - lower), 1), -1)
alpha = math.pow(osc, 2) / osclength
ama := nz(ama[1] + alpha * (osc - ama[1]), osc)
hist = ta.ema(osc - ama, smooth)
//----
fix_css = osc > 0 ? #0cb51a : #ff1100
var_css = osc > 0 ? array.get(up_col, math.round(osc * 99)) : array.get(dn_col, math.round(osc * -1 * 99))
sig_css = ama > 0 ? #2157f3 : #673ab7
plot(fixed ? osc * 100 : na, 'Main Fixed', fix_css, 1, plot.style_area)
plot(fixed ? na : osc * 100, 'Main Transp', var_css, 1, plot.style_columns, editable=false)
plot(hist * 100, 'Histogram', color.new(#808080, 40), 1, plot.style_area)
plot(ama * 100, 'Signal', sig_css)
//----
a = hline(80)
b = hline(-80)
fill(a, b, color.new(#2157f3, 90))
//----
css = osc > 0 ? #ff1100 : #0cb51a
sig = ta.change(math.sign(osc)) ? osc * -100 : na
plot(show_ln ? sig : na, color=css)
//----
n = bar_index
cross = ta.cross(src, Spt)
x2 = ta.valuewhen(cross, n, 0)
//----
false_buy = ta.valuewhen(ta.crossunder(src, Spt), src, 0) < ta.valuewhen(ta.crossover(src, Spt), src, 0)
false_sell = ta.valuewhen(ta.crossover(src, Spt), src, 0) > ta.valuewhen(ta.crossunder(src, Spt), src, 0)
num = ta.cum(cross and (false_buy or false_sell) ? 1 : 0)
den = ta.cum(cross ? 1 : 0)
per = num / den * 100
//----
if barstate.islast and show_ln
line.delete(line.new(x2, math.sign(osc) * -100, n, osc * 100, color=osc < 0 ? #ff1100 : #0cb51a)[1])
if show_lb
if ta.crossover(src, Spt)
txt = false_sell ? '❌' : '✔️'
label.new(x2,-80,txt,color=#00000000,style=label.style_label_up,textcolor=color.gray,textalign=text.align_center)
if ta.crossunder(src, Spt)
txt = false_buy ? '❌' : '✔️'
label.new(x2,80,txt,color=#00000000,style=label.style_label_down,textcolor=color.gray,textalign=text.align_center)
if barstate.islast and show_per
txt = '❌' + str.tostring(per, '#.##') + '%'
label.delete(label.new(n, osc, txt, color=#00000000, style=label.style_label_left, textcolor=color.gray, textalign=text.align_left)[1])
How do I make it so a "buy" alert displays on the chart anytime a bar closes with an oscillator value reaching 100 or more?