Moving Average Crossovers

BenTen

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

Craighaber71

Active member
2019 Donor
VIP
Hey guys I'm looking for a watchlist script for a 9EMA cross Vwap..With the background color coded to the up/downside....also plot how many bars ago this happened...I've found many online but not like this...

Thanks
 

BenTen

Administrative
Staff member
Staff
VIP
Give this a try

Code:
# Price crossing above or below 9 EMA and VWAP
# By BenTen of useThinkScript.com

declare upper;

# Moving Average
input priceMA = close;
input lengthMA = 9;
input displace = 0;
input showBreakoutSignals = yes;
input price = close;

def EMA = ExpAverage(priceMA[-displace], lengthMA);

# VWAP
input numDevDn = -2.0;
input numDevUp = 2.0;
input timeFrame = {default DAY, WEEK, MONTH};

def cap = GetAggregationPeriod();
def errorInAggregation =
    timeFrame == timeFrame.DAY and cap >= AggregationPeriod.WEEK or
    timeFrame == timeFrame.WEEK and cap >= AggregationPeriod.MONTH;
Assert(!errorInAggregation, "timeFrame should be not less than current chart aggregation period");

def yyyyMmDd = GetYYYYMMDD();
def periodIndx;
switch (timeFrame) {
case DAY:
    periodIndx = yyyyMmDd;
case WEEK:
    periodIndx = Floor((DaysFromDate(First(yyyyMmDd)) + GetDayOfWeek(First(yyyyMmDd))) / 7);
case MONTH:
    periodIndx = RoundDown(yyyyMmDd / 100, 0);
}
def isPeriodRolled = CompoundValue(1, periodIndx != periodIndx[1], yes);

def volumeSum;
def volumeVwapSum;
def volumeVwap2Sum;

if (isPeriodRolled) {
    volumeSum = volume;
    volumeVwapSum = volume * vwap;
    volumeVwap2Sum = volume * Sqr(vwap);
} else {
    volumeSum = CompoundValue(1, volumeSum[1] + volume, volume);
    volumeVwapSum = CompoundValue(1, volumeVwapSum[1] + volume * vwap, volume * vwap);
    volumeVwap2Sum = CompoundValue(1, volumeVwap2Sum[1] + volume * Sqr(vwap), volume * Sqr(vwap));
}
def priceVWAP = volumeVwapSum / volumeSum;
def deviation = Sqrt(Max(volumeVwap2Sum / volumeSum - Sqr(priceVWAP), 0));

def VWAP = priceVWAP;

def bullish_signal = EMA crosses above priceVWAP;
def bearish_signal = EMA crosses below priceVWAP;

# Plot Signals
plot bullish = bullish_signal;
bullish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
bullish.SetDefaultColor(Color.CYAN);
bullish.SetLineWeight(3);

plot bearish = bearish_signal;
bearish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
bearish.SetDefaultColor(Color.CYAN);
bearish.SetLineWeight(3);
 
Last edited:

zeek

Active member
2019 Donor
Hi guys, one of my long strategies is to look for the 5EMA to reclaim/cross the VWAP to the upside on the 5min chart and was wondering if anyone could code an indicator for this. Preferably, when the cross happens, a label lights up in a strong color and when there is no cross happening, it stays in a grey color.

Can this be done?
 

horserider

Well-known member
VIP
@zeek See if this works. You can turn off the plots if confirm it is working.

9bjqsba.png


Code:
# 5 EMA and VWAP cross. Modified 2 ToS studies and added labels for crosses. By Horserider 7/21/2019

# TD Ameritrade IP Company, Inc. (c) 2011-2019
#

input timeFrame = {default DAY, WEEK, MONTH};

def cap = getAggregationPeriod();
def errorInAggregation =
    timeFrame == timeFrame.DAY and cap >= AggregationPeriod.WEEK or
    timeFrame == timeFrame.WEEK and cap >= AggregationPeriod.MONTH;
assert(!errorInAggregation, "timeFrame should be not less than current chart aggregation period");

def yyyyMmDd = getYyyyMmDd();
def periodIndx;
switch (timeFrame) {
case DAY:
    periodIndx = yyyyMmDd;
case WEEK:
    periodIndx = Floor((daysFromDate(first(yyyyMmDd)) + getDayOfWeek(first(yyyyMmDd))) / 7);
case MONTH:
    periodIndx = roundDown(yyyyMmDd / 100, 0);
}
def isPeriodRolled = compoundValue(1, periodIndx != periodIndx[1], yes);

def volumeSum;
def volumeVwapSum;
def volumeVwap2Sum;

if (isPeriodRolled) {
    volumeSum = volume;
    volumeVwapSum = volume * vwap;
    volumeVwap2Sum = volume * Sqr(vwap);
} else {
    volumeSum = compoundValue(1, volumeSum[1] + volume, volume);
    volumeVwapSum = compoundValue(1, volumeVwapSum[1] + volume * vwap, volume * vwap);
    volumeVwap2Sum = compoundValue(1, volumeVwap2Sum[1] + volume * Sqr(vwap), volume * Sqr(vwap));
}
def price = volumeVwapSum / volumeSum;


