Moving Average Breakout

Trigun1127

Member
Could someone edit this code so that the MA only changes colors when there are 2 consecutive green closes above and 2 consecutive red closes below.

plot myindicator=ExpAverage(close,20);
myindicator.SetDefaultColor(Color.White);
myindicator.AssignValueColor(if close>=myindicator then Color.Green else Color.Red);
myindicator.SetStyle(curve.LONG_DASH);
myindicator.SetPaintingStrategy(paintingstrategy.LINE_VS_SQUARES);
myindicator.SetLineWeight(5);
myindicator.setHiding(if close>open(period="DAY") then 0 else 1);
 
Solution
Perhaps there's a misunderstanding for image 1. The Low of the bar I don't believe should be part of the criteria. Just the Close of the bar. 2 consecutive green closes above the moving average. The moving average here was 3859.45 as you pointed out but the close of the bars were C: 3865.25 and C: 3866.25

Changed to 2 bar criteria as noted above.

Ruby:
#1. If the day opens below the EMA Line = Red
#2. If day opens above EMA Line = Green
#3. If above and Green only 2 bar breakouts below to red are possible.
#4. If below and Red only 2 bar breakouts above to green are possible.
#5. Pictures show where these things do not happen
input length1 = 20;
input avg     = AverageType.EXPONENTIAL;
input price1  = close;

plot...

SleepyZ

Well-known member
VIP
Lifetime
Could someone edit this code so that the MA only changes colors when there are 2 consecutive green closes above and 2 consecutive red closes below.

plot myindicator=ExpAverage(close,20);
myindicator.SetDefaultColor(Color.White);
myindicator.AssignValueColor(if close>=myindicator then Color.Green else Color.Red);
myindicator.SetStyle(curve.LONG_DASH);
myindicator.SetPaintingStrategy(paintingstrategy.LINE_VS_SQUARES);
myindicator.SetLineWeight(5);
myindicator.setHiding(if close>open(period="DAY") then 0 else 1);

This gives an option to color the price bars as well as the moving average line.

Capture.jpg
Ruby:
DefineGlobalColor("Long", Color.CYAN);
DefineGlobalColor("Short", Color.YELLOW);
DefineGlobalColor("Else", Color.WHITE);

input length1 = 20;
input avg     = AverageType.EXPONENTIAL;
input price1  = close;
plot ma1      = MovingAverage(averagetype = avg, price1, length1);
ma1.SetPaintingStrategy(PaintingStrategy.LINE_VS_SQUARES);
ma1.SetLineWeight(5);

# 2 consective bars red bars above ma1, including cross above
def currentbarAbove = if close >= open and close crosses above ma1 then 1 else 0;
def onebarafterAbove = if close >= open and currentbarAbove[1] and close > ma1  then 1 else 0;

# 2 consective bars red bars below ma1, including cross below
def currentbarBelow = if close < open and close crosses below ma1 then 1 else  0;
def onebarafterBelow = if currentbarBelow[1] and close < open and close < ma1 then 1 else 0;

ma1.AssignValueColor(if  onebarafterAbove[-1] or onebarafterAbove then Color.GREEN else if onebarafterBelow[-1] or onebarafterBelow then Color.RED else GlobalColor("Else"));

input pricecolor = no;
AssignPriceColor(if !pricecolor then Color.CURRENT else if  onebarafterAbove[-1] or onebarafterAbove then GlobalColor("Long") else if onebarafterBelow[-1] or onebarafterBelow then GlobalColor("Short") else GlobalColor("Else"));
#
 

Trigun1127

Member
I haven’t been able to plug this code in yet but could you keep the color of the line (red/green) until the next breakout. So 2 consecutive bars above the moving average from that point is green until two consecutive bars below -> red. Like the below pictures

I'm attempting to clean up the signals a bit
Below are examples of where I'm trying to do this.
/mes today

First picture was from your code. you can see that it turned red on 2 consecutive bars down but it shouldnt have to since its already a bear trend. It just shouldn't turn green . In the other pictures you can see where there are false signals or where the signal should start later rather then earlier.

 

