Price crossing Moving Average For ThinkOrSwim

nheminism21

New member
Moving Average Label
Hello Y'all..I'm trying to create a label that display the current value of the 21ema on the chart in thinkorswim. I would also like the label to be colored green if the last bar is over the 21ema or red if the last bar is below the 21ema. I'm not much of a programmer, so I would appreciate any help you can help me with this..thank you in advance
 
Last edited by a moderator:
Solution
How can I add Buy/Sell arrows?

Needing a down arrow to print when price closes below the ema3 and a buy arrow when price closes above the ema1. Each time i've tried to add the arrow coding, the ema lines dissappear.
What is your definition of price?
There are many choices for definition of price: Open Close High Low hl2 hlc3 ohlc4. With today's volatility, all these definitions can miss the mark.

FYI
This thread was started because price crosses average isn't a thing found on the forum.
This is because the standard is moving average crossing another moving average.
Using a moving average w/ a length of 2 or 3 bars provides a clearer signal than attempting to apply one of the above seven definitions of price.
That is why there...
## Global Inputs
input price = close;
input displace = 0;
input ShowLabels = yes;

DefineGlobalColor("Green", CreateColor(51, 255, 51));
DefineGlobalColor("Red", CreateColor(255, 0, 0));

DefineGlobalColor("8-Yellow", CreateColor(255, 255, 51));

input EMA_8_length = 8;
def EMA_8_avg = ExpAverage(price[-displace], EMA_8_length);
plot EMA_8 = EMA_8_avg;
EMA_8.SetDefaultColor(GlobalColor("8-Yellow"));
EMA_8.SetLineWeight(2);

## Definitions if EMA SMA above Price
def ema8up = price > EMA_8;

## Labels Below
AddLabel(ShowLabels, "E8->", GlobalColor("8-Yellow"));
AddLabel(ShowLabels, EMA_8, if ema8up then GlobalColor("Green") else GlobalColor("Red"));


This should be easily modifiable to suit your needs.
 
How can I add Buy/Sell arrows?

Needing a down arrow to print when price closes below the ema3 and a buy arrow when price closes above the ema1. Each time i've tried to add the arrow coding, the ema lines dissappear.

declare upper;

input emaLength = 21;

plot ema1 = ExpAverage (high, emaLength);
plot ema2 = ExpAverage (close, emaLength);
plot ema3 = ExpAverage (low, emaLength);

ema1.AssignValueColor(if ema1 > ema1[1] then Color.cyan else Color.magenta);
ema1.SetLineWeight(2);
ema2.AssignValueColor(if ema2 > ema2[1] then Color.cyan else Color.magenta);
ema2.SetLineWeight(2);
ema3.AssignValueColor(if ema3 > ema3[1] then Color.cyan else Color.magenta);
ema3.SetLineWeight(2);
 
How can I add Buy/Sell arrows?

Needing a down arrow to print when price closes below the ema3 and a buy arrow when price closes above the ema1. Each time i've tried to add the arrow coding, the ema lines dissappear.
What is your definition of price?
There are many choices for definition of price: Open Close High Low hl2 hlc3 ohlc4. With today's volatility, all these definitions can miss the mark.

FYI
This thread was started because price crosses average isn't a thing found on the forum.
This is because the standard is moving average crossing another moving average.
Using a moving average w/ a length of 2 or 3 bars provides a clearer signal than attempting to apply one of the above seven definitions of price.
That is why there is are 280 posts discussing moving averages crosses and only 6 posts discussing price crossing MA.

When you decide on a definition of price, here is the syntax for the arrows:
Rich (BB code):
plot down_arrow =  if PriceDefinition crosses below ema3 then high else double.NaN;
       down.arrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

plot up_arrow =  if  PriceDefinition crosses above ema1 then low else double.NaN;
       up.arrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
 
Solution
Please help me how to tell TOS alerts me when EMA5 crossed above or below EMA20 using thinkscripts.

or

can i use thinkscrips to alert me on candles chart when EMA5 crossed above or below EMA20

thank you,
Kden
 
Last edited:
Go To Scan

Add Filter > Study > Crossovers > MovingAveCrossover

In Search Results tap on the "Show Results Icon" on top right.

Tap on "Alert When Scan Results Change". You decide how you want the alert to come to you.
 
Below and Above the SMA9 Strategy:

Here's a Strategy that Buys at 25cents below SMA9 and Sells at 20cents above SMA9.
It seems to work well with SQQQ, SDOW the generated profit report for both 30 day
and 90 day periods looks good but it's a mixed bag with other stocks.
Can any one here suggest changes that might improve its performance with all stocks?
I want to be able to use the Study version in Sequential Conditional Orders.
Here's the Strategy Script. It's pretty simple.

Code:
def buy =
 close < Average(close - 0.25, 9)
;

def sell = 
 close > Average(close + 0.20, 9)
