-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbithumb.py
132 lines (116 loc) · 4.04 KB
/
bithumb.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
#
# XCoin API-call related functions
#
# @author btckorea
# @date 2017-04-12
#
# Compatible with python3 version.
import time
import base64
import hmac, hashlib
import urllib.parse
import requests
import json
import threading
import traceback
class Bithumb:
api_url = "https://api.bithumb.com"
api_key = ""
api_secret = ""
name = "bithumb"
price = {}
balance = {}
def __init__(self, key, secret):
self.api_key = key
self.api_secret = secret
self.run_worker()
def get_header(self, endpoint, str_data):
nonce = str(int(time.time()*1000))
data = endpoint + chr(0) + str_data + chr(0) + nonce
signature = hmac.new(self.api_secret.encode(), data.encode(), hashlib.sha512).hexdigest()
signature64 = base64.b64encode(signature.encode()).decode()
return {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Api-Key': self.api_key,
'Api-Sign': str(signature64),
'Api-Nonce': nonce,
}
def secret_api(self, endpoint, **kwargs):
endpoint_item_array = {
"endpoint": endpoint
}
uri_array = dict(endpoint_item_array, **kwargs) # Concatenate the two arrays.
json_data = json.dumps(uri_array)
str_data = urllib.parse.urlencode(uri_array)
session = requests.Session()
session.cookies.clear()
resp = session.request('POST', self.api_url+endpoint, data=str_data, headers=self.get_header(endpoint, str_data))
if endpoint != '/info/balance':
print('bithumb secert_api ' + endpoint + ' ' + str(resp.status_code) + ' ' + resp.text)
return resp
def bid(self):
return self.price
def run_worker(self):
p_thread = threading.Thread(target=get_bithumb_price, args=(self,))
p_thread.daemon = True
p_thread.start()
b_thread = threading.Thread(target=get_bithumb_balance, args=(self,))
b_thread.daemon = True
b_thread.start()
# Pre check doned
def buy_coin(self, cur, amount, account):
if round(amount / self.price[cur], 4) < account:
units = str(round(amount / self.price[cur], 4))
else:
units = str(round(account, 4))
try:
if float(units) == 0:
raise Exception('size Error')
r = self.secret_api("/trade/place", order_currency=str(cur).upper(), units=units, price=str(int(self.price[cur])), type='bid').json()
print(json.dumps(r))
print(json.dumps(r['data']))
if int(r['status']) == 0:
return {
'units': units,
'price': self.price[cur]
}
else:
raise Exception('http error')
except Exception as e:
print(e)
print(traceback.format_exc())
return {
'units': 0,
'price': 0,
'error': True
}
# Pre check doned
def sell_coin(self, cur, amount):
r = self.secret_api("/trade/market_sell", currency=str(cur).upper(), units=str(amount))
if r.status_code != requests.codes.ok:
return {'units': 0, 'price': 0, 'error': True}
return r.json()
def get_bithumb_balance(api):
while True:
r = api.secret_api("/info/balance", currency='ALL')
if r.status_code != requests.codes.ok:
continue
r = r.json()
for k in r['data']:
if str.startswith(k, 'total'):
api.balance[k[6:]] = r['data'][k]
time.sleep(5)
def get_bithumb_price(api):
while True:
result = {}
r = requests.get("https://api.bithumb.com/public/orderbook/all")
r = r.json()
for cur in r['data'].keys():
try:
result[str.lower(cur)] = float(r['data'][cur]['bids'][0]['price'])
except:
pass
api.price = result
time.sleep(5)