Heikin Ashi For ThinkOrSwim

Vision

Member
2019 Donor
I want to play around with pairs trading and using Heikin Ashi on a lower chart with a second symbol. Turns out Heikin Ashi code doesn't seem to work with code not in the upper chart. There seems to be problems with the simple arrays being created. Anybody have some ideas or is this a limitation of thinkscript?
 

Drgrcrpilot

New member
Hi, I understand the need to use heikin ashi candles for the averages and to smooth out the chart. but, is there a way to run normal candlestick bars like a shadow/overlay? I like to watch the exact price point. (Yes I know I can watch the bid/ask, but i like to watch the candle forming). Thanks
 

BenTen

Administrative
Staff member
Staff
VIP
Lifetime
@Drgrcrpilot You can use this code below to display Heikin Ashi as a lower study:

Code:
#TSI_HeikinAshi_Bars
# (c) 2009
#Copyright Authorship: ThinkSwimIndicators.com


#==========================================================================
# >>>                H E I K I N - A S H I   B A R S                  <<< [
#.........................................................................[
#                                                                         [
#                         -----=== O ===-----                             [
#                                                                         [
#****COPYRIGHT NOTICE:  "Heikin-Ashi Bars" is free to use by the general  [
# public. Distribution or modification is prohibited. All content, form,  [
# and style, likewise, is protected by copyright.                         [
#                                                                         [
#                         -----=== x ===-----                             [
#                                                                         [
# ThinkSwimIndicators.com  will  CONTINUE  to release FREE indicators--of [
# the  highest quality and caliber--for the Thinkorswim Trading platform, [
# for use by all.  Many of our free indicators surpass the Quality & Use- [
# fulness of indicators offered for "purchase" by other sites. We suggest [
# that  you  visit the free "Learning Center"  at our website for further [
# information on the use of this indicator. "GO: Master the Markets!" (TM)[
#==========================================================================


declare lower;

def haclose = (open + high + low + close) / 4;
rec haopen = compoundValue(1, (haopen[1] + haclose[1]) / 2, (open[1] +
close[1]) / 2);
def diff = haclose - haopen;

plot HA_Down = if  diff > 0 and diff[1] >= 0 then 0 else 1;
plot HA_Up = if diff < 0 and diff[1] <= 0 then 0 else 1;

HA_Up.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
HA_Up.AssignValueColor(color.GREEN);
HA_Up.SetLineWeight(5);

HA_Down.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
HA_Down.AssignValueColor(color.RED);
HA_Down.SetLineWeight(5);
 

Moose

Member
This will show you the exact price point on Heikin Ashi

Code:
# sdi_closeLevel
plot cl = close;
cl.setpaintingStrategy(PaintingStrategy.HORIZONTAL);
#hint: plot the close level as a horizontal line with the color determined by its relationship to the heiken-ashi body.
cl.defineColor("above h-a body", color.GREEN);
cl.defineColor("inside h-a body", color.dark_gray);
# author: allen everhart
# date: 7jun2015
cl.defineColor("below h-a body", color.RED);
# copylefts reserved. This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
# Help me get the word out about my blog by keeping this header
# in place.
cl.assignValueColor(
    if close>ohlc4 && heikinAshiDiff()>0 then cl.color("above h-a body")
    else if close<ohlc4 && heikinAshiDiff()<0 then cl.color("below h-a body")
# copylefts reserved. This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
    else if heikinAshiDiff()<0 and close>ohlc4-heikinAshiDiff() then  cl.color("above h-a body")
    else if heikinAshiDiff()>0 and close<ohlc4-heikinAshiDiff() then cl.color("below h-a body")
    else cl.color("inside h-a body"));
 

Parker427

New member
Can’t believe no one has done this but can someone create the “heikin ashi” indicator into the candles? I’m trying to see if it does a better job than the TTM trend. Or if theirs a code out their can someone link it?
 

BenTen

