Percent Distance Between EMAs or Any 2 Plots For ThinkOrSwim

MerryDay

Administrative
Staff member
Staff
VIP
Lifetime
Scan For Price Within A Percentage Of Moving Average
  1. Where price is below 100 ma
  2. Where price is rising (hl2 is greater than hl2 from 1 bars ago)
  3. Where price is within -2% of the 100 ma
The scan below utilizes @markos script from post #8
Ruby:
# MA Distance Percentage
# Paris
# 4.13.2018
# Computes percentage the current close is above/below the 200 DSMA
# Displays on a lower chart

declare lower;

input length = 200;

def data = close;
def avg = Average(data, length);
def pct = (data/avg) - 1;

plot dist = pct;
plot zero = 0;

zero.SetDefaultColor(Color.WHITE);
zero.SetLineWeight(2);
AddLabel(1, "Percentage from " + length + " MA: " + AsPercent(pct), if pct > 0 then Color.GREEN else Color.PINK);
Copy the above code
In Studies, click Create
Paste the above study
Name the study: Pct_From_MA
Save
Click on the scanner.

Where price is below ma
  1. Click on +Add filter
  2. Click on the pencil icon next to the filter you just added
  3. Click edit
  4. In the left column, click on the 1st pull-down window, click study
  5. Type in Pct_From_MA
  6. Under Plot, click on the pull-down window, choose dist
  7. In length change the 200 ma length to 100 ma length .... (or whatever moving average length that you want)
  8. In the middle column, choose Less than or equal to .... (if scanning for above ma change this to Greater than)
  9. In the right column, click on the pull-down window, click value
  10. Change 100 in the next box to 0
  11. Save

Where price is rising (hl2 is greater than hl2 from 1 bars ago)
  1. Click on +Add filter
  2. Click on the pencil icon next to the filter you just added
  3. Click edit
  4. In the left column, click on the 1st pull-down window, click price
  5. Click hl2 .... (or what ever representation of price that floats your boat)
  6. In the middle column, choose greater than or equal to
  7. In the right column, click on the pull-down window, click price
  8. Click hl2 .... (or what ever representation of price that floats your boat)
  9. In the box under hl2, change the 0 to 1 offset
  10. Save

Where price is within -2% of the ma
  1. Click on +Add filter
  2. Click on the pencil icon next to the filter you just added
  3. Click edit
  4. In the left column, click on the 1st pull-down window, click study
  5. Type in Pct_From_MA
  6. Under Plot, click on the pull-down window, choose dist
  7. In length change the 200 ma length to 100 ma length .... (or whatever moving average length that you want)
  8. In the middle column, choose greater than or equal to .... (or Less than if scanning for above ma)
  9. In the right column, click on the pull-down window, click value
  10. In the box under value, change the value from 100 to -0.02 .... (negative values represent under ma; positive values for above ma)
  11. Save .... (change the percentage to anything you want)

Remember: Change the aggregation of each filter to what you want
83orWtu.png


Here is a Shared Link: http://tos.mx/kXoe4Db
The shared link will only work if you copy and pasted the above study and named it: Pct_From_MA
A poster was having difficulty scanning for within a percentage of ma so I wrote this brief tutorial. I don't use moving average studies so I can not assist w/ how people are utilizing this in their strategies.
 
Last edited:
Here you go:

Code:
MovAvgExponential()."AvgExp" crosses MovAvgExponential("length" = 50)."AvgExp" or MovAvgExponential()."AvgExp" crosses MovAvgExponential("length" = 200)."AvgExp"
 

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

Thank you BenTen !!!
One little question:

MovAvgExponential()."AvgExp" crosses...

Which AvgExp does it reffers to ? how does it know which AvgExp i want to cross the 50?

because after that I see you wrote length=50

And: Is there an option so the cross will be only above the 50 and 200 ?

Thanks again !!!
 
Last edited:
Hi Nervo,

I wrote something similar to what you are looking for the for ATR Trailing Stop. It's not too complicated, but it gets the job done in my watchlist and helps me enter trades with minimal losses. It merely gets the distance in a % between the price and the trailing stop.

