我想计算比特币价格的 RSI -(相对强弱指数)(过去 14 天)。过去 14 天的必要数据来自 API。结果应存储在变量中以供进一步处理。我尝试了不同的方法,但结果并不奏效。我想我没有找到解决这个问题的正确方法。我无法创建一个完整的工作结果,所以我在这里问我关于 Stack Overflow 的第一个问题。
- How can I ask the API for the course of the past 14 days via iterative timestamp manipulation?
时间戳现在 -1 天/-2 天.... (&ts=xxxxxxxxxxxx) - 示例:(ts=1452680400)
https://min-api.cryptocompare.com/data/pricehistorical?fsym=BTC&tsyms=USD&ts=1452680400
- How can i put the values from the API in an array?:
var closePrices= {
var : 'text',
array: [BTCDay1, BTCDay2, BTCDay3, BTCDay4, BTCDay5, BTCDay6, BTCDay7, BTCDay8, BTCDay9, BTCDay10, BTCDay11, BTCDay12, BTCDay13, BTCDay14]
};
- Then I want to put the array in this calculation formular:
public static double CalculateRsi(IEnumerable<double> closePrices)
{
var prices = closePrices as double[] ?? closePrices.ToArray();
double sumGain = 0;
double sumLoss = 0;
for (int i = 1; i < prices.Length; i++)
{
var difference = prices[i] - prices[i - 1];
if (difference >= 0)
{
sumGain += difference;
}
else
{
sumLoss -= difference;
}
}
if (sumGain == 0) return 0;
if (Math.Abs(sumLoss) < Tolerance) return 100;
var relativeStrength = sumGain / sumLoss;
return 100.0 - (100.0 / (1 + relativeStrength));
}
最佳答案
几个相当宽泛的问题(如果您发布一些您已经尝试自己编写的代码,通常效果会更好)...但是要解决的问题很有趣。
假设我们可以使用 es6 语法、Promises 和 fetch(如果不能,请查看如何填充和转译)。
创建时间戳数组
要获取当前日期的时间戳,您可以编写 Date.now()
。要将此时间戳更改为 n
天前的一天,我们将其减少一天中的毫秒数:
const timeStampForDaysAgo =
nrOfDays => Date.now() - 1000 * 60 * 60 * 24 * nrOfDays;
// e.g.: yesterday
const yesterday = timeStampForDaysAgo(1);
现在,如果我们填充整数数组 0...14
,我们可以使用 map
创建时间戳数组!
const lastTwoWeeks = Array.from(Array(14), (_, i) => timeStampForDaysAgo(i))
执行请求
在现代浏览器中,您可以使用fetch
进行请求。不过,我们需要一个 URL 列表,而不仅仅是时间戳。为了制作 URL,我们再次使用 map
:
const urls = lastTwoWeeks.map(ts => `https://your-url.com?ts=${ts}`);
现在我们有了 URL,我们可以创建我们的请求(再次使用 map
):
const btcRequests = urls.map(url => fetch(url).then(r => r.json()));
计算结果
在所有请求完成之前,我们无法开始计算结果。这就是 Promise.all
的用武之地:
Promise.all(btcRequests).then(calcRSI);
这确保我们只调用 calcRSI
直到所有 请求完成。
因为 API 返回 { BTC: { USD: Number } }
的对象,我们必须在计算之前提取数字。
Promise
.all(btcRequests)
.then(responses => responses.map(obj => obj.BTC.USD))
现在我们有了一个数字数组,我们终于可以调用您在 C# 代码中提供的计算函数了。当然,您必须先将其翻译成 javascript。
const calcRSI = (arrayOfValues) => /* do math, return value */
Promise
.all(btcRequests)
.then(responses => responses.map(obj => obj.BTC.USD))
.then(calcRSI)
.then(rsi => console.log("The RSI for the last 14 days, is:", rsi);
查看此 fiddle 中的代码(确保打开控制台)
关于javascript - 如何通过迭代时间戳操作向 API 询问许多值(过去 14 天)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45590653/