Create a custom strategy from Hull moving average

Alex

Active member
VIP
Hey! I would like to turn the default thinkorswim Hull moving average into a custom strategy. Whenever the color of the hull moving average slope changes its color from up / down I’d like the strategy to open / close an order only on the close of the candle / bar. In addition I would like an alert to pop up whenever all of the conditions are met. I'm not much of a coder myself so hopefully this isn't too complicated...

ASFxmFe.png


Here is the default thinkorswim HullMovingAvg code:

Code:
#
# TD Ameritrade IP Company, Inc. (c) 2008-2020
#

input price = close;
input length = 20;
input displace = 0;

plot HMA = MovingAverage(AverageType.HULL, price, length)[-displace];

HMA.DefineColor("Up", GetColor(1));

HMA.DefineColor("Down", GetColor(0));

HMA.AssignValueColor(if HMA > HMA[1] then HMA.color("Up") else HMA.color("Down"));
 
@Alex, try adding this to the bottom of your code.
Code:
AddOrder(OrderType.BUY_AUTO, HMA > HMA[1]);
AddOrder(OrderType.SELL_AUTO, HMA < HMA[1]);

Alert(HMA > HMA[1] and HMA[1] < HMA[2], "BUY SIGNAL", Alert.BAR, Sound.Ring);
Alert(HMA < HMA[1] and HMA[1] > HMA[2], "SELL SIGNAL", Alert.BAR, Sound.Ring);
Make sure you add the completed code to the Strategies section. It should place simulation trades in either direction on a change in the HMA color and give alerts. If you want to backtest only buy orders, change "BUY_AUTO" and "SELL_AUTO" to "BUY_TO_OPEN" and SELL_TO_CLOSE". Hope this helps! :)
 
Last edited:
Can someone help with this strategy:
input tradeSize = 1;
def signal = HullMovingAvg(price=close, "length" = 10, "displace" = 1) crosses above HullMovingAvg(price=close,"length" = 20);
addOrder(OrderType.buy_TO_OPEN, signal, open[-1], tradeSize, Color.CYAN, Color.CYAN);
def exit = HullMovingAvg(price=close, "length" = 10, "displace" = 1) crosses below HullMovingAvg(price=close,"length" = 20);
addOrder(OrderType.sell_TO_CLOSE, exit, open[-1], tradeSize, Color.MAGENTA, Color.MAGENTA);

I want the strategy and conditional order to only execute when the bar closes and it's true. For both it's executing when it is true.
 
Hello, I appreciate all your guy's time and effort. I was wondering if its possible to do this same thing but conditionally with multiple HMA's, for example when a slow HMA's trend up or down matches a mid HMA and a fast HMA it enters the trade and when the fast HMA changes trend it exits. Please see attached picture. Any help would be awesome. Thank you

S5CngsH.png
 
Thank you @MerryDay. I'm still exploring on how to utilize. Thank you
@MerryDay @BenTen

Thank you for the help. The above doesn't show when two HMA turned either green or red at the same time. Could you please take another look?

Another query for the code posted above, both up and down plots are having the same code. Should the down plot be used less than symbol?

Also, please help on how to add a column on scan results where red or green shown in the above snapshot?

Thank you.
 
@VenB I haven't had the chance to look at this request, but are you sure that both moving averages can turn either green or red at the same time? I imagine it would not be possible because one is 2x of the other.

Maybe you can post a screenshot of the scenario. I'll look at this later tonight.
 
edited 1am...
@VenB Here are the plots on a chart.

TaDa.... I got the scan to work.
And I must say, that you may have something here.
It is showing some interesting potential results.

Code:
# ########################################################
# TOS HullMovingAVg
plot HMA1 = HullMovingAvg(price = HL2, length = 10); #12
plot HMA2 = HullMovingAvg(price = HL2, length = 20); #89

def HMA1up = HMA1>HMA1[1];
def HMA2up = HMA2>HMA2[1];
plot HMAup = HMA1up and HMA2up ;

def HMA1dn = HMA1<HMA1[1];
def HMA2dn = HMA2<HMA2[1];
plot HMAdn = HMA1dn and HMA2dn ;