*Just thought I would share

Code:
# By Dan Dude
# Get distance to ATR Trailing Stop
# Copyright forever
input price = close;

# 1 Reference Trailing Spot in TOS
def ATR = reference ATRTrailingStop();

# 2 Get the distance from PRICE to trailing stop => Sq the number and get the Sqrt to avoid pesky negatives
def distanceToStop = (Sqrt(Sqr(price / ATR - 1))) * 100;

# 3 assign a background color based on my tinkering
AssignBackgroundColor(if distanceToStop >= .35 then color.dark_red else if distanceToStop < .35 then color.dark_green else color.current);

# 4 add a label
AddLabel(yes, asPercent(round(distanceToStop,2)));

I'll see what I can do to modify this into a EMA expression for you

Let me know if this is a step in the right direction.

**All this will do is add a label for the distance between the moving averages on your chart. Is there a specific distance between the averages you are targeting? If so, I can set the color of the label so that it changes when it meets the criteria.

Hope this helps!

Code:
# Dan Dude

# By Dan Dude
# Get distance Between Moving Averages
# Copyright forever


input price = close;
input EMALength50 = 50;
input EMALength200 = 200;

def EMASlow = MovingAverage(AverageType.Exponential, price, EMALength200);

def EMAFast = MovingAverage(AverageType.Exponential, price, EMALength50);


def DistanceBetween = (Sqrt(Sqr(EMASlow / EMAFast))) / 100;


#AssignBackgroundColor(if DistanceBetween >= 2 then color.dark_red else if DistanceBetween < 2 then color.dark_green else color.current);

AddLabel(yes, "Distance Between Averages =  " + asPercent(round(DistanceBetween,4)));
 
Last edited by a moderator:
@JabronLames, quick question on the code for ATR if I may please. I am trying to test my strategy, so lets say my strategy generated a BUY signal, what I want to do is (if possible) is TOS to get the ATR value at that BUY signal and multiply that number by 4 and that would be my EXIT signal. is this possible? I am trying to figure out with "getvalue" function in TOS but i dont understand that function that well
 
@Learnbot,

The line def ATR = reference ATRTrailingStop(); assigns the current price value(y-axis on chart) of the ATR to the variable(def).

You can certainly create a new variable that multiples this by 4, def ATRx4 = ATR * 4; but this would cause your exit to be 400% of the current price of the trailing stop. I don't think this is what you are trying to accomplish.

Can you show an example of a setup on a chart? It may help me understand what you are trying to do.

*PS - If you are setting your limit sells at 400% gain we should be best friends =)

I'm here to help
 
Last edited:
@Learnbot lol dude 400% gains, I would quit my day job tomorrow! lol I am new with TOS so it was my error. So here is what I am trying to do is let's say I bought 1 stock is of COHN at $18.59 and at that time ATR is 1.31. So what I am trying to do is have a stop loss to be Stock price - (ATR*2), so in this case, it would be 18.59-2.62 = 15.97 and Exit price would be Stock price + (ATR*4) = 18.59+5.42 = 23.83.
NS4nt4.jpg


Hope this makes sense, the goal basically is to test my strategy. I have entry signals just not exit so I am trying to exit based on % profit.

thanks again for your time.
 
Ah, got it. You want the distance represented in $ instead of a percent.

If you're looking for the label on the chart to change color (i.e. GREEN to RED), that's easy peazy. But the ATR is not a static value, it follows the price, so the x4 would zig-zag around and your exit signal would change every candle...

One thing I'm not sure of how to do is reference the market price of the most recent filled order?... Perhaps @BenTen would be able to better answer that question for you, as it is a bit out of my league.

I'm happy to help with this more later, but the market is opening and I got moves to make 💪💪

The script below will change the label to a $.

Code:
input price = close;
input Labels = "Yes";
def ATR = reference ATRTrailingStop();
def distanceToStopInDollars=  (Sqrt(Sqr(price - ATR)));

