-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathcryptsy_api.py
128 lines (113 loc) · 5.24 KB
/
cryptsy_api.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
import collections
import exchange_api
import hashlib
import hmac
import json
import time
try:
import http.client
import urllib.request
import urllib.error
import urllib.parse
except ImportError:
# Python 2.7 compatbility
import httplib
class http: client = httplib
import urllib
import urllib2
class urllib: request = urllib2; error = urllib2; parse = urllib
class Market(exchange_api.Market):
_TRADE_MINIMUMS = {('Points', 'BTC') : 0.1}
def __init__(self, exchange, source_currency, target_currency, market_id, reverse_market):
exchange_api.Market.__init__(self, exchange)
self._source_currency = source_currency
self._target_currency = target_currency
self._market_id = market_id
self._reverse_market = reverse_market
def GetSourceCurrency(self):
return self._source_currency
def GetTargetCurrency(self):
return self._target_currency
def GetTradeMinimum(self):
return self._TRADE_MINIMUMS.get((self._source_currency, self._target_currency), 0.0000001)
def GetPublicOrders(self):
try:
post_dict = {'marketid' : self._market_id}
orders = self._exchange._Request('marketorders', post_dict)['return']
return ([exchange_api.Order(self, 'N/A', True,
float(order['quantity']),
float(order['buyprice'])) for
order in orders.get('buyorders', [])],
[exchange_api.Order(self, 'N/A', False,
float(order['quantity']),
float(order['sellprice'])) for
order in orders.get('sellorders', [])])
except (TypeError, LookupError) as e:
raise exchange_api.ExchangeException(e)
def CreateOrder(self, bid_order, amount, price):
if self._reverse_market:
bid_order = not bid_order
post_dict = {'marketid' : self._market_id,
'ordertype' : 'Buy' if bid_order else 'Sell',
'quantity' : amount,
'price' : max(0.0000001, price)}
try:
order_id = self._exchange._Request('createorder', post_dict)['orderid']
return exchange_api.Order(self, order_id, bid_order, amount, price)
except (TypeError, LookupError) as e:
raise exchange_api.ExchangeException(e)
class Cryptsy(exchange_api.Exchange):
@staticmethod
def GetName():
return 'Cryptsy'
def __init__(self, api_public_key, api_private_key):
self.api_auth_url = 'https://api.cryptsy.com/api'
self.api_headers = {'Content-type' : 'application/x-www-form-urlencoded',
'Accept' : 'application/json',
'User-Agent' : 'autocoin-autosell'}
self.api_public_key = api_public_key
self.api_private_key = api_private_key.encode('utf-8')
self._markets = collections.defaultdict(dict)
try:
for market in self._Request('getmarkets')['return']:
market1 = Market(self, market['primary_currency_code'],
market['secondary_currency_code'], market['marketid'], False)
self._markets[market1.GetSourceCurrency()][market1.GetTargetCurrency()] = market1
market2 = Market(self, market['secondary_currency_code'],
market['primary_currency_code'], market['marketid'], True)
self._markets[market2.GetSourceCurrency()][market2.GetTargetCurrency()] = market2
except (TypeError, LookupError) as e:
raise exchange_api.ExchangeException(e)
def _Request(self, method, post_dict=None):
if post_dict is None:
post_dict = {}
post_dict['method'] = method
post_dict['nonce'] = int(time.time())
post_data = urllib.parse.urlencode(post_dict).encode('utf-8')
digest = hmac.new(self.api_private_key, post_data, hashlib.sha512).hexdigest()
headers = {'Key' : self.api_public_key,
'Sign': digest}
headers.update(self.api_headers.items())
try:
request = urllib.request.Request(self.api_auth_url, post_data, headers)
response = urllib.request.urlopen(request)
try:
response_json = json.loads(response.read().decode('utf-8'))
if 'error' in response_json and response_json['error']:
raise exchange_api.ExchangeException(response_json['error'])
return response_json
finally:
response.close()
except (urllib.error.URLError, urllib.error.HTTPError, http.client.HTTPException,
ValueError) as e:
raise exchange_api.ExchangeException(e)
def GetCurrencies(self):
return self._markets.keys()
def GetMarkets(self):
return self._markets
def GetBalances(self):
try:
return {currency: float(balance) for currency, balance in
self._Request('getinfo')['return']['balances_available'].items()}
except (TypeError, LookupError, ValueError, AttributeError) as e:
raise exchange_api.ExchangeException(e)