Administrative
Staff member
Staff
VIP
Lifetime
What do you mean create the heikin ashi indicator into the candles? Are you trying to display heikin ashi candlesticks on your chart? Or do you want to overlay heikin ashi candles on top of the default candles?
 

Parker427

New member
What do you mean create the heikin ashi indicator into the candles? Are you trying to display heikin ashi candlesticks on your chart? Or do you want to overlay heikin ashi candles on top of the default candles?
I’m just looking for the indicator. The coding for it. I’ve looked everywhere. I just want it displayed on my chart, not overlap current candles
 

Pensar

Well-known member
VIP
Lifetime
@Parker427 Maybe this is what you're looking for? Full credit goes to MTS1 of the TSL.

Code:
# HeikinAshiPaintBars_MTSmod180412
# MTS1 1804 based on JQ shared script TSL
# http://tos.mx/jKArTG##
# Updated formula based on http://stockcharts.com/school/doku.php?id=chart_school:chart_analysis:heikin_ashi which seems to match ToS HA Chart

def o = open;
def h = high;
def l = low;
def c = close;
def HAopen;
def HAhigh;
def HAlow;
def HAclose;
HAopen = CompoundValue(1, (haopen[1] + haclose[1]) / 2, (o[1] + c[1]) / 2);
HAhigh = Max(Max(h, haopen), haclose[1]);
HAlow = Min(Min(l, haopen), haclose[1]);
HAclose = (open + high + low + close) / 4;
AssignPricecolor(if haclose > haopen
                 then Color.Green
                 else Color.Red);

and here is a MTF version -

Code:
# HeikinAshiPaintBars_MTSmod180412
# MTS1 1804 based on JQ shared script TSL
# http://tos.mx/jKArTG##
# Updated formula based on http://stockcharts.com/school/doku.php?id=chart_school:chart_analysis:heikin_ashi which seems to match ToS HA Chart
# Pensar - added MTF 7/30/2020

input agg = aggregationPeriod.TEN_MIN;

def o = open(period = agg);
def h = high(period = agg);
def l = low(period = agg);
def c = close(period = agg);
def HAopen;
def HAhigh;
def HAlow;
def HAclose;
HAopen = CompoundValue(1, (haopen[1] + haclose[1]) / 2, (o[1] + c[1]) / 2);
HAhigh = Max(Max(h, haopen), haclose[1]);
HAlow = Min(Min(l, haopen), haclose[1]);
HAclose = (o + h + l + c) / 4;
AssignPricecolor(if haclose > haopen
                 then Color.Green
                 else Color.Red);
 

Chence27

Active member
Does anyone know of a way to combine Heikin Ashi and Japanese candlesticks together in one chart? I'd like a way to see the true price of the bar, which usually isn't shown with HA.
 

barbaros

Well-known member
Here is a stupid version to test performance. I didn't spend more than a few minutes on this and I am not familiar with how to use it. Excuse the poor coding and interpretation if I am wrong. You need to add it as a strategy.

Y7U9TSJ.png


Python:
#study(title = "Smoothed Heiken Ashi Candles", shorttitle="Smoothed Ha Candles", overlay=true)
#translated and modified by BLT 20170804
#v1 - added HACO (HACOLT by S Vervoot) and HACO_Mod (by D Valcu) smoothing options
#version whatever - added orders for strategy testing by Barbaros

input onlyTradeTime = yes;
input startTime = 930;
input stopTime = 1500;
def tradeTime = if onlyTradeTime then SecondsFromTime(startTime) >= 0 and SecondsTillTime(stopTime) >= 0 else yes;

input candleSmoothing = {default HACO, HACO_Mod};

input avg = averageType.EXPONENTIAL;
input len = 8;#=input(10)
def o = movingAverage(avg,open, len);
def c = movingAverage(avg,close, len);
def h = movingAverage(avg,high, len);
def l = movingAverage(avg,low, len);