def ATRx4 = distanceToStopInDollars * 4; # <--- This will multiple the spot by 4

AddLabel(distanceToStopInDollars and yes, "ATR Dist. = $" + asText(round(distanceToStopInDollars,2)), color.light_green);
 
Hello.

Is it possible on TOS to be able to know how far apart the EMA 3 and EMA 9 are away from each other at a given time?

and If so, could this value be converted into a chart label AND a column on a watchlist?

I am really REALLY wanting to figure this out, so anyone who can help would be a hero! Thank you!
 
@ProfessorAR15 I use the relationship between two moving averages to do three things. 1) I have the MAs plotted on a chart to show the visual relationship. You can get a lot of info from this just by the way the MAs cross (quickly or gradually) the steepness of the MAs and the relationship of price to the MAs (does price ride along the MAs or criss-cross them). 2) I have up/down arrows plotted where the crosses occur for a visual alert. 3) I also have a very simple script which plots the relationship of the two MAs. This acts as a visual rendering of the relationship of the two MAs. My system uses crosses and price pattern on the one minute chart for entry trigger. The codes provided by the other knowledgeable traders above is a great beginning and should be either what you are looking for or close. Both of the codes above create labels, or my codes can be modified to give sound, labels or bubbles. Just a quick question. If you are using 3 & 9 MAs, are you using Dennis Anderson's E-mini system by any chance? He has written several books and has a blog (I read it every Tuesday - google it) and is VERY successful. He claims to have made $543,000 for the year up to October, and he is not fibbing. I've been following him for years and he swings a big stick and makes some serious money.
 
@scott69 Thank you so much for this! I am very familiar with the things you mentioned above. I use the 3/9 cross to determine when short term trends begin/end, but don’t have a system for it. I do have several studies related to the EMA cross though that are very helpful. I will definitely Google him when I get home from work. Thank you again!
 
@ProfessorAR15 Please note that Dr. Anderson has multiple accounts and probably has a line of several million and trades multiple contracts in each one of those accounts so results may vary. Set your initial goals for a few hundred a day until you know what you are doing. $200 a day is $50K a year. Not too shabby with a $20,000 or so account (margin on one e-mini contract is $18,000? now) . Trading with a bigger account doesn't mean you are going to make more money, it usually means you are going to lose more money. :) I would also advise starting out with e-micros if you insist on trading index futures ( you will have to qualify to trade futures at TDA). Good luck !!
 
@ProfessorAR15 Here is the code that you need to look at. It was posted by @horserider

Code:
declare lower;

input price = close;
input length = 200;
input AverageType = {default Simple, Exponential};
input pdl = 3;
input ndl = -3;
def MA = MovingAverage(AverageType, ( price[0]), length);
plot DEV = (price / MA - 1 ) * 1000;

plot pdll = pdl;
plot ndll = ndl;
plot zero = 0;

DEV.SetDefaultColor(GetColor(1));

AddLabel(1, "Percentage from " + length + " MA: " + AsPercent(DEV * .01), if DEV > 0 then Color.GREEN else Color.PINK);

A simple moving average has already been added. Now your job is to add another moving average into it. Take a stab at it. We'll be here to help.
 
Last edited by a moderator:
@ProfessorAR15 here's the code if you're still interested. It'll work for both chart and watchlist.

Code:
input price = close;
input length_1 = 3;
input length_2 = 9;
input AverageType = AverageType.SIMPLE;

def MA_1 = MovingAverage(AverageType, price, length_1);
def MA_2 = MovingAverage(AverageType, price, length_2);

def MA_delta = Round(MA_1 - MA_2, 2);

AddLabel(yes, MA_delta, if MA_delta > 0 then Color.GREEN else Color.RED);
 
Last edited by a moderator:
Good day folks,

I have been trying to create a scanner in TOS which highlights current candlesticks that are being squeezed between a 21 & 55 Simple Moving Average

The conditions I seek are:

1. For the 21 SMA to be within 2.5% - 5% above the close price of the candle (green candle) and
2. For the 55 SMA to be within 2.5% - 5% below the open of the candle (green candle).

