Page 1 of 1

TradingView - How to change negative values into positive?

Posted: Sun Apr 17, 2022 1:34 pm
by FMU FMU
I have an indicator that goes from 1 to -1. I am trying to normalize the data so that it goes from 1 to 0. The problem is, I just can't figure out how to change this calculation. Kindly help me out in this matter!

//@version=5
indicator('Stochastics Momentum Index', shorttitle='Fear Greed')
a = input(10, 'Percent K Length')
b = input(3, 'Percent D Length')
ob = input(1, 'Overbought')
os = input(-1, 'Oversold')
// Range Calculation
ll = ta.lowest(low, a)
hh = ta.highest(high, a)
diff = hh - ll
rdiff = close - (hh + ll) / 2

avgrel = ta.ema(ta.ema(rdiff, b), b)
avgdiff = ta.ema(ta.ema(diff, b), b)
// SMI calculations
SMI = avgdiff != 0 ? avgrel / (avgdiff / 2) * 100 : 0
SMIsignal = ta.ema(SMI, b)
emasignal = ta.ema(SMI, 4)



//Color Definition for Stochastic Line
//col = SMI >= 40 ? green : SMI <= -40 ? red : black

plot(SMIsignal, title='Stochastic', style=plot.style_line, color=color.new(#00FFFF, 0))

plot(emasignal, title='EMA', style=plot.style_line, color=color.new(#E040FB, 0))

level_40 = 1
level_40smi = SMIsignal > level_40 ? SMIsignal : level_40

level_m40 = -1
level_m40smi = SMIsignal < level_m40 ? SMIsignal : level_m40

p1 = plot(level_40)
p2 = plot(level_40smi)

p3 = plot(level_m40)
p4 = plot(level_m40smi)

fill(p1, p2, color=color.new(#9C27B0, 1), title='OverSold')

It can be used with Bitcoin.

Thanks!

Re: TradingView - How to change negative values into positive?

Posted: Thu May 19, 2022 9:06 pm
by flyingdad
There is an absolute value function: math.abs(number)
https://www.tradingview.com/pine-script ... th{dot}abs

Re: TradingView - How to change negative values into positive?

Posted: Fri May 20, 2022 11:58 am
by ocaptain
And if not for the abs function, to turn a negative value into a positive it's x = x - (x*2)

x = -1 - (-1 * 2)
x = -1 - (-2)
x = -1 + 2
x = 1

So, though you didn't need to do this for this example as we have the function, remember, there's *always* a workaround 😜

-Anthony