Heikin_Ashi Indicator For ThinkOrSwim

thought as much, but all i get are a bunch of errors, so i must be doing something boneheaded. if you get a moment, could you have a look-see at my code; conversely, i'll keep on trying to sort it out myself. thanks!

Code:
#Heiken_Ashi based on Sylvan Verboort's Trading with HA Candlestick Oscillator
#Bon Bon _last update Jan 17th 2021
#Influenced by script from HoboTheClown / blt,http://www.thinkscripter.com, TD Hacolt etc.
#MTF based on HannTech's MTF_MACD script
#update 1/2/21 - changed the default moving average to TEMA.  Changed the period to 35.
#update changed reversal arrows to reversal bubbles with price

### YOU MUST HAVE THE STYLE SETTING FIT STUDIES ENABLED ###
#hint: The style setting Fit Studies must be enabled to use these bars.


input period = 50;
input hideCandles = yes;
input candleSmoothing = {default Valcu, Vervoort};
input show_bubble_labels = yes;
input bubbles = yes;
input arrows = yes;


#input smoothingLength = 3;

input movingAverageType = {default  TEMA, Exponential, Hull };

def openMA;
def closeMA;
def highMA;
def lowMA;

switch (movingAverageType) {
case Exponential:
    openMA = CompoundValue(1, ExpAverage(open, period), open);
    closeMA = CompoundValue(1, ExpAverage(close, period), close);
    highMA = CompoundValue(1, ExpAverage(high, period), high);
    lowMA = CompoundValue(1, ExpAverage(low, period), low);

case Hull:
    openMA = CompoundValue(1, HullMovingAvg(open, period), open);
    closeMA = CompoundValue(1,  HullMovingAvg(close, period), close);
    highMA = CompoundValue(1,  HullMovingAvg(high, period), high);
    lowMA = CompoundValue(1,  HullMovingAvg(low, period), low);

case TEMA:
    openMA = CompoundValue(1, TEMA(open, period), open);
    closeMA = CompoundValue(1, TEMA(close, period), close);
    highMA = CompoundValue(1, TEMA(high, period), high);
    lowMA = CompoundValue(1, TEMA(low, period), low);

}


HidePricePlot(hideCandles);

def haOpen;
def haClose;

switch (candleSmoothing){
case Valcu:
    haOpen = CompoundValue(1, ( (haOpen[1] + (openMA[1] + highMA[1] + lowMA[1] + closeMA[1]) / 4.0) / 2.0), open);
    haClose = ((((openMA + highMA + lowMA + closeMA) / 4.0) + haOpen + Max(highMA, haOpen) + Min(lowMA, haOpen)) / 4.0);
case Vervoort:
    haOpen = CompoundValue(1, ( (haOpen[1] + (openMA[1] + highMA[1] + lowMA[1] + closeMA[1]) / 4.0 ) / 2.0), open);
    haClose = ((((openMA + highMA + lowMA + closeMA) / 4.0) + haOpen + Max(highMA, haOpen) + Min(lowMA, haOpen)) / 4.0);

}

plot o = haOpen;
o.Hide();

def haLow =  Min(lowMA, haOpen);
def haHigh = Max(highMA, haOpen);

#Zero Lag System - MetaStock Crossover Formula
#zero-lagging principle
#Zero-lagging TEMA average on closing prices

#Medium-term price reversals - upward trend

def avg = 34;
def TMA1 = reference TEMA(haClose, avg); # triple exponential moving average (TEMA) of 34 bars
def TMA2 =  reference TEMA(TMA1, avg);
def Diff = TMA1 - TMA2;
def ZlHa = TMA1 + Diff; #Zero-lagging TEMA average on closing prices - medium term uptrend;

#Medium-term price reversals - downward trend
def TMA1_ = reference TEMA((high + low) / 2, avg);
def Diff2 = TMA1_ - TMA2;
def ZlCl = TMA1_ + Diff2; #Zero-lagging TEMA average on closing prices - medium term doenwardtrend;