Ideally these SMAs could be interchanged with a 13 & 50 Exponential Moving Aveage with the same conditions and could be used on multiple time frames but primarily on 30 min time frame option and stock charts.


Below you will find an image of what I'm looking for.
The candle in question is the one circled in red. The yellow line above the candle is the 21 SMA and the pink line below is the 55 SMA

xN149A0.png


I have tried searching on the Stock Hacker tab under the Scan tab in TOS and also have been searching through various posts here but can't seem to find anything remotely close to what I seek. Being that I am also new to scripting, creating a custom script poses a challenge currently.

I appreciate and look forward to any assistance I may receive with this script and am also open to anyone pointing me in the right direction to something similar that has already been created.


Kind regards,
Mordecai
 
@Mordecai 2.5 - 5% of what? The body of the candle? The range of the candle? 2.5-5% of close price is really high and same for below open.
I make reference to the options contract .ABBV201127C104, 30 min timeframe (3:30 pm candle) as an example:

The candle has Close = 0.48 and the 21 SMA at that point is approximately = 0.49. By my calculations, the value of the 21 SMA is about 2% above the candles close.
Same with the Open = 0.4 and the value of the 55 SMA at that point is approximately = 0.39. That make the 55 SMA about 2.5% below the open of that candle.
Based on this example, and what I seek is for the SMAs on either side of the candle to be very close, effectively creating a 'squeeze'.

I tried applying @horserider's code above to suit my needs, however, I seem to be encountering an error when I get to the 'if statement'.

The code below I was tinkering with ( with my limited coding abilities) is attempting to, when run as a scan, find stocks/options with current candle (green candle) having a closed price about 2% below the respective 21 SMA value at that point. I would then try to do the same with the 55 SMA but have that below the open of the candle (green candle) then combine the two conditions in a scan.

Thank you for taking the time to respond.

Code:
declare lower;

input price = close;
input length = 21;
input AverageType = {default Simple, Exponential};
input pdl = 6;
input ndl = -6;
def MA = MovingAverage(AverageType, ( price[0]), length);
def PercentDiff = ((MA/price) - 1)* 100;

if PercentDiff <= 5{
plot pdll = pdl;
plot ndll = ndl;
plot zero = 0;
plot PercentDiff;
}
else {double.NaN;}

The candle I made reference to from the contract is on 11/25/20 @3:30 pm. (30 min TF)
 
@Mordecai Ah, my mistake I thought you were using this for individual tickers and not for the contracts itself. I'll take a stab at it tmr if nobody else posts.
Ideally, I would like to use this on both individual tickers as well as options contracts.

I'm just now seeing the point you made earlier - that based on the underlying price, 2% could end up being quite a distance away from the open & close of the candle especially for tickers with significant prices. In that regard, I might have to rethink my approach in achieving the desired result so it fits right across the board.

Thank you for your consideration and looking forward to hearing from you tomorrow.
 
@Mordecai It works for stock scanner but not option scanner, not sure if you can use studies with option hacker since I tested some built-in studies.

Code:
def price = close;
input length1 = 21;
input length2 = 55;
input AverageType1 = AverageType.SIMPLE;
input AverageType2 = AverageType.SIMPLE;
input top_multi = 2.5;
input bot_multi = 2.5;

def o = open;
def c = close;
def MA1 = Round(MovingAverage(AverageType1, price, length1), 2);
def MA2 = Round(MovingAverage(AverageType2, price, length2), 2);
def green = c > o;
def top = Round(c * (1 + top_multi/100), 2);
def bot = Round(o * (1 - bot_multi/100), 2);
def topcondition = MA1 > c and MA1 < top;
def botcondition = MA2 < o and MA2 > bot;

#FOR SCANNER
plot squeeze = green and topcondition and botcondition;

#FOR CHART
#def squeeze = green and topcondition and botcondition;
#AssignPriceColor(if squeeze then color.WHITE else color.CURRENT);
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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