HMA1.SetLineWeight(2);
HMA1.DefineColor("Positive", Color.violet);
HMA1.DefineColor("Negative", Color.light_orange);
HMA1.AssignValueColor(if HMA1 > HMA1[1] then HMA1.color("Positive") else HMA1.color("Negative"));
                                                                 
HMA2.SetLineWeight(2);
HMA2.DefineColor("Positive", Color.green);
HMA2.DefineColor("Negative", Color.red);
HMA2.AssignValueColor(if HMA2 > HMA2[1] then HMA2.color("Positive") else HMA2.color("Negative"));

aaa2.png
 
Last edited:
@VenB To make a scan:
  1. Save the above code as a study
  2. Scan for HMAup is true
In the scan image where it says: A2_HMAplot, you need to substitute the name you saved your study as.

aaa2.png
 
Yes, it does Ben. Unfortunately, it's not allowing me to attach a snapshot. Will share over discord.

WRaCBKg.jpg


Thank you @MerryDay, I will check again as per your instructions. How do you get red/green column in the search results?
 
@VenB
That is the Finite Volume Elements (FVE) Indicator. It is a rather complex indicator. Red is not necessarily bad and Green is not necessarily good.

Instead of the FVE Volume; I combined your Hull script with the following volume profile:
Code:
# Scan for Price in value area and volume spike
# Mobius
# Chat Room Request 04.05.2018
def yyyymmdd = GetYYYYMMDD();
def day_number = DaysFromDate(First(yyyymmdd)) + GetDayOfWeek(First(yyyymmdd));
def period = Floor(day_number / 7);
def cond = 0 < period - period[1];
profile vol = VolumeProfile("startNewProfile" = cond, "onExpansion" = no);
vol.Show("va color" = Color.YELLOW);
def b = vol.GetHighestValueArea();
def a = vol.GetLowestValueArea();
plot condition = between(close, a, b) and volume > Average(volume, 21);
I scan for the Hull10 and Hull20 to be up on a daily agg and for the above volume profile to be true on a 15min agg.
This provides a nice pool of stocks against which I then run my favorite strategies such as @BenTen's BTD indicator.
 
Last edited:
Hello,

I am following this youtube link and trying to recreate the same, but would like to understand why the Sell Signal is shown after multiple candles. I have tried it on different time frames but but result remains the same. I would like to get the Buy signal when the HMA turns Green and i would like it to give me a sell signal atleast closer to the top and not after a significant dip. Thank You

Daily Candle of a different stock
1613362866230.png

Daily Candle of a different stock
1613362979025.png
 
Last edited by a moderator:
@mohitdas Virtually all MA-based Strategies work in this manner, basically because they are based on crossovers alone... For a true trading strategy, or system if you will, it requires multiple methods of determining entry and exit... One simple method would be the use of a Trailing Stop Loss... Another would be to base exit on RSI reaching OverBought or loss of momentum based on a lower indicator with histogram such as Waddah Attar, MACD, ErgodicOsc, one of the TTM suite of indicators, or others...

Remember, it is virtually impossible to catch the absolute bottom entry price and top exit price... Doing so it a recipe for disaster in the long run... What you really want to do is to ride the momentum portion of the trade... That means waiting until you are certain that there is enough momentum to carry you from entry point to profit and then exit before the price pulls back too far... With simple MA crossovers you are essentially doing just that - most of the time but not always... But in doing so you may be losing profit by waiting for the exit crossover... Nobody says you have to wait for the entry or exit crossovers if you are fairly certain that they will occur in the near future... You can just as easily enter and exit based on the MA's convergence and divergence and, in doing so, enter and exit a candle or two earlier with increased profit...

In addition, monitoring the trade on multiple timeframes can be extremely beneficial... A slower timeframe can determine overall trend but a faster timeframe can help determine actual entry and exit... Just make sure you don't use too short of a timeframe or you'll make false entries and exits which can be costly over time...

And you also need to take your style of trading into consideration, whether scalping, day trading, swing, or long term trading... What works best for one style may not be ideal for another... Only you can make those decisions based on your risk factor, trading style, and understanding of how the trade instrument is currently performing...
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
338 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