Search code examples
pine-scriptpine-script-v5

How to change simple int variable values without making them series int variables?


I would like to make a ta.ema() function adaptive so I need to change its length value based on some math.

But it expects simple int variable for its length variable, while a changing length value is a series int so the function returns with an error.

How to make it work? How to make a simple int variable change but with keeping it a Simple (not Series) Int variable. (I don't need its past values so it's not needed to be a series int, just be changed sometimes).

Disfunctional example code:

AdaptiveFactor = ta.highest(high, 100) / ta.lowest(low, 100)
length = int(20 * AdaptiveFactor / AdaptiveFactor[100])
EMA = ta.ema(close, length)

Solution

  • You cannot do that with the built-in function. However, you can achieve that behavior if you simple write the ema() function yourself. Its implementation is actually open-source so you can use it.

    //@version=5
    indicator("My script", overlay=true)
    
    pine_ema(src, length) =>
        alpha = 2 / (length + 1)
        sum = 0.0
        sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
    
    AdaptiveFactor = ta.highest(high, 100) / ta.lowest(low, 100)
    length = int(20 * AdaptiveFactor / AdaptiveFactor[100])
    EMA = pine_ema(close, length)
    
    plot(EMA)