LWMA

init = () => {
  indicator({ onMainPanel: true, format: "inherit" });
  input.int("Period", 20, "period");
};

const closeArray = [];

const calculateLWMA = (values, period) => {
  if (values.length < period) return null;
  let weightedSum = 0,
    weightTotal = 0;
  for (let i = 0; i < period; i++) {
    const weight = period - i;
    weightedSum += values[values.length - 1 - i] * weight;
    weightTotal += weight;
  }
  return weightedSum / weightTotal;
};

onTick = (length, _moment, _, ta, inputs) => {
  const close = closeC(0);
  closeArray.push(close);
  if (closeArray.length >= inputs.period) {
    const lwma = calculateLWMA(closeArray, inputs.period);
    plot.line("LWMA", lwma, "#FFA500", 1);
  }
};

Last updated