SleepyZ

Well-known member
VIP
Lifetime
I haven’t been able to plug this code in yet but could you keep the color of the line (red/green) until the next breakout. So 2 consecutive bars above the moving average from that point is green until two consecutive bars below -> red. Like the below pictures

I'm attempting to clean up the signals a bit
Below are examples of where I'm trying to do this.
/mes today

First picture was from your code. you can see that it turned red on 2 consecutive bars down but it shouldnt have to since its already a bear trend. It just shouldn't turn green . In the other pictures you can see where there are false signals or where the signal should start later rather then earlier.


Here is a green/red movingaverage line based upon the 2 candle breakouts. I do not know how you define trend so there is not any condition for it in this code.

Capture.jpg
Ruby:
DefineGlobalColor("Long", Color.CYAN);
DefineGlobalColor("Short", Color.YELLOW);
DefineGlobalColor("Else", Color.WHITE);

input length1 = 20;
input avg     = AverageType.EXPONENTIAL;
input price1  = close;
plot ma1      = MovingAverage(averagetype = avg, price1, length1);
ma1.SetPaintingStrategy(PaintingStrategy.LINE_VS_SQUARES);
ma1.SetLineWeight(5);

# 2 consective bars red bars above ma1, including cross above
def currentbarAbove = if close >= open and close crosses above ma1 then 1 else 0;
def onebarafterAbove = if close >= open and currentbarAbove[1] and close > ma1  then 1 else 0;

# 2 consective bars red bars below ma1, including cross below
def currentbarBelow = if close < open and close crosses below ma1 then 1 else  0;
def onebarafterBelow = if currentbarBelow[1] and close < open and close < ma1 then 1 else 0;

def malinecolor = if isnan(malinecolor[1]) then 0
                  else if onebarafterAbove[-1] or onebarafterAbove
                  then 1 else if onebarafterBelow[-1] or onebarafterBelow
                  then 0 else malinecolor[1];
ma1.AssignValueColor(if malinecolor then Color.GREEN else if malinecolor==0 then Color.RED else GlobalColor("Else"));

input pricecolor = no;
AssignPriceColor(if !pricecolor then Color.CURRENT else if  onebarafterAbove[-1] or onebarafterAbove then GlobalColor("Long") else if onebarafterBelow[-1] or onebarafterBelow then GlobalColor("Short") else GlobalColor("Else"));
#
 

Trigun1127

Member
Almost perfect, I'm probably doing a bad job explaining this.
Here's is an example from todays /MES and Yesterdays
Today Its showing the Line as Red although trend is up. No Consecutive 2 bars below MA so line stays green.
The other example shows that the break above didn't change the line color.
Another rule is Doji closes do not count but I think you have that in the code already.
Thank you!

 

SleepyZ

Well-known member
VIP
Lifetime
Almost perfect, I'm probably doing a bad job explaining this.
Here's is an example from todays /MES and Yesterdays
Today Its showing the Line as Red although trend is up. No Consecutive 2 bars below MA so line stays green.
The other example shows that the break above didn't change the line color.
Another rule is Doji closes do not count but I think you have that in the code already.
Thank you!

In coding I need to know what you are defining as the trend. The code currently only does what I think you originally requested is to define 2 consecutive bar breakout above or below the ma with the same type of candles for both. It then does not change until the opposite breakout occurs. This results sometimes when things are going up visually but the last 2 bar breakout was below the movavg. So what do you want to use code logic wise to stop that breakout color and change it to whatever you think the trend is. I do not want to guesss.

Please turn on the pricecolor so you can see all of the bars that constitute a breakout, which should create a change in color. If not, then give me the chart details in like chart timeframe, symbol, time it occurred, etc....
 

Trigun1127

