Moving Average Crossovers For ThinkOrSwim

try this and adjust t he way you want.

CSS:
def FastMA = ExpAverage(close, 3);
def SlowMA = ExpAverage(close, 8);

def Condition = FastMA>SlowMA;
def barssince = if Condition then barssince[1] + 1 else 0;

def bar = if barssince>0 then  barssince else Double.NaN;

plot scan = bar within 3 bars;

scan.SetDefaultColor(Color.BLACK);
AssignBackgroundColor(if bar >= 10 then color.CYAN else if bar  >= 3 then color.GREEN else if bar  > 0 then color.YELLOW else color.LIGHT_RED);
Dang, that was quick. Thank you for your help. I have been trying to do this for hours and haven't got it to work. LOL I was no where near that code. If the 8 ema goes above the 3 MA does the color go to red? And does this get affected by timeframes? Can I also have the number represent how many bars it has crossed?

@samer800 I just tested using OnDemand. It does show colors but they are way off on bar timing. For instance, I waited for the 3MA to cross over the 8MA. It was below it for at least 20 bars on the 1 min and the watch list was already showing a green colored box. When it did cross over, nothing actually changed. What I was hoping to achieve, was to have the box turn green when the 3 ma crosses over the 8 ma for at least 3 bars and then go to red when the 8 ma crosses over the 3 ma for at least 3 bars anything outside of 3 bars can be yellow/gray/or no color. No need for the number of bars displayed as mentioned above.
 
Last edited by a moderator:
Hi @SleepyZ,
Can you please show how to addlabel for the price where the two EMAs Crossover?

input price = close;
input length1 = 200;
input length2 = 50;
input displace = 0;
input showBreakoutSignals = no;
def bn=barnumber();
def AvgExp1 = ExpAverage(price[-displace], length1);
def AvgExp2 = ExpAverage(price[-displace], length2);
plot x = if AvgExp2 crosses above AvgExp1 then price else 0;
addlabel(yes, x, "$"+Round(x,2),color.yellow);

it produced the following error: 3 params expected but 4 found while calling addlabel
 
Last edited by a moderator:
Hi @SleepyZ,
Can you please show how to addlabel for the price where the two EMAs Crossover?

input price = close;
input length1 = 200;
input length2 = 50;
input displace = 0;
input showBreakoutSignals = no;
def bn=barnumber();
def AvgExp1 = ExpAverage(price[-displace], length1);
def AvgExp2 = ExpAverage(price[-displace], length2);
plot x = if AvgExp2 crosses above AvgExp1 then price else 0;
addlabel(yes, x, "$"+Round(x,2),color.yellow);

it produced the following error: 3 params expected but 4 found while calling addlabel

This will find the last close price when the expavgs crossed

Screenshot-2022-12-21-120117.png
Ruby:
input price = close;
input length1 = 200;
input length2 = 50;
input displace = 0;
input showBreakoutSignals = no;
def bn=barnumber();
plot AvgExp1 = ExpAverage(price[-displace], length1);
plot AvgExp2 = ExpAverage(price[-displace], length2);
def x = if AvgExp2 crosses above AvgExp1 then price else x[1];
addlabel(yes, "Last AvgExp Crossover Close Price: $"+Round(x,2),color.yellow);
 
Here is my try.. TwoLines with Colored bars

Code:
#TwoLines with Colored bars
input price = close;
input fastLength = 10;
input slowLength = 10;
input displace = 0;
input FastAverageType = AverageType.SIMPLE;
input SlowAverageType = AverageType.EXPONENTIAL;

plot fastAvg = MovingAverage(FastAverageType, price[-displace], fastLength);
plot slowAvg = MovingAverage(SlowAverageType, price[-displace], slowLength);

fastAvg.SetDefaultColor(GetColor(1));
slowAvg.SetDefaultColor(GetColor(0));

input paintBars = yes;
AssignPriceColor(if !paintBars
    then Color.CURRENT
    else if fastAvg < slowAvg
        then Color.BLUE
        else if  fastAvg > slowAvg
            then Color.RED
            else Color.CURRENT);
 
Last edited:
Here is my try.. TwoLines with Colored bars

Code:
#TwoLines with Colored bars
input price = close;
input fastLength = 10;
input slowLength = 10;
input displace = 0;
input FastAverageType = AverageType.SIMPLE;
input SlowAverageType = AverageType.EXPONENTIAL;

plot fastAvg = MovingAverage(FastAverageType, price[-displace], fastLength);
plot slowAvg = MovingAverage(SlowAverageType, price[-displace], slowLength);

fastAvg.SetDefaultColor(GetColor(1));
slowAvg.SetDefaultColor(GetColor(0));

