0
votes

Struggling with v2 to v4 pinescript Conversion, "Cannot modify global variable inside function" Error And I'm not really sure how to access the variable and modify inside the function, to complete the loop, and its not showing up on the chart.

I have tried p = 0 followed by p := "normal function text" inside the function, got that to compile, but had the indicator dissapear from the chart. V4 pine is clearly affecting the math calculation via bad syntax.

https://www.tradingview.com/script/9P5AUAMl-Adaptive-Least-Squares/

//@version=2
study("Adaptive Least Squares",overlay=true)
length = input(500),smooth = input(1.5)
//
alpha = pow(tr/highest(tr,length),smooth)
m(a) =>
    p = alpha * a + (1-alpha) * nz(p[1],a)
//
x = n
y = close
x_ = m(x)
y_ = m(y)
//
dx = abs(x-x_)
dy = abs(y-y_)
mx = m(dx)
my = m(dy)
//
a1 = pow(2/alpha+1,2)*m(x*y) - ((2/alpha+1)*m(x))*((2/alpha+1)*m(y))
b1 = sqrt((pow(2/alpha+1,2)*m(x*x) - pow((2/alpha+1)*m(x),2)) * (pow(2/alpha+1,2)*m(y*y) - pow((2/alpha+1)*m(y),2)))
r = a1/b1
//
a = r * (my/mx)
b = y_ - a*x_
reg = x*a + b
//
plot(reg,color=red,transp=0)
1
Hi, Styles. Your script lost the markup and it's impossible to read it. Could you fix that?Michel_T.
I've yet to figure out how to get stack overflow to highlight pinescriptStyles Grant
don't need to highlight pinescript. Just make enough spaces to see where the function p ends.Michel_T.
Or maybe just publish the script on tradingview and add here a link to the published script.Michel_T.

1 Answers

1
votes

I think, in v.4 it should be something like this:

//@version=4
study("Adaptive Least Squares", overlay=true)
length = input(500)
smooth = input(1.5)
//
alpha = pow(tr / highest(tr, length), smooth)
m(a, prevVal) =>
    alpha * a + (1 - alpha) * nz(prevVal, a)
//
x = bar_index
y = close
x_ = 0.0
x_ := m(x, x_[1])

y_ = 0.0
y_ := m(y, y_[1])
//
dx = abs(x - x_)
dy = abs(y - y_)

mx = 0.0
mx := m(dx, mx[1])
my = 0.0
my := m(dy, my[1])
//

xx = 0.0
xx := m(x * x, xx[1])

xy = 0.0
xy := m(x * y, xy[1])

yy = 0.0
yy := m(y * y, yy[1])

a1 = pow(2 / alpha + 1, 2) * xy - (2 / alpha + 1) * x_ * (2 / alpha + 1) * y_
b1 = sqrt((pow(2 / alpha + 1, 2) * xx - pow((2 / alpha + 1) * x_, 2)) * (pow(2 / alpha + 1, 2) * yy - pow((2 / alpha + 1) * y_, 2)))
r = a1 / b1
//
a = r * (my / mx)
b = y_ - a * x_
reg = x * a + b
//
plot(reg, color=color.red, transp=0)