Skip to content

Commit 9fa65b9

Browse files
authored
feat: Add utility to generate previous timestamp (#136)
1 parent d721a40 commit 9fa65b9

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/product/CandleBucketUtil.test.ts

+26
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,32 @@ describe('CandleBucketUtil', () => {
3535
});
3636
});
3737

38+
describe('removeUnitISO', () => {
39+
it('calculates the previous timestamp', () => {
40+
const time = '2020-04-20T11:38:00.000Z';
41+
const granularity = CandleGranularity.ONE_HOUR;
42+
const expected = '2020-04-20T10:38:00.000Z';
43+
const actual = CandleBucketUtil.removeUnitISO(time, granularity, 1);
44+
expect(actual).toBe(expected);
45+
});
46+
47+
it('works with numbers', () => {
48+
const time = new Date('2020-04-20T11:38:00.000Z').getTime();
49+
const granularity = CandleGranularity.ONE_HOUR;
50+
const expected = '2020-04-20T10:38:00.000Z';
51+
const actual = CandleBucketUtil.removeUnitISO(time, granularity, 1);
52+
expect(actual).toBe(expected);
53+
});
54+
55+
it('works with multiple units', () => {
56+
const time = '2020-04-20T11:38:00.000Z';
57+
const granularity = CandleGranularity.ONE_MINUTE;
58+
const expected = '2020-04-20T11:36:00.000Z';
59+
const actual = CandleBucketUtil.removeUnitISO(time, granularity, 2);
60+
expect(actual).toBe(expected);
61+
});
62+
});
63+
3864
describe('mapInterval', () => {
3965
it('matches a value within a range', () => {
4066
const range = [60, 300, 900, 3600, 21600, 86400];

src/product/CandleBucketUtil.ts

+11
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,17 @@ export class CandleBucketUtil {
2121
return new Date(nextTimestamp).toISOString();
2222
}
2323

24+
static removeUnitMillis(openTime: number | string, granularity: CandleGranularity, amount: number): number {
25+
const granularityInMs = granularity * 1000;
26+
const units = amount * granularityInMs;
27+
return new Date(openTime).getTime() - units;
28+
}
29+
30+
static removeUnitISO(openTime: number | string, granularity: CandleGranularity, amount: number): ISO_8601_MS_UTC {
31+
const nextTimestamp = CandleBucketUtil.removeUnitMillis(openTime, granularity, amount);
32+
return new Date(nextTimestamp).toISOString();
33+
}
34+
2435
static getIntervals(): number[] {
2536
return [60, 300, 900, 3600, 21600, 86400];
2637
}

0 commit comments

Comments
 (0)