Repaints MTF Moving Average Slope Histogram For ThinkOrSwim

Repaints

DaysOff

New member
updated version:
https://usethinkscript.com/threads/...e-histogram-for-thinkorswim.6076/#post-113649

Hey good people...thought I'd break the ice with a cut and paste of the first ToS indicator that I've managed to cobble together.

Looking at Rob Hoffman's IRB strategy, I thought it would be handy to have a view of the slope of a higher timeframe moving average. I've been using this to day trade ES mini futures, 2 min chart. I like using the EZ Trend indicator on 2 min and MA Slope Histogram on 5 min or 10 min...trade in the direction the colors line up. Do whatever works for you. Simple but it works.

I did some digging and put this together:

Code:
# MTF Moving Average Slope Histogram
# DaysOff

declare lower;

input price = close;
input length = 10;
input agperiod = { "1 min", "2 min", "5 min", default "10 min", "15 min", "30 min", "60 min", "4 hours"};

def avg = ExpAverage(close(period = agperiod), length);
plot height = avg - avg[length];

height.setPaintingStrategy(PaintingStrategy.HISTOGRAM);
height.DefineColor("height >= 0" , Color.GREEN);
height.DefineColor("height < 0", Color.RED);
height.assignValueColor(if height >= 0 then height.color("height >= 0") else height.color("height < 0"));

S&P E-micro futures, 2 min chart w/ EMA slope histogram on 10 min...

cIF4oD7.jpg
[/COLOR]
 
Last edited by a moderator:
@DaysOff This is a perfect illustration of the use of a higher time-frame on a lower aggregation. Your chart provides clear indications of long-term direction, slope, trend, momentum which is a textbook because it is always better to trade with the trend as defined by the higher timeframe as you said. Love it!

Click here for ---> Explanation of How this and other MultiTimeFrame Indicators work is for any future readers who might not be aware of how to read and trade with a higher aggregation plotted on a lower timeframe.
 
Last edited:
As stated in OP, I created this indicator to give me a quick view of higher timeframe MA trend for day trading/scalping the ES futures. Combined with the EZ Trend indicator which can be found here, I have been trading the IRB strategy (see here) when the 2 min EZ Trend indicator lines up with the MA slope on higher timeframe...usually 5 min or 10 min. You miss some entries, but better to trade with the trend as defined by the higher timeframe.

Cheers.

WhAoTAc.jpg
 
Hey good people...thought I'd break the ice with a cut and paste of the first ToS indicator that I've managed to cobble together.

Looking at Rob Hoffman's IRB strategy, I thought it would be handy to have a view of the slope of a higher timeframe moving average. I've been using this to day trade ES mini futures, 2 min chart. I like using the EZ Trend indicator on 2 min and MA Slope Histogram on 5 min or 10 min...trade in the direction the colors line up. Do whatever works for you. Simple but it works.

I did some digging and put this together:

Code:
# MTF Moving Average Slope Histogram
# DaysOff

declare lower;

input price = close;
input length = 10;
input agperiod = { "1 min", "2 min", "5 min", default "10 min", "15 min", "30 min", "60 min", "4 hours"};

def avg = ExpAverage(close(period = agperiod), length);
plot height = avg - avg[length];

height.setPaintingStrategy(PaintingStrategy.HISTOGRAM);
height.DefineColor("height >= 0" , Color.GREEN);
height.DefineColor("height < 0", Color.RED);
height.assignValueColor(if height >= 0 then height.color("height >= 0") else height.color("height < 0"));

S&P E-micro futures, 2 min chart w/ EMA slope histogram on 10 min...

cIF4oD7.jpg
I literally only signed into my account right now just to thank you for this contribution to the trading community! Thank you so much! This is remarkably efficient for visual people like me, and it definitely shows you another perspective -- a color coded multi time frame histogram to plot a higher timeframe's moving average slope curve was absolutely brilliant! This study was created at the intersection of ingenuity and conceptual refinement. I am very satisfied with this, please be well!
 
