TradingView ALMA算法转JS后与Binance数据计算结果不符排查
Hey there! Let's dig into why your ALMA calculation in JavaScript doesn't match TradingView's result. The key issue here is a mismatch between how you're indexing the K-line data and how Pine Script applies weights to the bars.
Core Problem: Reversed Bar-Weight Pairing
First, let's clarify the data order logic in Pine Script vs. your JavaScript array:
- In Pine Script, when calculating the ALMA for the latest bar,
series[0]refers to the current (newest) bar, whileseries[n]refers to the bar that occurrednperiods ago (older bars). For a 30-period ALMA, it uses bars fromseries[29](oldest in the window) up toseries[0](newest). - Your
seriesarray is ordered from oldest to newest (the first element is the earliest K-line, last is the latest).
Looking at your loop:
In Pine Script, the line sum := sum + series[windowsize - i - 1] * weight iterates from the oldest bar to the newest:
- When
i=0, it takesseries[29](oldest bar) * weight - When
i=29, it takesseries[0](newest bar) * weight
But in your JS code, series[windowsize - i - 1].close does the opposite:
- When
i=0, it takesseries[29].close(newest bar) * weight - When
i=29, it takesseries[0].close(oldest bar) * weight
Since your ALMA uses offset=0.85, the weight distribution is not symmetric (the peak weight is shifted toward newer bars). Reversing the order of bars paired with weights breaks the calculation entirely.
Fixed JavaScript Code
Here's the adjusted function that aligns with Pine Script's logic:
function calculateALMA(series, windowsize, offset, sigma) { let m = Math.floor(offset * (windowsize - 1)); let s = windowsize / sigma; let weight = 0.0; let norm = 0.0; let sum = 0.0; for (let i = 0; i < windowsize; i++) { weight = Math.exp(-1 * Math.pow(i - m, 2) / (2 * Math.pow(s, 2))); norm += weight; // Now we take series[i].close (oldest to newest) to match Pine Script's order sum += series[i].close * weight; } return sum / norm; }
Quick Verification Tip
With offset=0.85 and windowsize=30, m = floor(0.85*(30-1)) = 24. This means the 25th bar in your series array (index 24, 0-based) gets the highest weight—this aligns with Pine Script's logic where the peak weight lands on the bar that's 5 periods before the newest one.
内容的提问来源于stack exchange,提问作者Pie

