-
Notifications
You must be signed in to change notification settings - Fork 336
/
prices.ts
320 lines (285 loc) · 9.18 KB
/
prices.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import { useMemo } from "react";
import { gql } from "@apollo/client";
import useSWR from "swr";
import { ethers } from "ethers";
import { USD_DECIMALS, CHART_PERIODS } from "lib/legacy";
import { GMX_STATS_API_URL } from "config/backend";
import { chainlinkClient } from "lib/subgraph/clients";
import { sleep } from "lib/sleep";
import { formatAmount } from "lib/numbers";
import { getNativeToken, getNormalizedTokenSymbol, isChartAvailabeForToken } from "config/tokens";
const BigNumber = ethers.BigNumber;
// Ethereum network, Chainlink Aggregator contracts
const FEED_ID_MAP = {
BTC_USD: "0xae74faa92cb67a95ebcab07358bc222e33a34da7",
ETH_USD: "0x37bc7498f4ff12c19678ee8fe19d713b87f6a9e6",
BNB_USD: "0xc45ebd0f901ba6b2b8c7e70b717778f055ef5e6d",
LINK_USD: "0xdfd03bfc3465107ce570a0397b247f546a42d0fa",
UNI_USD: "0x68577f915131087199fe48913d8b416b3984fd38",
SUSHI_USD: "0x7213536a36094cd8a768a5e45203ec286cba2d74",
AVAX_USD: "0x0fc3657899693648bba4dbd2d8b33b82e875105d",
AAVE_USD: "0xe3f0dede4b499c07e12475087ab1a084b5f93bc0",
YFI_USD: "0x8a4d74003870064d41d4f84940550911fbfccf04",
SPELL_USD: "0x8640b23468815902e011948f3ab173e1e83f9879",
};
export const timezoneOffset = -new Date().getTimezoneOffset() * 60;
function formatBarInfo(bar) {
const { t, o: open, c: close, h: high, l: low } = bar;
return {
time: t + timezoneOffset,
open,
close,
high,
low,
};
}
export function fillGaps(prices, periodSeconds) {
if (prices.length < 2) {
return prices;
}
const newPrices = [prices[0]];
let prevTime = prices[0].time;
for (let i = 1; i < prices.length; i++) {
const { time, open } = prices[i];
if (prevTime) {
let j = (time - prevTime) / periodSeconds - 1;
while (j > 0) {
newPrices.push({
time: time - j * periodSeconds,
open,
close: open,
high: open * 1.0003,
low: open * 0.9996,
});
j--;
}
}
prevTime = time;
newPrices.push(prices[i]);
}
return newPrices;
}
export async function getLimitChartPricesFromStats(chainId, symbol, period, limit = 1) {
symbol = getNormalizedTokenSymbol(symbol);
if (!isChartAvailabeForToken(chainId, symbol)) {
symbol = getNativeToken(chainId).symbol;
}
const url = `${GMX_STATS_API_URL}/candles/${symbol}?preferableChainId=${chainId}&period=${period}&limit=${limit}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const prices = await response.json().then(({ prices }) => prices);
return prices.map(formatBarInfo);
} catch (error) {
// eslint-disable-next-line no-console
console.log(`Error fetching data: ${error}`);
}
}
export async function getChartPricesFromStats(chainId, symbol, period) {
symbol = getNormalizedTokenSymbol(symbol);
const timeDiff = CHART_PERIODS[period] * 3000;
const from = Math.floor(Date.now() / 1000 - timeDiff);
const url = `${GMX_STATS_API_URL}/candles/${symbol}?preferableChainId=${chainId}&period=${period}&from=${from}&preferableSource=fast`;
const TIMEOUT = 5000;
const res: Response = await new Promise(async (resolve, reject) => {
let done = false;
setTimeout(() => {
done = true;
reject(new Error(`request timeout ${url}`));
}, TIMEOUT);
let lastEx;
for (let i = 0; i < 3; i++) {
if (done) return;
try {
const res = await fetch(url);
resolve(res);
return;
} catch (ex) {
await sleep(300);
lastEx = ex;
}
}
reject(lastEx);
});
if (!res.ok) {
throw new Error(`request failed ${res.status} ${res.statusText}`);
}
const json = await res.json();
let prices = json?.prices;
if (!prices || prices.length < 1) {
throw new Error(`not enough prices data: ${prices?.length}`);
}
const OBSOLETE_THRESHOLD = Date.now() / 1000 - 60 * 30; // 30 min ago
const updatedAt = json?.updatedAt || 0;
if (updatedAt < OBSOLETE_THRESHOLD) {
throw new Error(
"chart data is obsolete, last price record at " +
new Date(updatedAt * 1000).toISOString() +
" now: " +
new Date().toISOString()
);
}
prices = prices.map(formatBarInfo);
return prices;
}
function getCandlesFromPrices(prices, period) {
const periodTime = CHART_PERIODS[period];
if (prices.length < 2) {
return [];
}
const candles: any[] = [];
const first = prices[0];
let prevTsGroup = Math.floor(first[0] / periodTime) * periodTime;
let prevPrice = first[1];
let o = prevPrice;
let h = prevPrice;
let l = prevPrice;
let c = prevPrice;
for (let i = 1; i < prices.length; i++) {
const [ts, price] = prices[i];
const tsGroup = Math.floor(ts / periodTime) * periodTime;
if (prevTsGroup !== tsGroup) {
candles.push({ t: prevTsGroup + timezoneOffset, o, h, l, c });
o = c;
h = Math.max(o, c);
l = Math.min(o, c);
}
c = price;
h = Math.max(h, price);
l = Math.min(l, price);
prevTsGroup = tsGroup;
}
return candles.map(({ t: time, o: open, c: close, h: high, l: low }) => ({
time,
open,
close,
high,
low,
}));
}
export function getChainlinkChartPricesFromGraph(tokenSymbol, period) {
tokenSymbol = getNormalizedTokenSymbol(tokenSymbol);
const marketName = tokenSymbol + "_USD";
const feedId = FEED_ID_MAP[marketName];
if (!feedId) {
throw new Error(`undefined marketName ${marketName}`);
}
const PER_CHUNK = 1000;
const CHUNKS_TOTAL = 6;
const requests: any[] = [];
for (let i = 0; i < CHUNKS_TOTAL; i++) {
const query = gql(`{
rounds(
first: ${PER_CHUNK},
skip: ${i * PER_CHUNK},
orderBy: unixTimestamp,
orderDirection: desc,
where: {feed: "${feedId}"}
) {
unixTimestamp,
value
}
}`);
requests.push(chainlinkClient.query({ query }));
}
return Promise.all(requests)
.then((chunks) => {
let prices: any[] = [];
const uniqTs = new Set();
chunks.forEach((chunk) => {
chunk.data.rounds.forEach((item) => {
if (uniqTs.has(item.unixTimestamp)) {
return;
}
uniqTs.add(item.unixTimestamp);
prices.push([item.unixTimestamp, Number(item.value) / 1e8]);
});
});
prices.sort(([timeA], [timeB]) => timeA - timeB);
prices = getCandlesFromPrices(prices, period);
return prices;
})
.catch((err) => {
// eslint-disable-next-line no-console
console.error(err);
});
}
export function useChartPrices(chainId, symbol, isStable, period, currentAveragePrice) {
const swrKey = !isStable && symbol ? ["getChartCandles", chainId, symbol, period] : null;
let { data: prices, mutate: updatePrices } = useSWR(swrKey, {
fetcher: async (...args) => {
try {
return await getChartPricesFromStats(chainId, symbol, period);
} catch (ex) {
// eslint-disable-next-line no-console
console.warn(ex);
// eslint-disable-next-line no-console
console.warn("Switching to graph chainlink data");
try {
return await getChainlinkChartPricesFromGraph(symbol, period);
} catch (ex2) {
// eslint-disable-next-line no-console
console.warn("getChainlinkChartPricesFromGraph failed");
// eslint-disable-next-line no-console
console.warn(ex2);
return [];
}
}
},
dedupingInterval: 60000,
focusThrottleInterval: 60000 * 10,
});
const currentAveragePriceString = currentAveragePrice && currentAveragePrice.toString();
const retPrices = useMemo(() => {
if (isStable) {
return getStablePriceData(period);
}
if (!prices) {
return [];
}
let _prices = [...prices];
if (currentAveragePriceString && prices.length) {
_prices = appendCurrentAveragePrice(_prices, BigNumber.from(currentAveragePriceString), period);
}
return fillGaps(_prices, CHART_PERIODS[period]);
}, [prices, isStable, currentAveragePriceString, period]);
return [retPrices, updatePrices];
}
function appendCurrentAveragePrice(prices, currentAveragePrice, period) {
const periodSeconds = CHART_PERIODS[period];
const currentCandleTime = Math.floor(Date.now() / 1000 / periodSeconds) * periodSeconds + timezoneOffset;
const last = prices[prices.length - 1];
const averagePriceValue = parseFloat(formatAmount(currentAveragePrice, USD_DECIMALS, 2));
if (currentCandleTime === last.time) {
last.close = averagePriceValue;
last.high = Math.max(last.high, averagePriceValue);
last.low = Math.max(last.low, averagePriceValue);
return prices;
} else {
const newCandle = {
time: currentCandleTime,
open: last.close,
close: averagePriceValue,
high: averagePriceValue,
low: averagePriceValue,
};
return [...prices, newCandle];
}
}
export function getStablePriceData(period, countBack = 100) {
const periodSeconds = CHART_PERIODS[period];
const now = Math.floor(Date.now() / 1000 / periodSeconds) * periodSeconds;
let priceData: any = [];
for (let i = countBack; i > 0; i--) {
priceData.push({
time: now - i * periodSeconds,
open: 1,
close: 1,
high: 1,
low: 1,
});
}
return priceData;
}