def HAopen;
def HAclose;
switch(candleSmoothing) {
    
case HACO:
    haOpen = CompoundValue(1, ( (haOpen[1] + (o[1] + h[1] + l[1] + c[1]) /4)/2), open);
    haClose = ((((O + H + L + C)/4) + haOpen + Max(H, haOpen) + Min(L, haOpen))/4);

case HACO_Mod:

    haOpen = CompoundValue(1, ( (haOpen[1] + (o[1] + h[1] + l[1] + c[1]) /4)/2), open);
    haClose = ((o + h + l + c)/4) ;
}
def HAhigh    = Max( h, Max( HAopen, HAclose ) );
def HAlow     = Min( l, Min( HAopen, HAclose ) );

input len2 = 17;#input(10)
def o2 = movingAverage(avg,HAopen, len2);
def c2 = movingAverage(avg,HAclose, len2);
def h2 = movingAverage(avg,HAhigh, len2);
def l2 = movingAverage(avg,HAlow, len2);

input charttype=chartType.CANDLE;
def o3 = o2;
def h3 = h2;
def l3 = l2;
def c3 = c2;

input nowicks = yes;

def o4 = if o3<c3 then if nowicks then l3 else o3 else double.nan;
def c4 = if o3<c3 then if nowicks then h3 else c3 else double.nan;
def h4 = if o3<c3 then h3 else double.nan;
def l4 = if o3<c3 then l3 else double.nan;

def o5 = if o3 >=c3 then if nowicks then h3 else o3 else double.nan;
def h5 = h3;
def l5 = l3;
def c5 = if o3 >=c3 then if nowicks then l3 else  c3 else double.nan;

AddOrder(type = OrderType.BUY_AUTO, tradeSize = 1, condition = !isNaN(c4) and tradeTime);
AddOrder(type = OrderType.SELL_AUTO, tradeSize = 1, condition = !isNaN(c5) and tradeTime);

AddOrder(type = OrderType.SELL_TO_CLOSE, tradeSize = 1, condition = !tradeTime);
AddOrder(type = OrderType.BUY_TO_CLOSE, tradeSize = 1, condition = !tradeTime);
 

Seeder

New member
Hello,
I am new here.
Can Someone help build a script to display Heikin Ashi chart as Regular (OHLC) bars? (meaning to use OHLC of Heinkin Ashi bars and dispaly it in regular bars, not candles)?
 

TomTim

New member
Hello,
I found what I was looking for in this post. Some of the questions here was asking for displaying Heinkin Ashi candle on the same chart of the standard candle. I didn't see any code posted, so here it is:

#Draw the Heinkin Ashi candle
def HAhigh;
def HAlow;
def HAclose;
rec HAopen = CompoundValue(1, (HAopen[1] + HAclose[1]) / 2, (open[1] + close[1]) / 2);
HAclose = (open + high + low + close) / 4;
HAhigh = Max(Max(high, HAopen), HAclose[1]);
HAlow = Min(Min(low, HAopen), HAclose[1]);
def HA_open = round(HAopen, 2);
def diff = HAclose - HAopen;

AddChart(HAhigh, HAlow, HA_open, HAclose, type = ChartType.candle, growcolor = color.light_orange);


#Edit the plot for these as boolean type and use up/down arrow to show on your chart if you want to add Heinkin Ashi Signal for trend changing
plot HA_Down = if diff > 0 and diff[1] <= 0 then 1 else 0;
plot HA_Up = if diff < 0 and diff[1] >= 0 then 1 else 0;
 

OGK

New member
Here is a stupid version to test performance. I didn't spend more than a few minutes on this and I am not familiar with how to use it. Excuse the poor coding and interpretation if I am wrong. You need to add it as a strategy.

Y7U9TSJ.png


