Pine Script V5 - Not getting expected breakout entry price and entry in expected bar - pine-script-v5

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)

Related

Plotshape and label

In below code, I am getting syntax error for plotshape and several for label. Even for max / min i am getting too many arguments. I used label to get the value from intraburst formula as text. Will need help to resolve these.
//#version=4
study("Intraburst", overlay=true)
truemove = abs(open[2] - close) dayTrueHigh = max(high[1], high,
close[2]) dayTrueLow = min(low[1], low, close[2]) dayTrueRange =
dayTrueHigh - dayTrueLow intraburstLevel = truemove / dayTrueRange *
100
if intraburstLevel > 30
plotshape(series=intraburstLevel, text="ON", style=shape.circle, location=location.abovebar, color=color.green, size=size.normal) else
plotshape(series=intraburstLevel, text="OFF", style=shape.circle, location=location.abovebar, color=color.red, size=size.normal)
label = label.new(bar_index=0, yloc=y_top, xloc=xloc.bar_index,
text=tostring(intraburstLevel, "0.00"), size=size.large,
color=color.black) label.location = location.top label.y = y_top
label.x = x_right label.text = tostring(intraburstLevel, "0.00")
In series, use a ternary
Something like that:
plotshape(
intraburstLevel > 30 ? intraburstLevel : na,
text = "ON",
style = shape.circle,
location = location.abovebar,
color = color.green,
size = size.normal)
plotshape(
intraburstLevel <= 30 ? intraburstLevel : na,
text = "OFF",
style = shape.circle,
location = location.abovebar,
color = color.red,
size = size.normal)
and the label
label.new(
bar_index,
close,
tostring (intraburstLevel, "##.00"),
color = color.black,
textcolor = color.white)

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)

Condition only run ONCE (instead on all bars)

On checking for condition gap(high-low) > 0.1%(which is met multiple times), the label only gets
rendered ONCE (instead of on relevant bars within 25 bar lookback).
Plz provide a solution.
CODE :
Historical Bars
//#version=5
indicator("PriceMomemtum",overlay = true,max_bars_back = 25)
gap = (math.abs(high - low)/low ) * 100
//var gap = (math.abs(high - low)/low ) * 100
if gap > 0.1
var lbl = label.new(x = bar_index,y = na , text = na ,text_font_family = font.family_default ,xloc = xloc.bar_index,yloc =yloc.abovebar,style = label.style_arrowdown ,textcolor = color.white,size =size.small,textalign = text.align_left,tooltip = na)
label.set_text(lbl,str.tostring(gap,"#.00")+"%")
label.set_xy(lbl,bar_index,high )
Realtime Bars
//#version=5
indicator("PriceMomemtum",overlay = true,max_bars_back = 25)
if barstate.isrealtime
gap = (math.abs(high - low)/low ) * 100
//var gap = (math.abs(high - low)/low ) * 100
if gap > 0.1
var lbl = label.new(x = bar_index,y = na , text = na ,text_font_family = font.family_default ,xloc = xloc.bar_index,yloc =yloc.abovebar,style = label.style_arrowdown ,textcolor = color.white,size =size.small,textalign = text.align_left,tooltip = na)
label.set_text(lbl,str.tostring(gap,"#.00")+"%")
label.set_xy(lbl,bar_index,high )
alert(str.tostring(time(syminfo.timezone)) + "(PriceMomentum)", alert.freq_once_per_bar)
Have you tried defining "lbl" variable without "var"?
result

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

Code not plotting - Function should be called on each calculation for consistency. It is recommended to extract the call from this scope"

I am getting this as an orange error - not sure what I have done wrong or whether this error is the reason that the code doesn't plot. I am brand new to Pine-script and any assistance would be invaluable. Many thanks in advance Alastair
//#version=5
indicator("PCY TEST4")
//Get User Inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
//Variables
a = 0.33
PCY = 0.0
PCYi = 0.0
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
minMacd=0.0
for i = 0 to (signal_length[1])
minMacd := ta.min(macd)
maxMacd=0.0
for i = 0 to (signal_length[1])
maxMacd := ta.max(macd)
//maxMacd = ta.min(macd)
//minMacd = ta.max(macd)
//signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
//hist = macd - signal
delta = maxMacd-(fast_ma - slow_ma)/(maxMacd -minMacd)
for i = 0 to (signal_length)
PCYi := a*((delta - PCYi[1])+PCYi[1])
PCYi
//Plotting
plot(PCYi)
I think it's because you're calculating the min/max in a for loop
Those functions should (not mandatory but strongly recommended) be calculated at every candle instead
for i = 0 to (signal_length[1])
minMacd := ta.min(macd)
maxMacd=0.0
for i = 0 to (signal_length[1])
maxMacd := ta.max(macd)
If you want to calculate the min/max over a X period of time, maybe use the ta.highest/ta.lowest functions instead :)
And of course, those 2 should be called at every candle (i.e. not in a if, for,... statement)