forked from manishym/cryptopia-api-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cryptopia_api.py
177 lines (152 loc) · 8.09 KB
/
cryptopia_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
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
""" This is a wrapper for Cryptopia.co.nz API """
import json
import time
import hmac
import hashlib
import base64
import requests
# using requests.compat to wrap urlparse (python cross compatibility over 9000!!!)
from requests.compat import quote_plus
class Api(object):
""" Represents a wrapper for cryptopia API """
def __init__(self, key, secret):
self.key = key
self.secret = secret
self.public = ['GetCurrencies', 'GetTradePairs', 'GetMarkets',
'GetMarket', 'GetMarketHistory', 'GetMarketOrders', 'GetMarketOrderGroups']
self.private = ['GetBalance', 'GetDepositAddress', 'GetOpenOrders',
'GetTradeHistory', 'GetTransactions', 'SubmitTrade',
'CancelTrade', 'SubmitTip', 'SubmitWithdraw', 'SubmitTransfer']
def api_query(self, feature_requested, get_parameters=None, post_parameters=None):
""" Performs a generic api request """
time.sleep(1)
if feature_requested in self.private:
url = "https://www.cryptopia.co.nz/Api/" + feature_requested
post_data = json.dumps(post_parameters)
headers = self.secure_headers(url=url, post_data=post_data)
req = requests.post(url, data=post_data, headers=headers)
if req.status_code != 200:
try:
req.raise_for_status()
except requests.exceptions.RequestException as ex:
return None, "Status Code : " + str(ex)
req = req.json()
if 'Success' in req and req['Success'] is True:
result = req['Data']
error = None
else:
result = None
error = req['Error'] if 'Error' in req else 'Unknown Error'
return (result, error)
elif feature_requested in self.public:
url = "https://www.cryptopia.co.nz/Api/" + feature_requested + "/" + \
('/'.join(i for i in get_parameters.values()
) if get_parameters is not None else "")
req = requests.get(url, params=get_parameters)
if req.status_code != 200:
try:
req.raise_for_status()
except requests.exceptions.RequestException as ex:
return None, "Status Code : " + str(ex)
req = req.json()
if 'Success' in req and req['Success'] is True:
result = req['Data']
error = None
else:
result = None
error = req['Error'] if 'Error' in req else 'Unknown Error'
return (result, error)
else:
return None, "Unknown feature"
def get_currencies(self):
""" Gets all the currencies """
return self.api_query(feature_requested='GetCurrencies')
def get_tradepairs(self):
""" GEts all the trade pairs """
return self.api_query(feature_requested='GetTradePairs')
def get_markets(self):
""" Gets data for all markets """
return self.api_query(feature_requested='GetMarkets')
def get_market(self, market):
""" Gets market data """
return self.api_query(feature_requested='GetMarket',
get_parameters={'market': market})
def get_history(self, market):
""" Gets the full order history for the market (all users) """
return self.api_query(feature_requested='GetMarketHistory',
get_parameters={'market': market})
def get_orders(self, market):
""" Gets the user history for the specified market """
return self.api_query(feature_requested='GetMarketOrders',
get_parameters={'market': market})
def get_ordergroups(self, markets):
""" Gets the order groups for the specified market """
return self.api_query(feature_requested='GetMarketOrderGroups',
get_parameters={'markets': markets})
def get_balance(self, currency):
""" Gets the balance of the user in the specified currency """
result, error = self.api_query(feature_requested='GetBalance',
post_parameters={'Currency': currency})
if error is None:
result = result[0]
return (result, error)
def get_openorders(self, market):
""" Gets the open order for the user in the specified market """
return self.api_query(feature_requested='GetOpenOrders',
post_parameters={'Market': market})
def get_deposit_address(self, currency):
""" Gets the deposit address for the specified currency """
return self.api_query(feature_requested='GetDepositAddress',
post_parameters={'Currency': currency})
def get_tradehistory(self, market):
""" Gets the trade history for a market """
return self.api_query(feature_requested='GetTradeHistory',
post_parameters={'Market': market})
def get_transactions(self, transaction_type):
""" Gets all transactions for a user """
return self.api_query(feature_requested='GetTransactions',
post_parameters={'Type': transaction_type})
def submit_trade(self, market, trade_type, rate, amount):
""" Submits a trade """
return self.api_query(feature_requested='SubmitTrade',
post_parameters={'Market': market,
'Type': trade_type,
'Rate': rate,
'Amount': amount})
def cancel_trade(self, trade_type, order_id, tradepair_id):
""" Cancels an active trade """
return self.api_query(feature_requested='CancelTrade',
post_parameters={'Type': trade_type,
'OrderID': order_id,
'TradePairID': tradepair_id})
def submit_tip(self, currency, active_users, amount):
""" Submits a tip """
return self.api_query(feature_requested='SubmitTip',
post_parameters={'Currency': currency,
'ActiveUsers': active_users,
'Amount': amount})
def submit_withdraw(self, currency, address, amount):
""" Submits a withdraw request """
return self.api_query(feature_requested='SubmitWithdraw',
post_parameters={'Currency': currency,
'Address': address,
'Amount': amount})
def submit_transfer(self, currency, username, amount):
""" Submits a transfer """
return self.api_query(feature_requested='SubmitTransfer',
post_parameters={'Currency': currency,
'Username': username,
'Amount': amount})
def secure_headers(self, url, post_data):
""" Creates secure header for cryptopia private api. """
nonce = str(int(time.time()))
md5 = hashlib.md5()
jsonparams = post_data.encode('utf-8')
md5.update(jsonparams)
rcb64 = base64.b64encode(md5.digest()).decode('utf-8')
signature = self.key + "POST" + quote_plus(url).lower() + nonce + rcb64
hmacsignature = base64.b64encode(hmac.new(base64.b64decode(self.secret),
signature.encode('utf-8'),
hashlib.sha256).digest())
header_value = "amx " + self.key + ":" + hmacsignature.decode('utf-8') + ":" + nonce
return {'Authorization': header_value, 'Content-Type': 'application/json; charset=utf-8'}