offset in atr in tradingview - pine script - offset

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)

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)

When the RSI is Divergence, I want the position not to open until the certain candle time expires

In a Pine script,
I am running dca strategy within 1 minute time frame. When the RSI Deviation occurs in a different time frame (for example, 1 hour), I want the position not to be opened until the certain candle period ends (for example, 40 minutes). How can I do that
Thank you
You can do a manual check the time of the current candle in the different time frame and only open a position if the candle has completed.
timeFrame = 40m
timeRSIDeviation = 60m
timeFrame = time(timeFrame)
timeRSIDeviation = time(timeRSIDeviation)
currentTime = timestamp()
rsiDeviationOccurred = (currentTime > timeRSIDeviation)
if (rsiDeviationOccurred and currentTime == timeFrame)
strategy.entry("DCA", strategy.long)

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

Swift - How to set x-Axis to show hourly intervals using iOS Charts

I have the following data:
2019-08-14T13:00:00.000Z, 0.0015378000
2019-08-14T12:30:00.000Z, 0.0015172000
2019-08-14T12:00:00.000Z, 0.0014922000
2019-08-14T11:30:00.000Z, 0.0014706000
2019-08-14T11:00:00.000Z, 0.0014229000
2019-08-14T10:30:00.000Z, 0.0000989000
2019-08-14T10:00:00.000Z, 0.0000736000
2019-08-14T09:30:00.000Z, 0.0000508000
2019-08-14T09:00:00.000Z, 0.0000214000
2019-08-13T17:30:00.000Z, 0.0012805000
And have plotted this data into a Line Chart using the Charts library as shown below:
The data appears correct in the graph, however I've noticed that the x Axis is showing a scale that is not hourly, which I would ideally like to show.
The following code was applied to generate the above graph in an attempt to set an hourly scale on the x-Axis:
xAxis.drawAxisLineEnabled = true
xAxis.drawGridLinesEnabled = true
xAxis.granularityEnabled = true
xAxis.granularity = 1.0 / 24.0
When applying a granularity of 1.0 / 2.4 however, I was able to show a 10 hour interval on the graph as shown below:
It seems that the granularity does not line up to the hourly rate for the given graph, which may be associated with the fact that it contains a minimum interval between axis-values (In my case the maximum duration can be up to 2 days).
Is there a way to lock/snap the x-Axis grid to an hourly scale?
While I believe this is a workaround, I was able to snap the grid to an hourly basis for up to 5 x-axis labels using the following code (where diff is the date range in days presented on the graph:
// Determine a reasonable scale that complies to an hourly grid (Assume no more than 5 labels on grid)
let hourRange = diff * 24.0
let interval = Int(hourRange.rounded(FloatingPointRoundingRule.up)) / 5
if (interval <= 0)
{
xAxis.granularity = 1.0 / 24.0
} else {
xAxis.granularity = 1.0 / 24.0 * Double(interval)
}

How to round off x-ticklabels to the nearest 50

I need to round off the X-ticklabels in an excel chart to the nearest 50. The charts are created in VBA, the data series is in a worksheet so I would be happy to use a solution in either. I have written the following function that rounds to the nearest 50:
Function RoundTo50(number As Double) As Double
RoundTo50 = WorksheetFunction.Round(number * 2, -2) / 2
End Function
I have applied it to the min and max x limits of the chart and it works for them, but I can't work out how to apply this to all the ticklabels in between. I thought of applying it to all the data before plotting but that would alter the plot which I don't want to do. I would prefer for the ticklabels to be slightly misaligned due the rounding.
Can you do this with a formatting string? Or any other way?
Thanks
So the answer is as follows (thanks to Sam Ward for the comment that pushed me in the right direction):
Use my RoundTo50() function to round of the min and max limits to the nearest 50. Calculate what the interval should be for a reasonable amount of grid lines, in my case 12. Round this interval to the nearest 50.
Function RoundTo50(number As Double) As Double
RoundTo50 = WorksheetFunction.Round(number * 2, -2) / 2
End Function
and
With Sheets("Report").ChartObjects.Add(...)
.Chart.Axes(xlCategory).MinimumScale = RoundTo50(Sheets(sheetName).Range("M4"))
.Chart.Axes(xlCategory).MaximumScale = RoundTo50(Sheets(sheetName).Range("M124"))
.Chart.Axes(xlCategory).MajorUnit = RoundTo50((.Chart.Axes(xlCategory).MaximumScale - .Chart.Axes(xlCategory).MinimumScale) / 12)
.Chart.Axes(xlCategory).MinorUnit = .Chart.Axes(xlCategory).MajorUnit / 3
I would still be very much interested in being able to do this with a formatting string though as I have a secondary axis in percent and the grid lines from rounding to 50 are slightly offset with the tick marks of the secondary axis. With a formatting string they would be perfectly aligned (because they would be slightly in the wrong place but I would prefer that).