Skip to content

Commit 5b9524b

Browse files
committed
A lot of refactoring and started adding tests
1 parent d5a847e commit 5b9524b

4 files changed

Lines changed: 129 additions & 93 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22
__pycache__/
33
*.pyc
44
*.pyo
5+
do_not_commit.py

‎Cryptsy.py‎

Lines changed: 85 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -2,78 +2,69 @@
22
import urllib2
33
import json
44
import time
5-
import hmac,hashlib
6-
7-
def createTimeStamp(datestr, format="%Y-%m-%d %H:%M:%S"):
8-
return time.mktime(time.strptime(datestr, format))
9-
10-
class Cryptsy:
11-
def __init__(self, APIKey, Secret):
12-
self.APIKey = APIKey
13-
self.Secret = Secret
14-
15-
def post_process(self, before):
16-
after = before
17-
18-
# Add timestamps if there isnt one but is a datetime
19-
if('return' in after):
20-
if(isinstance(after['return'], list)):
21-
for x in xrange(0, len(after['return'])):
22-
if(isinstance(after['return'][x], dict)):
23-
if('datetime' in after['return'][x] and 'timestamp' not in after['return'][x]):
24-
after['return'][x]['timestamp'] = float(createTimeStamp(after['return'][x]['datetime']))
25-
26-
return after
27-
28-
def api_query(self, method, req={}):
29-
30-
if(method == "marketdata" or method == "orderdata" or method == "marketdatav2"):
31-
ret = urllib2.urlopen(urllib2.Request('http://pubapi.cryptsy.com/api.php?method=' + method))
32-
return json.loads(ret.read())
33-
elif(method == "singlemarketdata" or method == "singleorderdata"):
34-
ret = urllib2.urlopen(urllib2.Request('http://pubapi.cryptsy.com/api.php?method=' + method + '&marketid=' + str(req['marketid'])))
35-
return json.loads(ret.read())
36-
else:
37-
req['method'] = method
38-
req['nonce'] = int(time.time())
39-
post_data = urllib.urlencode(req)
5+
import hmac
6+
import hashlib
7+
8+
9+
class Api:
10+
def __init__(self, key, secret):
11+
self.API_KEY = key
12+
self.SECRET = secret
13+
14+
def _public_api_query(self, method, marketid=None):
15+
""" Call to the public api and return the loaded json. """
16+
request_url = 'http://pubapi.cryptsy.com/api.php?method=%s' % method
17+
if marketid is not None:
18+
request_url += '&marketid=%d' % marketid
19+
20+
rv = urllib2.urlopen(urllib2.Request(request_url))
21+
return json.loads(rv.read())
4022

41-
sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()
42-
headers = {
43-
'Sign': sign,
44-
'Key': self.APIKey
45-
}
23+
def _api_query(self, method, request_data=None):
24+
""" Call to the "private" api and return the loaded json. """
25+
request_data['method'] = method
26+
request_data['nonce'] = int(time.time())
27+
post_data = urllib.urlencode(request_data)
4628

47-
ret = urllib2.urlopen(urllib2.Request('https://www.cryptsy.com/api', post_data, headers))
48-
jsonRet = json.loads(ret.read())
49-
return self.post_process(jsonRet)
29+
signed_data = hmac.new(self.SECRET, post_data, hashlib.sha512)\
30+
.hexdigest()
31+
headers = {
32+
'Sign': signed_data,
33+
'Key': self.API_KEY
34+
}
35+
36+
rv = urllib2.urlopen(urllib2.Request('https://www.cryptsy.com/api',
37+
post_data,
38+
headers))
39+
40+
return json.loads(rv.read())
5041

5142
def getMarketData(self):
52-
return self.api_query("marketdata")
43+
return self._public_api_query("marketdata")
5344

5445
def getMarketDataV2(self):
55-
return self.api_query("marketdatav2")
46+
return self._public_api_query("marketdatav2")
5647

57-
def getSingleMarketData(self, marketid):
58-
return self.api_query("singlemarketdata", {'marketid': marketid})
48+
def getSingleMarketData(self, marketid=None):
49+
return self._public_api_query("singlemarketdata", marketid=marketid)
5950

6051
def getOrderbookData(self, marketid=None):
61-
if(marketid == None):
62-
return self.api_query("orderdata")
63-
return self.api_query("singleorderdata", {'marketid': marketid})
52+
if marketid is None:
53+
return self._public_api_query("orderdata")
54+
return self._public_api_query("singleorderdata", marketid=marketid)
6455

65-
# Outputs:
56+
# Outputs:
6657
# balances_available Array of currencies and the balances availalbe for each
6758
# balances_hold Array of currencies and the amounts currently on hold for open orders
6859
# servertimestamp Current server timestamp
6960
# servertimezone Current timezone for the server
7061
# serverdatetime Current date/time on the server
7162
# openordercount Count of open orders on your account
7263
def getInfo(self):
73-
return self.api_query('getinfo')
64+
return self._api_query('getinfo')
7465

7566

