Counting bars since highest high of last 50 bars in Pine Script - pine-script-v5

i am trying to count number o fbars since highest high of last 50 bars in pine script. But it is giving me error that "Study error, too many candles referenced in history". Can anyone help
//#version=5
indicator("Trendline" , overlay = true)
h1=ta.highest(high, 50)
l1=ta.lowest(low, 50)
bari=ta.barssince(h1)
bari2=ta.barssince(l1)
if(barstate.islast)
highline=line.new(x1=bari, y1=high[h1], x2=bar_index, y2=high)
line.set_color(highline, color.red)
line.set_extend(highline, extend.none)
line.set_width(highline, 2)
line.delete(highline[1])``

at x2, it should be the last candle (bar_index). so x1 must be the last candle minus 50 periods
y1 and y2, must be the value of highest high (h1)
Something like that:
//#version=5
indicator("Trendline" , overlay = true)
h1 = ta.highest(high, 50)
if(barstate.islast)
highline=line.new(x1=bar_index - 50, y1=h1, x2=bar_index, y2=h1)
line.set_color(highline, color.red)
line.set_extend(highline, extend.none)
line.set_width(highline, 2)
line.delete(highline[1])

Related

Fixing the Plot Shape signals on a highly profitable Pinescript strategy

I want to fix the attached pine script code in version 5 of Tradingview for a strategy I formed which is highly profitable but the signals for Buy, Sell, Exit Buy and Exit Sell are not occurring on the chart at the right points.
If someone can help me fix the attached code it would be great for even them as the strategy is highly profitable in trending markets and can be easily used to implement on a Trading Bot.
The strategy is as follows
I have 2 Exponential Moving Averages plotted on the chart, mainly EMA of 144 and EMA of 169. Once you plot these EMA's on the chart, they appear like a tunnel.
Buy Condition is - If the candle closes above both the EMA's, then a Buy Plot shape should occur on that candle.
Exit Buy Condition is - if the candle breaks the low of both the EMA's, even if not on a closing basis (even if the low of the candle is below both the EMA's), then a Exit Buy Plot shape should occur on that candle.
Sell Condition is - If the candle closes below both the EMA's, then a Sell Plot shape should occur on that candle.
Exit Sell Condition is - if the candle breaks the high of both the EMA's, even if not on a closing basis (even if the high of the candle is above both the EMA's), then a Exit Buy Plot shape should occur on that candle.
Also the most important aspect is that these shapes should not occur repeatedly. They should only occur on the specific candle when the condition is met.
I have attached the current pinescript code that I drafted but it isint working properly.
//#version=5
indicator("WavyCrorepati v2.0", overlay=true)
tunnel1 = ta.ema(close, 144)
tunnel2 = ta.ema(close, 169)
plot(tunnel1, color=color.white, linewidth=2)
plot(tunnel2, color=color.white, linewidth=2)
intradelong = 0
intradeshort = 0
// BUY
long = close > tunnel1 and close > tunnel2 or (ta.crossover(close,tunnel1) and ta.crossover(close,tunnel2))
if long
intradelong := 10
exitlong = low < tunnel2 and low < tunnel1
if exitlong
intradelong := 5
// SHORT
short = close < tunnel1 and close < tunnel2 or (ta.crossunder(close, tunnel1) and ta.crossunder(close, tunnel2))
if short
intradeshort := -10
exitshort = high > tunnel1 and high > tunnel2
if exitshort
intradeshort := -5
// PLOT SHAPES
plotshape(long and intradelong[1] == 5 , style=shape.labelup, color=color.green, location=location.belowbar, size=size.small,text="B",textcolor=color.white)
plotshape(exitlong and long[1], style=shape.diamond,color=color.white,location=location.belowbar,size=size.tiny)
plotshape(short and intradeshort[1] == -5 , style=shape.labeldown, color=color.red, location=location.abovebar, size=size.small,text="S",textcolor=color.yellow)
plotshape(exitshort and short[1], style=shape.diamond,color=color.yellow, location=location.abovebar,size=size.tiny)
plot(intradelong, color = color.green, display = display.status_line)
plot(intradeshort, color = color.red, display = display.status_line)

Plot standard deviation lines in Pine Script

