# 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:

#### kici

##### New member
VIP
## 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, EMA_8, if ema8up then GlobalColor("Green") else GlobalColor("Red"));

This should be easily modifiable to suit your needs.

#### Haidason7

##### New member
VIP

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);

#### MerryDay

Staff member
Staff
VIP

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);``````

#### Kden

##### New member

or

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

thank you,
Kden

Last edited:

#### PaulS

##### New member
VIP
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.

#### Mocnarf1

##### Member
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 sellsignal = sell;
AddOrder(OrderType.SELL_TO_CLOSE, sellsignal, name = "Sell", tickcolor = Color.GREEN, arrowcolor = Color.GREEN);``````

#### halcyonguy

##### Well-known member
VIP
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 sell_off1 = 0.20;

def sell_sig_a = ma1 + sell_off1;
def sell_sig_b = ma2;

#def sell = close > sell_sig_a and close > sell_sig_b;

def sell = close > sell_sig_a and close > sell_sig_b;

input show_lines = yes;
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 sell2 = close > (ma1+selloff1);

def sellsignal = sell;
#AddOrder(OrderType.SELL_TO_CLOSE, sellsignal, name = "Sell", tickcolor = Color.GREEN, arrowcolor = Color.GREEN);

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

#``````

Last edited:

#### Tej_Pra

##### New member
VIP
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.

Last edited by a moderator:

#### MerryDay

Staff member
Staff
VIP
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.
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:

OR

scan for within a certain percentage:

#### Mocnarf1

##### Member
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?

#### MerryDay

Staff member
Staff
VIP
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.

#### Tej_Pra

##### New member
VIP
You need to define price.
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:

OR

scan for within a certain percentage:
Thank you Merry..

#### Mocnarf1

##### Member
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?

#### william9in

##### New member
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!

#### MerryDay

Staff member
Staff
VIP
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:

#### ulle73

##### New member
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

#### MerryDay

Staff member
Staff
VIP
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?
and this:

Last edited:

#### Cori

##### New member
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.

#### MerryDay

Staff member
Staff
VIP
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.

Last edited:

## The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
• Exclusive indicators
• Proven strategies & setups
• Private Discord community
• Exclusive members-only content
• 1 full year of unlimited support

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?