-
Notifications
You must be signed in to change notification settings - Fork 18
/
PyCryptsy.py
167 lines (147 loc) · 5.32 KB
/
PyCryptsy.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
#!/usr/bin/env python
# coding=iso-8859-1
# PyCryptsy: a Python binding to the Cryptsy API
#
# Copyright © 2013-2014 Scott Alfter
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import pycurl
import time
import hmac
import hashlib
import urllib
import StringIO
import json
class PyCryptsy:
# constructor (Key: API public key, Secret: API private key)
def __init__(self, Key, Secret):
self.key=Key
self.secret=Secret
# issue any supported query (method: string, req: dictionary with method parameters)
def Query(self, method, req):
# generate POST data string
req["method"]=method
req["nonce"]=int(time.time())
post_data=urllib.urlencode(req)
# sign it
sign=hmac.new(self.secret, post_data, hashlib.sha512).hexdigest()
# extra headers for request
headers=["Sign: "+sign, "Key: "+self.key]
# curl handle
b=StringIO.StringIO()
ch=pycurl.Curl()
ch.setopt(pycurl.URL, "https://api.cryptsy.com/api")
ch.setopt(pycurl.POSTFIELDS, post_data)
ch.setopt(pycurl.HTTPHEADER, headers)
ch.setopt(pycurl.SSL_VERIFYPEER, 0)
ch.setopt(pycurl.WRITEFUNCTION, b.write)
try:
ch.perform()
except pycurl.error, error:
errno, errstr=error
raise Exception("pycurl error: "+errstr)
# decode and return
try:
rtnval=json.loads(b.getvalue())
except:
raise Exception("unable to decode response")
return rtnval
# issue any supported public query (method: string, req: dictionary with method paramet ers)
def PublicQuery(self, method, req):
# build URL
url="http://pubapi.cryptsy.com/api.php?method="+method
for i, opt in enumerate(req):
url+="&"+str(opt)+"="+str(req[opt])
# curl handle
b=StringIO.StringIO()
ch=pycurl.Curl()
ch.setopt(pycurl.URL, url)
ch.setopt(pycurl.SSL_VERIFYPEER, 0)
ch.setopt(pycurl.WRITEFUNCTION, b.write)
try:
ch.perform()
except pycurl.error, error:
errno, errstr=error
raise Exception("pycurl error: "+errstr)
# decode and return
try:
rtnval=json.loads(b.getvalue())
except:
raise Exception("unable to decode response")
return rtnval
# get market ID (return None if not found)
def GetMarketID (self, src, dest):
try:
r=self.Query("getmarkets", {})
for i, market in enumerate(r["return"]):
if market["primary_currency_code"].upper()==src.upper() and market["secondary_currency_code"].upper()==dest.upper():
mkt_id=market["marketid"]
return mkt_id
except:
return None
# get market IDs for a destination currency
def GetMarketIDs (self, dest):
try:
rtnval={}
r=self.Query("getmarkets", {})
for i, market in enumerate(r["return"]):
if market["secondary_currency_code"].upper()==dest.upper():
rtnval[market["primary_currency_code"].upper()]=market["marketid"]
return rtnval
except:
return None
# get buy price for a market ID
def GetBuyPriceByID (self, mktid):
try:
r=self.Query("marketorders", {"marketid": mktid})
return float(r["return"]["buyorders"][0]["buyprice"])
except:
return 0
# get sell price for a market ID
def GetSellPriceByID (self, mktid):
try:
r=self.Query("marketorders", {"marketid": mktid})
return float(r["return"]["sellorders"][0]["sellprice"])
except:
return 0
# get buy price for a currency pair
def GetBuyPrice (self, src, dest):
return self.GetBuyPriceByID(self.GetMarketIDs(dest)[src])
# get sell price for a currency pair
def GetSellPrice (self, src, dest):
return self.GetSellPriceByID(self.GetMarketIDs(dest)[src])
# get available balance for a currency
def GetAvailableBalance (self, curr):
try:
r=self.Query("getinfo", {})
return float(r["return"]["balances_available"][curr.upper()])
except:
return 0
# create a sell order
def CreateSellOrder (self, src, dest, qty, price):
try:
return self.Query("createorder", {"marketid": self.GetMarketID(src, dest), "ordertype": "Sell", "quantity": qty, "price": price})
except:
return None
# create a buy order
def CreateBuyOrder (self, src, dest, qty, price):
try:
return self.Query("createorder", {"marketid": self.GetMarketID(src, dest), "ordertype": "Buy", "quantity": qty, "price": price})
except:
return None