javascript - 根据 Kraken OHLC 计算 RSI
问题描述
我想准确地反映cryptowatch.de上的 RSI 值(在我的情况下为 LTC-EUR),我使用了解释如何计算 RSI的网站 stockcharts.com 用Javascript (节点)编写计算器。
到目前为止我的代码:
// data is an array of open-prices in descending date order (the current price is the last element)
function calculateRSI(data) {
data = data.reverse(); // Reverse to handle it better
let avgGain = 0;
let aveLoss = 0;
// Calculate first 14 periods
for (let i = 0; i < 14; i++) {
const ch = data[i] - data[i + 1];
if (ch >= 0) {
avgGain += ch;
} else {
aveLoss -= ch;
}
}
avgGain /= 14;
aveLoss /= 14;
// Smooth values 250 times
for (let i = 14; i < 264; i++) {
const ch = data[i] - data[i + 1];
if (ch >= 0) {
avgGain = (avgGain * 13 + ch) / 14;
aveLoss = (aveLoss * 13) / 14;
} else {
avgGain = (avgGain * 13) / 14;
aveLoss = (aveLoss * 13 - ch) / 14;
}
}
// Calculate relative strength index
const rs = avgGain / aveLoss;
return 100 - 100 / (1 + rs);
}
但结果总是与 cryptowatch.de上显示的值相差甚远,这是怎么回事?如何正确计算?(其他编程语言发帖也可以)
感谢@jingx,但结果仍然错误
解决方案
我知道这是一个记录时间,但我只是遇到了这个问题并且得到了正确的技术。这让我花了很长时间才弄清楚在 C# 中如此享受。
第 1 步。您正在从 API 接收从过去 [0] 到现在 [x] 的值。对于“收盘/14”,您必须计算“收盘”值(利润/损失)的差异,如下所示:
var profitAndLoss = new List<double>();
for (int i = 0; i < values.Count - 1; i++)
profitAndLoss.Add(values[i + 1] - values[i]); //newer - older value will give you negative values for losses and positiv values for profits
第 2 步。计算您的初始 rsi 值(通常称为 RSI StepOne),注意我没有反转收到的值。此初始计算是使用“最旧”值完成的。_samples 是您最初用于计算 RSI 的值的数量,在我的情况下默认为“关闭/14”_samples = 14:
var avgGain = 0.0;
var avgLoss = 0.0;
//initial
for (int i = 0; i < _samples; i++)
{
var value = profitAndLoss[i];
if (value >= 0)
avgGain += value;
else
avgLoss += value * -1; //here i multiply -1 so i only have positive values
}
avgGain /= _samples;
avgLoss /= _samples;
步骤 3. 使用从 API 获得的剩余值平滑平均值:
//smooth with given values
for (int i = _samples; i < profitAndLoss.Count; i++)
{
var value = profitAndLoss[i];
if (value >= 0)
{
avgGain = (avgGain * (_samples - 1) + value) / _samples;
avgLoss = (avgLoss * (_samples - 1)) / _samples;
}
else
{
value *= -1;
avgLoss = (avgLoss * (_samples - 1) + value) / _samples;
avgGain = (avgGain * (_samples - 1)) / _samples;
}
}
步骤 4. 计算 RSI 的时间:
var rs = avgGain / avgLoss;
var rsi = 100 - (100 / (1 + rs));
这将为您提供与 Kraken 在其 RSI 图表中相同的值(+/- 0.05,取决于您的更新频率)
结果图像1