Search code examples
pine-scriptalgorithmic-tradingtrading

TradingView HeikenAhi algorithm


I try to calculate heiken ashi OHLC on tradingview panel .
Please note:
enter image description here

this picure is for ADAUSDTPERP at 21/Oct/2021 (Daily Timeframe)
left side is normal candle and right is Heiken Ashi.
OHLC of second candle (Left side) is :

O: 2.1121   
H: 2.2102    
L: 2.0939 
C: 2.1924 

According to Heiken Ashi algorithm :
Open = (Open(Previous candle) + Close(Previous candle))/2

so :

(2.1121 + 2.1924)/2 = 2.15225

but in tradingview heiken ashi Open candle by 2.1470 ! (last candle right side)
How tradingview calculate that ?
I miss somethings ?!


Solution

  • Open = (Open(Previous candle) + Close(Previous candle))/2
    

    To calculate the heikin ashi open value take into account the previous values of haOpen and haClose instead of regular candle's open and close. Use the regular candle values only on the very first bar to calculate the first value in the series, as is shown below:

    float haClose = ohlc4
    var float haOpen = na
    
    if barstate.isfirst
        haOpen := (open + close) / 2
    else
        haOpen := (nz(haOpen[1]) + nz(haClose[1])) / 2
    

    You can find the open-source example that match the built-in Tradingview's HA candles in the public library: https://www.tradingview.com/script/qRNix8Bh-Heiken-Ashi-Candles/