Repaints Hull Moving Average Turning Points and Concavity (2nd Derivatives)

Repaints
Status
Not open for further replies.
Hi there forum members,
I created the following backtest strategy and only the bearish signals are showing on the chart. I need help in the code so that the bullish signals will also show. Thanks.
Code:
input price = CLOSE;
input HMA_Length = 8;

def HMA = HullMovingAvg(price = price, length = HMA_Length);

def MA_Max = HMA[-1] < HMA and HMA > HMA[1];
def MA_Min = HMA[-1] > HMA and HMA < HMA[1];

addOrder(OrderType.BUY_AUTO, MA_Min[1], open[-1],100, name = "BUY");
addOrder(OrderType.SELL_AUTO,MA_Max[1], open[-1],100, name = "Sell");
Haven't checked it in TOS but I fixed your code and cleaned up the unnecessary parts.[/CODE]
 
Last edited:

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

Hi there TK,

Thank you so much for the above code...your suggestion helped me see what I was missing in my original code...So I changed the order type to "auto" and the buy/sell signal to [-1]. If I wish to have an input for how may shares to use what input code would I use? Thank you.

-JP
 
Hi there TK,

Thank you so much for the above code...your suggestion helped me see what I was missing in my original code...So I changed the order type to "auto" and the buy/sell signal to [-1]. If I wish to have an input for how may shares to use what input code would I use? Thank you.

-JP
You want the buy/sell orders to be [1], not [-1] or even 0, since the MA_Max and min are already triggering on an index of -1. That means that unless you have the buy/sell orders at [1] then the backtest results will be way off, since it will have you predicting the future. See my previous posts on this thread replying to Summies who made the same mistake (which was also made in earlier pages of this same thread and pointed out by Mashume and others.)

As for changing the shares, you can use this:
Code:
input price = CLOSE;
input HMA_Length = 8;
input shares = 100;

def HMA = HullMovingAvg(price = price, length = HMA_Length);

def MA_Max = HMA[-1] < HMA and HMA > HMA[1];
def MA_Min = HMA[-1] > HMA and HMA < HMA[1];


addOrder(OrderType.BUY_AUTO, MA_Min[1], open[-1], shares, name = "BUY");
addOrder(OrderType.SELL_AUTO,MA_Max[1], open[-1], shares, name = "Sell");
 
Hello Mashume, could you please walk me step by step how to install the script to get it to work . coz i've tried to cut and paste it into script editor but just CAN NOT save nor click OK ... Or would anyone please help. Thanks
 
@TraderKevin I tried copying and pasting your code to test the results on some symbols - for some reason I am not seeing the indicator on the screen. I looked at all the available options bit all I get is a basic stock chart without the indicator.
 
Here is screen shot of Renko scalper with /CL oil futs, have messed around but never just traded it fully on all signals, I added the info from Summie settings to what I had HMA and it was about the same
 
Hi there forum members,

What would the code be to add an alert when MA_Max & MA_Min are plotted?
Below is the code that I used but to no avail, not sure what I am missing:

Alert(MA_Min, "Buy", Alert.BAR, Sound.Bell);

Alert(MA_Max, "Sell", Alert.BAR, Sound.Chimes);
 
Last edited:
Hello, would anyone please help with this code, i tried to get this code to work.. cut and pasted it under Editor but could not get it to work or as picture shown. Thanks so much.
 
@TraderKevin I tried copying and pasting your code to test the results on some symbols - for some reason I am not seeing the indicator on the screen. I looked at all the available options bit all I get is a basic stock chart without the indicator.
This code was meant to just be a strategy, not a pretty indicator. The prettier indicator that the strategy is based on you can find in Mashume's original code or elsewhere in this thread. You could run this strategy and the indicator at the same time if you wanted as well.

Edited to add that this strategy is also not really based on Mashume's excellent work with the concavity of the Hull Moving Average. Using just the MA_Min and MA_Max means you are just basing it off the Hull Moving Average.
 
Last edited:
@mashume I wanted to let you know how AMAZING the concavity indicator (sub graph) of your overall study package is. I scalp stocks on a 3 min chart and have changed a few of its settings to adjust to my timeframe - (H+L)/2,30,1
I use the HMA9, SMA20 and SMA200 on my main chart with heiken ashi candles.

What amazes me is the signals that are printed on your subgraph. I call this set up Pure Gold.
On a bullish trend (price above 20 which is above 200), I take the positive signals for entries and ignore the negative signals.
On a bearish trend, I only consider the negative signals for entries.

Your concavity indicator is nothing short of genius / crystal ball.. Thank you very very much!!! You have changed my trading for ever, POSITIVELY of course!!
God Bless
 