and
close > Average(close, 21)
;

def buysignal = buy;
def sellsignal = sell;
AddOrder(OrderType.BUY_TO_OPEN, buysignal, name = "Buy", tickcolor = Color.DARK_RED, arrowcolor = Color.RED);
AddOrder(OrderType.SELL_TO_CLOSE, sellsignal, name = "Sell", tickcolor = Color.GREEN, arrowcolor = Color.GREEN);
 
Below and Above the SMA9 Strategy:

Here's a Strategy that Buys at 25cents below SMA9 and Sells at 20cents above SMA9.
It seems to work well with SQQQ, SDOW the generated profit report for both 30 day
and 90 day periods looks good but it's a mixed bag with other stocks.
Can any one here suggest changes that might improve its performance with all stocks?
I want to be able to use the Study version in Sequential Conditional Orders.
Here's the Strategy Script. It's pretty simple.

why is the buy red and the sell green? did you mix them up?
i swapped them in the addorders and it looks pretty good on a few stocks. ( on a 15 min chart)

might add, check if long average length is dropping, then don't buy

for testing, i like to use changeable variables. ( input x = ... )
i like to plot the signals and see how they move in relation to the price.
a length longer than 9 will reduce false actions from little jumps.
an exponential average will track closer to price and respond faster.

here is a modified version
can change the type of average and length.

Code:
#  ma9_buysell_strat_00

def na = double.nan;
def bn = barnumber();

def price = close;
input MA1_len = 9;
input MA1_type =  AverageType.simple;
#input MA1_type =  AverageType.EXPONENTIAL;
def ma1 = MovingAverage(ma1_type, price, ma1_len);

input MA2_len = 21;
input MA2_type =  AverageType.simple;
#input MA2_type =  AverageType.EXPONENTIAL;
def ma2 = MovingAverage(ma2_type, price, ma2_len);

#input MA3_len = 41;
#input MA3_type =  AverageType.EXPONENTIAL;
#def ma3 = MovingAverage(ma3_type, price, ma3_len);

# -----------------------------------------------------

#def buy = close < Average(close - 0.25, 9);
#def sell = close > Average(close + 0.20, 9) and close > Average(close, 21);

input buy_off1 = 0.25;
input sell_off1 = 0.20;

def buy_sig = ma1 - buy_off1;
def sell_sig_a = ma1 + sell_off1;
def sell_sig_b = ma2;

#def buy = close < buy_sig;
#def sell = close > sell_sig_a and close > sell_sig_b;

# buy, is
def buy = close < buy_sig;
def sell = close > sell_sig_a and close > sell_sig_b;


input show_lines = yes;
plot zb1 = buy_sig;
zb1.SetDefaultColor(Color.green);
#z1.setlineweight(1);
zb1.hidebubble();
zb1.SetHiding(!show_lines);

#plot zs1 = sell_sig_a;
#zs1.SetDefaultColor(Color.magenta);
##zs1.setlineweight(1);
#zs1.hidebubble();
#zs1.SetHiding(!show_lines);

plot zs2 = sell_sig_b;
zs2.SetDefaultColor(Color.magenta);
#zs2.setlineweight(1);
zs2.hidebubble();
zs2.SetHiding(!show_lines);

#==========================================


#def buy2 = close < (ma1-buyoff1);
#def sell2 = close > (ma1+selloff1);

def buysignal = buy;
def sellsignal = sell;
#AddOrder(OrderType.BUY_TO_OPEN, buysignal, name = "Buy", tickcolor = Color.DARK_RED, arrowcolor = Color.RED);
#AddOrder(OrderType.SELL_TO_CLOSE, sellsignal, name = "Sell", tickcolor = Color.GREEN, arrowcolor = Color.GREEN);

#AddOrder(OrderType.BUY_TO_OPEN, buysignal, name = "Buy", tickcolor = Color.green, arrowcolor = Color.green);
#AddOrder(OrderType.SELL_TO_CLOSE, sellsignal, name = "Sell", tickcolor = Color.red, arrowcolor = Color.red);

# rev buy/sell actions
AddOrder(OrderType.BUY_TO_OPEN, sellsignal, name = "buy", tickcolor = Color.GREEN, arrowcolor = Color.GREEN);
AddOrder(OrderType.sell_to_close, buysignal, name = "sell", tickcolor = Color.DARK_RED, arrowcolor = Color.RED);
#
 
Last edited:
Hello,

Can anyone help to create a scan for below please

1. When the price crosses above 21 EMA on 5min TF - to go long
2. When the price crosses below 21 EMA on 5min TF - for short.

1663181987431.png
 
Last edited by a moderator:
Hello,

Can anyone help to create a scan for below please

1. When the price crosses above 21 EMA on 5min TF - to go long
2. When the price crosses below 21 EMA on 5min TF - for short.
You need to define price.
Here are your choices:
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Fundamentals

