This script is to help people with converting arrays to Simple Moving Average and Exponential Moving Average arrays. It is the same as using ta.sma() or ta.ema() in v5 with series but it takes an array as input instead. Both functions have inbuilt bad-input checking logic to ensure that the period length is not too high or too low - which could give unwanted results. If such values are used, the functions will output an array of the same length with NaN values. The EMA function also has an optional argument called sma_seed, which determines whether the first value in the output array will be the SMA of the first value from the input array (true) or the first value itself (false). Both functions work independently of one another, all you have to do is copy the entire function into your code and off you go! I can add more functions such as RMA or VWMA if there is demand, let me know and leave a like! ~ if you want.
This is giving me values that are about 0.1% off from what they should be. It's not a lot but I need it to be close to spot on. Is there a rounding error somewhere that I can fix?
rm250ripper
⋅
Never mind, I had an error in my code.
kurtsmock
⋅
Awesome. Most of the work was done for me here. Thanks. I made some modifications. In my case I have an array that clears outside of the session and another that carries N data points. Basically I want to calculate JUST the ema provided there's sufficient data points to calculate it. Let me know if you think this looks right. I'm going to test it further to make sure the results are coming back accurately, but they seem to be.
array_ema(input_array, int ema_length = 2, bool sma_seed = true) => // SMA seed: True for first value being SMA. False for first value being used and unchanged
array_size = array.size(input_array)
output_array = array.new_float(ema_length, na)
if(array_size >= ema_length and ema_length > 0) // Avoids bugs where period length is longer than the array
for index = 0 to ema_length - 1
alpha = 2 / (ema_length + 1)
sum = 0.0
if(index == 0)
if(sma_seed)
array.set(output_array, index, array.get(input_array, index) / ema_length)
else
array.set(output_array, index, array.get(input_array, index))
else
array.set(output_array, index, (alpha * array.get(input_array, index)) + (1 - alpha) * array.get(output_array, index - 1))
output_array
var emaAr = array.new_float(1,0)
if bear_avgSizeRgID > 0
emaAr := array_ema(bear_intradayRgArr, 9, false)
kurtsmock
⋅
@kurtsmock, It's not dead on but very close. I imagine it's putting 1 bar of lag in there. But that's fine really.
jemque1206
⋅
it doesnt work for me. it makes a new pane for some reason instead of applying it in the price chart.