def ZlDif = ZlCl - ZlHa; # Zero-Lag close - Zero-Lag HA(green candle) Uptrend when ZlDif is equal to or greater than zero

#uptrend {green candle}
def keep1 = if (haClose >= haOpen and haClose[1] >= haOpen[1]) then 1 else 0;
def keep2 = if ZlDif >= 0 then 1 else 0;
def keep3 = if (AbsValue(close - open) < ((high - low) * 0.35)) and high >= low[1] then 1 else 0;
def keeping = if (keep1 or keep2) then 1 else 0;
def keepall = if keeping or (keeping[1]) and close >= open or close >= (close[1]) then 1 else 0;

def utr = if keepall or (keepall[1]) and keep3 then 1 else 0;

#downtrend red candle

def keep1_ = if (haClose < haOpen and haClose[1] < haOpen[1]) then 1 else 0;
def keep2_ = if ZlDif < 0 then 1 else 0;
def keep3_ = if (AbsValue(close - open) < ((high - low) * 0.35)) and low <= high[1] then 1 else 0;
def keeping_ = if (keep1_ or keep2_) then 1 else 0;
def dkeepall_ = if keeping_ or (keeping_[1]) and close < open or close < (close[1]) then 1 else 0;

def dtr = if dkeepall_ or (dkeepall_[1] - 1) and keep3_ == 1 then 1 else 0;  #downtrend
def upw = if dtr and (dtr[1]) and utr then 1 else 0;
def dnw = if !utr and (utr[1] ) and dtr then 1 else 0;

def results = if upw then 1 else if dnw then 0 else results[1];

#Change the color of HA and Japanese Candles - turn off to show only HA on chart
AssignPriceColor(if haClose >= haOpen
                then Color.GREEN else
                if  haClose < haOpen
                then Color.RED else Color.WHITE);


#Heiken_A script

#####################################################################################################
input charttype = ChartType.CANDLE;

def haopen_ = if haClose <= haOpen
              then haOpen + 0
             else Double.NaN;

def HAhi   = if haClose <= haOpen
              then haHigh
              else Double.NaN;

def HAlo =   if haClose <= haOpen
              then haLow
              else Double.NaN;


AddChart(growColor = Color.RED, neutralColor = Color.CURRENT, high = HAhi, low = HAlo, open = haopen_, close = haClose, type = ChartType.CANDLE);

def HAclose1 = ohlc4;
def HAopen1  = if haClose >= haOpen
               then CompoundValue(1, (haOpen[1] + haClose[1]) / 2, (open[1] + close[1]) / 2)   
               else Double.NaN;

def haopen_1 = if haOpen <= haClose
               then HAopen1 + 0  else Double.NaN;

def HAhigh1  = haHigh;
def HAlow1   = haLow;


AddChart(growColor = Color.GREEN, neutralColor = Color.CURRENT,  high = HAhigh1, low = HAlow1, open = haopen_1, close = haClose, type = ChartType.CANDLE);

#####################################################################################################
#Buy and sell signals
def trend =  haClose >= haOpen; #high color;
def trendup = trend and !trend[1];
def trendd =  haClose < haOpen;
def trendDown = trendd and !trendd[1];

AddChartBubble(bubbles and trendup and trendup, HAlow1, ("Reversal:"    + round(HAlow1, 2)), Color.GREEN, no);

AddChartBubble(bubbles and trendDown and trendDown, HAhigh1, ("Reversal:"  + round(HAhigh1,2)), Color.LIGHT_RED, yes);



def price = close;
def superfast_length = 21;
def fast_length = 50;
def slow_length = 100;
def displace = 0;
def mah = reference TEMA(haHigh, avg);
def mal = reference TEMA(haLow, avg);