Last edited:
@westonsloan, thanks for the kind words. I'm glad someone finds this indicator useful!
Back again, still the most useful indicator that I have to date -- I have a question.

How can I turn this into a scan to find upwards trending stocks or to query results that have a trending positive ratio? Anything that can basically tell me a trend reversal would be nice. I tried to work with what I got yet the system says that the code cannot use the second time aggregate (error). I am assuming bc if I set the time aggregate for scan to 5MIN yet the study is taking another higher timeframe (15) its like having the data double the scan on itself. Idk if that makes sense. Any tips? Have you made this into a scanner? Even when I set study is greater than or equal to "value" that I sent, still does not work. Any insight is greatly appreciated. @BenTen @DaysOff @MerryDay
 
Hi @westonsloan...very happy to hear you find the indicator useful. However, I'm sorry I can't offer assistance with the question on using it to scan. Scanning in ToS is not a feature I use. Hopefully someone else will chime in with some advice.
 
@westonsloan Try this code. I removed the higher aggregation from the code since it isnt compatible with the scanner - it has to be chosen from the dropdown menu. I havent tested it or anything, but it should scan for the bullish direction by default. When testing the results, make sure that the scan and the indicator you're using on the chart have the same aggregation selections.

Code:
# --- SCAN CODE ---
# Choose your desired aggregation from the scanner choices

# MTF Moving Average Slope Histogram Scan
# DaysOff

declare lower;

input price = close;
input length = 10;

def avg = ExpAverage(close, length);

# --- comment out the unwanted scan side

# bullish direction
plot height = avg - avg[length] >= 0;

# bearish direction
#plot height = avg - avg[length] < 0;
 
@westonsloan Try this code. I removed the higher aggregation from the code since it isnt compatible with the scanner - it has to be chosen from the dropdown menu. I havent tested it or anything, but it should scan for the bullish direction by default. When testing the results, make sure that the scan and the indicator you're using on the chart have the same aggregation selections.

Code:
# --- SCAN CODE ---
# Choose your desired aggregation from the scanner choices

# MTF Moving Average Slope Histogram Scan
# DaysOff

declare lower;

input price = close;
input length = 10;

def avg = ExpAverage(close, length);

# --- comment out the unwanted scan side

# bullish direction
plot height = avg - avg[length] >= 0;

# bearish direction
#plot height = avg - avg[length] < 0;
Hello, just checked back and saw this contribution -- I appreciate your finding! I will backtest the code right away.

Also, I have created a scanner that seems to ONLY work with 10 min aggregate period which removes the "error: secondary time frame not allowed" message that you get while in thinkscript editor. All I did was set the scan period to 10 Min. Seems like the only time period for a scan that worked. That was before coming back to this amazing community and seeing this reply to my question. Thank you so much! Cheers to you!
 
Hello, just checked back and saw this contribution -- I appreciate your finding! I will backtest the code right away.

