Count green and red candles separately from the market open time

Viewed 28

In this code, I am getting the Green and red candle Counts being overwritten and it's not clearly shown in the chart and it leaves out the first candles at the market open time.. Guys, I want the gren and red candle counts separately including the first candle at the market open time and i dont want the overwritten counts and I want the correct counts..I am just a beginner..Please help me on this one..Thanks..

plot(close)
t = ta.change(time('D'))
up = close > open ? 1 : 0
dn = close < open ? 1 : 0
a = 0.
a := t ? up : a[1] + up
b = 0.
b := t ? dn : b[1] + dn
label.new(bar_index, high, str.tostring(a), textcolor=color.blue, style=label.style_none)
label.new(bar_index, high, str.tostring(b), textcolor=color.blue, style=label.style_none)
1 Answers

As far as I can see your code should count up and down bars correctly, except that up bar is when close >= open. In order for the values not to be overwritten and not to confuse you, you can delete the old labels on all bars except the first one.

Here is an example

//@version=5
indicator("Candles Up/Down Counts", overlay=true)
label upCountLbl = na
label dnCountLbl = na
upCounts = 0
dnCounts = 0

resetState = ta.change(time("1D"))

upBar = close >= open ? 1 : 0
dnBar = close < open ? 1 : 0

upCounts := resetState ? upBar : upCounts[1] + upBar
dnCounts := resetState ? dnBar : dnCounts[1] + dnBar

upCountLbl := label.new(bar_index, high, str.tostring(upCounts), textcolor=color.green, style=label.style_none, yloc=yloc.abovebar)
dnCountLbl := label.new(bar_index, high, str.tostring(dnCounts), textcolor=color.red, style=label.style_none, yloc=yloc.belowbar)
if not(resetState)
    label.delete(upCountLbl[1])
    label.delete(dnCountLbl[1])
Related