plot VWAP = price;


# TD Ameritrade IP Company, Inc. (c) 2017-2019
#

input price2 = close;
input length = 5;
input displace = 0;


plot AvgExp = ExpAverage(price2[-displace], length);


AddLabel(yes, "Buy ", if avgexp > vwap then Color.GREEN else color.GRAY);

AddLabel(yes, "Sell", if avgexp < vwap then Color.RED else color.GRAY);
 

wilmanv

Member
VIP
Any VWAP Cross Over Indicator with Moving Average?

Edit: Thanks to all, I thinks that script above resolve my question 👍 👍 👍
 

jay2

Member
Thanks @BenTen

Using this for the 9EMA crossing 20SMA as signal for possibly entry/exit. Although I dont see Bubble at Cross. Show Bubble is enabled.

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 = 9;
input slowLength = 20;
input averageType = AverageType.EXPONENTIAL;
input averageType2 = AverageType.SIMPLE;

plot FastMA = MovingAverage(averageType, price, fastLength);
plot SlowMA = MovingAverage(averageType2, 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
 

tomsk

Well-known member
VIP
@jay2 - If you read the notes in the study @BenTen posted, he mentioned he modified the study slightly.

Here is the original version of Mobius study configured with the 9/20 EMA using your desired periods. It does have bubbles but only for the very last cross

Code:
# Moving Average Crossover With Arrows, Alerts, Crossing Count and Bubble at Cross and trend colors
# Mobius
# Chat Room Request 01.25.2017

input price = close;
input fastLength = 9;
input slowLength = 20;
input averageType = AverageType.EXPONENTIAL;

plot FastMA = MovingAverage(averageType, price, fastLength);
plot SlowMA = MovingAverage(averageType, price, slowLength);
FastMA.AssignValueColor(if FastMA > SlowMA then color.green else color.red);
SlowMA.AssignValueColor(if FastMA > SlowMA then color.green else color.red);

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);
def countUP = if FastMA crosses above SlowMA
              then 1
              else if FastMA > SlowMA
                   then countUP[1] + 1
              else if ArrowDN
                   then 0
                   else countUP[1];
AddLabel(1, "Count UP = " + countUP, color.white);
def CrossBar = if FastMA crosses SlowMa
               then barNumber()
               else double.nan;
AddChartBubble(barNumber() == HighestAll(CrossBar), FastMA, "Cross", color.cyan);
# End Code
 

Ty199

New member
I have been looking for MA's to combine with other indicators. Here is another version, just a little differant. You can use it also as a entry for the Super Trend or Reversal Trend to get in on a trade between Reversal candles.

As you can see Im not a photo editor lol...
Code only for MA's you can adjust to your setting easy.

Code:
#hint: <b>Find Moving Average Xover</b>\nFinds when a fast moving average crosses over or under a slow.\n The fast average going above the slow average (bullish crossover) is a signal to buy, while the opposite situation (bearish crossover) is a signal to sell.

input price = close;#hint price: The price used to calculate the crossover. <b>(Default is CLOSE)</b>
input fastLength = 3;#hint fastLength: The number of bars used to calculate the fast moving average. <b>(Default is 3)</b>
input slowLength = 8;#hint slowLength: The number of bars used to calculate the slow moving average. <b>(Default is 8)</b>
input slowAvgType = {default Simple, Exponential, Weighted, Wilders, Hull};#hint slowAvgType: Type of the fast moving average to be used for calculation. <b>(Default is Expontential)</b>
input fastAvgType = {default Simple, Exponential, Weighted, Wilders, Hull};#hint fastAvgType: Type of the fast moving average to be used for calculation. <b>(Default is Exponential)</b>
Input DoArrows = no;#hint DoArrows:Yes shows arrows to define crosses
Input DoPlots = yes;#hint DoPlots: Yes shows MA plots to define crosses. Default is 'YES'
Input DoAlerts = No;#hint DoAlerts:No turns off alerts

Assert( fastLength < slowLength, "fastLength ["+fastLength+"] must be less than slowLength["+slowLength+"]");

def fastAvg;
switch (slowAvgType) {
  case Simple:
    fastAvg = Average(price, fastLength);
  case Exponential:
    fastAvg = ExpAverage(price, fastLength);
  case Weighted:
    fastAvg = wma(price, fastLength);
  case Wilders:
    fastAvg = WildersAverage(price, fastLength);
  case Hull:
    fastAvg = HullMovingAvg(price, fastLength);
}