Member
Ok, I think I understand. So in the normal code the trend is defined as any close above (bullish) or below (bearish) the 20 EMA. In the first example here the day opened well under the Moving average in these cases, bulls need to prove that they can break above the average price. So the color here should be red with only the possibility of a green breakout, that breakout is less noisy I believe with consecutive green bars.

The second picture shows again that price opened well below the MA and bulls need to prove a breakout beyond the MA, here it became resistance.
The third picture everything looks good besides how the day opened.
The 4th picture shows the code working perfectly and how the Consecutive breakout cuts out noise. The only error is that the trend momentarily turns green due to a doji.
The 5th picture There is a 2 bar bear breakout that isn't detected so trend should have turned red
Last picture is another example where there is a 2 bar breakout and the trend doesn't change.

Tell me if this makes sense now
date and times are included upper left of picture
 

halcyonguy

Well-known member
VIP
Lifetime
Ok, I think I understand. So in the normal code the trend is defined as any close above (bullish) or below (bearish) the 20 EMA. In the first example here the day opened well under the Moving average in these cases, bulls need to prove that they can break above the average price. So the color here should be red with only the possibility of a green breakout, that breakout is less noisy I believe with consecutive green bars.

The second picture shows again that price opened well below the MA and bulls need to prove a breakout beyond the MA, here it became resistance.
The third picture everything looks good besides how the day opened.
The 4th picture shows the code working perfectly and how the Consecutive breakout cuts out noise. The only error is that the trend momentarily turns green due to a doji.
The 5th picture There is a 2 bar bear breakout that isn't detected so trend should have turned red
Last picture is another example where there is a 2 bar breakout and the trend doesn't change.

Tell me if this makes sense now
date and times are included upper left of picture

please allow me to pop in with my 2 cents,

@Trigun1127
no, you don't seem to understand.
you are mixing in your interpretation of the chart activity with what is actually happening.
programmers need to follow a set of rules. if this happens, do this. if that happens then do this...
if close is above an average for 3 bars, then plot an up arrow.

programmers don't care about these statements. they mean nothing.
..bulls need to prove that...
..that breakout is less noisy...
..bulls need to prove a breakout...
..breakout cuts out noise...

if you want to mention your thoughts , please do it after listing a specific set of rules.
 

Trigun1127

Member
1. If the day opens below the EMA Line = Red
2. If day opens above EMA Line = Green
3. If above and Green only 2 bar breakouts below to red are possible.
4. If below and Red only 2 bar breakouts above to green are possible.
5. Pictures show where these things do not happen
 

SleepyZ

Well-known member
VIP
Lifetime
1. If the day opens below the EMA Line = Red
2. If day opens above EMA Line = Green
3. If above and Green only 2 bar breakouts below to red are possible.
4. If below and Red only 2 bar breakouts above to green are possible.
5. Pictures show where these things do not happen

Here is the revised code that attempts to:
1. The trend 'def' results in a 1 (green) if day opens above EMA and a -1 (red) if day opens below EMA and the lines will be painted those colors accordingly.
2. The trend will then change if the previous line was green and a bear (yellow) 2 bar appears changing the line to red.
3. The trend will then change if the previous line was red and bull (cyan) 2 bar appears, changing the line to green.
4. A red line will not change to green by a bear (yellow) 2 bar nor will a green line change to red by a bull (cyan) line to red.

The image has the input test set to yes to see the trend showin as values below the candles.

The line coloring is controlled by the malinecolor def.

I believe the images 1 and 2 matches, 3,4 and 5 do not have any chart settings that I couldd see, and for image 6 I did not understand how if you wanted the line to change from red to green with bear 2 bars to logically do that.


Capture.jpg
Ruby:
#1. If the day opens below the EMA Line = Red
#2. If day opens above EMA Line = Green
#3. If above and Green only 2 bar breakouts below to red are possible.
#4. If below and Red only 2 bar breakouts above to green are possible.
#5. Pictures show where these things do not happen
input length1 = 20;
input avg     = AverageType.EXPONENTIAL;
input price1  = close;

plot ma1=MovingAverage(averagetype = avg, price1, length1);

