You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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, while series[n] refers to the bar that occurred n periods ago (older bars). For a 30-period ALMA, it uses bars from series[29] (oldest in the window) up to series[0] (newest).
  • Your series array 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 takes series[29] (oldest bar) * weight
  • When i=29, it takes series[0] (newest bar) * weight

But in your JS code, series[windowsize - i - 1].close does the opposite:

  • When i=0, it takes series[29].close (newest bar) * weight
  • When i=29, it takes series[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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:44:04