Reputation: 1
I am trying to calculate the ATR for 15m candles of data given by a security function by using a modified TR (true range) and RMA function.
I'm nearly done but one thing I am missing and I can't figure out what the problem might be. Do you have any idea what's wrong? My calculated atr is shifted when comparing it to the native atr.
This is my code.
//@version=5
indicator("Table with Indicators", overlay=true, dynamic_requests=true)
if timeframe.period != "5"
log.error("This script runs on 5m timeframe only.")
label.new(bar_index, high, "Please use 5m timeframe only!", color=color.red, textcolor=color.white, size=size.small)
runtime.error("This script runs on 5m timeframe only.")
rma(x, y, preSumIndex) =>
alpha = y
var float sum = na
sum := (x + (alpha - 1) * nz(sum[preSumIndex])) / alpha
tr(_high, _low, preClose) =>
math.max(_high - _low, math.max(math.abs(_high - preClose), math.abs(_low - preClose)))
var float atr15 = na
var float trueRange = na
var fixChartTimeframe = timeframe.period
var timeframe = 15
period_length = timeframe/str.tonumber(fixChartTimeframe)
timeframe_in_ms = timeframe * 60 * 1000
length = 14
current_time = time
start_time = current_time - (current_time % timeframe_in_ms)
time_elapsed = (current_time - start_time) / 1000
// last_start = m15_start_time - timeframe_in_ms
bars_since_period_start = int(time_elapsed / (5 * 60)) // 5 Minuten = 300 Sekunden
int period_offset = math.round(bars_since_period_start % period_length)
pre_candle_index = period_offset + 1
[h5, l5, c5] = request.security(syminfo.tickerid, "5", [high, low, close], lookahead=barmerge.lookahead_off)
log.error(str.tostring(period_offset))
float h15 = h5[0]
float l15 = l5[0]
float c15 = c5[0]
bool isCandleEnd = (period_offset == period_length - 1) or barstate.islast
if period_offset > 0
h15 := ta.highest(h15, period_offset)
l15 := ta.lowest(l15, period_offset)
if isCandleEnd
trueRange := tr(h5, l5, c5[pre_candle_index])
atr15 := rma(trueRange, length, pre_candle_index)
atr15_native = request.security(syminfo.tickerid, str.tostring(timeframe), ta.atr(length), lookahead=barmerge.lookahead_off)
plot(atr15_native, title="ATR 15min native", color=color.red, linewidth=2)
plot(atr15, title="ATR 15min", color=color.blue, linewidth=2)
Upvotes: 0
Views: 22