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

如何将TradingView的Pine Script代码转换为JavaScript?

Nadaraya-Watson Estimator 指标JS转换方案

原Pine Script实现的核心逻辑已完整转换为JavaScript,适配前端网页端常用图表库调用:

转换后JS代码

/**
 *  Nadaraya-Watson Estimator 核回归指标
 *  原作者:LuxAlgo 许可协议:CC BY-NC-SA 4.0 非商用共享
 * @param {Array} klineData K线数组,每一项至少包含close、time字段
 * @param {Number} bandwidth 带宽参数,默认8
 * @param {Number} maxBars 最多参与计算的K线数量,默认500
 * @returns {Object} 包含平滑线数据、拐点信号数据
 */
function calcNadarayaWatson(klineData, bandwidth = 8, maxBars = 500) {
    // 取最近maxBars根K线参与计算,和原指标逻辑一致
    const data = klineData.slice(-maxBars);
    const n = data.length;
    const smoothPoints = [];
    const signals = [];
    let y1 = null;
    let y1_d = null;
    for (let i = 0; i < n; i++) {
        let sum = 0;
        let sumw = 0;
        // 高斯核权重计算
        for (let j = 0; j < n; j++) {
            const w = Math.exp(-(Math.pow(i - j, 2) / (bandwidth * bandwidth * 2)));
            sum += data[j].close * w;
            sumw += w;
        }
        const y2 = sum / sumw;
        smoothPoints.push({
            time: data[i].time,
            value: y2,
            color: y2 > (y1 ?? y2) ? '#ff1100' : '#39ff14'
        });
        if (y1 !== null) {
            const d = y2 - y1;
            // 拐点信号判断
            if (d > 0 && y1_d < 0) {
                signals.push({
                    time: data[i].time,
                    position: 'belowBar',
                    color: '#39ff14',
                    shape: 'arrowUp',
                    text: '▲'
                });
            }
            if (d < 0 && y1_d > 0) {
                signals.push({
                    time: data[i].time,
                    position: 'aboveBar',
                    color: '#ff1100',
                    shape: 'arrowDown',
                    text: '▼'
                });
            }
            y1_d = d;
        }
        y1 = y2;
    }
    return { smoothLine: smoothPoints, signals: signals };
}

前端图表库对接示例(以Lightweight Charts为例)

  • 初始化图表后,先获取全量K线数据,调用calcNadarayaWatson方法得到计算结果
  • 添加折线系列渲染平滑曲线:
const lineSeries = chart.addLineSeries({ lineWidth: 2 });
const { smoothLine, signals } = calcNadarayaWatson(yourKlineData);
lineSeries.setData(smoothLine.map(item => ({ time: item.time, value: item.value })));
  • 添加标记系列渲染拐点箭头:
const markerSeries = chart.addHistogramSeries({});
markerSeries.setMarkers(signals);

注意事项

  • 原指标采用CC BY-NC-SA 4.0非商业共享许可,商业使用需联系原作者LuxAlgo取得授权
  • 双重循环计算复杂度为O(n²),如果需要处理更多K线可以加入滑动窗口优化,仅取最近N根K线参与计算,降低性能损耗

内容的提问来源于stack exchange,提问作者yaghoob_pr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:36:04