As I was looking at the Hull Moving Average, it occurred to me that taking the local minimums and maximums might not be the most effective use of it's smooth nature. Nor did it seem that a moving average cross over would provide timely signals.

And then I remembered that I used to teach physics and calculus and decided to look at rates of change and that lead me to...

CONCAVITY

which is nothing but the second derivative of the function (if you remember or not) :) and so this indicator was born.

It is in two parts -- the upper which is the Hull Moving Average with the addition of colored segments representing concavity and turning points: maxima, minima and inflection. The last of these are of the greatest interest. The second part is a plot of the calculation used in finding the turning points (which is roughly the second derivative of the HMA function, where zero crosses are the inflection points.

SDcVypw.png


UPPER INDICATOR

Upper HMA colors:
  • Green: Concave Up but HMA decreasing. The 'mood' has changed and the declining trend of the HMA is slowing. Long trades were entered at the turning point
  • Light Green: Concave up and HMA increasing. Price is increasing, and since the curve is still concave up, it is accelerating upward.
  • Orange: Concavity is now downward, and though price is still increasing, the rate has slowed, perhaps the mood has become less enthusiastic. We EXIT the trade (long) when this phase starts. Very little additional upward price movement is likely.
  • Red: Concave down and HMA decreasing. Not good for long trades, but get ready for a turning point to enter long on again.

Upper Label Colors:
these are useful for getting ready to enter a trade, or exit a trade and serve as warnings that a turning point may be reached soon
  • Green: Concave up and divergence (the distance from the expected HMA value to the actual HMA value is increasing). That is, we're moving away from a 2nd derivative zero crossover.
  • Yellow: Concave up but the divergence is decreasing (heading toward a 2nd derivative zero crossover); it may soon be time to exit the trade.
  • Red: Concave down and the absolute value of the divergence is increasing (moving away from crossover)
  • Pink: Concave down but approaching a zero crossover from below (remember that that is the entry signal, so pink means 'get ready').
Arrows are provided as Buy and Sell and could perhaps be scanned against.

LOWER INDICATOR

For those who prefer less cluttered uppers, I offer the plot of the divergence from expected HMA values; analogous to the second derivative in that the zero crossovers are of interest, as is the slope of the line. The further from zero, the stronger the curve of the concavity, and the more likely to reach a local minima or maxima in short order.


Miscelaneous

If you find that there are too many buy and sell signals, you can change the length of the HMA (I find 34 a happy medium, though 55 and sometimes 89 can be appropriate). You can also play with the value of the lookback, though that will slow down signals.

This works well on Daily timeframes as well as intraday candles.

I set it up with High + Low / 2 as the default so that it shouldn't wait for close prices. That may not be appropriate to how you wish to trade.

Comments welcome. Let me know how you use it, how it works for your trades, and whether it made your head hurt trying to remember your calculus.

Happy Trading,
Mashume

UPPER:
https://tos.mx/cgKFdmm

LOWER:
https://tos.mx/p0k7ims

UPPER CODE

Code:
#
# Hull Moving Average Concavity and Turning Points
#  or
# The Second Derivative of the Hull Moving Average
#
# Author: Seth Urion (Mashume)
# Version: 2020-02-23 V3
# Faster, but not necessarily mathematically as good as the first
#
# This code is licensed (as applicable) under the GPL v3
#
# ----------------------


declare upper;

input price = HL2;
input HMA_Length = 21;
input lookback = 2;

plot HMA = HullMovingAvg(price = price, length = HMA_Length);

# def delta_per_bar =
# (fold n = 0 to lookback with s do s + getValue(HMA, n, lookback - 1)) / lookback;

def delta = HMA[1] - HMA[lookback + 1];
def delta_per_bar = delta / lookback;

def next_bar = HMA[1] + delta_per_bar;

def concavity = if HMA > next_bar then 1 else -1;

plot turning_point = if concavity[1] != concavity then HMA else double.nan;

HMA.AssignValueColor(color = if concavity[1] == -1 then
    if HMA > HMA[1] then color.dark_orange else color.red else
    if HMA < HMA[1] then color.dark_green else color.green);

HMA.SetLineWeight(3);

turning_point.SetLineWeight(4);
turning_point.SetPaintingStrategy(paintingStrategy = PaintingStrategy.POINTS);
turning_point.SetDefaultColor(color.white);

plot MA_Max = if HMA[-1] < HMA and HMA > HMA[1] then HMA else Double.NaN;
MA_Max.SetDefaultColor(Color.WHITE);
MA_Max.SetPaintingStrategy(PaintingStrategy.SQUARES);

#####
# Added Alerts 2020-02-23
Alert(condition = buy, text = "Buy", "alert type" = Alert.BAR, sound = Sound.Chimes);
Alert(condition = sell, text = "Sell", "alert type" = Alert.BAR, sound = Sound.Chimes);

LOWER CODE

Code:
#
# Hull Moving Average Concavity Divergence
#  or
# The Second Derivative of the Hull Moving Average
#
# Author: Seth Urion (Mashume)
# Version: 2020-02-23 V3
#
# This code is licensed (as applicable) under the GPL v3
#
# ----------------------

declare lower;

input price = OPEN;

input HMA_length = 55;
input lookback = 2;

def HMA = HullMovingAvg(length = HMA_length, price = price);

def delta = HMA[1] - HMA[lookback + 1];
def delta_per_bar = delta / lookback;

def next_bar = HMA[1] + delta_per_bar;

def concavity = if HMA > next_bar then 1 else -1;

plot zero = 0;
zero.setdefaultcolor(color.gray);
zero.setpaintingstrategy(PaintingStrategy.DASHES);

plot divergence = HMA - next_bar;
divergence.setDefaultColor(Color.LIME);
divergence.SetLineweight(2);

plot cx_up = if divergence crosses above zero then 0 else double.nan;
cx_up.SetPaintingStrategy(PaintingStrategy.POINTS);
cx_up.SetDefaultColor(Color.LIGHT_GREEN);
cx_up.SetLineWeight(4);

plot cx_down = if divergence crosses below zero then 0 else double.nan;
cx_down.SetPaintingStrategy(PaintingStrategy.POINTS);
cx_down.SetDefaultColor(Color.RED);
cx_down.SetLineWeight(4);

NEW VERSION 4

Now with Mobile!
https://tos.mx/NXqbYE9
I could not get these codes to work, Could someone please help, I cut and Paste the code, went to Studies, Edit Studies, Create ( studies ), Deleted the Preset code, and Pasted the new Upper Code, Save and OK then Create another one for Lower code. But it doesn't work neither. Please help or if you help with a Video would be great, Thanks so much
 
@mashume I wanted to let you know how AMAZING the concavity indicator (sub graph) of your overall study package is. I scalp stocks on a 3 min chart and have changed a few of its settings to adjust to my timeframe - (H+L)/2,30,1
I use the HMA9, SMA20 and SMA200 on my main chart with heiken ashi candles.

What amazes me is the signals that are printed on your subgraph. I call this set up Pure Gold.
On a bullish trend (price above 20 which is above 200), I take the positive signals for entries and ignore the negative signals.
On a bearish trend, I only consider the negative signals for entries.

Your concavity indicator is nothing short of genius / crystal ball.. Thank you very very much!!! You have changed my trading for ever, POSITIVELY of course!!
God Bless
Do you have a systematic way of exiting your trades? If so, I'd be happy to setup your system as a strategy so we can backtest the results.
 
Do you have a systematic way of exiting your trades? If so, I'd be happy to setup your system as a strategy so we can backtest the results.
@TraderKevin I typically draw fib extensions and exit at one of the relevant levels on the Fibs. The other way I exit is when prices start coming close to the 20 SMA. So essentially, there is no hard coded exit plan that I adhere to. It is more fluid. And since I scalp, I also exit if the ticker meets my $/% targets
 
Kudos to the creator of this creator. It works really well. Thank you.
I do have a request. Whenever it displays a triangles or a square, is there a way to get sound notification for each of them.
I tried to tinker with it but wasn't successfully.

For Ex . code snippet

Code:
plot MA_Max = if HMA[-1] < HMA and HMA > HMA[1] then HMA else Double.NaN;
MA_Max.SetDefaultColor(Color.WHITE);
MA_Max.SetPaintingStrategy(PaintingStrategy.SQUARES);
MA_Max.SetLineWeight(3);

How can I set it to play a sounds alert.
 
Code:
#Alert(condition = buy, text = "Buy", "alert type" = Alert.BAR, sound = Sound.Bell);
Alert(condition = MA_Min, text = "Buy Confirmed", "alert type" = Alert.BAR, sound = Sound.Bell);
#Alert(condition = sell, text = "Sell", "alert type" = Alert.BAR, sound = Sound.Chimes);
Alert(condition = MA_Max, text = "Sell Confirmed", "alert type" = Alert.BAR, sound = Sound.Chimes);

This is what I did, but I still don't get the alerts.
 
Status
Not open for further replies.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
224 Online
Create Post

Similar threads

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