I have this pine script I'm using on tradingview to plot a line that is the average of the highs and lows of a given time period.
I'd like to plot the standard deviation on the chart of this value:
highLowAvg =(sum(maxValue,length_avg) + sum(minValue,length_avg)) / (length_avg*2)
Is there an easy way to do this? Below is the whole script.
//Fill Arrays with latest LOWS/HIGHS
//Get highest HIGH and lowest LOW values from the arrays.
//Do Average between X highest highs and X lowest lows and plot line (Length can be modified)
//If price LOW is above line, Up Trending (Green) (Source can be modified)
//If price HIGH is below line, Down Trending (Red) (Source can be modified)
//If neither above, slow down in trend / reversal might occur (White)
study("Low - High Simple Tracker",overlay=true)
////==================Inputs
length = input(8)
length_avg = input(8)
up_Trend_Condition = input(high)
down_Trend_Condition = input(low)
stdev = stdev(highLowAvg, length)
////==================Array setup and calculations
lowArray = array.new_float(0)
highArray = array.new_float(0)
//Fill Lows to an array
for i = 0 to length-1
array.push(highArray,high[i])
//Fill Highs to an array
for i = 0 to length-1
array.push(lowArray,low[i])
//Get the highest value from the high array
maxValue= array.max(highArray)
//Get the lowest value from the low array
minValue= array.min(lowArray)
//Average between highest and lowest (length can be modifed)
highLowAvg =(sum(maxValue,length_avg) + sum(minValue,length_avg)) / (length_avg*2)
////////==================Plotting
colorHL = down_Trend_Condition > highLowAvg ? color.green : up_Trend_Condition < highLowAvg ?
color.red : color.white
plot(highLowAvg, color =colorHL, style = plot.style_line, linewidth = 2)

Charting OHLC candle with SMA 200 using mplfinance plot function

I'm using mplfinance plot function to draw OHLC candlestick chart of a symbol. OHLC data is of 2 min timeframe. Also, I'm plotting sma 20 period and sma 200 period on the same chart. Because of sma200, the number of candles which are displayed on chart is quite huge (almost two days of 2min candle)
Since moving average is calculated internally by plot function so I've to pass the two days of 2 min candle to plot function so that I could get some data points of sma200. Candlestick chart is saved as png file. Now because of around 300 candles displayed on chart (sma20 and sma200 line also displayed), candles are not very clearly displayed.
Is there a way to restrict number of candles which get displayed on chart. If I slice my dataframe to lets say 30 candle, then sma200 will not be calculated in that case due to insufficient number of candles. What I need is sma200 with complete dataset but only fixed number of candle or for a fixed duration chart get displayed like last one hour candle data only.
mpf.plot(df, type='candle', style='charles',
title=title,
ylabel='Price',
ylabel_lower='Shares \nTraded',
mav=(20,200),
savefig=file)
I would suggest that you calculate your own moving average, and plot it using mpf.make_addplot(). This will allow you to calculate a moving average based on one-minute or two-minute candles, while plotting five-minute or ten-minute candles. For example:
# calculate mav values
mav20 = twominute_df['Close'].rolling( 20).mean()
mav200 = twominute_df['Close'].rolling(200).mean()
# resample:
resample_ohlcmap = {'Open' :'first',
'High' :'max',
'Low' :'min',
'Close' :'last',
'Volume':'sum'
}
tenminute_df = twominute_df.resample('10T').agg(resample_ohlcmap)
# plot ten-minute candles with two-minute mavs:
apmavs = [ mpf.make_addplot(mav20),
mpf.make_addplot(mav200) ]
mpf.plot(tenminute_df, type='candle', style='charles',
title=title, ylabel='Price', ylabel_lower='Shares \nTraded',
addplot=apmavs, savefig=file)
References:
resampling
moving average calculation
Thanks Daniel for your help. I'm now able to plot a chart for 60 candles with sma 20 and 200.
Well I don't need resampling as my chart timeframe and moving average time frame both are same.
Please find my code snippet.
# get list of close prices from symbol_docs. symbol_docs contain 2 min OHLC.
close_list = list(map(lambda a: a['close'], symbol_docs))
# sma20 and 200 calculated using ta-lib
sma20 = sma(close_list, 20)
sma200 = sma(close_list, 200)
# call to plot_chart function
plot_chart('TCS', symbol_docs, sma20, sma200)
def plot_chart(symbol, docs, sma20, sma200):
df = pd.DataFrame(docs)
df = df.set_index(['time'])
df.rename(columns={'open': 'Open', 'close': 'Close', 'high': 'High', 'low': 'Low'},
inplace=True)
title = symbol.upper() + ' - 2min'
file = saved_chart_image_abs_path + symbol + '.png'
df['sma20'] = sma20
df['sma200'] = sma200
df_sliced = df[-60:]
apmavs = [mpf.make_addplot(df_sliced['sma20']), mpf.make_addplot(df_sliced['sma200'])]
mpf.plot(df_sliced, type='candle', style='charles',
title=title,
ylabel='Price',
ylabel_lower='Shares \nTraded',
addplot=apmavs,
savefig=file)
telegram_message_sender.send_document(file)
os.remove(file)
Below chart is sent as a document on my telegram group :)

