P粉0717437322023-09-04 00:37:22
在下面的示例中,将 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)
<div id="result"></div>
P粉5634465792023-09-04 00:18:21
我发现了问题。它来自 MetaTrader 的 api,“getHistoricalCandles”无法按预期正常工作。 api中写的是:
getHistoricalCandles(symbol, timeframe, startTime, limit) symbol: symbol to retrieve candles for TimeFrame: define the timeframe according to which the candles must be generated StartTime: time to start loading candles from. Note that candles are loaded in backward direction, so this should be the latest time, **leave it empty to request latest candles** Limit: maximum of candles to retrieve, must be less or equals to 1000
这里的问题是 StartTime 参数,它绝对不会像他们所说的那样工作,当我将其留空时,或者当我放置 Date.now()
时,它会检索 5 小时前的蜡烛,为了检索绝对的最后一根蜡烛,我必须输入 Date.now()+10000000000
,所以这可能是一个时区错误,暂时无法解决,因为它来自 api 端...