def slowAvg;
switch (fastAvgType) {
  case Simple:
    slowAvg = Average(price, slowLength);
  case Exponential:
    slowAvg = ExpAverage(price, slowLength);
  case Weighted:
    slowAvg = wma(price, slowLength);
  case Wilders:
    slowAvg = WildersAverage(price, slowLength);
  case Hull:
    slowAvg = HullMovingAvg(price, slowLength);
}

plot signalXup = If DoArrows Then crosses(fastAvg, slowAvg, CrossingDirection.above) else Double.nan;

signalXup.SetDefaultColor(Color.pink);
signalXup.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
signalXup.SetLineWeight(3);
plot signalXdn =  If DoArrows Then crosses(fastAvg, slowAvg, CrossingDirection.below) else Double.nan;

signalXdn.SetDefaultColor(Color.Green);
signalXdn.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
signalXdn.SetLineWeight(3);

Alert(signalXup && DoAlerts, "UP...Fast MA Cross Above Slow MA", Alert.BAR, Sound.Ring );
Alert(signalXdn && DoAlerts, "Down...Fast Ma Cross Below Slow MA", Alert.BAR, Sound.Bell );

Plot fast_Avg = If DoPlots  then Fastavg else double.nan;
fast_Avg.SetDefaultColor(Color.pink);
fast_Avg.SetPaintingStrategy(PaintingStrategy.line);
fast_Avg.SetLineWeight(2);

Plot Slo_Avg = If DoPlots  then Slowavg else double.nan;
Slo_Avg.SetDefaultColor(Color.cyan);
Slo_Avg.SetPaintingStrategy(PaintingStrategy.line);
Slo_Avg.SetLineWeight(2);

AddCloud(fastAvg, slowAvg, color.green, color.red);
AddLabel(1, "Fast MA(" + fastLength + ")",color.pink);
AddLabel(1, "Slow MA(" + slowLength + ")",color.cyan);
 
Last edited by a moderator:

Bung Bang

New member
Hi! I am trying to get a TOS scanner for EMA(9) crosses VWAP by certain lookback bars (1bar, 2 bars, 3 bars etc) for intraday trading? I am not sure how to change the codes in the watchlist above.; can anybody help ?
 

tomsk

Well-known member
VIP
@Bung Bang A scan code that looks for EMA(9) crossing VWAP can be simply coded as follows. If you want this to lookback 2 bars, just change the value of the variable lookback to 2. Be default it is set to 0, which means it looks at the current bar.

Code:
def lookback = 0;
def EMA = ExpAverage(close, 9);
def vwapValue = VWAP()[lookback];

plot scan = EMA crosses vwapValue;
 

rive7579

New member
HI guys, great work here.

Can anyone help me with weekly moving average Cross overs. I don't know why weekly moving average crossovers return no results in my scan. As soon as i change it to lower time frames from daily downward, I get plenty results. I thought there just wasn't any right this moment (1/6/2020), but when I checked manually, I see there are plenty crossovers of the 2 day / 200SMA as well as price going above and below 200SMA.

So clearly TOS just doesn't give me results for some reason. Can you help? Maybe there is already a thread here, which I just haven't seen.

MA
WPB, FL
 

markos

Well-known member
VIP
HI guys, great work here.

Can anyone help me with weekly moving average Cross overs. I don't know why weekly moving average crossovers return no results in my scan. As soon as i change it to lower time frames from daily downward, I get plenty results. I thought there just wasn't any right this moment (1/6/2020), but when I checked manually, I see there are plenty crossovers of the 2 day / 200SMA as well as price going above and below 200SMA.

So clearly TOS just doesn't give me results for some reason. Can you help? Maybe there is already a thread here, which I just haven't seen.

MA
WPB, FL
@rive7579 Put the code from #3 above into TOS Studies. That code will give you what you want. It should put the MA's on your chart, just set them for your 2 crossing parameters. You should confirm on the chart first that there is a weekly crossover - then scan for it to be sure it comes up. Please start with S&P100 to narrow your range and get the study dialed in.
Markos
Welcome to our great community!
 

J007RMC

Well-known member
2019 Donor
Not sure if I'm in the right forum Ive been playing with the ma cross and beleive to be a very very useful script. I'm using this as an alert to show the 8/15, 15/49 cross overs.
Code:
# tomsk
# 1.5.2020
input price = close;
input length1 = 8;
input length2 = 20;
def MA1 = Average(price, length1);
def MA2 = Average(price, length2);
AddLabel(1, "Moving Average " + length1 + "/" + length2 + " Cross Direction = " + if MA1 > MA2 then "UP" else "DOWN", if MA1 > MA2 then Color.GREEN else Color.RED);
# End Moving Average Cross Direction Label
 
Last edited by a moderator:

Lees

New member
Is there a way to color code watchlist stocks with custom filed based on price Cross over vwap upper band and vwap lower band and vwap?

i saw a post to mark bullish and bearish when price move above and below vwap but i would like to leave rage that to identify vwap upper and lower band cross also with different coloring so that it will be easy for us to watch the stock when it reaches those levels.
 

Similar threads

Top