Also, I have created a scanner that seems to ONLY work with 10 min aggregate period which removes the "error: secondary time frame not allowed" message that you get while in thinkscript editor. All I did was set the scan period to 10 Min. Seems like the only time period for a scan that worked. That was before coming back to this amazing community and seeing this reply to my question. Thank you so much! Cheers to you!
Can confirm this works. Comment out (#) the commands whether you want bearish or bullish directions. Match the aggregate to the aggregate you have on the indicator. For me it scans on the 15 min aggregation with the indicator placed on 5MIN chart. Brilliant work. This alone has increased efficiency tenfold and reduced chart time by a landslide. This contribution can win a nobel prize. Cheers!
 
@westonsloan Try this code. I removed the higher aggregation from the code since it isnt compatible with the scanner - it has to be chosen from the dropdown menu. I havent tested it or anything, but it should scan for the bullish direction by default. When testing the results, make sure that the scan and the indicator you're using on the chart have the same aggregation selections.

Code:
# --- SCAN CODE ---
# Choose your desired aggregation from the scanner choices

# MTF Moving Average Slope Histogram Scan
# DaysOff

declare lower;

input price = close;
input length = 10;

def avg = ExpAverage(close, length);

# --- comment out the unwanted scan side

# bullish direction
plot height = avg - avg[length] >= 0;

# bearish direction
#plot height = avg - avg[length] < 0;
Hello back months later to say that the MTF slope histogram is at the center of my trading strategy and to also wish the creator behind this masterfully crafted code a wonderful life! Shoutout to the creator of this scanner as well! It has helped. Lets evolve this one step further!

Notes:
  • Agreed to remove aggregation as it will not work on scanner.
  • Catch here is that histogram bars must be painted above zero line before it shows on scanner. Which can cause delays in showing setups already in momentum to approach then cross over. Timing is everything in trading.

My question is this. Yes this scan can show bullish direction, but the limitation is that this has to crossover 0 integer line (equilibrium) -- my question is how can this code be refined to show "CURRENT histogram bar is greater than or equal to the PREVIOUS CLOSE histogram bar" on any timeframe (user selects this option from dropdown menu) regardless of it being above zero line. I do not know the right syntax to make this possible yet it seems simple in theory to me.

For example... hypothetically I would have this scanner to reflect 15MIN. I would love to have the scanner show the instant a current histogram bar is greater than the close of the previous histogram bar that was painted right before it. Below is a rough visual of what I am asking for help with.
  • Lets say that we have these numbers here shown on the MTF histogram study: 3 > 2 > 1 > 0 > -1 > -2 < [ -1 ]* < 0 < 1 < 2 < 3.
  • From that list above, I would like the scanner to be able to tell when the current bar paints [ - 1 ]* which is clearly greater than or equal to the previous close of the histogram bar right behind it with a value of -2.
  • The scanner does not mind that the current histogram bar value is greater than previous histogram bar value even though its below zero line. This is one addition to the code can yield a faster reaction time to identifying potential setups.

Can this be done? Please follow up! @BenTen @Pensar @DaysOff @MerryDay @horserider
 
Last edited:
@westonsloan it 'sounds' like simple logic to be coded. Worked on it for several days but sorry, could not get accurate results :(
Thank you so much for taking the time to try! That means a lot to me. This indicator is easily one of the most important pieces of my daytrading system and evolving it would make all the difference!
 
Hey guys I finally was able to pinpoint how to make the scanner work to find uptrends according to the MTF Histogram indicator regardless if it below or above zero line and compares the previous bar to current bar on timeframe of your choice. I evolved the code from the suggestions above. This was a collective effort. I thank you all and hope you can make this work to your liking.
Hello back months later to say that the MTF slope histogram is at the center of my trading strategy and to also wish the creator behind this masterfully crafted code a wonderful life! Shoutout to the creator of this scanner as well! It has helped. Lets evolve this one step further!

Notes:
  • Agreed to remove aggregation as it will not work on scanner.
  • Catch here is that histogram bars must be painted above zero line before it shows on scanner. Which can cause delays in showing setups already in momentum to approach then cross over. Timing is everything in trading.

My question is this. Yes this scan can show bullish direction, but the limitation is that this has to crossover 0 integer line (equilibrium) -- my question is how can this code be refined to show "CURRENT histogram bar is greater than or equal to the PREVIOUS CLOSE histogram bar" on any timeframe (user selects this option from dropdown menu) regardless of it being above zero line. I do not know the right syntax to make this possible yet it seems simple in theory to me.

For example... hypothetically I would have this scanner to reflect 15MIN. I would love to have the scanner show the instant a current histogram bar is greater than the close of the previous histogram bar that was painted right before it. Below is a rough visual of what I am asking for help with.
  • Lets say that we have these numbers here shown on the MTF histogram study: 3 > 2 > 1 > 0 > -1 > -2 < [ -1 ]* < 0 < 1 < 2 < 3.
  • From that list above, I would like the scanner to be able to tell when the current bar paints [ - 1 ]* which is clearly greater than or equal to the previous close of the histogram bar right behind it with a value of -2.
  • The scanner does not mind that the current histogram bar value is greater than previous histogram bar value even though its below zero line. This is one addition to the code can yield a faster reaction time to identifying potential setups.

Can this be done? Please follow up! @BenTen @Pensar @DaysOff @MerryDay @horserider
I FIGURED IT OUT! HERE IS THE CODE!
  • Match the agperiod to the scan timeframe (ie. 15 min agperiod input matches my 15 min timeframe scan)
    • Available timeframes per referenced in original code: "1 min", "2 min", "5 min", default "10 min", "15 min", "30 min", "60 min", "4 hours"... you will then match this to the scan timeframe criteria of the study.
  • This is built for bullish direction.
@Pensar @DaysOff @MerryDay @BenTen

# --- SCAN CODE ---
# Choose your desired aggregation from the scanner choices

# MTF Moving Average Slope Histogram Scan
# DaysOff

declare lower;

input price = close;
input length = 10;
input agperiod = "15 min";

def avg = ExpAverage(close(period = agperiod), length);
def height = avg - avg[length];

# --- comment out the unwanted scan side

# bullish direction
plot scan = height >= height[1];
 
Last edited:
@Pensar version only searches for stocks that have histogram height above zero line (yes this is generally bullish). But just because the histogram is above zero line, does NOT mean that it is in a bullish uptrend. That was the main point of my questions/requests before. This indicator is visually responsive to the moving average trend. And that undeniable ingenuity is the main reason why this is x-ray vision into any stock. One catch on his version is that the histogram height value has to be a positive whole number since it has to be greater than or equal to zero. What about stocks that have histogram height values below zero line that are beginning an uptrend? (ie. -3 is greater than -7). Another catch here is that the histogram bars literally can be showing a downtrend which is bearish even though it is above zero line. Not ideal to trade on down slope just because it is above zero line. You can even look at his provided screenshot to see that point.

MY code that I evolved the provided code to return when the current histogram height value is above the previous bar's value right before it. And it does not matter if it is above or below zero line. As long as current bar's height value is above the previous bar's height value, which is a clear sign of an uptrend -- the scan will find it. Eliminates the need for the histogram to only be above zero line. Reduces clutter of chart time on downtrend stocks. My version of this code actually improves the original design to only returns stocks that are in an active uptrend. Refines results in a more efficient and accurate way.
 
Last edited by a moderator:
Totally awesome explanation. Thanks for sharing.

FYI:
This part of your code run on a 15min scan:
input agperiod = "15 min";
def avg = ExpAverage(close(period = agperiod), length);
Is the same as @Pensar's code:
def avg = ExpAverage(close, length);
Take out the aggregation. It will make it easier for you to use on any timeframe.
 
Last edited:
@MerryDay
Thank you so much! The code was posted by @Pensar. I kept the title and everything the exact same way. I just wanted a way to only return active uptrends. Your suggestion is helpful too! Removing aggregation makes it easier to scan on any timeframe. I only trade using 1, 5, and 15. And specially only scan for 15 min chart (highest timeframe that I use) to be in an active uptrend while waiting for an entry on lower timeframes. I am glad my explanation gave more insight into what my intentions were!
 
Last edited:
Hey good people...thought I'd break the ice with a cut and paste of the first ToS indicator that I've managed to cobble together.

Looking at Rob Hoffman's IRB strategy, I thought it would be handy to have a view of the slope of a higher timeframe moving average. I've been using this to day trade ES mini futures, 2 min chart. I like using the EZ Trend indicator on 2 min and MA Slope Histogram on 5 min or 10 min...trade in the direction the colors line up. Do whatever works for you. Simple but it works.

I did some digging and put this together:

Code:
# MTF Moving Average Slope Histogram
# DaysOff

declare lower;

input price = close;
input length = 10;
input agperiod = { "1 min", "2 min", "5 min", default "10 min", "15 min", "30 min", "60 min", "4 hours"};

def avg = ExpAverage(close(period = agperiod), length);
plot height = avg - avg[length];

height.setPaintingStrategy(PaintingStrategy.HISTOGRAM);
height.DefineColor("height >= 0" , Color.GREEN);
height.DefineColor("height < 0", Color.RED);
height.assignValueColor(if height >= 0 then height.color("height >= 0") else height.color("height < 0"));

S&P E-micro futures, 2 min chart w/ EMA slope histogram on 10 min...

cIF4oD7.jpg
. thanks for this great indicator. Is it possible to have input value for different types of moving averages that can be used with this indicator. Example SMA, Hull and others.
 
@DaysOff - I gave your code a shot of much needed vitamins - I hope you'll like it -

1) Select any Average-Type.
2) Select Sessions - for Day-Trading and Scalping calculations
3) Select Session Time and Length
4) Labels
5) Default inputs are same as yours.

