'Pine Script: Is there a way to only consider specific hours of the day when calculating averages?
For example: I'm using the following code to calculate the average daily volume of the past 7 days:
isess = session.regular
t = ticker.new(syminfo.prefix, syminfo.ticker, session=isess)
AvgVol7 = ta.sma(volume, 7)
SecAvgVol7 = request.security(t, 'D', AvgVol7[1], gaps=barmerge.gaps_off , lookahead=barmerge.lookahead_on)
But what I would like to do is to calculate the same average daily volume of the past 7 days, but only consider hours from 6am to 6pm. Is there a way to do that?
Solution 1:[1]
//@version=5
indicator("Custom Range Daily Volume", overlay = false)
start_hr = input.int(6, title = "Start hour")
end_hr = input.int(18, title = "End hour")
num_days = input.int(7, title = "Number of days")
var float[] daily_volumes = array.new_float()
var float todays_volume = 0.0
new_day = ta.change(time("D")) != 0
eod_time_close = request.security(syminfo.tickerid, "D", time_close, barmerge.gaps_off, barmerge.lookahead_on)
in_time_range = hour >= start_hr and hour < end_hr
is_eod = time_close == eod_time_close and barstate.isconfirmed
if new_day
todays_volume := 0.0
else if in_time_range
todays_volume += volume
if is_eod
array.unshift(daily_volumes, todays_volume)
if array.size(daily_volumes) > num_days
array.pop(daily_volumes)
float daily_avg_vol = na
float repainting_avg_vol = na
if array.size(daily_volumes) == num_days
daily_avg_vol := array.avg(daily_volumes)
repainting_avg_vol := in_time_range ? (array.sum(daily_volumes) - array.get(daily_volumes, num_days - 1) + todays_volume) / num_days : na
plot(daily_avg_vol)
plot(fixnan(repainting_avg_vol), color = in_time_range ? color.yellow : color.gray, style = plot.style_circles)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rumpypumpydumpy |
