Search code examples
pine-scriptpine-script-v5

How to create Heikin Ashi Candles from scratch?


I am trying to build heikin ashi candle by myself. Based on the definition enter image description here

I am doing it like:


ha_close = (open + high + low + close)/4
ha_high = math.max(open , high, low , close)
ha_low = math.min(open , high, low , close)
var float ha_open = na
ha_open := na(ha_open[1]) ? (open + close)/2 : (ha_open[1] + ha_close[1]) / 2
plotcandle(ha_open, ha_high, ha_low, ha_close, title='Title', color = ha_open < ha_close ? color.rgb(161, 143, 239) : color.rgb(120, 134, 122, 40), wickcolor=ha_open < ha_close ? color.navy : color.rgb(120, 123, 134, 40),bordercolor = ha_open < ha_close ? color.navy : color.rgb(120, 123, 134, 40) )

The tricky part is ha_open and I am not sure how to do it...

Also, this the current version is not accurate, because use the HA candle of TV or if I do the following

[closeh,openh,lowh,highh] = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, [close,open,low,high])

plotcandle(openh, highh, lowh, closeh, title='Title', color = openh < closeh ? color.navy : color.rgb(120, 123, 134, 40), wickcolor=openh < closeh ? color.navy : color.rgb(120, 123, 134, 40),bordercolor = openh < closeh ? color.navy : color.rgb(120, 123, 134, 40) )

the charts dont match.


Solution

  • Your formula is almost correct. You need to use the calculated open and close prices in high and low calculations.

    Also, for the high and low calculations, you need to pass three variables and not four.

    Here is the code for you.

    I have also added a test code that compares the calculated values with the results from the security() call. It should change the background color to red if there is any mismatch. I did not see any :)

    //@version=5
    indicator("HA", overlay=true)
    
    var float ha_open = na
    ha_close = (open + high + low + close)/4
    ha_open := na(ha_open[1]) ? (open + close)/2 : (ha_open[1] + ha_close[1]) / 2
    ha_high = math.max(ha_open , high, ha_close)
    ha_low = math.min(ha_open , low , ha_close)
    
    [closeh,openh,lowh,highh] = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, [close,open,low,high])
    
    is_not_correct = (ha_close != closeh) or (ha_open != openh) or (ha_high != highh) or (ha_low != lowh)
    
    bgcolor(is_not_correct ? color.red : na)
    
    plotcandle(ha_open, ha_high, ha_low, ha_close, title='Title', color = ha_open < ha_close ? color.rgb(161, 143, 239) : color.rgb(120, 134, 122, 40), wickcolor=ha_open < ha_close ? color.navy : color.rgb(120, 123, 134, 40),bordercolor = ha_open < ha_close ? color.navy : color.rgb(120, 123, 134, 40) )