This snippet separates the real-time, intra-candle volume into up-volume and down-volume based on whether the last price update moved higher or not. It solves the problem of seeing buying vs. selling pressure building during a candle rather than only after the candle closes.
if not isset($volumes[barindex]) then
$volumesUp[barindex] = 0
$volumesDn[barindex] = 0
$volumes[barindex] = 0
$lastPrice[barindex] = close
endif
if islastbarupdate then
diff=volume-$volumes[barindex]
if close>$lastPrice[barindex] then
$volumesUp[barindex]=$volumesUp[barindex]+diff
else
$volumesDn[barindex]=$volumesDn[barindex]+diff
endif
$lastPrice[barindex] = close
$volumes[barindex] = volume
endif
return $volumesUp[barindex] coloured("lightgreen") style(histogram,2), -$volumesDn[barindex] coloured("crimson") style(histogram,2)
Code Logic
- isset($volumes[barindex]): Initializes per-bar storage the first time the script encounters a bar, preventing undefined values.
- $volumesUp[barindex]: Accumulates the incremental volume (diff) when the latest update’s close is greater than the stored $lastPrice, treating it as up-tick volume.
- $volumesDn[barindex]: Accumulates the incremental volume (diff) when price did not move up (i.e., close is less than or equal to $lastPrice), treating it as down/neutral tick volume.
- $volumes[barindex]: Stores the last known volume value for the current bar so the script can compute only the newly added volume since the previous update.
- $lastPrice[barindex]: Stores the last observed close for the bar; it is the reference used to classify the next update as up or down.
- islastbarupdate: Ensures the accumulation logic runs only on the actively forming candle (the last bar), where volume and price are updating in real time.
- diff = volume – $volumes[barindex]: Calculates the incremental volume added since the last update; this is the amount assigned to up-volume or down-volume.
- return … histogram: Plots up-volume as a positive light-green histogram and down-volume as a negative crimson histogram (using – $volumesDn) so both sides are visually separated around the zero line.