input test = no;

def o=if getday()!=getday()[1] then open else o[1];
def ma=if getday()!=getday()[1] then ma1 else ma[1];
def trend=if secondsfromTime(1600)<=0 and o>ma then 1 else if secondsfromTime(1600)<=0 and o<ma then -1 else trend[1];
plot xtrend = if !test then double.nan else trend;
xtrend.setpaintingStrategy(paintingStrategy.VALUES_BELOW);


DefineGlobalColor("Long", Color.CYAN);
DefineGlobalColor("Short", Color.YELLOW);
DefineGlobalColor("Else", Color.WHITE);

# 2 consective bars red bars above ma1, including cross above
def currentbarAbove = if close >= open and close crosses above ma1 then 1 else 0;
def onebarafterAbove = if close >= open and currentbarAbove[1] and close > ma1  then 1 else 0;

# 2 consective bars red bars below ma1, including cross below
def currentbarBelow = if close < open and close crosses below ma1 then 1 else  0;
def onebarafterBelow = if currentbarBelow[1] and close < open and close < ma1 then 1 else 0;

def malinecolor = if isnan(malinecolor[1])
                  then 0
                  else if getday()!=getday()[1] and trend==1
                  then 1
                  else if trend==1 and onebarafterBelow[-1] or onebarafterBelow
                  then 0
                  else if getday()!=getday()[1] and trend==-1
                  then 0
                  else if trend==-1 and onebarafterabove[-1] or onebarafterabove
                  then 1                 
                  else malinecolor[1];
ma1.AssignValueColor(if malinecolor then Color.GREEN else if malinecolor==0 then Color.RED else GlobalColor("Else"));
ma1.SetPaintingStrategy(PaintingStrategy.LINE_VS_SQUARES);
ma1.SetLineWeight(5);


AssignPriceColor(if !test then Color.CURRENT else if  onebarafterAbove[-1] or onebarafterAbove then GlobalColor("Long") else if onebarafterBelow[-1] or onebarafterBelow then GlobalColor("Short") else GlobalColor("Else"));
#
 

Trigun1127

Member
Everything looks much better. The moving average at the open looks correct now as well. There are still a couple places where the line color is incorrect though.

Here there are several occurrences where there are 2 bar breakouts and the line color doesn't change. Chart times double checked in top left.
 

SleepyZ

Well-known member
VIP
Lifetime
Everything looks much better. The moving average at the open looks correct now as well. There are still a couple places where the line color is incorrect though.

Here there are several occurrences where there are 2 bar breakouts and the line color doesn't change. Chart times double checked in top left.
According to my criteria I used that did not qualify as a bull break. The first bar @1455 had a low of 3859.50 whereas the moving average was at 3859.45, thereby disqualifying that bar. Same scenario with first bar @1155.

The 3rd image @930 on 8/30, I adjusted the code to pick up a cross of close to include the wick on the same candle, in this case the high wick and then close below. Let me know if that created any problems. elsewhere.

The 2nd image appears fixed by what I did to fix the 3rd image.

Ruby:
#1. If the day opens below the EMA Line = Red
#2. If day opens above EMA Line = Green
#3. If above and Green only 2 bar breakouts below to red are possible.
#4. If below and Red only 2 bar breakouts above to green are possible.
#5. Pictures show where these things do not happen
input length1 = 20;
input avg     = AverageType.EXPONENTIAL;
input price1  = close;

plot ma1=MovingAverage(averagetype = avg, price1, length1);

input test = no;

def o=if getday()!=getday()[1] then open else o[1];
def ma=if getday()!=getday()[1] then ma1 else ma[1];
def trend=if secondsfromTime(1600)<=0 and o>ma then 1 else if secondsfromTime(1600)<=0 and o<ma then -1 else trend[1];
plot xtrend = if !test then double.nan else trend;
xtrend.setpaintingStrategy(paintingStrategy.VALUES_BELOW);


