Skip to content

Instantly share code, notes, and snippets.

@megasent1
Created February 4, 2018 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save megasent1/ab8c296756c2cb17847da6b84cc46035 to your computer and use it in GitHub Desktop.
Save megasent1/ab8c296756c2cb17847da6b84cc46035 to your computer and use it in GitHub Desktop.
import time
import json
import urllib, http.client
import hmac, hashlib
from urllib.parse import urlparse, urlencode
class Poloniex():
public_methods = [
'returnTicker',
'return24hVolume',
'returnOrderBook',
'returnTradeHistory',
'returnChartData',
'returnCurrencies',
'returnLoanOrders'
]
def __init__(self, API_KEY, API_SECRET):
self.API_KEY = API_KEY
self.API_SECRET = bytearray(API_SECRET, encoding='utf-8')
def __getattr__(self, name):
def wrapper(*args, **kwargs):
method = 'public' if name in self.public_methods else 'tradingApi'
kwargs.update(method=method, command=name)
return self.call_api(**kwargs)
return wrapper
def call_api(self, **kwargs):
api_url='https://poloniex.com/'+kwargs['method']
if kwargs['method'] == 'public':
api_url += '?'+urlencode(kwargs)
http_method="GET"
else:
http_method="POST"
time.sleep(0.2) # По правилам биржи нельзя больше 6 запросов в секунду
payload = {'nonce': int(round(time.time()*1000))}
if kwargs:
payload.update(kwargs)
payload = urllib.parse.urlencode(payload)
H = hmac.new(key=self.API_SECRET, digestmod=hashlib.sha512)
H.update(payload.encode('utf-8'))
sign = H.hexdigest()
headers = {"Content-type": "application/x-www-form-urlencoded",
"Key":self.API_KEY,
"Sign":sign}
url_o = urlparse(api_url)
conn = http.client.HTTPSConnection(url_o.netloc)
conn.request(http_method, api_url, payload, headers)
response = conn.getresponse().read()
conn.close()
try:
obj = json.loads(response.decode('utf-8'))
if 'error' in obj and obj['error']:
raise Exception(obj['error'])
return obj
except ValueError:
raise Exception('Получены некорректные данные (проверьте, правильно ли указан метод API {api_method})'.format(api_method=kwargs['command']))
####
my_polo = Poloniex(
API_KEY = '',
API_SECRET = ''
)
ticker = my_polo.returnTicker()
print('TICKER', ticker)
#### return:
---------------------------------------------------------------------------
JSONDecodeError Traceback (most recent call last)
<ipython-input-2-099bfb0a7c1c> in call_api(self, **kwargs)
63 try:
---> 64 obj = json.loads(response.decode('utf-8'))
65
D:\ProgramData\Anaconda3\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
353 parse_constant is None and object_pairs_hook is None and not kw):
--> 354 return _default_decoder.decode(s)
355 if cls is None:
D:\ProgramData\Anaconda3\lib\json\decoder.py in decode(self, s, _w)
338 """
--> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
340 end = _w(s, end).end()
D:\ProgramData\Anaconda3\lib\json\decoder.py in raw_decode(self, s, idx)
356 except StopIteration as err:
--> 357 raise JSONDecodeError("Expecting value", s, err.value) from None
358 return obj, end
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
During handling of the above exception, another exception occurred:
Exception Traceback (most recent call last)
<ipython-input-3-0383b65e3ebe> in <module>()
4 )
5
----> 6 ticker = my_polo.returnTicker()
7 print('TICKER', ticker)
<ipython-input-2-099bfb0a7c1c> in wrapper(*args, **kwargs)
26 method = 'public' if name in self.public_methods else 'tradingApi'
27 kwargs.update(method=method, command=name)
---> 28 return self.call_api(**kwargs)
29 return wrapper
30
<ipython-input-2-099bfb0a7c1c> in call_api(self, **kwargs)
68 return obj
69 except ValueError:
---> 70 raise Exception('Получены некорректные данные (проверьте, правильно ли указан метод API {api_method})'.format(api_method=kwargs['command']))
Exception: Получены некорректные данные (проверьте, правильно ли указан метод API returnTicker)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment