draw line and color the area above in indicator in Trading View with Pine Script - pine-script-v5

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))

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)

Compare bool and float to determine plot (pine script v5)

You folks helped me with another part of this script and I'm making good progress. However, I'm stuck again.
I added a code to produce a dynamic overbought/oversold line on the indicator. That part works great. Now, I'm wanting to add a plotshape when conditions are met to signal long or short. Unfortunately, I can't figure out how to compare a bool variable and a float variable. The dynamic OB/OS lines are floats. The crossover lines are bool.
What I want is for the (green/long) shape to plot when a crossover happens below the dynamic oversold line and the (red/short) shape to plot when the crossunder happens above the dynamic overbought line.
I've tried all kinds of things (var, loop with "while" using sb value as a trigger). I either break the code or I get every crossover plotted. Here is what I have that is stable. I took all my junk that didn't work out:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HammerGeek
//#version=5
indicator('Impulse MACD [HammerGeek - LazyBear]', shorttitle='IMACD_HG_LB', overlay=false)
lengthMA = input(34)
lengthSignal = input(9)
//OverBought = input.float(0.1)
//OverSold = input.float(-0.1)
calc_smma(src, len) =>
smma = 0.0
sma_1 = ta.sma(src, len)
smma := na(smma[1]) ? sma_1 : (smma[1] * (len - 1) + src) / len
smma
calc_zlema(src, length) =>
ema1 = ta.ema(src, length)
ema2 = ta.ema(ema1, length)
d = ema1 - ema2
ema1 + d
src = hlc3
hi = calc_smma(high, lengthMA)
lo = calc_smma(low, lengthMA)
mi = calc_zlema(src, lengthMA)
md = mi > hi ? mi - hi : mi < lo ? mi - lo : 0
sb = ta.sma(md, lengthSignal)
sh = md - sb
mda = ta.sma(md, lengthSignal)
OverBoughtLine = ta.highest(sb * 0.5, lengthMA*100)
OverSoldLine = ta.lowest(sb * 0.5, lengthSignal*100)
shsbCrossOver = ta.crossover(md, sb)
shsbCrossUnder = ta.crossunder(md, sb)
//mdc = src > mi ? src > hi ? color.lime : color.green : src < lo ? color.red : color.orange
mdc = color.green
plot(0, color=color.new(color.gray, 0), linewidth=1, title='MidLine')
plot(md, color=mdc, linewidth=2, title='ImpulseMACD', style=plot.style_line)
plot(sh, color=color.rgb(122, 5, 168, 40), linewidth=2, title='ImpulseHisto', style=plot.style_area)
plot(sb, color=color.rgb(255, 255, 255, transp = 40), linewidth=2, title='ImpulseMACDCDSignal')
plot(OverBoughtLine, color=color.new(#f3e032, 0), linewidth=1, title = 'Overbought Line')
plot(OverSoldLine, color=color.new(color.yellow, 0), linewidth=1, title = 'Oversold Line')
plotshape(shsbCrossOver, "LONG", shape.triangleup, location.bottom, color.new(color.green, 0))
plotshape(shsbCrossUnder, "SHORT", shape.triangledown, location.top, color.new(#cd0808, 0))
//ebc = input(false, title='Enable bar colors')
//barcolor(ebc ? mdc : na)
You cannot compare a bool with a float. It doesn't make any sense and it is not legal in pinescript.
What I want is for the (green/long) shape to plot when a crossover
happens below the dynamic oversold line and the (red/short) shape to
plot when the crossunder happens above the dynamic overbought line.
You want to check if the values you use in that crossover is under your dynamic oversold line at the time of crossover.
OverSoldLine = ta.lowest(sb * 0.5, lengthSignal*100)
shsbCrossOver = ta.crossover(md, sb)
is_good = shsbCrossOver and (md < OverSoldLine) and (sb < OverSoldLine)

Change RSI Plot Range - Possible or not?

We know that RSI plotting range is between 0 to 100.
Is it possible to change a plotted indicator line so that it will fluctuate in an extended range, say -50 to 100 ?
In simple way I want it to be (stretched) so I can easily draw trend line on the RSI line.
Attached photo is sample of what I mean on is perfect , one that I have is not like it.
I want the the RSI to cross the green and red area without affecting the movement of the indicator. I just want it to be stretching.
enter image description here
enter image description here
//#version=5
indicator(title="Relative Strength Index", shorttitle="RSI", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"Bollinger Bands" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings")
maLengthInput = input.int(50, title="MA Length", group="MA Settings")
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiMA = ma(rsi, maLengthInput, maTypeInput)
rsicolor = rsi > 70 ? color.new(#ff0057, 0) : rsi < 30 ? color.new(#ff0057, 0) : #1056ee
plot(rsi, "RSI", color=rsicolor, linewidth=2, style=plot.style_stepline)
plot(rsiMA, "RSI-based MA", color=color.rgb(120, 206, 255))
OverBought1 = input.int(80, minval=1)
OverBought2 = input.int(90, minval=1)
OverSold1 = input.int(20, minval=1)
OverSold2 = input.int(10, minval=1)
OB1 = hline(OverBought1 , color=color.red, linestyle=hline.style_dashed)
OB2 = hline(OverBought2 , color=color.red, linestyle=hline.style_dashed)
OS1 = hline(OverSold1 , color=color.green, linestyle=hline.style_dashed)
OS2 = hline(OverSold2 , color=color.green, linestyle=hline.style_dashed)
fill(OB1 , OB2, color=color.rgb(255, 82, 82, 80), title="Red Zoon Fill")
fill(OS1 , OS2 , color=color.rgb(76, 175, 79, 80), title="Green Zoon Fill")
Any ideas, please?
Thank you!
Colin
Is it possible to change a plotted indicator line so that it will fluctuate in an extended range, say -50 to 100 ?
In simple way I want it to be (stretched) so I can easily draw trend line on the RSI line.
Attached photo is sample of what I mean on is perfect , one that I have is not like it.
I want the the RSI to cross the green and red area without affecting the movement of the indicator. I just want it to be stretching.
You can use normalize() function:
//#version=5
indicator("My script")
normalize(_src, _min, _max) =>
// Normalizes series with unknown min/max using historical min/max.
// _src : series to rescale.
// _min, _min: min/max values of rescaled series.
var _historicMin = 10e10
var _historicMax = -10e10
_historicMin := math.min(nz(_src, _historicMin), _historicMin)
_historicMax := math.max(nz(_src, _historicMax), _historicMax)
_min + (_max - _min) * (_src - _historicMin) / math.max(_historicMax - _historicMin, 10e-10)
rsi = ta.rsi(close, 20)
rsiNormalized = normalize(rsi, -50, 100)
plot(rsiNormalized)
hline(-50)
hline(100)
EDIT
In your case, since we know the scale will always be between 0 to 100, we can use math to solve the issue much more accurately:
//#version=5
indicator("My script")
rsi = ta.rsi(close, 20) // this will give a value between 0 to 100
// find the value compared to a scale of 100
rsiPerc = rsi / 100
// multiply by the new range to get the position of rsi on the new range
rsiOnNewScale = rsiPerc * 150
// place the newRsi on a scale of -50 to 100
newRsi = rsiOnNewScale - 50
plot(newRsi)
hline(-50)
hline(100)
Or in short:
//#version=5
indicator("My script")
rsi = ta.rsi(close, 20) // this will give a value between 0 to 100
newRsi = (rsi / 100 * 150) - 50
plot(newRsi)
hline(-50)
hline(100)

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?