input paintBars = yes;
AssignPriceColor(if !paintBars
    then Color.CURRENT
    else if fastAvg < slowAvg
        then Color.BLUE
        else if  fastAvg > slowAvg
            then Color.RED
            else Color.CURRENT);
Thank you for this. I just adjusted the EMA and SMA value for 15mins TF to fit my needs.
 
Hello
Is there a Scan for 3 MA Crosses, 15, 50, 200 or 15,50, 100?
I have taken the original code for the two crossovers and I am playing with adding a third. I have it correctly defined etc, but I am having trouble adding the statement for when the 9 crosses the 21 AND the 34 to correctly plot and alert. If I get it to work, I will post it here. Unless someone beats me to it.
 
Sounds like you might be a Benzinga fan :) . Here is a script I use that was inspired by them. The plot lines are hidden since I use it for the cloud.
I added in the Alerts for you and have not tested them. You can change the Tick to Bar if you want it to sound only once per crossing within the bar. Comment out # out the Hide() if you want the lines or don't want the labels.


Code:
# 8 EMA  above 21 Ema  = bullish
# Benzinga inspired
#AddLabel(yes, "8/21 EMA", color.cyan);


def s_ema = ExpAverage(close, 8);
def l_ema = ExpAverage(close, 21);

def bullish = s_ema > l_ema;
def bearish = l_ema > s_ema;

  AddLabel(yes, if bullish then "bullish_8/21ema" else "", CreateColor(175,250,175));
  AddLabel(yes, if bearish then "bearish_8/21ema" else "", CreateColor(250,125,125));

plot DEMAS = s_ema;
DEMAS.SetDefaultColor(GetColor(1));
DEMAS.Hide();

plot DEMAL = l_ema;
DEMAL.SetDefaultColor(GetColor(1));
demal.Hide();

AddCloud(DEMAS,  DEMAL,  CreateColor(175,250,175),  CreateColor(250,125,125));


#--Alerts added for Town7425  Change Alert from Tick to Bar if you want it to sound only once on crossing per each bar
Alert(s_ema crosses above l_ema, "8 ema crossed up", Alert.Tick, Sound.Ding);
Alert(l_ema crosses above s_ema, "21 ema crossed up", Alert.Tick, Sound.Chimes);
can you be alerted on the daily? how would that work coding wise?
 
This is just a simple indicator for moving average crossover but added scanner, cloud, and alerts for additional visual effect and enhancement.

For example, if 5/10 EMA crossover is your strategy, then this indicator plot an up arrow on the golden cross and down arrow on the death cross. You can also use the scanner to scan for stocks with EMA crossover and the built-in alerts to let you know as it happens.

1XlzIJA.png


thinkScript Code

Rich (BB code):
# Moving Average Crossover With Arrows, Alerts, Crossing Count and Bubble at Cross
# Mobius
# Chat Room Request 01.25.2017
# Modified a bit by BenTen

input price = close;
input fastLength = 8;
input slowLength = 21;
input averageType = AverageType.EXPONENTIAL;

plot FastMA = MovingAverage(averageType, price, fastLength);
plot SlowMA = MovingAverage(averageType, price, slowLength);
FastMA.SetDefaultColor(GetColor(1));
SlowMA.SetDefaultColor(GetColor(2));

plot ArrowUp = if FastMA crosses above SlowMA
               then low
               else double.nan;
     ArrowUP.SetPaintingStrategy(PaintingStrategy.Arrow_UP);
     ArrowUP.SetLineWeight(3);
     ArrowUP.SetDefaultColor(Color.Green);
plot ArrowDN = if FastMA crosses below SlowMA
               then high
               else double.nan;
     ArrowDN.SetPaintingStrategy(PaintingStrategy.Arrow_DOWN);
     ArrowDN.SetLineWeight(3);
     ArrowDN.SetDefaultColor(Color.Red);
Alert(ArrowUp, " ", Alert.Bar, Sound.Chimes);
Alert(ArrowDN, " ", Alert.Bar, Sound.Bell);

AddCloud(FastMA, SlowMA, Color.GREEN, Color.RED);
# End Code

Shareable Link

https://tos.mx/2ZED6i
@BenTen , Can you show how to add addOrder(OrderType.BUY_AUTO, no); to your this crossover study so that I can backtest it in thinkorswim?
 
@BenTen , Can you show how to add addOrder(OrderType.BUY_AUTO, no); to your this crossover study so that I can backtest it in thinkorswim?
Is there anyway to make an alert for when a candle crosses over two moving averages rather than a moving average crossing a moving average? Like maybe make it red if the price is below the two averages, yellow if it is above one of the averages, and green if it crosses both the averages for your watchlist and you can have the same buy/sell signals in the charts.