FYI, because "price" is difficult to quantify on a candle, most members either scan for when a short moving average crosses a long moving average as you did in your other post:
https://usethinkscript.com/threads/moving-average-crossovers-for-thinkorswim.229/page-8#post-86826

OR

scan for within a certain percentage:
https://usethinkscript.com/threads/...een-emas-or-any-2-plots-for-thinkorswim.1345/
 
why is the buy red and the sell green? did you mix them up?
i swapped them in the addorders and it looks pretty good on a few stocks. ( on a 15 min chart)

Thank you for the pure Think Script version. I am not yet skilled enough with ThinkScript so this will help me a lot in learning. Thanks

Is it more efficient to use ThinkScript rather than the prebuilt studies? Is there an advantage to the pure ThinkScript verses using TOS Studies?
 
i swapped them in the addorders and it looks pretty good on a few stocks. ( on a 15 min chart)

Thank you for the pure Think Script version. I am not yet skilled enough with ThinkScript so this will help me a lot in learning. Thanks

Is it more efficient to use ThinkScript rather than the prebuilt studies? Is there an advantage to the pure ThinkScript verses using TOS Studies?
On the ToS platform, there is no difference in "efficiency" between custom versus prebuilt studies.
 
You need to define price.
Here are your choices:
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Fundamentals

FYI, because "price" is difficult to quantify on a candle, most members either scan for when a short moving average crosses a long moving average as you did in your other post:
https://usethinkscript.com/threads/moving-average-crossovers-for-thinkorswim.229/page-8#post-86826

OR

scan for within a certain percentage:
https://usethinkscript.com/threads/...een-emas-or-any-2-plots-for-thinkorswim.1345/
Thank you Merry..
 
halcyonguy, Because am not well versed in ThinkScript yet. I tried to copy and paste sections of the code into separate Buy and Sell Studies i am not being successful.
I would like to separate the Buy side and the Sell side and put them in their own Study Buy_Study and Sell_Study which would evaluate to either true or false. Could you please break the Strategy into Buy and Sell Studies?
 
Can someone help? I'm trying to create a strategy backtest for this particular code.
Buy when close crosses above MovAvgExponential("length" = 21)."AvgExp"
Sell when close crosses below MovAvgExponential("length" = 21)."AvgExp"
Thank You!
 
Can someone help? I'm trying to create a strategy backtest for this particular code.
Buy when close crosses above MovAvgExponential("length" = 21)."AvgExp"
Sell when close crosses below MovAvgExponential("length" = 21)."AvgExp"
Thank You!
Sorry, no one in the community responded to your post.
It is generally unadvisable to use 'close' as your cross. This requires that a specific part of the candle must be where the cross occurs.
The more standard strategy uses a fast (short) moving average as the cross over the EMA21
You will find many of these types of crossover strategies here:
https://usethinkscript.com/threads/moving-average-crossovers-for-thinkorswim.229/
 
But can that really be true? Tos cant Scan for stocks above its 20 day moving average?!
Last Price > ma20 ? But cant get any results to show when i use the scanner. I want to see if scanner shows result of 2500/5000 stocks i know 50% are above its ma20. Then i dont need tos to add that special ticker of percent above its ma20
 
But can that really be true? Tos cant Scan for stocks above its 20 day moving average?!
Last Price > ma20 ? But cant get any results to show when i use the scanner. I want to see if scanner shows result of 2500/5000 stocks i know 50% are above its ma20. Then i dont need tos to add that special ticker of percent above its ma20
If you want to scan for close > average(close,20)
put this in the scan hacker:
Ruby:
 close > average(close,20)

You realize that a stock can be falling like a rock and still be above it's 20-day average?
read through this:
https://usethinkscript.com/threads/price-crossing-moving-average.10161/#post-91597
and this:
https://usethinkscript.com/threads/price-crossing-moving-average-for-thinkorswim.10161/#post-109862
 
Last edited:
Hi, How do I go by creating a script that include sound.bell on a alert.bar for the 20 EMA study for all symbols all at once. I learned how to create the sound alert for the EMA, but I have to create it for each symbol at a time. Currently, I input the symbol of choice, press price, create alert, choose under price "study", close crosses EMA 20, is (True), options (create regular alert) and press create.
 
Hi, How do I go by creating a script that include sound.bell on a alert.bar for the 20 EMA study for all symbols all at once. I learned how to create the sound alert for the EMA, but I have to create it for each symbol at a time. Currently, I input the symbol of choice, press price, create alert, choose under price "study", close crosses EMA 20, is (True), options (create regular alert) and press create.
On the ToS platform to "find all symbols", you use the scan hacker. Set up your alert condition close crosses ExpAverage(close, 20) as the filter and then set up an alert on that scan.
Read more:
 
Last edited:

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