How to implement a conditional length moving average in TradingView pinescript?

Viewed 813

I'd like to implement a moving average where the length is based on an n-back average cycle length K. Thus, I need the length to be a function of the variable K.

The built-in moving average allows only a static integer value for length.

I have a variable called cycle_difference based on a long-term vs shorter-term cycle length.

    time_since_zero=round(barssince(cross(zero_check,0)))

    max_cycle=highest(time_since_zero,50)
    cycle = ema(max_cycle,200)
    cycle_long = ema(max_cycle,1000)

    cycle_difference =  cycle - cycle_long

I'd like to have a moving average with length based on this, something like

    macd_length_scaled = 20 - cycle_difference
    macd_wma = ema(foo,macd_length_scaled)

However, the built in moving averages only allow int values for length. I'd like to find a work around.

1 Answers
Related