mirror of
https://github.com/freqtrade/frequi.git
synced 2024-11-21 23:53:52 +00:00
Improve time-math functions
This commit is contained in:
parent
3083bef4bf
commit
3f1314677c
|
@ -1,13 +1,26 @@
|
|||
export const ROUND_UP = 2;
|
||||
export const ROUND_DOWN = 3;
|
||||
/** Rounds to the closer candle starting time */
|
||||
export const ROUND_CLOSER = 4;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param timeframems timeframe in milliseconds
|
||||
* @param timestamp timestamp in milliseconds
|
||||
* @param direction Direction (see ROUND_* constants)
|
||||
* @returns timestamp in ms rounded to the timeframe
|
||||
*/
|
||||
export function roundTimeframe(
|
||||
timeframems: number,
|
||||
timestamp: number,
|
||||
direction: number = ROUND_DOWN,
|
||||
) {
|
||||
const offset = timestamp % timeframems;
|
||||
return timestamp - offset + (direction === ROUND_UP ? timeframems : 0);
|
||||
let up = direction === ROUND_UP;
|
||||
if (direction === ROUND_CLOSER) {
|
||||
up = offset > timeframems / 2;
|
||||
}
|
||||
return timestamp - offset + (up ? timeframems : 0);
|
||||
}
|
||||
|
||||
export default {
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import { roundTimeframe, ROUND_DOWN, ROUND_UP } from '@/shared/timemath';
|
||||
import { roundTimeframe, ROUND_DOWN, ROUND_UP, ROUND_CLOSER } from '@/shared/timemath';
|
||||
|
||||
// 1651021200000 = 2022-04-27T11:05:00+00:00
|
||||
|
||||
|
@ -49,4 +49,31 @@ describe('timemath.ts', () => {
|
|||
expect(roundTimeframe(TIMEFRAME_MS_1D, 1651057500000, ROUND_UP)).toEqual(1651104000000);
|
||||
expect(roundTimeframe(TIMEFRAME_MS_1D, 1651057500200, ROUND_UP)).toEqual(1651104000000);
|
||||
});
|
||||
it('rounds values Closer 1m', () => {
|
||||
Date.parse('2022-04-27T11:05:05+00:00');
|
||||
|
||||
expect(
|
||||
roundTimeframe(TIMEFRAME_MS_1M, Date.parse('2022-04-27T11:05:05+00:00'), ROUND_CLOSER),
|
||||
).toEqual(Date.parse('2022-04-27T11:05:00+00:00'));
|
||||
|
||||
expect(
|
||||
roundTimeframe(TIMEFRAME_MS_1M, Date.parse('2022-04-27T11:05:29+00:00'), ROUND_CLOSER),
|
||||
).toEqual(Date.parse('2022-04-27T11:05:00+00:00'));
|
||||
|
||||
expect(
|
||||
roundTimeframe(TIMEFRAME_MS_1M, Date.parse('2022-04-27T11:05:31+00:00'), ROUND_CLOSER),
|
||||
).toEqual(Date.parse('2022-04-27T11:06:00+00:00'));
|
||||
|
||||
// Expect to round down to :00
|
||||
expect(
|
||||
roundTimeframe(TIMEFRAME_MS_1M, Date.parse('2022-04-27T11:05:30+00:00'), ROUND_CLOSER),
|
||||
).toEqual(Date.parse('2022-04-27T11:05:00+00:00'));
|
||||
|
||||
expect(
|
||||
roundTimeframe(TIMEFRAME_MS_1H, Date.parse('2022-04-27T11:05:30+00:00'), ROUND_CLOSER),
|
||||
).toEqual(Date.parse('2022-04-27T11:00:00+00:00'));
|
||||
expect(
|
||||
roundTimeframe(TIMEFRAME_MS_1H, Date.parse('2022-04-27T11:30:01+00:00'), ROUND_CLOSER),
|
||||
).toEqual(Date.parse('2022-04-27T12:00:00+00:00'));
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue
Block a user