-
Notifications
You must be signed in to change notification settings - Fork 4
/
btce.py
127 lines (104 loc) · 2.89 KB
/
btce.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
#!/usr/bin/python
import sys
import httplib
import urllib
import json
import hashlib
import hmac
import config
def nonce_generator():
try:
fd = open("nonce_state", "r")
nonce = int(fd.read())
fd.close()
except IOError:
nonce = 1
pass
while (True):
nonce = nonce+1
fd = open("nonce_state", "w")
fd.write(str(nonce))
fd.close()
yield nonce
nonce = nonce_generator()
class BTCEError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
def api_request(method, misc_params = {}):
params = {
"method": method,
"nonce": nonce.next()
}
params.update(misc_params)
params = urllib.urlencode(params)
H = hmac.new(config.BTC_api_secret, digestmod=hashlib.sha512)
H.update(params)
sign = H.hexdigest()
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Key":config.BTC_api_key,
"Sign":sign
}
conn = httplib.HTTPSConnection("btc-e.com")
try:
conn.request("POST", "/tapi", params, headers)
except httplib.HTTPException:
raise BTCEError("HTTP error: " + response.reason)
try:
reply = json.load(conn.getresponse())
if reply['success'] == 1:
return reply['return']
else:
raise BTCEError("API returned error: " + reply['error'])
print "API returned error: " + reply['error']
print response.status, response.reason
except BTCEError:
raise
except:
raise BTCEError("Unexpected error: " + str(sys.exc_info()[0]))
def pubapi_request(pair, type):
url = "https://btc-e.com/api/2/" + pair + "/" + type
try:
f = urllib.urlopen(url)
return json.load(f)
except IOError:
print f.code()
# TODO: support btc_eur, ltc_btc, ltc_usd, nmc_btc, eur_usd
correct_pairs = [['btc', 'usd'], ['btc', 'rur'], ['usd','rur']]
def ticker(pair):
return pubapi_request(pair, "ticker")['ticker']
def trades(pair):
return pubapi_request(pair, "trades")
def depth(pair):
return pubapi_request(pair, "depth")
def getinfo():
return api_request('getInfo')
def order_list(filter = {}):
return api_request('OrderList', filter)
def trans_history(filter = {}):
return api_request('TransHistory', filter)
def trade_history(filter = {}):
return api_request('TradeHistory', filter)
def prepare_deal(from_currency, to_currency, rate, amount):
pair = [from_currency, to_currency]
for p in correct_pairs:
if pair == p:
type = 'sell'
elif pair == [p[1], p[0]]:
type = 'buy'
pair = p
amount = float(amount) / float(rate)
pair = '_'.join(pair)
if not type:
raise BTCEError("Unsupported currency pair: " + pair[0] + "_" + pair[1])
return {'pair': pair, 'type':type, 'rate': rate, 'amount': amount}
def trade(deal):
# print pair, type, amount, rate
if deal.has_key('pair') and deal.has_key('type') and deal.has_key('rate') and deal.has_key('amount'):
return api_request('Trade', deal)
else:
raise BTCEError("Wrong deal specified: ", str(deal))
def cancel_order(id):
return api_request('CancelOrder', {'order_id': id})