CSS:
# MTF Moving Average Slope Histogram
# V 1.0: DaysOff
# V 2.0: TraderZen

declare lower;

input length = 10;
input MAtype = AverageType.EXPONENTIAL;
input agPeriod = AggregationPeriod.TEN_MIN;
Input SessionLength = {Default "24_7", "DayTrade"};
Input ShowLabel = {Default "no", "yes"};

def CurrentTP = GetAggregationPeriod();

def AlgoExec = if agperiod <= CurrentTP then no else yes;
AddLabel(yes, if AlgoExec == no then "The Current Time Period Should be Less then the Selected Time Period! " + agPeriod else "" , Color.WHITE) ;

input nightSessionFromMidnight = 0100; # 0100;
Input PreMkt = 730;
input firstHourTrading = 930;
input mainSession = 1030;
input nightSessionFromMainSessionEnd = 1615;
input MainSessionEnd = 1600; 

def isNightSessionFromMidnight = SecondsFromTime(nightSessionFromMidnight) >= 0 and SecondsTillTime(firstHourTrading) > 0;
def isDaySessionFromStart = secondsFromTime(FirstHourTrading) >= 0 and SecondsTillTime(MainSession) >= 0; # RB Code
def isFirstHourTrading = SecondsFromTime(firstHourTrading) >= 0 and SecondsTillTime(mainSession) > 0;
def isPreMkt = SecondsFromTime(PreMkt) >= 0 and SecondsTillTime(FirstHourTrading) > 0;
def isMainSession = SecondsFromTime(MainSession) >= 0 and SecondsTillTime(MainSessionEnd) > 0;

def newNightSessionFromMidnight = isNightSessionFromMidnight and !isNightSessionFromMidnight[1];
def newMainSessionFromSessionStart = isDaySessionFromStart and !isDaySessionFromStart[1]; # RB Code

def avg_DayTrade = if (IsPreMkt or isMainSession or isDaySessionFromStart)
                     then Fold i = 1 to length with Avg_DT do
                            MovingAverage(AverageType =MAType, close(period=agPeriod), length)
                   else double.nan;

def avg_247 = fold j = 1 to length with Avg_all do MovingAverage(AverageType = maType , close(period=agPeriod) , length);


plot height;

Switch (sessionLength) {
Case "24_7" :
height = avg_247 - avg_247[length] ;
case "DayTrade":
height = avg_DayTrade - avg_DayTrade[length] ;
}

height.setPaintingStrategy(PaintingStrategy.HISTOGRAM);
height.DefineColor("height >= 0" , Color.GREEN);
height.DefineColor("height < 0", Color.RED);
height.assignValueColor(if height >= 0 then height.color("height >= 0") else height.color("height < 0"));

AddLabel(showLabel, SessionLength, color=color.white);

# Happy Trading TraderZen 12/4/2022
 

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
356 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