-
Notifications
You must be signed in to change notification settings - Fork 54
/
GetPoolData.py
428 lines (354 loc) · 20.9 KB
/
GetPoolData.py
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import pandas as pd
from datetime import datetime, timedelta
import requests
import pickle
import importlib
from itertools import compress
# Extract all Mint, Burn, and Swap Events
# From a given pool
# Returns json requests
def get_pool_data_raw(contract_address,api_token,DOWNLOAD_DATA=False):
# Break out into block height chunks to rate limit
block_height_limits = [0,12800000,14000000]
request_mint = []
request_burn = []
request_swap = []
if DOWNLOAD_DATA:
for i in range(len(block_height_limits)-1):
event = "Mint"
request_mint.append(run_query(generate_event_payload(event,contract_address,block_height_limits[i],block_height_limits[i+1]),api_token))
event = "Burn"
request_burn.append(run_query(generate_event_payload(event,contract_address,block_height_limits[i],block_height_limits[i+1]),api_token))
event = "Swap"
request_swap.append(run_query(generate_event_payload(event,contract_address,block_height_limits[i],block_height_limits[i+1]),api_token))
with open('eth_usdc_mint.pkl', 'wb') as output:
pickle.dump(request_mint, output, pickle.HIGHEST_PROTOCOL)
with open('eth_usdc_burn.pkl', 'wb') as output:
pickle.dump(request_burn, output, pickle.HIGHEST_PROTOCOL)
with open('eth_usdc_swap.pkl', 'wb') as output:
pickle.dump(request_swap, output, pickle.HIGHEST_PROTOCOL)
else:
with open('eth_usdc_mint.pkl', 'rb') as input:
request_mint = pickle.load(input)
with open('eth_usdc_burn.pkl', 'rb') as input:
request_burn = pickle.load(input)
with open('eth_usdc_swap.pkl', 'rb') as input:
request_swap = pickle.load(input)
return request_mint,request_burn,request_swap
##############################################################
# Convert mint_burn data json to pandas DataFrame
##############################################################
def process_mint_burn_data(request_mint_in,request_burn_in):
mint_data = pd.concat([pd.DataFrame({
'block': [int(x['block']['height']) for x in request_mint['data']['ethereum']['smartContractEvents']],
'time': [x['block']['timestamp']['iso8601'] for x in request_mint['data']['ethereum']['smartContractEvents']],
'tickLower': [x['arguments'][2]['value'] for x in request_mint['data']['ethereum']['smartContractEvents']],
'tickUpper': [x['arguments'][3]['value'] for x in request_mint['data']['ethereum']['smartContractEvents']],
'amount': [x['arguments'][4]['value'] for x in request_mint['data']['ethereum']['smartContractEvents']],
'amount0': [x['arguments'][5]['value'] for x in request_mint['data']['ethereum']['smartContractEvents']],
'amount1': [x['arguments'][6]['value'] for x in request_mint['data']['ethereum']['smartContractEvents']],
'txHash': [x['transaction']['hash'] for x in request_mint['data']['ethereum']['smartContractEvents']],
'txFrom': [x['transaction']['txFrom']['address'] for x in request_mint['data']['ethereum']['smartContractEvents']],
'name' : 'Mint'
}) for request_mint in request_mint_in])
burn_data = pd.concat([pd.DataFrame({
'block': [int(x['block']['height']) for x in request_burn['data']['ethereum']['smartContractEvents']],
'time': [x['block']['timestamp']['iso8601'] for x in request_burn['data']['ethereum']['smartContractEvents']],
'tickLower': [x['arguments'][1]['value'] for x in request_burn['data']['ethereum']['smartContractEvents']],
'tickUpper': [x['arguments'][2]['value'] for x in request_burn['data']['ethereum']['smartContractEvents']],
'amount': [x['arguments'][3]['value'] for x in request_burn['data']['ethereum']['smartContractEvents']],
'amount0': [x['arguments'][4]['value'] for x in request_burn['data']['ethereum']['smartContractEvents']],
'amount1': [x['arguments'][5]['value'] for x in request_burn['data']['ethereum']['smartContractEvents']],
'txHash': [x['transaction']['hash'] for x in request_burn['data']['ethereum']['smartContractEvents']],
'txFrom': [x['transaction']['txFrom']['address'] for x in request_burn['data']['ethereum']['smartContractEvents']],
'name' : 'Burn'
}) for request_burn in request_burn_in])
##############################################################
# Drop events with errors in the arguments
# For example some transaction hashes show up in parameters
##############################################################
# Mint
wrong_inputs = mint_data[mint_data['amount'].str.contains('x',na=False)].index
mint_data = mint_data.drop(wrong_inputs)
wrong_inputs = mint_data[mint_data['tickLower'].str.contains('x',na=False)].index
mint_data = mint_data.drop(wrong_inputs)
wrong_inputs = mint_data[mint_data['tickLower'].str.contains('x',na=False)].index
mint_data = mint_data.drop(wrong_inputs)
# Burn
wrong_inputs = burn_data[burn_data['amount'].str.contains('x',na=False)].index
burn_data = burn_data.drop(wrong_inputs)
wrong_inputs = burn_data[burn_data['tickLower'].str.contains('x',na=False)].index
burn_data = burn_data.drop(wrong_inputs)
wrong_inputs = burn_data[burn_data['tickLower'].str.contains('x',na=False)].index
burn_data = burn_data.drop(wrong_inputs)
# Convert amounts in burn to negative to compute cumulatie liquidity
mint_data['amount'] = mint_data['amount'].astype(float)
burn_data['amount'] = burn_data['amount'].astype(float)
mint_data['amount_for_calc'] = mint_data['amount']
burn_data['amount_for_calc'] = -burn_data['amount']
# Merge Mint burn data
mb_data = pd.concat([mint_data,burn_data])
# Save ticks as integers
mb_data['tickLower'] = mb_data['tickLower'].astype(float)
mb_data['tickUpper'] = mb_data['tickUpper'].astype(float)
return mb_data
##############################################################
# Convert JSON Request with Swap Events to Pandas
##############################################################
def process_swap_data(request_swap_in):
swap_data = pd.concat([pd.DataFrame({
'block': [x['block']['height'] for x in request_swap['data']['ethereum']['smartContractEvents']],
'time': [x['block']['timestamp']['iso8601'] for x in request_swap['data']['ethereum']['smartContractEvents']],
'amount0': [x['arguments'][2]['value'] for x in request_swap['data']['ethereum']['smartContractEvents']],
'amount1': [x['arguments'][3]['value'] for x in request_swap['data']['ethereum']['smartContractEvents']],
'sqrtPrice': [x['arguments'][4]['value'] for x in request_swap['data']['ethereum']['smartContractEvents']],
'liquidity': [x['arguments'][5]['value'] for x in request_swap['data']['ethereum']['smartContractEvents']],
'tick': [x['arguments'][6]['value'] for x in request_swap['data']['ethereum']['smartContractEvents']],
'txHash': [x['transaction']['hash'] for x in request_swap['data']['ethereum']['smartContractEvents']],
'txFrom': [x['transaction']['txFrom']['address'] for x in request_swap['data']['ethereum']['smartContractEvents']],
'name' : 'Swap'
}) for request_swap in request_swap_in])
# Sort by block
swap_data = swap_data.sort_values('block',ascending=True)
return swap_data
##############################################################
# Get Pool Data using Mint and Burn Events from Bitquery
##############################################################
def get_pool_data_mint_burn(contract_address,api_token,DOWNLOAD_DATA = False):
request_mint,request_burn,request_swap = get_pool_data_raw(contract_address,api_token,DOWNLOAD_DATA)
mb_data = process_mint_burn_data(request_mint,request_burn)
mb_data_max_block = mb_data[['block','cumulative_liquidity']].groupby('block').last()
swap_data = process_swap_data(request_swap)
full_data = pd.merge_asof(swap_data,mb_data_max_block,on='block',direction='backward',allow_exact_matches = False)
# Remove swap with wrong inputs
wrong_inputs = full_data[full_data['amount0'].str.contains('x')].index
full_data = full_data.drop(wrong_inputs)
wrong_inputs = full_data[full_data['amount1'].str.contains('x')].index
full_data = full_data.drop(wrong_inputs)
wrong_inputs = full_data[full_data['tick'].str.contains('x')].index
full_data = full_data.drop(wrong_inputs)
DECIMALS_0 = 6
DECIMALS_1 = 18
FEE_TIER = 0.0003
full_data['amount0'] = full_data['amount0'].astype(float)
full_data['amount1'] = full_data['amount1'].astype(float)
full_data['tick'] = full_data['tick'].astype(float)
full_data['token_in'] = full_data.apply(lambda x: 'token0' if (x['amount0'] < 0) else 'token1',axis=1)
full_data['traded_in'] = full_data.apply(lambda x: -x['amount0']/(10**DECIMALS_0) if (x['amount0'] < 0) else -x['amount1']/(10**DECIMALS_1),axis=1)
full_data['traded_out'] = full_data.apply(lambda x: x['amount0']/(10**DECIMALS_0) if (x['amount0'] > 0) else x['amount1']/(10**DECIMALS_1),axis=1)
return full_data
##############################################################
# Get Pool Virtual Liquidity Data using Flipside Data Pool Stats Table
##############################################################
def get_liquidity_flipside(DOWNLOAD_DATA = False):
DECIMALS_0 = 6
DECIMALS_1 = 18
DECIMAL_ADJUSTMENT = 10**(DECIMALS_1 - DECIMALS_0)
flipside_queries = ['https://api.flipsidecrypto.com/api/v2/queries/b8ad3087-803a-478b-9ed3-c4f3c096bc47/data/latest',
'https://api.flipsidecrypto.com/api/v2/queries/de277680-5ff6-4d58-bfff-29ef114215be/data/latest']
if DOWNLOAD_DATA:
for i in flipside_queries:
request_stats = [pd.DataFrame(requests.get(x).json()) for x in flipside_queries]
with open('eth_usdc_liquidity.pkl', 'wb') as output:
pickle.dump(request_stats, output, pickle.HIGHEST_PROTOCOL)
else:
with open('eth_usdc_liquidity.pkl', 'rb') as input:
request_stats = pickle.load(input)
stats_data = pd.concat(request_stats)
stats_data['block'] = stats_data['BLOCK_ID']
stats_data['virtual_liquidity'] = stats_data['VIRTUAL_LIQUIDITY_ADJUSTED']*DECIMAL_ADJUSTMENT
stats_data['price_usd'] = stats_data['PRICE_0_1']
stats_data['price_tick'] = stats_data['TICK']
stats_data.sort_values('block',ascending=True,inplace=True)
return stats_data
##############################################################
# Get all swaps for the pool using flipside data's price feed
# For the contract's liquidity
##############################################################
def get_pool_data_flipside(contract_address,api_token,DOWNLOAD_DATA = False):
request_mint,request_burn,request_swap = get_pool_data_raw(contract_address,api_token,DOWNLOAD_DATA)
swap_data = process_swap_data(request_swap)
stats_data = get_liquidity_flipside(DOWNLOAD_DATA)
full_data = pd.merge_asof(swap_data,stats_data[['block','virtual_liquidity','price_usd','price_tick']],on='block',direction='backward',allow_exact_matches = False)
# Remove swap with wrong arguments
wrong_inputs = full_data[full_data['amount0'].str.contains('x')].index
full_data = full_data.drop(wrong_inputs)
wrong_inputs = full_data[full_data['amount1'].str.contains('x')].index
full_data = full_data.drop(wrong_inputs)
wrong_inputs = full_data[full_data['tick'].str.contains('x')].index
full_data = full_data.drop(wrong_inputs)
wrong_inputs = full_data[full_data['sqrtPrice'].str.contains('x')].index
full_data = full_data.drop(wrong_inputs)
DECIMALS_0 = 6
DECIMALS_1 = 18
FEE_TIER = 0.0003
full_data['amount0'] = full_data['amount0'].astype(float)
full_data['amount1'] = full_data['amount1'].astype(float)
full_data['tick'] = full_data['tick'].astype(float)
full_data['sqrtPrice'] = full_data['sqrtPrice'].astype(float)
full_data['liquidity'] = full_data['liquidity'].astype(float)
full_data['token_in'] = full_data.apply(lambda x: 'token0' if (x['amount0'] < 0) else 'token1',axis=1)
full_data['traded_in'] = full_data.apply(lambda x: -x['amount0']/(10**DECIMALS_0) if (x['amount0'] < 0) else -x['amount1']/(10**DECIMALS_1),axis=1).astype(float)
full_data['traded_out'] = full_data.apply(lambda x: x['amount0']/(10**DECIMALS_0) if (x['amount0'] > 0) else x['amount1']/(10**DECIMALS_1),axis=1).astype(float)
full_data['pool_price'] = 1/(full_data['sqrtPrice']**2 * 10**(DECIMALS_0 - DECIMALS_1) / (2**192))
full_data['prior_sqrtPrice'] = full_data['sqrtPrice'].shift(1)
full_data['prior_tick'] = full_data['tick'].shift(1)
# Set index in pandas UTC Time
full_data['time_pd'] = pd.to_datetime(full_data['time'],utc=True)
full_data = full_data.set_index('time_pd',drop=False)
return full_data
##############################################################
# Get Price Data from Bitquery
##############################################################
def get_price_data_bitquery(token_0_address,token_1_address,date_begin,date_end,api_token,DOWNLOAD_DATA = False):
request = []
# Break out into months to rate limit
months_to_request = pd.date_range(date_begin,date_end,freq="M").strftime("%Y-%m-%d").tolist()
if DOWNLOAD_DATA:
for i in range(len(months_to_request)-1):
request.append(run_query(generate_price_payload(token_0_address,token_1_address,months_to_request[i],months_to_request[i+1]),api_token))
with open('eth_usdc_1min.pkl', 'wb') as output:
pickle.dump(request, output, pickle.HIGHEST_PROTOCOL)
else:
with open('eth_usdc_1min.pkl', 'rb') as input:
request = pickle.load(input)
# Prepare data for strategy:
# Collect json data and add to a pandas Data Frame
requests_with_data = [len(x['data']['ethereum']['dexTrades']) > 0 for x in request]
relevant_requests = list(compress(request, requests_with_data))
price_data = pd.concat([pd.DataFrame({
'time': [x['timeInterval']['minute'] for x in request_price['data']['ethereum']['dexTrades']],
'baseCurrency': [x['baseCurrency']['symbol'] for x in request_price['data']['ethereum']['dexTrades']],
'quoteCurrency': [x['quoteCurrency']['symbol'] for x in request_price['data']['ethereum']['dexTrades']],
'quoteAmount': [x['quoteAmount'] for x in request_price['data']['ethereum']['dexTrades']],
'baseAmount': [x['baseAmount'] for x in request_price['data']['ethereum']['dexTrades']],
'quotePrice': [x['quotePrice'] for x in request_price['data']['ethereum']['dexTrades']],
'average_price': [x['average_price'] for x in request_price['data']['ethereum']['dexTrades']],
'median_price': [x['average_price'] for x in request_price['data']['ethereum']['dexTrades']],
'median_price': [x['average_price'] for x in request_price['data']['ethereum']['dexTrades']],
'open_price': [x['average_price'] for x in request_price['data']['ethereum']['dexTrades']],
'close_price': [x['average_price'] for x in request_price['data']['ethereum']['dexTrades']]
}) for request_price in relevant_requests])
price_data['time'] = pd.to_datetime(price_data['time'], format = '%Y-%m-%d %H:%M:%S')
price_data['time_pd'] = pd.to_datetime(price_data['time'],utc=True)
price_data.set_index('time_pd',drop=False,inplace=True)
# Convert price to float
price_data['close_price'] = price_data["close_price"].astype(dtype=float)
# Create minute variable for easier filtering and aggregating
price_data['minute'] = [timeperiod.strftime('%M') for timeperiod in price_data['time']]
price_data['minute'] = price_data['minute'].astype(dtype=int)
return price_data
##############################################################
# Generate payload for bitquery events
##############################################################
def generate_event_payload(event,address,block_begin,block_end):
payload = '''{
ethereum {
smartContractEvents(
options: {desc: "block.height"}
smartContractEvent: {is: "'''+event+'''"}
smartContractAddress: {is: "'''+address+'''"}
height: {between: ['''+str(block_begin)+''','''+str(block_end)+''' ]}
) {
smartContractEvent {
name
}
block {
height
timestamp {
iso8601
unixtime
}
}
arguments {
value
argument
}
transaction {
hash
txFrom {
address
}
}
}
}
}'''
return payload
def generate_all_event_payload(address):
payload = '''{
ethereum {
smartContractEvents(
options: {desc: "block.height"}
smartContractAddress: {is: "'''+address+'''"}
) {
smartContractEvent {
name
}
block {
height
timestamp {
iso8601
unixtime
}
}
arguments {
value
argument
}
transaction {
hash
txFrom {
address
}
}
}
}
}'''
return payload
def generate_price_payload(token_0_address,token_1_address,date_begin,date_end):
payload = '''{
ethereum(network: ethereum) {
dexTrades(
options: {asc: "timeInterval.minute"}
date: {between: ["'''+date_begin+'''","'''+date_end+'''"]}
exchangeName: {is: "Uniswap"}
baseCurrency: {is: "'''+token_0_address+'''"}
quoteCurrency: {is: "'''+token_1_address+'''"}
) {
timeInterval {
minute(count: 1)
}
baseCurrency {
symbol
address
}
baseAmount
quoteCurrency {
symbol
address
}
quoteAmount
trades: count
quotePrice
average_price: quotePrice(calculate: average)
median_price: quotePrice(calculate: median)
open_price: minimum(of: time, get: quote_price)
close_price: maximum(of: time, get: quote_price)
}
}
}'''
return payload
# Make dependent on smart contract?
#smartContractAddress: {is: "'''+contract_address+'''"}
##############################################################
# A simple function to use requests.post to make the API call
##############################################################
def run_query(query,api_token):
url = 'https://graphql.bitquery.io/'
headers = {'X-API-KEY': api_token}
request = requests.post(url,
json={'query': query}, headers=headers)
if request.status_code == 200:
return request.json()
else:
raise Exception('Query failed and return code is {}. {}'.format(request.status_code,query))