Arjen
Pine Script Rookie
Pine Script Rookie
Posts: 1
Joined: February 24th, 2022

cannot calculate if MA20 and MA200 are close

Setting my first Pine steps and making all the basic errors.. appreciate help!

Purpose: trying to determine how close moving average 20 is to moving average 200
Thought: division of both should be close to 1.
However, the below calculation is true for all values?
Similar also for if I use 1 condition.

Looks like an issue with floats vs integer or rounding?

float ma1 = ta.sma(close, 20)
float ma2 = ta.sma(close, 200)
float xRatio = ma2/ma1
xUp = xRatio>0.8 and xRatio<1.2
plotchar(xUp, "xUp", "▲", location.top, size = size.tiny)

chooka
Pine Script Master
Pine Script Master
Posts: 18
Joined: February 7th, 2022

Re: cannot calculate if MA20 and MA200 are close

Hi there,

What you have coded looks to be working correctly.

I think the ratio limits you have chosen are far too wide (20%)?

Try changing these limits to only 2% away (ie. xUp = xRatio>0.98 and xRatio<1.02)

See how this goes

processingclouds
Pine Script Master
Pine Script Master
Posts: 115
Joined: January 30th, 2022

Re: cannot calculate if MA20 and MA200 are close

Hey, as @chooka pointed out , your code is working correctly. You do see it as true when the sma are close to each other. If you do a 1 Day chart and zoom out, you will see it is not true at all points, but only when sma get close together.

Perhaps what you are trying to do is , mark only when one crosses the other and nothing else. If so you can try using

Code: Select all

 plotchar(xUp and not xUp[1] ? xUp : na, "xUp", "▲", location.top, size = size.tiny)
this will only print the arrow when it first encounters the change in ratio and than stop printing till next swing

Return to “Pine Script Q&A”