offset in atr in tradingview - pine script

Need to have offset in ATR function in pine script
Background: The indicator script below is based on the hypothesis that this period's range will be mostly within [last period high + atr(14)] and [last period low - atr(14)]. I want to sell the high call option and low put option and enjoy the premium at the end of the period (week, month).
I have created a pine script that will calculate this period range based on [last period high + atr(14)] and [last period low - atr(14)].
However, because atr(14) applies to current period as well, it plots the dots that change with the current price.
I need to have an atr(14) days till the last period and not considering this current period. Could you please advise how to achieve that.
//#version=3
study(title="High and Low Levels", shorttitle="HL Levels", overlay = true)
Width = input(2, minval=1)
SelectPeriod = input("W", defval="W", type=string)
LookBack = input(1, minval=1)
xHigh = high[LookBack]
xHigh := xHigh + (atr(14))
xLow = low[LookBack] - atr(14)
vS1 = xHigh
vR1 = xLow
plot(vS1, color=#ff0000, title="S1", style = circles, linewidth = Width)
plot(vR1, color=#009600, title="R1", style = circles, linewidth = Width)
Expected: the dots plotted should be plotted based on last period high + last period atr(14) and last period low - last period atr(14)
Actual: the dots plotted based on last week high + atr(14) till the current period and last week low - atr(14) till the current period. This is changing the dots based on the current price movement.
Maybe, I got it wrong, but I think what you want is to take the previous value of atr(14). So it looks like that:
xLow = low[LookBack] - atr(14)[1]
I think, you've got my idea.
This should help....
plot(vS1[1], color=#ff0000, title="S1", style = circles, linewidth = Width)
plot(vR1[1], color=#009600, title="R1", style = circles, linewidth = Width)

Matlab Stepinfo Function

S = stepinfo(Y,T,180,'SettlingTimeThreshold',ST) ;
ts=S.SettlingTime;
in this does it mean ts is the time at which |Y-180| becomes less than ( ST/100 )or something else...
in my code though |Y-180| is less than ST/100 but i am getting ts = NAN;
pls help me out
My code:
if ee(end)>160
S = stepinfo(ee,times,180,'SettlingTimeThreshold',0.01);
else
S = stepinfo(ee,times,0.5,'SettlingTimeThreshold',1);
end
settling_time = S.SettlingTime;
end
where 'ee' is an array of values at each 'times'
ee is basically error angle which becomes 180 or 0 after some time..
thanks
From the help:
The response has settled when the error |y(t) - yfinal| becomes
smaller than a fraction ST of its peak value.
This means that it's the fraction of the peak error value, not an absolute threshold - e.g. if your system was something that started at around 30, and eventually rose and settled at near 180 (yfinal = 180), then the max error is 150, and the threshold would be 0.01*150 = 1.5. So it would need to get to 178.5 (180-1.5).
If your system started at 100 and settled at about 180, your max error is 80, and the threshold is then only 0.8, so your value needs to be at 179.2.
Look at what your min(ee) and max(ee) are and then decide on what a sensible threshold is.
EDIT:
If you want to set a fixed threshold you'll have to calculate it on the fly:
desiredthreshold = 1.8 % absolute value, e.g. 0.01*180
maxerror = 180-min(ee); % assuming your values are all between 0 and 180
actualthreshold = 1.8/maxerror; %if your min value is 0 then this goes to 0.01, otherwise it will be larger