DefineGlobalColor("Long", Color.CYAN);
DefineGlobalColor("Short", Color.YELLOW);
DefineGlobalColor("Else", Color.WHITE);

# 2 consective bars red bars above ma1, including cross above
def currentbarAbove = if close >= open and low<ma1 and (close crosses above ma1 or close>ma1) then 1 else 0;
def onebarafterAbove = if close >= open and currentbarAbove[1] and close > ma1  then 1 else 0;

# 2 consective bars red bars below ma1, including cross below
def currentbarBelow = if close < open and high>ma1 and (close crosses below ma1 or close<ma1) then 1 else  0;
def onebarafterBelow = if currentbarBelow[1] and close < open and close < ma1 then 1 else 0;

def malinecolor = if isnan(malinecolor[1])
                  then 0
                  else if getday()!=getday()[1] and trend==1
                  then 1
                  else if trend==1 and onebarafterBelow[-1] or onebarafterBelow
                  then 0
                  else if getday()!=getday()[1] and trend==-1
                  then 0
                  else if trend==-1 and onebarafterabove[-1] or onebarafterabove
                  then 1                
                  else malinecolor[1];
ma1.AssignValueColor(if malinecolor then Color.GREEN else if malinecolor==0 then Color.RED else GlobalColor("Else"));
ma1.SetPaintingStrategy(PaintingStrategy.LINE_VS_SQUARES);
ma1.SetLineWeight(5);


AssignPriceColor(if !test then Color.CURRENT else if  onebarafterAbove[-1] or onebarafterAbove then GlobalColor("Long") else if onebarafterBelow[-1] or onebarafterBelow then GlobalColor("Short") else color.current);
#
 

Trigun1127

Member
Perhaps there's a misunderstanding for image 1. The Low of the bar I don't believe should be part of the criteria. Just the Close of the bar. 2 consecutive green closes above the moving average. The moving average here was 3859.45 as you pointed out but the close of the bars were C: 3865.25 and C: 3866.25
 

SleepyZ

Well-known member
VIP
Lifetime
Perhaps there's a misunderstanding for image 1. The Low of the bar I don't believe should be part of the criteria. Just the Close of the bar. 2 consecutive green closes above the moving average. The moving average here was 3859.45 as you pointed out but the close of the bars were C: 3865.25 and C: 3866.25

Changed to 2 bar criteria as noted above.

Ruby:
#1. If the day opens below the EMA Line = Red
#2. If day opens above EMA Line = Green
#3. If above and Green only 2 bar breakouts below to red are possible.
#4. If below and Red only 2 bar breakouts above to green are possible.
#5. Pictures show where these things do not happen
input length1 = 20;
input avg     = AverageType.EXPONENTIAL;
input price1  = close;

plot ma1=MovingAverage(averagetype = avg, price1, length1);

input test = no;

def o=if getday()!=getday()[1] then open else o[1];
def ma=if getday()!=getday()[1] then ma1 else ma[1];
def trend=if secondsfromTime(1600)<=0 and o>ma then 1 else if secondsfromTime(1600)<=0 and o<ma then -1 else trend[1];
plot xtrend = if !test then double.nan else trend;
xtrend.setpaintingStrategy(paintingStrategy.VALUES_BELOW);


DefineGlobalColor("Long", Color.CYAN);
DefineGlobalColor("Short", Color.YELLOW);
DefineGlobalColor("Else", Color.WHITE);

# 2 consective bars red bars above ma1, including cross above
def currentbarAbove = if close >= open and close>ma1 then 1 else 0;
def onebarafterAbove = if close >= open and currentbarAbove[1] and close > ma1  then 1 else 0;

# 2 consective bars red bars below ma1, including cross below
def currentbarBelow = if close < open and close<ma1 then 1 else  0;
def onebarafterBelow = if currentbarBelow[1] and close < open and close < ma1 then 1 else 0;