def mov_avg21 = reference TEMA(price[-displace], superfast_length);
def mov_avg50 = reference TEMA(price[-displace], fast_length);
def mov_avg100 = reference TEMA(price[-displace], slow_length);

#moving averages
def Superfast = mov_avg21;
def Fast = mov_avg50;
def Slow = mov_avg100;

def stopbuy = mov_avg21 <= mov_avg50;
def buynow = !buy[1] and buy;
def buysignal = CompoundValue(1, if buynow and !stopbuy then 1 else if buysignal[1] == 1 and stopbuy then 0 else buysignal[1], 0);

def Buy_Signal = buysignal[1] == 0 and buysignal == 1;

#Alert(condition = buysignal[1] == 0 and buysignal == 1, text = "Buy Signal", sound = Sound.Bell, "alert type" = Alert.BAR);

def Momentum_Down = buysignal[1] == 1 and buysignal == 0;

#Alert(condition = buysignal[1] == 1 and buysignal == 0, text = "Momentum_Down", sound = Sound.Bell, "alert type" = Alert.BAR);

def stopsell = mov_avg21 >= mov_avg50;
def sellnow = !sell[1] and sell;
def sellsignal = CompoundValue(1, if sellnow and !stopsell then 1 else if sellsignal[1] == 1 and stopsell then 0 else sellsignal[1], 0);

def Sell_Signal = sellsignal[1] == 0 and sellsignal;

#Alert(condition = sellsignal[1] == 0 and sellsignal == 1, text = "Sell Signal", sound = Sound.Bell, "alert type" = Alert.BAR);

def Momentum_Up = sellsignal[1] == 1 and sellsignal == 0;

#Alert(condition = sellsignal[1] == 1 and sellSignal == 0, text = "Momentum_Up", sound = Sound.Bell, "alert type" = Alert.BAR);

def Colorbars = if buysignal == 1 then 1 else if sellsignal == 1 then 2 else if buysignal == 0 or sellsignal == 0 then 3 else 0;
#Colorbars.Hide();
#Colorbars.DefineColor("Buy_Signal_Bars", Color.GREEN);
#Colorbars.DefineColor("Sell_Signal_Bars", Color.RED);
#Colorbars.DefineColor("Neutral", Color.PLUM);

def HA = ZigZagHighLow("price h" = mah, "price l" = mal, "percentage reversal" = percentamount, "absolute reversal" = revAmount, "atr length" = atrlength, "atr reversal" = atrreversal);
rec HASave = if !IsNaN(HA) then HA else GetValue(HASave, 1);
def chg = (if HASave == mah then mah else mal) - GetValue(HASave, 1);
def isUp = chg >= 0;
def HA_L = if !IsNaN(HA) and !isUp then mal else GetValue(HA_L, 1);
def HA_H = if !IsNaN(HA) and isUp then mah else GetValue(HA_H, 1);
def dir = CompoundValue(1, if HA_L != HA_L[1] or mal == HA_L[1] and mal == HASave then 1 else if HA_H != HA_H[1] or mah == HA_H[1] and mah == HASave then -1 else dir[1], 0);
def signal = CompoundValue(1, if dir > 0 and mal > HA_L then if signal[1] <= 0 then 1 else signal[1] else if dir < 0 and mah < HA_H then if signal[1] >= 0 then -1 else signal[1] else signal[1], 0);

def showarrows = yes;
def barnumber = BarNumber()[10];
def U1 = showarrows and signal > 0 and signal[1] <= 0;
def D1 = showarrows and signal < 0 and signal[1] >= 0;

# Plot Signals
def bull = signal > 0 and signal[1] <= 0;
#bull.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#bull.SetDefaultColor(Color.YELLOW);
#bull.SetLineWeight(2);

def bear = signal < 0 and signal[1] >= 0;
#bear.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#bear.SetDefaultColor(Color.YELLOW);
#bear.SetLineWeight(2);