Python:
#study(title = "Smoothed Heiken Ashi Candles", shorttitle="Smoothed Ha Candles", overlay=true)
#translated and modified by BLT 20170804
#v1 - added HACO (HACOLT by S Vervoot) and HACO_Mod (by D Valcu) smoothing options
#version whatever - added orders for strategy testing by Barbaros

input onlyTradeTime = yes;
input startTime = 930;
input stopTime = 1500;
def tradeTime = if onlyTradeTime then SecondsFromTime(startTime) >= 0 and SecondsTillTime(stopTime) >= 0 else yes;

input candleSmoothing = {default HACO, HACO_Mod};

input avg = averageType.EXPONENTIAL;
input len = 8;#=input(10)
def o = movingAverage(avg,open, len);
def c = movingAverage(avg,close, len);
def h = movingAverage(avg,high, len);
def l = movingAverage(avg,low, len);

def HAopen;
def HAclose;
switch(candleSmoothing) {
   
case HACO:
    haOpen = CompoundValue(1, ( (haOpen[1] + (o[1] + h[1] + l[1] + c[1]) /4)/2), open);
    haClose = ((((O + H + L + C)/4) + haOpen + Max(H, haOpen) + Min(L, haOpen))/4);

case HACO_Mod:

    haOpen = CompoundValue(1, ( (haOpen[1] + (o[1] + h[1] + l[1] + c[1]) /4)/2), open);
    haClose = ((o + h + l + c)/4) ;
}
def HAhigh    = Max( h, Max( HAopen, HAclose ) );
def HAlow     = Min( l, Min( HAopen, HAclose ) );

input len2 = 17;#input(10)
def o2 = movingAverage(avg,HAopen, len2);
def c2 = movingAverage(avg,HAclose, len2);
def h2 = movingAverage(avg,HAhigh, len2);
def l2 = movingAverage(avg,HAlow, len2);

input charttype=chartType.CANDLE;
def o3 = o2;
def h3 = h2;
def l3 = l2;
def c3 = c2;

input nowicks = yes;

def o4 = if o3<c3 then if nowicks then l3 else o3 else double.nan;
def c4 = if o3<c3 then if nowicks then h3 else c3 else double.nan;
def h4 = if o3<c3 then h3 else double.nan;
def l4 = if o3<c3 then l3 else double.nan;

def o5 = if o3 >=c3 then if nowicks then h3 else o3 else double.nan;
def h5 = h3;
def l5 = l3;
def c5 = if o3 >=c3 then if nowicks then l3 else  c3 else double.nan;

AddOrder(type = OrderType.BUY_AUTO, tradeSize = 1, condition = !isNaN(c4) and tradeTime);
AddOrder(type = OrderType.SELL_AUTO, tradeSize = 1, condition = !isNaN(c5) and tradeTime);

AddOrder(type = OrderType.SELL_TO_CLOSE, tradeSize = 1, condition = !tradeTime);
AddOrder(type = OrderType.BUY_TO_CLOSE, tradeSize = 1, condition = !tradeTime);
I was on tradingview and really have been testing this SSS indicator, going to copy paste the code below. I am **** at coding but this was very close to what you posted.
I was not able to use your code above in TOS not sure why or if i need to change some chart settings etc.....
anyways here is a code if anyone can help translate this to thinkscript or update your code with parts of this code.

Code:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sultan_shaya

//@version=5
strategy("SSS", overlay=true, initial_capital=1000,currency=currency.USD,default_qty_type=strategy.percent_of_equity,default_qty_value=100,pyramiding=0)
//SSS = Sultan+Saud Strategy

//The original idea of the code belonges to saudALThaidy
//The strategy code is basically made out of two other indicators, edited and combined by me.
// 1- NSDT HAMA Candles => https://www.tradingview.com/script/k7nrF2oI-NSDT-HAMA-Candles/
// 2- SSL Channel => https://www.tradingview.com/script/6y9SkpnV-SSL-Channel/


