Nodejs MetaAPI Cloud / 计算移动平均值
                
             
            
            
                <p>我正在制作一个使用metaapi.cloud的交易机器人,我正在尝试计算移动平均值(快速/指数),但它返回给我无效值,这是我的代码:</p>
<pre class="brush:js;toolbar:false;">async movingAverage(symbol, period, type = "S") {
        let candles = (await this.account.getHistoricalCandles(symbol, this.params.timeframe, null, period)).map(c => c.close);
        const result = [];
        let sum = 0;
        if (type === "S") {
            for (let i = 0; i < period; i++) {
                sum += candles[i];
            }
            result.push(sum / period);
            for (let i = period; i < candles.length; i++) {
                sum = sum - candles[i - period] + candles[i];
                result.push(sum / period)
            }
        } else if (type === "E") {
            const weight = 2 / (period + 1);
            for (let i = 0; i < period; i++) {
                sum += candles[i];
            }
            sum /= period;
            result.push(sum);
            for (let i = period; i < candles.length; i++) {
                sum = (candles[i] * weight) + (sum * (1 - weight));
                result.push(sum);
            }
        } else {
            // throw Error()
        }
        return result;
    }
</pre>
<p>这是我的使用方法:</p>
<pre class="brush:js;toolbar:false;">async onTick(infos) {
        let sma = await this.movingAverage(infos.symbol, this.params.fast, "S");
        console.log('SMA ' + sma[0]);
}
</pre>
<p>现在,当我测试它时,SMA 应该返回“1906.6963”,但它给我的是“1900.7813”
也许我使用了错误的方法来计算它们?
如果有人有解决办法!提前致谢。</p>            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
         
        
        
            
            
            
            
            
         
     
在下面的示例中,将 period 设置为 1 以查看已处理的所有值,将 period 设置为非常大的数字以查看整个平均值。
肯定还有其他我没有想到的边缘情况。为简洁起见,下面的示例使用 SMA。
async function movingAverage(symbol, period, type = "S") { let candles = [1,2,3,"","",4, "0",0, null, "99,9123", undefined,"0.123e5", "wrongval", 9, 10, 20, 100] .map(d => parseFloat((d ?? "").toString().replace(",","."))) .filter(d => +d || +d === 0); const result = []; if (candles.length <= 0){return result} let sum = 0; period = Math.min(candles.length, period) || 1; for (let i = 0; i < period; i++) { sum += candles[i]; } result.push(sum / period); for (let i = period; i < candles.length; i++) { sum = sum - candles[i - period] + candles[i]; result.push(sum / period) } return result; } movingAverage("SPX",500).then(x => document.getElementById("result").textContent = x)我发现了问题。它来自 MetaTrader 的 api,“getHistoricalCandles”无法按预期正常工作。 api中写的是:
这里的问题是 StartTime 参数,它绝对不会像他们所说的那样工作,当我将其留空时,或者当我放置
Date.now()时,它会检索 5 小时前的蜡烛,为了检索绝对的最后一根蜡烛,我必须输入Date.now()+10000000000,所以这可能是一个时区错误,暂时无法解决,因为它来自 api 端...