-
Notifications
You must be signed in to change notification settings - Fork 3
/
manage_transactions.py
251 lines (175 loc) · 7.95 KB
/
manage_transactions.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
import os
from datetime import datetime
import config
from provider.etherscan import Etherscan
from util import logging
BASE_DIRECTORY = '/market-data/raw/transactions/'
log = logging.get_custom_logger(__name__, config.LOG_LEVEL)
def update_token_transactions(etherscan_api_token: str, symbol: str, token_address: str):
"""
fetches all transactions for the given token symbol. all data are fetched from etherscan.
:return:
Nothing
"""
symbol_dir = BASE_DIRECTORY + symbol
os.makedirs(symbol_dir, exist_ok=True)
max_time = datetime.utcnow()
max_time = max_time.replace(hour=0, minute=0, second=0, microsecond=0)
last_timestamp, last_block, last_hash = _get_last_transaction(symbol_dir)
log.debug('starting update from block: ' + str(last_block))
if last_hash:
log.debug('with hash: ' + last_hash)
log.debug('with timestamp: ' + str(last_timestamp))
transactions = Etherscan.get_token_trades(etherscan_api_token, token_address, last_block)
max_time_exceeded = False
file = None
filename = None
while not max_time_exceeded:
_clear_incomplete_data(symbol_dir, transactions)
for transaction in transactions:
# there are transaction with a very high value which seems to be not correct
# i.e. https://etherscan.io/tx/0xde99cab6cdd2011479e84cc46f3b0fea3594ed345922a825785c4a4ccfd9808f
# we will just ignore these transactions for now
if int(transaction['value']) > 1e30:
continue
last_batch_block = last_block
last_batch_timestamp = last_timestamp
last_batch_hash = last_hash
block_number = transaction['blockNumber']
timestamp = datetime.utcfromtimestamp(int(transaction['timeStamp']))
hash = transaction['hash']
if timestamp > max_time:
max_time_exceeded = True
break
act_filename = timestamp.strftime('%Y-%m-%d') + '.csv'
if not file or act_filename != filename:
filename = act_filename
if file:
file.close()
file = open(os.path.join(symbol_dir, filename), 'a')
# {
# "blockNumber": "4620855",
# "timeStamp": "1511634257",
# "hash": "0x5c9b0f9c6c32d2690771169ec62dd648fef7bce3d45fe8a6505d99fdcbade27a",
# "nonce": "5417",
# "blockHash": "0xee385ac028bb7d8863d70afa02d63181894e0b2d51b99c0c525ef24538c44c24",
# "from": "0x731c6f8c754fa404cfcc2ed8035ef79262f65702",
# "contractAddress": "0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2",
# "to": "0x642ae78fafbb8032da552d619ad43f1d81e4dd7c",
# "value": "1000000000000000000000000",
# "tokenName": "Maker",
# "tokenSymbol": "MKR",
# "tokenDecimal": "18",
# "transactionIndex": "55",
# "gas": "3000000",
# "gasPrice": "1000000000",
# "gasUsed": "1594668",
# "cumulativeGasUsed": "4047394",
# "input": "deprecated",
# "confirmations": "4924562"
# }
new_line = ','.join([transaction['blockNumber'],
transaction['timeStamp'],
transaction['hash'],
transaction['nonce'],
transaction['blockHash'],
transaction['from'],
transaction['to'],
transaction['value'],
transaction['tokenDecimal'],
transaction['transactionIndex'],
transaction['gas'],
transaction['gasPrice'],
transaction['gasUsed'],
transaction['cumulativeGasUsed'],
transaction['input'],
transaction['confirmations']])
file.write(new_line + '\n')
last_batch_timestamp = timestamp
last_batch_block = block_number
last_batch_hash = hash
log.debug('last block: ' + str(last_batch_block))
log.debug('last timestamp: ' + str(last_batch_timestamp))
transactions = Etherscan.get_token_trades(etherscan_api_token, token_address, last_batch_block)
if last_timestamp == last_batch_timestamp and last_block == last_batch_block and last_hash == last_batch_hash:
break
last_timestamp = last_batch_timestamp
last_block = last_batch_block
last_hash = last_batch_hash
if file:
file.flush()
os.fsync(file.fileno())
file.close()
file = None
def _clear_incomplete_data(symbol_dir, transactions):
last_file_timestamp = None
last_file = None
files = [f for f in os.listdir(symbol_dir) if os.path.isfile(os.path.join(symbol_dir, f))]
# get the file with the highest timestamp
for file in files:
filename = file.split('.')[0]
timestamp = datetime.strptime(filename, '%Y-%m-%d')
if not last_file_timestamp or timestamp > last_file_timestamp:
last_file_timestamp = timestamp
last_file = file
if not last_file:
return
first_transaction = transactions[0]
log.debug('removing incompleted block data')
log.debug('scanning for block number: ' + first_transaction['blockNumber'])
removed_lines = 0
new_lines = []
with open(os.path.join(symbol_dir, last_file), 'rt') as file:
for line in file:
line_split = line.split(',')
if str(line_split[0]) != str(first_transaction['blockNumber']):
new_lines.append(line)
else:
removed_lines += 1
file.flush()
file.close()
log.debug('removing number of lines: ' + str(removed_lines))
with open(os.path.join(symbol_dir, last_file), 'w') as file:
for line in new_lines:
file.write(line)
file.flush()
file.close()
def _get_last_transaction(symbol_dir):
last_file_timestamp = None
last_file = None
files = [f for f in os.listdir(symbol_dir) if os.path.isfile(os.path.join(symbol_dir, f))]
# get the file with the highest timestamp
for file in files:
filename = file.split('.')[0]
timestamp = datetime.strptime(filename, '%Y-%m-%d')
if not last_file_timestamp or timestamp > last_file_timestamp:
last_file_timestamp = timestamp
last_file = file
# if we don't have stored data for the given symbol
if not last_file:
return 0, 0, None
# getting the last line of the file an extract the timestamp
with open(os.path.join(symbol_dir, last_file), 'rt') as file:
last_line = file.readlines()[-1]
last_line = last_line.split(',')
return datetime.utcfromtimestamp(int(last_line[1])), last_line[0], last_line[2]
def get_first_transaction_timestamp(symbol):
last_file_timestamp = None
dir = BASE_DIRECTORY + symbol
files = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir, f))]
# get the file with the highest timestamp
for file in files:
filename = file.split('.')[0]
timestamp = datetime.strptime(filename, '%Y-%m-%d')
if not last_file_timestamp or timestamp < last_file_timestamp:
last_file_timestamp = timestamp
return last_file_timestamp
def get_transaction_data(symbol, date):
try:
with open(os.path.join(BASE_DIRECTORY, symbol, date.strftime('%Y-%m-%d') + '.csv'), 'rt') as file:
return_data = []
for line in file:
return_data.append(line.strip().split(','))
return return_data
except:
return []