//MA INFO
WickColor = input.color(color.rgb(80, 80, 80, 100), title='Wick Color', tooltip='Suggest Full Transparency.')
LengthMA = input.int(100, minval=1, title='MA Line Length', inline='MA Info')
TakeProfit = input.float(1, minval=0, title='Take Profit Percentage', step=1)
UseStopLose = input.bool(false, title='Use Stop Percentage')
StopLose = input.float(1, minval=0, title='StopLose Percentage', step=1)

MASource = close

ma(source, length, type) =>
    type == "SMA" ? ta.sma(source, length) :
     type == "EMA" ? ta.ema(source, length) :
     type == "SMMA (RMA)" ? ta.rma(source, length) :
     type == "WMA" ? ta.wma(source, length) :
     type == "VWMA" ? ta.vwma(source, length) :
     na

ma1_color  = color.green
ma1 = ma(high, 200, "SMA")

ma2_color  = color.red
ma2 = ma(low, 200, "SMA")

Hlv1 = float(na)
Hlv1 := close > ma1 ? 1 : close < ma2 ? -1 : Hlv1[1]
sslUp1   = Hlv1 < 0 ? ma2 : ma1
sslDown1 = Hlv1 < 0 ? ma1 : ma2

Color1 = Hlv1 == 1 ? ma1_color : ma2_color
fillColor1 = color.new(Color1, 90)

highLine1 = plot(sslUp1, title="UP", linewidth=2, color = Color1)
lowLine1 = plot(sslDown1, title="DOWN", linewidth=2, color = Color1)

OpenLength = 25
HighLength = 20
LowLength = 20
CloseLength = 20


    
SourceOpen = (open[1] + close[1]) / 2
SourceHigh = math.max(high, close)
SourceLow = math.min(low, close)
SourceClose = (open + high + low + close) / 4

funcCalcMA1(src1, len1) => ta.ema(src1, len1)
funcCalcOpen(SourceOpen, OpenLength) => ta.ema(SourceOpen, OpenLength)
funcCalcHigh(SourceHigh, HighLength) => ta.ema(SourceHigh, HighLength)
funcCalcLow(SourceLow, LowLength) => ta.ema(SourceLow, LowLength)
funcCalcClose(SourceClose, CloseLength) => ta.ema(SourceClose, CloseLength)

MA_1 = funcCalcMA1(MASource, LengthMA)

CandleOpen = funcCalcOpen(SourceOpen, OpenLength)
CandleHigh = funcCalcHigh(SourceHigh, HighLength)
CandleLow = funcCalcLow(SourceLow, LowLength)
CandleClose = funcCalcClose(SourceClose, CloseLength)

//PLOT CANDLES
//-------------------------------NSDT HAMA Candels
BodyColor = CandleOpen > CandleOpen[1] ? color.green : color.red
barcolor(BodyColor)
plotcandle(CandleOpen, CandleHigh, CandleLow, CandleClose, color=BodyColor, title='HAMA Candles', wickcolor=WickColor, bordercolor=na)
plot(MA_1, title='MA Line', color=BodyColor, style=plot.style_line, linewidth=2)

//------------------------------SSL Channel


plot_buy = false
avg = ((high-low)/2)+low
LongCondition = (Hlv1 == 1 and Hlv1[1] == -1) and (BodyColor == color.green) and (MA_1 < avg) and (CandleHigh < avg) and (strategy.opentrades == 0)
if LongCondition
    strategy.entry("BUY HERE", strategy.long)
    plot_buy := true

base = strategy.opentrades.entry_price(0)
baseProfit = (base+((base/100)*TakeProfit))
baseLose = (base-((base/100)*StopLose))

strategy.exit("SELL HERE","BUY HERE",limit = baseProfit)
if UseStopLose and (close < MA_1)
    strategy.exit("SELL HERE","BUY HERE",stop = baseLose)
if not UseStopLose and (close < MA_1)
    strategy.exit("SELL HERE","BUY HERE", stop = close)
    
