I’m looking for a way to calculate the previous close of a candle for a given timeframe in case of trading. Already figured it out for minute and hour based timeframes like H1, H4, H12, but struggling with daily, weekly and monthly as my formula doesn’t work for them. Some help would be highly appreciated 🙂
examples
current time in ms: 1691482660000
input: 4h
expected: 1691481600000 (Tue Aug 08 2023 08:00:00 GMT+0000)
actual: 1691481600000 (correct)
period: every 4 hours
input: 12h
expected: 1691452800000 (Tue Aug 08 2023 00:00:00 GMT+0000)
actual: 1691452800000 (correct)
period: every 12 hours
input: 3d
expected: 1691452800000 (Tue Aug 08 2023 00:00:00 GMT+0000)
actual: 1691280000000 (wrong)
period: every 3 days
input: 2d
expected: 1691366400000 (Mon Aug 07 2023 00:00:00 GMT+0000)
actual: 1691366400000(correct)
period: every 2 days
input: 2w
expected: 1690761600000 (Mon Jul 31 2023 00:00:00 GMT+0000)
actual: -
period: every 2 weeks
input: 3w
expected: 1690761600000 (Mon Jul 31 2023 00:00:00 GMT+0000)
actual: -
period: every 3 weeks
source
function getPreviousClose(timeframe) {
const value = Number(timeframe.slice(0, -1));
const unit = timeframe.slice(-1);
const now = new Date();
switch (unit) {
case 'm': {
const duration = value * 60 * 1000;
return now - (now % duration);
}
case 'h': {
const duration = value * 60 * 60 * 1000;
return now - (now % duration);
}
// NOT WORKING AS IT SHOULD
case 'd': {
const duration = value * 24 * 60 * 60 * 1000;
return now - (now % duration);
}
case 'w': {
// ????
}
case 'M': {
// ????
}
default:
throw new Error('getPreviousClose called with unsupported unit "'+ unit + '"');
}
}
2
Answers
Solved it
Could it be you mean this?
It is not clear from your description what you expect as output