def malinecolor = if isnan(malinecolor[1])
                  then 0
                  else if getday()!=getday()[1] and trend==1
                  then 1
                  else if trend==1 and onebarafterBelow[-1] or onebarafterBelow
                  then 0
                  else if getday()!=getday()[1] and trend==-1
                  then 0
                  else if trend==-1 and onebarafterabove[-1] or onebarafterabove
                  then 1                 
                  else malinecolor[1];
ma1.AssignValueColor(if malinecolor then Color.GREEN else if malinecolor==0 then Color.RED else GlobalColor("Else"));
ma1.SetPaintingStrategy(PaintingStrategy.LINE_VS_SQUARES);
ma1.SetLineWeight(5);


AssignPriceColor(if !test then Color.CURRENT else if  onebarafterAbove[-1] or onebarafterAbove then GlobalColor("Long") else if onebarafterBelow[-1] or onebarafterBelow then GlobalColor("Short") else color.current);
#
 
Solution

SleepyZ

Well-known member
VIP
Lifetime
Hey one small thing could make the tip of the moving average here the same color as the rest of it as its updating per bar?

As the use of [-1] causes the code to wait for the color after the current bar closes, this uses the color of the last closed bar for the current bar until it closes.

Capture.jpg
Ruby:
#1. If the day opens below the EMA Line = Red
#2. If day opens above EMA Line = Green
#3. If above and Green only 2 bar breakouts below to red are possible.
#4. If below and Red only 2 bar breakouts above to green are possible.
#5. Pictures show where these things do not happen
input length1 = 20;
input avg     = AverageType.EXPONENTIAL;
input price1  = close;

plot ma1 = MovingAverage(averagetype = avg, price1, length1);

input test = no;

def o = if GetDay() != GetDay()[1] then open else o[1];
def ma = if GetDay() != GetDay()[1] then ma1 else ma[1];
def trend = if SecondsFromTime(1600) <= 0 and o > ma then 1 else if SecondsFromTime(1600) <= 0 and o < ma then -1 else trend[1];
plot xtrend = if !test then Double.NaN else trend;
xtrend.SetPaintingStrategy(PaintingStrategy.VALUES_BELOW);


DefineGlobalColor("Long", Color.CYAN);
DefineGlobalColor("Short", Color.YELLOW);
DefineGlobalColor("Else", Color.WHITE);

# 2 consective bars red bars above ma1, including cross above
def currentbarAbove = if close >= open and close > ma1 then 1 else 0;
def onebarafterAbove = if close >= open and currentbarAbove[1] and close > ma1  then 1 else 0;

# 2 consective bars red bars below ma1, including cross below
def currentbarBelow = if close < open and close < ma1 then 1 else  0;
def onebarafterBelow = if currentbarBelow[1] and close < open and close < ma1 then 1 else 0;

def malinecolor = if IsNaN(malinecolor[1])
                  then 0
                  else if GetDay() != GetDay()[1] and trend == 1
                  then 1
                  else if trend == 1 and onebarafterBelow[-1] or onebarafterBelow
                  then 0
                  else if GetDay() != GetDay()[1] and trend == -1
                  then 0
                  else if trend == -1 and onebarafterAbove[-1] or onebarafterAbove
                  then 1                 
                  else malinecolor[1];

def lastbar     = BarNumber() == HighestAll(if IsNaN(close[-1]) and !IsNaN(close) then BarNumber() else Double.NaN);
ma1.AssignValueColor(if lastbar and malinecolor[1] == 1 then Color.GREEN else if lastbar and malinecolor[1] == 0 then Color.RED else if malinecolor then Color.GREEN else if malinecolor == 0 then Color.RED else GlobalColor("Else"));
ma1.SetPaintingStrategy(PaintingStrategy.LINE_VS_SQUARES);
ma1.SetLineWeight(5);


AssignPriceColor(if !test then Color.CURRENT else if  onebarafterAbove[-1] or onebarafterAbove then GlobalColor("Long") else if onebarafterBelow[-1] or onebarafterBelow then GlobalColor("Short") else Color.CURRENT);
#
 

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.
Top