#Buy Signal
AddChartBubble((barnumber and U1), if isUp then halow1 else hahigh1, if showarrows and signal > 0 and signal[1] <= 0 then "Reversal:" + round(halow1,2) else "" , if Colorbars == 3 then Color.PLUM else Color.UPTICK, no);

#Sellsignal
AddChartBubble((barnumber and D1), if isUp then halow1 else hahigh1, if showarrows and signal < 0 and signal[1] >= 0 then "Reversal:" + round(hahigh1,2) else "" , if Colorbars == 3 then Color.PLUM else Color.DOWNTICK, yes);
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

@floydddd Make sure when you copy the code that you actually get all of the code... I have had instances where while highlighting code once partway down the script the top part becomes un-selected... The longer the script, and the more extra long lines of code, the more apt this is to happen... I've even gone so far as to Copy & Paste in segments... This appears to be the issue with the code you posted... You are missing the top portion of the code... 💡
 
I made some additional changes to the script. The zigzag code was removed and I used my original script on page 1 minus the code on thread #64

The HA_Smooth was tested today.

2. Strategy- scanned for stocks with low float (under 100m, catalyst, RV over 2, volume over 1m. I normally focus on the first 5 stocks. Entry was on the pullback ( the last low and sold on the last high ( see chart ). The last low and high signals coincided with the HA trendup and trenddown signals. I normally use the 5min but found that the 1 min was better as it allowed me to enter at the lowest price of each pullback. Four trades were made and each trade averaged over $2500 with highest trade averaging over $5000. Trades were entered on each pullback. The total profits were over $14000.00.

3. Changes were made to the original timeframes as I went down to the 1 min timeframe.

Disclaimer: This is how I will be using the HA smoothed to trade. Individuals should have their own trading plan and strategy.

Here is the chart that was used today during trading to test the new script. The price reversals appear based on the HA_Smoothed change from uptrend to downtrend and vice versa as it follows the HA_Smoothed and not the Japanese candle sticks.

30DrhZf.jpg
 
Thanks @BonBon. You mentioned in your low float search, catalyst. Is that a type of search parameter or you are scanning news for it? Are you doing the scan in ToS?
 
Can a link be provided to load this. No luck with copy and Paste for lower MTF.I have set Fit studies.Thanks
 
Thanks @BonBon. You mentioned in your low float search, catalyst. Is that a type of search parameter or you are scanning news for it? Are you doing the scan in ToS?
Its a search parameters that I use on Think of Swim. I also use the below within the scan criteria as it produces stocks with high dollar volume. Basically the scan produces stocks that have momentum and/or gapped up with a catalyst and/or sympathy move etc.

Scan Criteria
plot DollarVolume = Round("number" = (hl2 *volume / 1000000), "numberOfDigits" = 1) is greater than 2;


hfUxpcF.jpg
 
@BonBon - Thank you for explaining the steps in details. Did you take trades in all the pull backs? Could you also help me understand how did you utilize the multi time frame and RSI as a confirmation for the last pull back (1 hr TF is red and RSI is above 80)?
 
@JoeSD I am not sure. However, you could turn off the smoothed HA by placing an hashtag in front of the "addchart ", turn on the assignpricecolor by removing the hashtag (if it is turned off) and change the candle in the "chart setting" to "Line" instead of "candle"
BonBon,

thanks tried that and didn't work and started getting blanks in the HA candles that continued to show..? I probably screwed something up as I know very little of changing code. :)
 
@floydddd Make sure when you copy the code that you actually get all of the code... I have had instances where while highlighting code once partway down the script the top part becomes un-selected... The longer the script, and the more extra long lines of code, the more apt this is to happen... I've even gone so far as to Copy & Paste in segments... This appears to be the issue with the code you posted... You are missing the top portion of the code... 💡

i have no doubt that you are right but no matter how many times i copy/paste, i still get a bunch o errors. i'll keep on plugging away at it, tho perhaps at some point bonbon might post the entire script as it stands now, with the above incorporated (or unincorperated, to some degree, if i understand her most recent words correctly). who knows -- i might get it on my own first. stranger things!
 
i have no doubt that you are right but no matter how many times i copy/paste, i still get a bunch o errors. i'll keep on plugging away at it, tho perhaps at some point bonbon might post the entire script as it stands now, with the above incorporated (or unincorperated, to some degree, if i understand her most recent words correctly). who knows -- i might get it on my own first. stranger things!

As I mentioned previously, it is sometimes easier to Copy & Paste in segments... I'm not sure about this forums software but when I hosted my open source CMS forum, code source had line numbers so members could reference a specific line umber or block of line numbers within the code when asking for or providing help... If @BenTen was to check into this there may be a way to enable line numbers which would help in multiple ways... There may ever be an option to provide a Copy icon in the code block header... For me it is still easier to perform multiple Copy & Pastes than to use shared links...
 
sounds right. one thing that's worked for me -- though not in this instance -- is to start highlighting the script from the bottom and then drag the highlighting to the top and only then do the copying. i've never had a failure that way ... until now, apparently. sigh.
 
sounds right. one thing that's worked for me -- though not in this instance -- is to start highlighting the script from the bottom and then drag the highlighting to the top and only then do the copying. i've never had a failure that way ... until now, apparently. sigh.

That works at times but not always, especially if the script is extremely long and has a lot of wide blocks of code adjacent to blank or very short lines of code... Those areas are where the problem arises... Another thing I've noticed is that the slower you allow the highlighting to scroll the better luck you will have compared to the code highlighting scrolling fast...

@BonBon Sorry for interjecting forum operational issues within your topic...
 
@BonBon , wonderful job on this indicator and strategy! Thank you for sharing. I think you've completely nailed the trendtraderpro.net indicator. I had looked into that awhile back (knowing that it was some sort of a smoothed heiken) but dropped it when I couldn't find a single review of it online. Further, apparently they had at one time testamonials on their site from individuals who were not even customers....or so I read.

Feedback: small point, but I'm finding that running a price line instead of candles is helpful for exits. For an exit on a long, when the price line closes below the HA midline (I think it is the cyan "o" plot) that would be an exit. That exit may be followed by the price line then closing above the HA midline, in which case it offers the opportunity for a new long entry.

@floydddd , I too am having difficulty with adding the new reversal code to the original. Lots of errors and can't figure it out. Let me know if you come up with the solution. Thanks!
 
@floydddd and others my apologies. I realized I made some changes to the code to accommodate the HA smooth and did not incorporate it in this script. I will edit the thread and it should be ready to be copied in a few minutes.

@rad14733 that is ok. The reason we are here is to learn from each other.
 
@RickK thank you for the feedback. I will definitely be looking into that as well. I am one of those traders who exit early and so I did some research on an indicator to add to my trading plan. Research and encountering the work of Vervoort along with scripts written by members contributed to my completion of this indicator. I am thankful that some members took up the work recently and this may be why you couldn't find any info on it. I utilized my research and analytical skills to figure out that the HA, zigzagsign, wave, etc. to decide on the course of action. Trial and error!! :giggle:.

I have learnt a lot from this forum and reached out to @BenTen as I wanted to not only receive feedback but share the completed indicator with members.

@Ghs I would refer to the the time frames to determine if they are also in an upward trend i.e if I am going long they should be green. This gives additional confirmation. Also I use the RSI to look for divergence etc. before taking the trade. Also, as a reminder, a stock pullbacks briefly before continuing in the trend so those minor pullbacks I would look at the RSI or stoch. However, ultimately the green and red HA smooth trends show the current trend with confirmation from the timeframes. If I missed the initial entry those pullbacks could be used to enter the trade.
 

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
417 Online
Create Post

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.
Back
Top