Using time_of(), library(), function()
This script paints Volume histogram with an "average volume for given time" line atop of it. This average volume is average volume for a given time of a day (i.e, 09:30) at a given time frame. In case if the current candle's volume is above the "typical volume for that time of a day" then its histogram column will be dark. Otherwise, it will be pale.
Example of reading it: avg volume for 09:30 at SPY,10 is 2.45M. Today it's 2.0M which is below the average, so the volume column will be pale.
describe_indicator('Volume by time', 'lower');
if (isNaN(constants.resolution)) {
throw Error('This indicator can only work on intraday charts');
}
const tinycolor = library('tinycolor2');
const volumeByTime = {};
const lookbackPeriod = input('Lookback', 5, { min: 1, max: 10 });
function computeAverageVolume(candleVolume, candleTime) {
const timeOfDay = time_of(candleTime);
const timeHash = `${timeOfDay.hours}:${timeOfDay.minutes}`;
if (!volumeByTime[timeHash]) {
volumeByTime[timeHash] = [];
}
const avgVolume = volumeByTime[timeHash].
slice(-lookbackPeriod).
reduce((result, value) => result + value, 0) / lookbackPeriod;
volumeByTime[timeHash].push(candleVolume);
return volumeByTime[timeHash].length >= lookbackPeriod + 1
? avgVolume
: null;
}
const averageVolumes = for_every(volume, time, computeAverageVolume);
const volumeColors = for_every(close, open, averageVolumes, volume, (c, o, avg, vol) => {
if (vol > avg) {
return c > o ? '#009900' : '#ee0000';
}
return c > o ? '#cddfcc' : '#ffe7e7';
});
paint(averageVolumes, { style: 'line', color: 'blue' });
paint(volume, { style: 'histogram', color: volumeColors });