I'm looking for when the candle crosses (doesn't have to close) above the 9 SMA and 9 WMA. I'd like to have a watchlist function for it. That way I'm not trying to switch back and forth between chart after chart.
 
Last edited by a moderator:
I'm trying to observe fluctations when certain EMA's intersect. Can anyone help me find a way to create indicators whenever two or more EMA's of my chooising intersect? Thank you in advance
 
I'm trying to observe fluctations when certain EMA's intersect. Can anyone help me find a way to create indicators whenever two or more EMA's of my chooising intersect? Thank you in advance

This should help with inputs for various options

Screenshot-2023-02-12-133656.png
Code:
# Example_Addchartbubble_movavgcrosser
#
#

input show_arrows  = yes;
input show_bubbles_up_dn = yes;
input show_bubbles_time  = yes;
input price = close;
input length1 = 15;
input length2 = 30;
input averageType1 = AverageType.EXPONENTIAL;
input averageType2 = AverageType.EXPONENTIAL;


plot avg1 = MovingAverage(averageType1, price, length1);
plot avg2 = MovingAverage(averageType2, price, length2);

plot signalup = if avg1 crosses above avg2 then avg1 else Double.NaN;
plot signaldn = if avg1 crosses below avg2 then avg2 else Double.NaN;

signalup.SetDefaultColor(Color.GREEN);
signaldn.SetDefaultColor(Color.RED);
signalup.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
signaldn.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
signalup.sethiding(!show_arrows);
signaldn.sethiding(!show_arrows);

#Time defined
input timezone = {default "ET", "CT", "MT", "PT"};

def starthour  = (if timezone == timezone."ET"
                        then 9
                        else if timezone == timezone."CT"
                        then 8
                        else if timezone == timezone."MT"
                        then 7
                        else 6) ;
def hour = Floor(((starthour * 60 + 30) + (GetTime() - RegularTradingStart(GetYYYYMMDD())) / 60000) / 60);
def minutes = (GetTime() - RegularTradingStart(GetYYYYMMDD())) / 60000 - ((hour - starthour) * 60 + 30) + 60;
#

AddChartBubble(show_bubbles_up_dn and signalup, avg1 - TickSize() * 2, "UP", Color.GREEN, no);
AddChartBubble(show_bubbles_time and signalup, avg1 - TickSize() * 2, hour + ":" + (if minutes < 10
            then "0" else "") + minutes, Color.WHITE, no);

AddChartBubble(show_bubbles_up_dn and signaldn, avg2 + TickSize() * 2, "DN", Color.RED, yes);
AddChartBubble(show_bubbles_time and signaldn, avg2 + TickSize() * 2, hour + ":" + (if minutes < 10
            then "0" else "") + minutes, Color.WHITE, yes);
 
I am trying to get this to work with a scan so it can be used with watchlists and alerts for a 15/50 EMA bullish crossover on a 10 minute time frame. How would I incorporate that?
 
This I think has good potential!!

I have been using this
https://www.tradingview.com/script/...s-for-Small-Quick-Profits-on-3commas-DCA-bot/
on trading view and think it would be killer for TOS. I have been using the TEMA setting on the 3 minutes with the setttings tweak and is has given some great signals. I am trying to learn how to code but i just wanted to see if we could get it for the TOS community!!


Thanks for all you guys do!!
Happy Trading!!
 
Last edited by a moderator:
This I think has good potential!!

I have been using this
https://www.tradingview.com/script/...s-for-Small-Quick-Profits-on-3commas-DCA-bot/
on trading view and think it would be killer for TOS. I have been using the TEMA setting on the 3 minutes with the setttings tweak and is has given some great signals. I am trying to learn how to code but i just wanted to see if we could get it for the TOS community!!


Thanks for all you guys do!!

Happy Trading!!




// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rouxam
// This simple study generates alerts for buying at MA Crossover in 3commas
// The alerts are best combined with a DCA bot like 3commas.
// This works very well on sideways markets with small Take Profits <= 0.6%
//@version=4
study("MA Crossover Buy Alerts", shorttitle="MA crossover", overlay=true)
//inputs
ma_type = input(7, minval=1, maxval=4, title="1=SMA, 2=EMA, 3=WMA, 4=HullMA, 5=VWMA, 6=RMA, 7=TEMA")
slow_ma_period = input(100, minval=30, maxval=200, title="Slow MA Period")
fast_ma_period = input(20, minval=5, maxval=40, title="Fast MA Period")
slow_mfi_period = input(50, minval=30, maxval=200, title="Slow MFI Period")
fast_mfi_period = input(7, minval=5, maxval=40, title="Fast MFI Period")
slow_mfi_ob = input(65, minval=50, maxval=100, title="Slow MFI Overbought Threshold")
fast_mfi_os = input(30, minval=0, maxval=50, title="Fast MFI Oversold Threshold")
get_ma(src, ma_type, len) =>
hullma = wma(2*wma(src, len/2) -wma(src, len), round(sqrt(len)))
ema1 = ema(src, len)
ema2 = ema(ema1, len)
ema3 = ema(ema2, len)
tema = 3 * (ema1 - ema2) + ema3
if ma_type == 1
sma(src, len)
else
if ma_type == 2
ema(src, len)
else
if ma_type == 3
wma(src, len)
else
if ma_type == 4
hullma
else
if ma_type == 5
vwma(src, len)
else
if ma_type == 6
rma(src, len)
else
tema
// Calculate Fast and Slow Moving averages
fast_ma = get_ma(close, ma_type, fast_ma_period)
slow_ma = get_ma(close, ma_type, slow_ma_period)
slow_ma_up = slow_ma >= slow_ma[1]
// Buy signal: MA Crossover, with slow MA trending upwards
buy = crossover(fast_ma, slow_ma) and slow_ma_up
// Low-pass filter to avoid generating too many consecutive orders
check(buy) => buy and not buy[1] and not buy[2] and not buy[3] and not buy[4] and not buy[5] and not buy[6]
buy_signal = check(buy)
alertcondition(buy_signal, title='MA Crossover Buy Signal', message='MA Crossover Buy Signal')
// Plot color: Green if fast MA higher than slow MA
color_uptrend = fast_ma >= slow_ma ? color.lime : color.red
plot(fast_ma, title="Fast Moving Average", linewidth=3, color=color_uptrend)
plot(slow_ma, title="Slow Moving Average", linewidth=1, color=color_uptrend)
plotshape(buy_signal ? low : na, 'Buy', shape.labelup, location.belowbar, color=color.teal, size=size.small)
find below

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
#// © rouxam
#// This simple study generates alerts for buying at MA Crossover in 3commas
#// The alerts are best combined with a DCA bot like 3commas.
#// This works very well on sideways markets with small Take Profits <= 0.6%
#study("MA Crossover Buy Alerts", shorttitle="MA crossover", overlay=true)
# converted by Sam4Cok@Samer800 - request from useThinkScript.com member - 06/2023
input ma_type         = {SMA, EMA, WMA, HullMA, VWMA, RMA, default TEMA};
input slow_ma_period  = 100;#, minval=30,  maxval=200, title="Slow MA Period")
input fast_ma_period  = 20;#, minval=5,   maxval=40,  title="Fast MA Period")

def na = Double.NaN;

#get_ma(src, ma_type, len) =>
script get_ma {
    input src = close;
    input ma_type = "TEMA";
    input len = 100;
    def hullma = HullMovingAvg(src, len);
    def vwma = Average(src * volume, len) / Average(volume, len);
    def ema1 = ExpAverage(src, len);
    def ema2 = ExpAverage(ema1, len);
    def ema3 = ExpAverage(ema2, len);
    def tema = 3 * (ema1 - ema2) + ema3;
    def ma = if ma_type == "SMA" then Average(src, len) else
        if ma_type == "EMA" then ExpAverage(src, len)   else
            if ma_type == "WMA" then WMA(src, len) else
                if ma_type == "HullMA" then hullma else
                    if ma_type == "VWMA" then vwma else
                        if ma_type == "RMA" then WildersAverage(src, len) else tema;
    plot out = ma;
}

#// Calculate Fast and Slow Moving averages
def fast_ma = get_ma(close, ma_type, fast_ma_period);
def slow_ma = get_ma(close, ma_type, slow_ma_period);
def slow_ma_up = slow_ma >= slow_ma[1];

#// Buy signal: MA Crossover, with slow MA trending upwards
def buy = crosses(fast_ma, slow_ma, CrossingDirection.ABOVE) and slow_ma_up;

#// Low-pass filter to avoid generating too many consecutive orders
def checkbuy = buy and !buy[1] and !buy[2] and !buy[3] and !buy[4] and !buy[5] and !buy[6];
def buy_signal = checkbuy;


#// Plot color: Green if fast MA higher than slow MA
def col = fast_ma >= slow_ma;
plot FastMovingAverage = fast_ma;#, title="Fast Moving Average", linewidth=3, color=color_uptrend)
plot SlowMovingAverage = slow_ma;#, title="Slow Moving Average", linewidth=1, color=color_uptrend)

FastMovingAverage.SetLineWeight(2);
FastMovingAverage.AssignValueColor(if col then Color.GREEN else Color.RED);
SlowMovingAverage.AssignValueColor(if col then Color.GREEN else Color.RED);

AddChartBubble(buy_signal, low, "Buy",  Color.GREEN, no);# shape.labelup, location.belowbar, color=color.teal,  size=size.small)


#-- END of CODE
 

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