I am trying to get only last week high/low values,NOT all weeks values
t = input(title = "study", defval="W", options=["D","W"])
shigh = security(tickerid, t, high[1], barmerge.gaps_off, barmerge.lookahead_on)
slow = security(tickerid, t, low[1], barmerge.gaps_off, barmerge.lookahead_on)
r = shigh-slow
center=(sclose)
h1=sclose + r*(1.1/12)
c5=sopen != sopen[1] ? na : red
plot(h5, title="H5",color=c5, linewidth=2)
As you can see in the chart are displayed all weeks since creation...I want only last week!not to show all of them into the chart.
Can someone show me how its done?
//#version=4
study("My Script", overlay=true)
t = input(title = "study", defval="W", options=["D","W"])
[sopen, shigh, slow, sclose] = security(syminfo.tickerid, t, [open[1], high[1],low[1],close[1]], barmerge.gaps_off, barmerge.lookahead_on)
r = shigh-slow
center = (sclose)
h5 = sclose + r*(1.1/12)
c5 = sopen != sopen[1] ? na : color.red
plot(h5, title="H5",color=c5, linewidth=2)
Update: only show current week.
//#version=4
study("My Script", overlay=true)
t = input(title = "study", defval="W", options=["D","W"])
thisweek = year(timenow) == year(time) and weekofyear(timenow) == weekofyear(time)
[sopen, shigh, slow, sclose] = security(syminfo.tickerid, t, [open[1], high[1],low[1],close[1]], barmerge.gaps_off, barmerge.lookahead_on)
r = shigh-slow
center = (sclose)
h5 = sclose + r*(1.1/12)
c5 = sopen != sopen[1] ? na : color.red
plot(thisweek ? h5 : na, title="H5",color=c5, linewidth=2)
Related
Assume lrcopen, lrchigh, lrclow, lrcclose are the open, high, low, close of Linear Regression Candle which is plotted using plotcandle(). I want to check and compare the lrcopen < lrcclose value for last two closed Linear Regression Candle to see whether it changes from false to true or vice versa after plotting
//#version=4
study(title="Humble LinReg Candles", shorttitle="LinReg Candles", format=format.price, precision=4, overlay=true)
signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 200, defval =7)
sma_signal = input(title="Simple MA (Signal Line)", type=input.bool, defval=true)
lin_reg = input(title="Lin Reg", type=input.bool, defval=true)
linreg_length = input(title="Linear Regression Length", type=input.integer, minval = 1, maxval = 200, defval = 11)
bopen = lin_reg ? linreg(open, linreg_length, 0) : open
bhigh = lin_reg ? linreg(high, linreg_length, 0) : high
blow = lin_reg ? linreg(low, linreg_length, 0) : low
bclose = lin_reg ? linreg(close, linreg_length, 0) : close
r = bopen < bclose
signal = sma_signal ? sma(bclose, signal_length) : ema(bclose, signal_length)
plotcandle(r ? bopen : na, r ? bhigh : na, r ? blow: na, r ? bclose : na, title="LinReg Candles", color= color.green, wickcolor=color.green, bordercolor=color.green, editable= true)
plotcandle(r ? na : bopen, r ? na : bhigh, r ? na : blow, r ? na : bclose, title="LinReg Candles", color=color.red, wickcolor=color.red, bordercolor=color.red, editable= true)
// I want to detect the change of color of just plotted Linear Regression Candle here
Original Question
Apparently, when using barstate.islast the values before zero in a series are not returned.
Is this the expected behavior? Or is it a problem?
//#version=5
indicator("barstate.islast invalidades series[1]", max_bars_back=5000)
index = bar_index
countNonNa(indices) =>
count = 0
for i = 0 to 4999 by 1
index = indices[i]
if not(na(index))
count += 1
count
count00 = countNonNa(index)
plot(count00, "count00", color = color.blue) // ok
count01 = barstate.isconfirmed ? countNonNa(index) : 0
plot(count01, "count01", color = color.black) // ok
count02 = barstate.islast ? countNonNa(index) : 0
plot(count02, "count02", color = color.red) // error expected 5000 in the last bar, but gets 1
You should execute your function on every bar, as stated in the console.
This will work:
//#version=5
indicator("barstate.islast invalidades series[1]", max_bars_back=5000)
index = bar_index
countNonNa(indices) =>
count = 0
for i = 0 to 4999 by 1
idx = indices[i]
if not(na(idx))
count += 1
count
c = countNonNa(index)
count00 = c
plot(count00, "count00", color = color.blue) // ok
count01 = barstate.isconfirmed ? c : 0
plot(count01, "count01", color = color.black) // ok
count02 = barstate.islast ? c : 0
plot(count02, "count02", color = color.red) // error expected 5000 in the last bar, but gets 1
Hello I'm new to pine and i have a question.
I would like to write a script that helps me drawing lines connecting the close of the first candle in a selected range and the close of every other candle in the range.
I think I have some problem understanding pine runtime because using for loops or conditional structures seems bad but I can't find a solution around this.
I tried with if but had no succes, the idea was that
after i select the start/end point, the code should be something like this:
if bar_index > bar_index[barStart] and bar_index < bar_index[barEnd]
line.new(bar_index[barStart], close[barStart], bar_index, close)
else na
After this I tried with a for loop, again with no success:
for i = bar_index[barStart]+1 to bar_index[barEnd]
line.new(bar_index[barStart], close[barStart], bar_index[i], close[i])
The code I use to select the range and count the candles inside it is this one:
//#version=5
indicator("Close", overlay=true)
// Range Start
t0 = input.time(timestamp("20 Jul 2021 00:00 +0300"), confirm = true)
p0 = input.price(defval = 0, confirm = true)
// Range End
t1 = input.time(timestamp("20 Jul 2021 00:00 +0300"), confirm = true)
p1 = input.price(defval = 0, confirm = true)
///////////////////////////////////////////////////////////////////////////////////
// Bar counting
t_bar(_t) =>
var int _bar = na
if time_close[1] <= _t and time >= _t
_bar := bar_index
_bar
start = int(t_bar(t0))
end = int(t_bar(t1))
//Counting bars in the selected range
barStart = bar_index - start
barEnd = bar_index - end
barDelta = end - start
//Print results
plot(barStart, "Range start")
plot(barEnd, "Range end")
plot(barDelta, "Candles in range")
But from here on I don't know how to proceed. This should be pretty easy but I'm stuck.
What I'm trying to draw
Thank you to anyone willing to help!!
You don't need the loop or the input price variables. The lines can be drawn bar by bar as the script's execution enters your time range and the price variables can also be obtained at the same time.
//#version=5
indicator("Close", overlay=true)
// Range Start
t0 = input.time(timestamp("20 Jul 2021 00:00 +0300"), confirm = true)
// Range End
t1 = input.time(timestamp("20 Jul 2021 00:00 +0300"), confirm = true)
///////////////////////////////////////////////////////////////////////////////////
first_bar = time >= t0 and time[1] < t0
in_range = time > t0 and time <= t1
post_bar = time > t1 and time[1] <= t1
var float start_close = na
var int start_index = na
if first_bar
start_close := close
start_index := bar_index
if in_range and not first_bar
line.new(x1 = start_index, y1 = start_close, x2 = bar_index, y2 = close)
if post_bar
num_bars = bar_index[1] - start_index
delta = close[1] - start_close
info_text = "Start Bar : " + str.tostring(start_index) + "\nEnd Bar : " + str.tostring(bar_index[1]) + "\nNumber of bars : " + str.tostring(num_bars) + "\nPrice delta : " + str.tostring(delta)
label.new(x = bar_index[1], y = high[1], style = label.style_label_lower_left, size = size.small, text = info_text)
Follow up question :
To draw the lines on a higher timeframe and have them "persist" once you move to a lower timeframe is a bit trickier. You will have to use an input to manually set the higher timeframe as the script has no way to determine the previous timeframe that it was applied to.
When you set t0 and t1 on the higher timeframe, the timestamp values will correspond to the opening time for those higher time frame bars. This isn't ideal as the lower timeframe candle that starts at this same time isn't the close value we are after.
By using request.security() we can then get the actual closing time of the higher timeframe bar which has the closing value we do want.
So we can use time to determine when we've started the correct higher time frame bars and then use time_close to determine when we are on the lower time frame bar that coincides with the higher timeframe close.
//#version=5
indicator("MTF Close", overlay=true)
// Range Start
t0 = input.time(timestamp("20 Jul 2021 00:00 +0300"), confirm = true)
// Range End
t1 = input.time(timestamp("20 Jul 2021 00:00 +0300"), confirm = true)
///////////////////////////////////////////////////////////////////////////////////
tf = input.timeframe("240", title = "higher timeframe")
htf_close = request.security(syminfo.tickerid, tf, time_close)
is_htf_closing_bar = time_close == htf_close
new_htf = ta.change(time(tf)) != 0
var bool started_first_htf_bar = false
var float start_close = na
var int start_index = na
var bool started_last_htf_bar = false
if time >= t0 and time[1] < t0 and new_htf
started_first_htf_bar := true
else if new_htf
started_first_htf_bar := false
if started_first_htf_bar and is_htf_closing_bar and na(start_close)
start_close := close
start_index := bar_index
else if not started_first_htf_bar and is_htf_closing_bar and time > t0 and time < t1
line.new(x1 = start_index, y1 = start_close, x2 = bar_index, y2 = close)
if time >= t1 and time[1] < t1 and new_htf
started_last_htf_bar := true
else if new_htf
started_last_htf_bar := false
if started_last_htf_bar and is_htf_closing_bar
line.new(x1 = start_index, y1 = start_close, x2 = bar_index, y2 = close)
post_bar = new_htf and started_last_htf_bar[1]
if post_bar
num_bars = bar_index[1] - start_index
delta = close[1] - start_close
info_text = "Start Bar : " + str.tostring(start_index) + "\nEnd Bar : " + str.tostring(bar_index[1]) + "\nNumber of bars : " + str.tostring(num_bars) + "\nPrice delta : " + str.tostring(delta)
label.new(x = bar_index[1], y = high[1], style = label.style_label_lower_left, size = size.small, text = info_text)
I'd like to plot an indicator only for the last x periods.
How do I do that?
If I could do time operations (substract x * period from plotStartDate), maybe I could use this code:
period = timeframe.ismonthly or timeframe.isweekly ? "12M" : "M"
plotStartDate = timestamp(year(timenow), month(timenow), dayofmonth(timenow), 00, 00)
isPlotDate = time >= plotStartDate
plot(isPlotDate ? mydata : na, color=mydata != mydata[1]:na, style=plot.style_line, linewidth=2)
Version 1
Not sure this is what you're looking for. It uses plot()'s show_last= parameter to restrict the number of last bars plotted after your isPlotDate constraint has been satisfied:
//#version=4
study("", "", true)
xPeriods = input(10)
plotStartDate = timestamp(year(timenow), month(timenow), dayofmonth(timenow), 00, 00)
isPlotDate = time >= plotStartDate
plot(isPlotDate ? close : na, show_last = xPeriods)
Version 2
//#version=4
study("Plot starting n months back", "", true)
monthsBack = input(3, minval = 0)
monthsExtra = monthsBack % 12
monthsExcedent = month(timenow) - monthsExtra
yearsBack = floor(monthsBack / 12) + (monthsExcedent <= 0 ? 1 : 0)
targetMonth = monthsExcedent <= 0 ? 12 + monthsExcedent : monthsExcedent
targetYearMonth = year == year(timenow) - yearsBack and month == targetMonth
beginMonth = not targetYearMonth[1] and targetYearMonth
var float valueToPlot = na
if beginMonth
valueToPlot := high
plot(valueToPlot)
bgcolor(beginMonth ? color.green : na)
Version 3
Simpler:
//#version=4
study("Plot starting n months back", "", true)
monthsBack = input(3, minval = 0)
targetDate = time >= timestamp(year(timenow), month(timenow) - monthsBack, 1, 0, 0, 0)
beginMonth = not targetDate[1] and targetDate
var float valueToPlot = na
if beginMonth
valueToPlot := high
plot(valueToPlot)
bgcolor(beginMonth ? color.green : na)
Version 4
At v4 you can set the variable show_last in the plot() function.
In "PineScript language reference manual" says:
show_last (input integer) If set, defines the number of bars (from the
last bar back to the past) to plot on chart.
https://www.tradingview.com/pine-script-reference/#fun_plot
I set a 3 layers neural network,it has 2 hidden layers,But when I try to implement gradient check ,I got my max_weigh=1 ,which means I have some error in my backprop.here are my backprop function,I really need some help
is there something wrong with my codes?
thanks!
def loss(self,X,y,reg = 0.0):
#forward prop
W1, b1 = self.params['W1'], self.params['b1']
W2, b2 = self.params['W2'], self.params['b2']
W3, b3 = self.params['W3'], self.params['b3']
N,D = X.shape
H1out = np.maximum(0,X.dot(W1)+b1) #H1out (N,H1)
H2out = np.maximum(0,H1out.dot(W2)+b2) #H2out (N,H2)
scores = None
scores = H2out.dot(W3)+b3
scores_shift = scores-np.max(scores,axis = 1).reshape(-1,1)
softmaxout = np.exp(scores_shift)/np.sum(np.exp(scores_shift),axis=1).reshape(-1,1)
loss_main = None
loss = None
loss_main = -np.sum(np.log(softmaxout[range(N),list(y)]))
loss = loss_main/N + reg*np.sum(W1*W1)*np.sum(
W2*W2)+np.sum(W3*W3)
#backward prop
dscores = softmaxout.copy() #dscores (N,C)
dscores[range(N),list(y)] -= 1
dscores /= N
dW3 = H2out.T.dot(dscores)
db3 = np.sum(dscores,axis = 0)
dh2 = dscores.dot(W3.T) #dh2 (N,H2)
dh_Relu2 = (H2out > 0) * dh2 #dh_ReLu2 (N,H2)
dW2 = H1out.T.dot(dh_Relu2)
db2 = np.sum(dh_Relu2,axis = 0)
dh1 = dh_Relu2.dot(W2.T) #dh1 (N,H1)
dh_Relu1 = (H1out>0) * dh1
dW1 = X.T.dot(dh_Relu1)
db1 = np.sum(dh_Relu1,axis = 0)
grad = {}
grad['W1'] = dW1
grad['b1'] = db1
grad['W2'] = dW2
grad['b2'] = db2
grad['W3'] = dW3
grad['b3'] = db3
return loss,grad