plotshape(plot_buy, title="Buy Label", text="Buy", location=location.belowbar, style=shape.labelup, size=size.tiny, color=Color1, textcolor=color.white)

fill(highLine1, lowLine1, color = fillColor1)
 

HotLemon

New member
Median Renko Bars
#Chart Setting - Time Axis - Range - 4 Tick - Renko Bars

input period = 1;
input length = 1;
input hideCandles = yes;
input Points = 1.0;
HidePricePlot(hideCandles);

def base = average(MidBodyVal(),length);
def CBB = if (base > high, base[1]+ Points, base - Points);
def CBT = if (base < low, base[1] + Points, base + Points);
def openMA = CompoundValue(1, ExpAverage(open, period), open);
def closeMA = CompoundValue(1, ExpAverage(close, period), close);
def highMA = CompoundValue(1, ExpAverage(high, period), high);
def lowMA = CompoundValue(1, ExpAverage(low, period), low);

def haOpen = CompoundValue(1,((haOpen[1] + (openMA[1] + highMA[1] + lowMA[1] + closeMA[1] + midBodyVal()) / 5.0) / 2.0), open);
def haClose = ((openMA + highMA + lowMA + closeMA) / 4.0) ;
#candles
def High_fall = if haOpen >= haClose
then high #then haHigh
else Double.NaN;
def Low_fall = if haOpen >= haClose
then low#then haLow
else Double.NaN;
AddChart(growColor = Color.plum,high = High_fall, low = Low_fall,open = cbt, close = cbb , type = ChartType.CANDLE);
def High_rise = if haOpen <= haClose
then high#then haHigh
else Double.NaN;
def Low_rise = if haOpen <= haClose
then low#then haLow
else Double.NaN;
AddChart(growColor = Color.white, high = High_rise, low = Low_rise, open = cbt, close = cbb, type = ChartType.CANDLE);
#:)
 
Last edited by a moderator:

Mocnarf1

Member
Here is a Strategy Script using HeikenAshi . Take a look it may give you some ideas.

Code:
# Test script Strategy with HeikenAshi  MACD SMA

def buy =
HeikinAshiDiff()."HADiff" from 1 bars ago is less than 0 
and HeikinAshiDiff()."HADiff" is greater than 0 
and close is greater than open 
and low is less than SimpleMovingAvg()."SMA" from 1 bars ago 
and SimpleMovingAvg()."SMA" is greater than or equal to SimpleMovingAvg()."SMA" from 1 bars ago 
and MACDHistogram()."Diff" is greater than or equal to MACDHistogram()."Diff" from 1 bars ago 
OR
HeikinAshiDiff()."HADiff" from 1 bars ago is less than 0 
and HeikinAshiDiff()."HADiff" is greater than 0
and close is greater than open 
and MACDHistogram()."Diff" is greater than MACDHistogram()."Diff" from 1 bars ago
;


def sell =
HeikinAshiDiff()."HADiff" from 1 bars ago is greater than 0 
and HeikinAshiDiff()."HADiff" is less than 0 
and close is less than open 
and MACDHistogram()."Diff" is less than or equal to MACDHistogram()."Diff" from 1 bars ago
OR
HeikinAshiDiff()."HADiff" from 1 bars ago is greater than 0 
and HeikinAshiDiff()."HADiff" is less than 0 
and close is less than open 
and SimpleMovingAvg()."SMA" is less than or equal to SimpleMovingAvg()."SMA" from 1 bars ago  
;

AddOrder(OrderType.BUY_To_open, buy, name = "CrossoverBUY", tickColor = Color.DARK_RED, arrowColor = Color.DARK_RED);
AddOrder(OrderType.SELL_TO_CLOSE, sell, name = "CrossoverSell", tickColor = Color.DARK_GREEN, arrowColor = Color.DARK_GREEN);
 

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Top