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 端.. .