forked from cbyn/bitpredict
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollect_books.py
53 lines (45 loc) · 1.22 KB
/
collect_books.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
import urllib2
import time
import json
from pymongo import MongoClient
import sys
api = 'https://api.bitfinex.com/v1'
symbol = sys.argv[1]
limit = 25
book_url = '{0}/book/{1}usd?limit_bids={2}&limit_asks={2}'\
.format(api, symbol, limit)
client = MongoClient()
db = client['bitmicro']
ltc_books = db[symbol+'_books']
def format_book_entry(entry):
'''
Converts book data to float
'''
if all(key in entry for key in ('amount', 'price', 'timestamp')):
entry['amount'] = float(entry['amount'])
entry['price'] = float(entry['price'])
entry['timestamp'] = float(entry['timestamp'])
return entry
def get_json(url):
'''
Gets json from the API
'''
resp = urllib2.urlopen(url)
return json.load(resp, object_hook=format_book_entry), resp.getcode()
print 'Running...'
while True:
start = time.time()
try:
book, code = get_json(book_url)
except Exception as e:
print e
sys.exc_clear()
else:
if code != 200:
print code
else:
book['_id'] = time.time()
ltc_books.insert_one(book)
time_delta = time.time()-start
if time_delta < 1.0:
time.sleep(1-time_delta)