76-
# Outputs: Array of Active Markets
67+
# Outputs: Array of Active Markets
7768
# marketid Integer value representing a market
7869
# label Name for this market, for example: AMC/BTC
7970
# primary_currency_code Primary currency code, for example: AMC
@@ -85,10 +76,10 @@ def getInfo(self):
8576
# high_trade 24 hour highest trade price in this market
8677
# low_trade 24 hour lowest trade price in this market
8778
def getMarkets(self):
88-
return self.api_query('getmarkets')
79+
return self._api_query('getmarkets')
8980

9081

91-
# Outputs: Array of Deposits and Withdrawals on your account
82+
# Outputs: Array of Deposits and Withdrawals on your account
9283
# currency Name of currency account
9384
# timestamp The timestamp the activity posted
9485
# datetime The datetime the activity posted
@@ -97,49 +88,50 @@ def getMarkets(self):
9788
# address Address to which the deposit posted or Withdrawal was sent
9889
# amount Amount of transaction
9990
def myTransactions(self):
100-
return self.api_query('mytransactions')
91+
return self._api_query('mytransactions')
10192

10293

10394
# Inputs:
10495
# marketid Market ID for which you are querying
10596
##
106-
# Outputs: Array of last 1000 Trades for this Market, in Date Decending Order
97+
# Outputs: Array of last 1000 Trades for this Market, in Date Decending Order
10798
# datetime Server datetime trade occurred
10899
# tradeprice The price the trade occurred at
109100
# quantity Quantity traded
110101
# total Total value of trade (tradeprice * quantity)
111102
def marketTrades(self, marketid):
112-
return self.api_query('markettrades', {'marketid': marketid})
103+
return self._api_query('markettrades', request_data={'marketid': marketid})
113104

114105

115106
# Inputs:
116107
# marketid Market ID for which you are querying
117108
##
118-
# Outputs: 2 Arrays. First array is sellorders listing current open sell orders ordered price ascending. Second array is buyorders listing current open buy orders ordered price descending.
109+
# Outputs: 2 Arrays. First array is sellorders listing current open sell orders ordered price ascending. Second array is buyorders listing current open buy orders ordered price descending.
119110
# sellprice If a sell order, price which order is selling at
120111
# buyprice If a buy order, price the order is buying at
121112
# quantity Quantity on order
122113
# total Total value of order (price * quantity)
123114
def marketOrders(self, marketid):
124-
return self.api_query('marketorders', {'marketid': marketid})
115+
return self._api_query('marketorders', request_data={'marketid': marketid})
125116

126117

127118
# Inputs:
128119
# marketid Market ID for which you are querying
129120
# limit (optional) Limit the number of results. Default: 200
130121
##
131-
# Outputs: Array your Trades for this Market, in Date Decending Order
122+
# Outputs: Array your Trades for this Market, in Date Decending Order
132123
# tradeid An integer identifier for this trade
133124
# tradetype Type of trade (Buy/Sell)
134125
# datetime Server datetime trade occurred
135126
# tradeprice The price the trade occurred at
136127
# quantity Quantity traded
137128
# total Total value of trade (tradeprice * quantity)
138129
def myTrades(self, marketid, limit=200):
139-
return self.api_query('mytrades', {'marketid': marketid, 'limit': limit})
130+
return self._api_query('mytrades', request_data={'marketid': marketid,
131+
'limit': limit})
140132

141133

142-
# Outputs: Array your Trades for all Markets, in Date Decending Order
134+
# Outputs: Array your Trades for all Markets, in Date Decending Order
143135
# tradeid An integer identifier for this trade
144136
# tradetype Type of trade (Buy/Sell)
145137
# datetime Server datetime trade occurred
@@ -148,45 +140,45 @@ def myTrades(self, marketid, limit=200):
148140
# quantity Quantity traded
149141
# total Total value of trade (tradeprice * quantity)
150142
def allMyTrades(self):
151-
return self.api_query('allmytrades')
143+
return self._api_query('allmytrades')
152144

153145

154146
# Inputs:
155147
# marketid Market ID for which you are querying
156148
##
157-
# Outputs: Array of your orders for this market listing your current open sell and buy orders.
149+
# Outputs: Array of your orders for this market listing your current open sell and buy orders.
158150
# orderid Order ID for this order
159151
# created Datetime the order was created
160152
# ordertype Type of order (Buy/Sell)
161153
# price The price per unit for this order
162154
# quantity Quantity for this order
163155
# total Total value of order (price * quantity)
164156
def myOrders(self, marketid):
165-
return self.api_query('myorders', {'marketid': marketid})
157+
return self._api_query('myorders', request_data={'marketid': marketid})
166158

167159

