def _Request(self, method, request_vars=None, headers=None, post_data=None, json_root=None): request_string = '?' + urllib.parse.urlencode( request_vars) if request_vars else '' if headers is None: headers = {} headers.update(self.api_headers.items()) try: request = urllib.request.Request( self.api_url + method + request_string, post_data, headers) response = urllib.request.urlopen(request) try: response_json = json.loads(response.read().decode('utf-8')) if not json_root: json_root = method if not json_root in response_json: raise exchange_api.ExchangeException( 'JSON root "%s" not in "%s".' % (json_root, method)) return response_json[json_root] finally: response.close() except (urllib.error.URLError, urllib.error.HTTPError, http.client.HTTPException, ValueError) 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 __init__(self, api_key, api_secret): self.api_url = 'https://coinex.pw/api/v2/' self.api_headers = { 'Content-type': 'application/json', 'Accept': 'application/json', 'User-Agent': 'autocoin-autosell' } self.api_key = api_key self.api_secret = api_secret.encode('utf-8') try: self._currency_names = { currency['id']: currency['name'] for currency in self._Request('currencies') } self._markets = collections.defaultdict(dict) for trade_pair in self._Request('trade_pairs'): market1 = Market(self, trade_pair['currency_id'], trade_pair['market_id'], trade_pair['id'], False) self._markets[market1.GetSourceCurrency()][ market1.GetTargetCurrency()] = market1 market2 = Market(self, trade_pair['market_id'], trade_pair['currency_id'], trade_pair['id'], True) self._markets[market2.GetSourceCurrency()][ market2.GetTargetCurrency()] = market2 except (TypeError, LookupError) as e: raise exchange_api.ExchangeException(e)
def GetMarkets(self): try: return [exchange_api.Market(trade_pair['currency_id'], trade_pair['market_id'], trade_pair['id']) for trade_pair in self._Request('trade_pairs')] except (TypeError, KeyError) as e: raise exchange_api.ExchangeException(e)
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 GetBalances(self): balances = {} try: for balance in self._PrivateRequest('balances'): balances[balance['currency_id']] = float(balance['amount']) / pow(10, 8) except (TypeError, KeyError) as e: raise exchange_api.ExchangeException(e) return balances
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)
def GetBalances(self): balances = {} try: for balance in self._PrivateRequest('balances'): balances[self._GetCurrencyName( balance['currency_id'])] = (float(balance['amount']) / pow(10, 8)) except (TypeError, LookupError) as e: raise exchange_api.ExchangeException(e) return balances
def CreateOrder(self, market_id, amount, bid=True, price=0): order = {'trade_pair_id' : market_id, 'amount' : int(amount * pow(10, 8)), 'bid' : bid, 'rate' : max(1, int(price * pow(10, 8)))} post_data = json.dumps({'order' : order}).encode('utf-8') try: return self._PrivateRequest('orders', post_data, 'order')['id'] except (TypeError, KeyError, IndexError) 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)
def CreateOrder(self, bid_order, amount, price): if self._reverse_market: bid_order = not bid_order order = { 'trade_pair_id': self._trade_pair_id, 'amount': int(amount * pow(10, 8)), 'bid': bid_order, 'rate': max(1, int(price * pow(10, 8))) } post_data = json.dumps({'order': order}).encode('utf-8') try: order_id = self._exchange._PrivateRequest('orders', post_data, 'order')['id'] return exchange_api.Order(self, order_id, bid_order, amount, price) except (TypeError, LookupError) as e: raise exchange_api.ExchangeException(e)
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 GetPublicOrders(self): try: request_vars = {'tradePair': self._trade_pair_id} orders = self._exchange._Request('orders', request_vars=request_vars) return ([ exchange_api.Order(self, order['id'], True, float(order['amount']) / pow(10, 8), float(order['rate']) / pow(10, 8)) for order in orders if order['bid'] ], [ exchange_api.Order(self, order['id'], False, float(order['amount']) / pow(10, 8), float(order['rate']) / pow(10, 8)) for order in orders if not order['bid'] ]) except (TypeError, LookupError) as e: raise exchange_api.ExchangeException(e)
def GetCurrencies(self): try: return {currency['id'] : str(currency['name']) for currency in self._Request('currencies')} except (TypeError, KeyError) as e: raise exchange_api.ExchangeException(e)