Setting A Multiple Ticker Alert On Barstate.islast in Pine Script - pine-script-v5
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
Related
Pine Script V5 - Not getting expected breakout entry price and entry in expected bar
I have a long entry buy condition where Candle time frame is 15 minutes Alert candle high is below lower band of bollinger bands. entry when next candle crossover the alert candle high This script gives entry oh high breakout + 0.01 but it does not give entry in the exact breakout candle and gives entry when price comes next time on expected entry price i.e. alert candle high + 0.01. Requesting solution to get entry in breakout candle itself and at expected breakout price. //#version=5 strategy("Bands Reversion", overlay=true, calc_on_every_tick=true) //// Indicator Bollinger Bands source = close length = input.int(20, minval=1) mult = input.float(1.5, minval=0.001, maxval=50) direction = input.int(0, title = "Strategy Direction", minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) basis = ta.sma(source, length) dev = mult * ta.stdev(source, length) upper = basis + dev lower = basis - dev plot(basis, color = color.red) plot(upper) plot(lower) /// Trade entry time and squareoff time TradeTime = input(title="Trade Timings",defval="0930-1130") SqoffTime = input(title="Squareoff Timings",defval="1530-1545") Barsinsession(TradeTime) => time(timeframe.period,TradeTime) != 0 Insession = Barsinsession(TradeTime) ? 1 : 0 endofsession = Insession == 0 and Insession[1] == 1 Sqsession = Barsinsession(SqoffTime) ? 1 : 0 SqTime = Sqsession == 1 and Sqsession[1] == 0 //// Input control and conditions buy_condition = high[1] < lower[1] and ta.crossover(high, high[1]) and Insession short_condition = low[1] > upper[1] and ta.crossunder(low, low[1]) and Insession buy_alert_high = ta.valuewhen(buy_condition, high[1],0) buy_alert_low = ta.valuewhen(buy_condition, low[1],0) short_alert_low = ta.valuewhen(short_condition, low[1],0) short_alert_high = ta.valuewhen(short_condition, high[1],0) buy_alert_high1 = ta.valuewhen(buy_condition, high,0) plot(buy_alert_high, style = plot.style_circles) plot(buy_alert_low, style = plot.style_circles, offset = -2) plot(short_alert_low, style = plot.style_circles) plot(short_alert_high, style = plot.style_circles) sell = ta.crossunder(close, low) or SqTime //// or SqTime if for intraday exit cover = ta.crossover(close,high) or SqTime //// or SqTime if for intraday exit plotshape(buy_condition, style = shape.triangleup, location = location.belowbar, color = color.green, text = "BUY") plotshape(short_condition, style = shape.triangledown, location = location.abovebar, color = color.red, text = "SHORT") long_price = ta.valuewhen(buy_condition, (buy_alert_high + 0.01),0 ) longstop = buy_alert_low - 0.01 longtgt = basis short_price = ta.valuewhen(short_condition,short_alert_low - 0.01,0) ////short_alert_low - (0.01 * 100 * syminfo.mintick) //// ta.valuewhen(short_condition,short_alert_low - 0.01,0) shortstop = short_alert_high + 0.01 shorttgt = basis strategy.entry("long",direction = strategy.long, when = buy_condition, limit = long_price, comment ="BUY") strategy.close("long", when = sell, comment = "SELL") strategy.exit("long", from_entry = "long", stop = longstop, limit = longtgt, comment = "TG/SL_EXIT") strategy.entry("short",direction = strategy.short, when = short_condition,limit = short_price, comment ="SHORT") strategy.close("short", when = cover, comment = "COVER") strategy.exit("short", from_entry = "short", stop = shortstop, limit = shorttgt, comment = "TG/SL_EXIT") plot(strategy.position_size > 0 ? longstop : na, style = plot.style_linebr, color = color.red) plot(strategy.position_size > 0 ? longtgt : na, style = plot.style_linebr, color = color.green) plot(strategy.position_size < 0 ? shortstop : na, style = plot.style_linebr, color = color.red) plot(strategy.position_size < 0 ? shorttgt : na, style = plot.style_linebr, color = color.green)
Error in output either line or envelope shows up
I have used 2 code on Tradingview by LUXALGO Nadaraya-Watson Estimator Nadaraya-Watson Envelope When the code is converted to ver 5.0 and compiled together, no compilation error is shown but the output only reflects either the Estimator Line or Estimator Envelope. Need both outputs together. To replicate the problem, first select either the Estimator Checkbox or Envelope Checkbox, when both the Estimator and Envelope checkboxes are selected, we get only the envelope and the Estimator line disappears. Need help in resolving this issue. The code is as below: I have updated the variables inorder to not mix up while merging 2 scripts // 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('Nadaraya-Watson Estimator & Envelope [LuxAlgo]', overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500) grp_1 = "Estimator Settings" show_est = input.bool(true, "Show Estimator", group = grp_1) h_est = input(8.,'Bandwidth', group = grp_1) src_est = input(close,'Source', group = grp_1) disclaimer = input(false, 'Hide Disclaimer', group = grp_1) //---- n_est = bar_index var ln_est = array.new_line(0) if barstate.isfirst for i = 0 to 499 array.push(ln_est,line.new(na,na,na,na)) //---- float y2_est = na float y1_est = na float y1_d_est = na //---- line l_est = na label lb_est = na if barstate.islast and show_est for i_est = 0 to math.min(499,n_est-1) sum_est = 0. sumw_est = 0. for j_est = 0 to math.min(499,n_est-1) w_est = math.exp(-(math.pow(i_est-j_est,2)/(h_est*h_est*2))) sum_est += src_est[j_est]*w_est sumw_est += w_est y2_est := sum_est/sumw_est d_est = y2_est - y1_est l_est := array.get(ln_est,i_est) line.set_xy1(l_est,n_est-i_est+1,y1_est) line.set_xy2(l_est,n_est-i_est,y2_est) line.set_color(l_est,y2_est > y1_est ? #ff1100 : #39ff14) line.set_width(l_est,2) if d_est > 0 and y1_d_est < 0 label.new(n_est-i_est+1,src_est[i_est],'▲',color=#00000000,style=label.style_label_up,textcolor=#39ff14,textalign=text.align_center) if d_est < 0 and y1_d_est > 0 label.new(n_est-i_est+1,src_est[i_est],'▼',color=#00000000,style=label.style_label_down,textcolor=#ff1100,textalign=text.align_center) y1_est := y2_est y1_d_est := d_est //---- var tb_est = table.new(position.top_right, 1, 1 , bgcolor = color.silver) if barstate.isfirst and not disclaimer table.cell(tb_est, 0, 0, 'Nadaraya-Watson Estimator [LUX] Repaints' , text_size = size.small , text_color = #cc2f3c) // // 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("Nadaraya-Watson Envelope [LuxAlgo]",overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500) grp_2 = "Envelope Settings" show_env = input.bool(false, "Show Envelope") length_env = input.float(500,'Window Size',maxval=500,minval=0, group = grp_2) h_env = input.float(8.,'Bandwidth', group = grp_2) mult_env = input.float(3., group = grp_2) src_env = input.source(close,'Source', group = grp_2) up_col_env = input.color(#39ff14,'Colors',inline='col', group = grp_2) dn_col_env = input.color(#ff1100,'',inline='col', group = grp_2) // disclaimer = input(false, 'Hide Disclaimer') //---- n_env = bar_index var k_env = 2 var upper_env = array.new_line(0) var lower_env = array.new_line(0) lset(l,x1,y1,x2,y2,col)=> line.set_xy1(l,x1,y1) line.set_xy2(l,x2,y2) line.set_color(l,col) line.set_width(l,2) if barstate.isfirst and show_env for i = 0 to length_env/k_env-1 array.push(upper_env,line.new(na,na,na,na)) array.push(lower_env,line.new(na,na,na,na)) //---- line up_env = na line dn_env = na //---- cross_up_env = 0. cross_dn_env = 0. if barstate.islast and show_env y_env = array.new_float(0) sum_e_env = 0. for i = 0 to length_env-1 sum_env = 0. sumw_env = 0. for j = 0 to length_env-1 w_env = math.exp(-(math.pow(i-j,2)/(h_env*h_env*2))) sum_env += src_env[j]*w_env sumw_env += w_env y2_env = sum_env/sumw_env sum_e_env += math.abs(src_env[i] - y2_env) array.push(y_env,y2_env) mae_env = sum_e_env/length_env*mult_env for i = 1 to length_env-1 y2_env = array.get(y_env,i) y1_env = array.get(y_env,i-1) up_env := array.get(upper_env,i/k_env) dn_env := array.get(lower_env,i/k_env) lset(up_env,n_env-i+1,y1_env + mae_env,n_env-i,y2_env + mae_env,up_col_env) lset(dn_env,n_env-i+1,y1_env - mae_env,n_env-i,y2_env - mae_env,dn_col_env) if src_env[i] > y1_env + mae_env and src_env[i+1] < y1_env + mae_env label.new(n_env-i,src_env[i],'▼',color=#00000000,style=label.style_label_down,textcolor=dn_col_env,textalign=text.align_center) if src_env[i] < y1_env - mae_env and src_env[i+1] > y1_env - mae_env label.new(n_env-i,src_env[i],'▲',color=#00000000,style=label.style_label_up,textcolor=up_col_env,textalign=text.align_center) cross_up_env := array.get(y_env,0) + mae_env cross_dn_env := array.get(y_env,0) - mae_env alertcondition(ta.crossover(src_env,cross_up_env),'Down','Down') alertcondition(ta.crossunder(src_env,cross_dn_env),'Up','Up') // //---- // var tb = table.new(position.top_right, 1, 1 // , bgcolor = #35202b) // if barstate.isfirst and not disclaimer // table.cell(tb, 0, 0, 'Nadaraya-Watson Envelope [LUX] Repaints' // , text_size = size.small // , text_color = #cc2f3c)
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)
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?