168160
# Inputs:
169161
# marketid Market ID for which you are querying
170162
##
171-
# Outputs: Array of buy and sell orders on the market representing market depth.
163+
# Outputs: Array of buy and sell orders on the market representing market depth.
172164
# Output Format is:
173165
# array(
174166
# 'sell'=>array(
175-
# array(price,quantity),
167+
# array(price,quantity),
176168
# array(price,quantity),
177169
# ....
178-
# ),
170+
# ),
179171
# 'buy'=>array(
180-
# array(price,quantity),
172+
# array(price,quantity),
181173
# array(price,quantity),
182174
# ....
183175
# )
184176
# )
185177
def depth(self, marketid):
186-
return self.api_query('depth', {'marketid': marketid})
178+
return self._api_query('depth', request_data={'marketid': marketid})
187179

188180

189-
# Outputs: Array of all open orders for your account.
181+
# Outputs: Array of all open orders for your account.
190182
# orderid Order ID for this order
191183
# marketid The Market ID this order was created for
192184
# created Datetime the order was created
@@ -195,7 +187,7 @@ def depth(self, marketid):
195187
# quantity Quantity for this order
196188
# total Total value of order (price * quantity)
197189
def allMyOrders(self):
198-
return self.api_query('allmyorders')
190+
return self._api_query('allmyorders')
199191

200192

201193
# Inputs:
@@ -204,30 +196,35 @@ def allMyOrders(self):
204196
# quantity Amount of units you are buying/selling in this order
205197
# price Price per unit you are buying/selling at
206198
##
207-
# Outputs:
199+
# Outputs:
208200
# orderid If successful, the Order ID for the order which was created
209201
def createOrder(self, marketid, ordertype, quantity, price):
210-
return self.api_query('createorder', {'marketid': marketid, 'ordertype': ordertype, 'quantity': quantity, 'price': price})
211-
202+
return self._api_query('createorder',
203+
request_data={'marketid': marketid,
204+
'ordertype': ordertype,
205+
'quantity': quantity,
206+
'price': price})
207+
212208

213209
# Inputs:
214210
# orderid Order ID for which you would like to cancel
215211
##
216-
# Outputs: If successful, it will return a success code.
212+
# Outputs: If successful, it will return a success code.
217213
def cancelOrder(self, orderid):
218-
return self.api_query('cancelorder', {'orderid': orderid})
214+
return self.api_query('cancelorder', request_data={'orderid': orderid})
219215

220216

221217
# Inputs:
222218
# marketid Market ID for which you would like to cancel all open orders
223219
##
224-
# Outputs:
220+
# Outputs:
225221
# return Array for return information on each order cancelled
226222
def cancelMarketOrders(self, marketid):
227-
return self.api_query('cancelmarketorders', {'marketid': marketid})
223+
return self.api_query('cancelmarketorders',
224+
request_data={'marketid': marketid})
228225

229226

230-
# Outputs:
227+
# Outputs:
231228
# return Array for return information on each order cancelled
232229
def cancelAllOrders(self):
233230
return self.api_query('cancelallorders')
@@ -237,18 +234,21 @@ def cancelAllOrders(self):
237234
# quantity Amount of units you are buying/selling
238235
# price Price per unit you are buying/selling at
239236
##
240-
# Outputs:
237+
# Outputs:
241238
# fee The that would be charged for provided inputs
242239
# net The net total with fees
243240
def calculateFees(self, ordertype, quantity, price):
244-
return self.api_query('calculatefees', {'ordertype': ordertype, 'quantity': quantity, 'price': price})
241+
return self.api_query('calculatefees',
242+
request_data={'ordertype': ordertype,
243+
'quantity': quantity,
244+
'price': price})
245245

246246

247247
# Inputs: (either currencyid OR currencycode required - you do not have to supply both)
248248
# currencyid Currency ID for the coin you want to generate a new address for (ie. 3 = BitCoin)
249249
# currencycode Currency Code for the coin you want to generate a new address for (ie. BTC = BitCoin)
250250
##
251-
# Outputs:
251+
# Outputs:
252252
# address The new generated address
253253
def generateNewAddress(self, currencyid=None, currencycode=None):
254254

@@ -259,4 +259,4 @@ def generateNewAddress(self, currencyid=None, currencycode=None):
259259
else:
260260
return None
261261

262-
return self.api_query('generatenewaddress', req)
262+
return self._api_query('generatenewaddress', request_data=req)

‎README.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ Example Usage
1414
-------------
1515
Create buy order for dgc, market id 26, then cancels all orders you have for dgc
1616
```python
17-
import Cryptsy
18-
Exchange = Cryptsy.Cryptsy('KEY HERE', 'SECRET HERE')
19-
print(Exchange.createOrder(26, "Buy", 100, 0.00000001)) # Buy 100 dgc at .00000001 each
20-
print(Exchange.cancelMarketOrders(26)) # Cancels all orders in market 26, dgc
17+
from Cryptsy import API
18+
exchange = API('KEY HERE', 'SECRET HERE')
19+
print(exchange.createOrder(26, "Buy", 100, 0.00000001)) # Buy 100 dgc at .00000001 each
20+
print(exchange.cancelMarketOrders(26)) # Cancels all orders in market 26, dgc
2121
```
2222

2323
Running the tests

0 commit comments

Comments
 (0)