Skip to content

Commit

Permalink
fix(virtual-clock): start when create exchange, fallback APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
iam4x committed Mar 2, 2023
1 parent 0983ff7 commit ad4b287
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 9 deletions.
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Binance } from './exchanges/binance/binance.exchange';
import { Bybit } from './exchanges/bybit/bybit.exchange';
import type { ExchangeOptions } from './types';
import { virtualClock } from './utils/virtual-clock';

const exchanges = {
bybit: Bybit,
Expand All @@ -11,6 +12,10 @@ export const createExchange = (
exchangeName: keyof typeof exchanges,
options: ExchangeOptions
) => {
// start the virtual clock to contact exchanges
// with a server timestamp
virtualClock.start();

const Exchange = exchanges[exchangeName];
return new Exchange(options);
};
51 changes: 42 additions & 9 deletions src/utils/virtual-clock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,19 @@ import utc from 'dayjs/plugin/utc';
dayjs.extend(utc);

class VirtualClock {
started = false;

private server: Dayjs | null = null;
private client: Dayjs | null = null;

constructor() {
this.fetchServerTime();
setInterval(() => this.fetchServerTime(), 60_000);
}
start = async () => {
if (!this.started) {
this.started = true;

await this.fetchServerTime();
setInterval(() => this.fetchServerTime(), 60_000);
}
};

getCurrentTime = () => {
if (this.server && this.client) {
Expand All @@ -25,12 +31,39 @@ class VirtualClock {
};

private fetchServerTime = async () => {
const { data } = await axios.get(
'https://worldtimeapi.org/api/timezone/etc/utc'
);
if (typeof window === 'undefined') {
// assume we are running onto a server
// this should have a better time sync
this.server = dayjs.utc();
this.client = dayjs.utc();

this.server = dayjs.utc(data.utc_datetime);
this.client = dayjs.utc();
return;
}

try {
const { data } = await axios.get(
'https://worldtimeapi.org/api/timezone/etc/utc',
{ timeout: 5000 }
);

this.server = dayjs.utc(data.utc_datetime);
this.client = dayjs.utc();
} catch {
// fallback to tuleep.trade server time
// we don't really want to use this API as its not meant for this
try {
const {
data: { time },
} = await axios.get('https://tuleep.trade/api/time');

this.server = dayjs.utc(time);
this.client = dayjs.utc();
} catch {
// fallback to local time if all else fails
this.server = dayjs.utc();
this.client = dayjs.utc();
}
}
};
}

Expand Down

0 comments on commit ad4b287

Please sign in to comment.