def create_order(self, amount, price, otype, typ='exchange limit', bfxexch='all'): if BLOCK_ORDERS: return "order blocked" if otype == 'bid': otype = 'buy' elif otype == 'ask': otype = 'sell' else: raise Exception('unknown side %r' % otype) params = { 'side': otype, 'symbol': 'btcusd', 'amount': "{:0.3f}".format(amount), 'price': "{:0.3f}".format(price), 'exchange': bfxexch, 'type': typ } try: order = self.bitfinex_request('/v1/order/new', params).json() except ValueError as e: raise ExchangeError('bitfinex', '%s %s while sending to bitfinex %r' % (type(e), str(e), params)) if 'is_live' in order and order['is_live']: return str(order['order_id']) raise ExchangeError('bitfinex', 'unable to create order %r response was %r' % (params, order))
def lakebtc_request(self, method, params=None): if params is None: params = {'params': []} params['method'] = method params['tonce'] = int(time.time() * 1000000) params['requestmethod'] = 'post' params['id'] = 1 auth_string = 'Basic %s' % base64.b64encode( "%s:%s" % (self.key, self.lakebtc_encode(params))) headers = { 'Authorization': auth_string, 'Json-Rpc-Tonce': params['tonce'] } try: response = requests.post(url=BASE_URL, data=json.dumps(params), headers=headers, timeout=REQ_TIMEOUT) except (ConnectionError, Timeout, ValueError) as e: raise ExchangeError( 'lakebtc', '%s %s while sending %r' % (type(e), str(e), params)) if response.status_code == 200: return response.json() else: raise ExchangeError( 'lakebtc', '%s %s while sending %r' % (response.status_code, response.text, params))
def create_order(self, amount, price, otype): rate=price if BLOCK_ORDERS: return "order blocked" if otype == 'bid': otype = 'buy' elif otype == 'ask': otype = 'sell' else: raise Exception('unknown side %r' % otype) params = { 'rate' : price, 'amount' : amount, 'currencyPair' : currencyPair } if otype == 'sell': try: order = polo.sell(amount=amount, rate=rate, currencyPair=currencyPair) except ValueError as e: raise ExchangeError('poloniex', '%s %s while sending to poloniex %r' % (type(e), str(e), params)) else: try: order = polo.buy(amount=amount, rate=rate, currencyPair=currencyPair) except ValueError as e: raise ExchangeError('poloniex', '%s %s while sending to poloniex %r' % (type(e), str(e), params)) if 'orderNumber' in order and order['orderNumber']: return str(order['orderNumber']) raise ExchangeError('poloniex', 'unable to create order %r response was %r' % (params, order))
def get_deposit_address(self): addys = self.submit_private_request('DepositAddresses', {'asset': 'BTC', 'method': 'Bitcoin'}) if len(addys['error']) > 0: raise ExchangeError('kraken', addys['error']) for addy in addys['result']: if int(addy['expiretm']) < time.time() + 1440: return str(addy['address']) raise ExchangeError('kraken', "unable to get deposit address")
def get_deposit_address(self): try: result = self.bitfinex_request('/v1/deposit/new', {'currency': 'BTC', 'method': 'bitcoin', 'wallet_name': 'exchange'}).json() if result['result'] == 'success' and 'address' in result: return str(result['address']) else: raise ExchangeError('bitfinex', result) except ValueError as e: raise ExchangeError('bitfinex', '%s %s while sending get_deposit_address' % (type(e), str(e)))
def get_transactions(self, limit=None, status=1, current_page=1, page_length=200, symbol='btc_cny', timestamp=None): """ :param limit: :param status: :param current_page: :param page_length: :param symbol: :param timestamp: The timestamp to begin searching at. Default is 24 hours ago. :return: """ if timestamp is None: timestamp = time.time() - 86400 # 24 hours params = {'params': [str(timestamp)]} resp = self.lakebtc_request('getTrades', params) if resp and isinstance(resp, list): return resp raise ExchangeError( 'lakebtc', 'unable to get transactions. response was %r' % resp)
def create_order(self, amount, price=0, otype='bid'): if BLOCK_ORDERS: return "order blocked" if isinstance(amount, Money): famount = round(float(amount.amount), 2) else: famount = float(amount) if int(famount) == famount: famount = float(famount) - 0.0001 if isinstance(price, Money): fprice = round(float(price.amount), 2) else: fprice = float(price) if int(fprice) == fprice: fprice = float(fprice) - 0.01 if otype in ('ask', 'sell'): order = btcny.sell(fprice, famount) else: order = btcny.buy(fprice, famount) if order and isinstance(order, bool): return "stupid btcchina does not return ids" else: raise ExchangeError( 'btcchina', 'unable to create %s %r at %r order for reason %s' % (otype, amount, price, order))
def get_order_status(self, order_id): params = {'order_id': int(order_id)} try: return self.bitfinex_request('/v1/order/status', params).json() except ValueError as e: raise ExchangeError('bitfinex', '%s %s while sending to bitfinex get_order_status for %s' % ( type(e), str(e), str(order_id)))
def create_order(self, amount, price, otype): if BLOCK_ORDERS: return "order blocked" if otype == 'bid': otype = 'buy' elif otype == 'ask': otype = 'sell' else: raise Exception('unknown side %r' % otype) # avoid round numbers to prevent hashing/auth issues price = float(price) amount = float(amount) if round(price) == price: if otype == 'buy': price -= 0.01 else: price += 0.01 if round(amount) == amount: amount += 0.001 params = { 'coin_type': 1, 'price': round(price, 2), 'amount': round(amount, 4), } data = self.huobi_request(otype, params) if 'result' in data and 'uccess' in data['result']: return str(data['id']) raise ExchangeError( 'huobi', 'unable to create order %r response was %r' % (params, data))
def submit_public_request(cls, method, params=None): path = '/0/public/%s' % method data = urllib.urlencode(params) try: return json.loads(requests.get(baseUrl + path + "?" + data, timeout=REQ_TIMEOUT).text) except (ConnectionError, Timeout, ValueError) as e: raise ExchangeError('btce', '%s %s while sending %r to %s' % (type(e), e, params, path))
def get_order_book(cls, pair='btc_usd', **kwargs): try: return requests.get('%sdepth.do?symbol=%s' % (BASE_URL, pair), timeout=REQ_TIMEOUT).json() except (ConnectionError, Timeout, ValueError) as e: raise ExchangeError( 'okcoin', '%s %s while sending get_order_book' % (type(e), str(e)))
def get_order_book(cls, pair='btc_cny', **kwargs): try: return requests.get(BASE_URL + 'bcorderbook_cny', timeout=REQ_TIMEOUT).json() except (ConnectionError, Timeout, ValueError) as e: raise ExchangeError( 'lakebtc', '%s %s while sending get_order_book' % (type(e), str(e)))
def get_order_book(cls, pair='btc_usd', **kwargs): try: return requests.get( 'https://market.huobi.com/staticmarket/depth_btc_json.js', timeout=REQ_TIMEOUT).json() except ValueError as e: raise ExchangeError( 'huobi', '%s %s while sending get_order_book' % (type(e), str(e)))
def get_ticker(cls, pair='btcusd'): try: rawtick = requests.get(BASE_URL + '/v1/pubticker/%s' % pair, timeout=REQ_TIMEOUT).json() except (ConnectionError, Timeout, ValueError) as e: raise ExchangeError('bitfinex', '%s %s while sending get_ticker to bitfinex' % (type(e), str(e))) return create_ticker(bid=rawtick['bid'], ask=rawtick['ask'], high=rawtick['high'], low=rawtick['low'], volume=rawtick['volume'], last=rawtick['last_price'], timestamp=rawtick['timestamp'], currency='USD')
def get_balance(self, btype='total'): try: data = self.bitfinex_request('/v1/balances').json() except ValueError as e: raise ExchangeError('bitfinex', '%s %s while sending to bitfinex get_open_orders' % (type(e), str(e))) if 'message' in data: raise ExchangeError(exchange='bitfinex', message=data['message']) relevant = filter(lambda x: x['currency'] in ('usd', 'btc'), data) if btype == 'total': total = MultiMoney(*map(lambda x: Money(x['amount'], x['currency'].upper()), relevant)) return total elif btype == 'available': available = MultiMoney(*map(lambda x: Money(x['available'], x['currency'].upper()), relevant)) return available else: total = MultiMoney(*map(lambda x: Money(x['amount'], x['currency'].upper()), relevant)) available = MultiMoney(*map(lambda x: Money(x['available'], x['currency'].upper()), relevant)) return total, available
def okcoin_request(self, endpoint, params=None): params = params or {} sig = self.okcoin_encode(params) params['partner'] = self.partner params['sign'] = sig headers = {'contentType': 'application/x-www-form-urlencoded'} try: response = requests.post(url=BASE_URL + endpoint, data=params, headers=headers, timeout=REQ_TIMEOUT).json() except (ConnectionError, Timeout, ValueError) as e: raise ExchangeError( 'okcoin', '%s %s while sending %r' % (type(e), str(e), params)) if 'error_code' in response: raise ExchangeError( 'okcoin', '%s while sending %r' % (str(response['error_code']), params)) return response
def get_open_orders(self): try: rawos = self.bitfinex_request('/v1/orders').json() except ValueError as e: raise ExchangeError('bitfinex', '%s %s while sending to bitfinex get_open_orders' % (type(e), str(e))) orders = [] for o in rawos: side = 'ask' if o['side'] == 'sell' else 'bid' orders.append(MyOrder(Money(o['price'], self.fiatcurrency), Money(o['remaining_amount']), side, self.name, str(o['id']))) return orders
def get_open_orders(self): try: rawos = polo.returnOpenOrders(currencyPair) except ValueError as e: raise ExchangeError('poloniex', '%s %s while sending to poloniex get_open_orders' % (type(e), str(e))) orders = [] for o in rawos: side = 'ask' if o['type'] == 'sell' else 'bid' orders.append(MyOrder(Money(o['rate'], self.fiatcurrency), Money(o['amount']), side, self.name, str(o['orderNumber']))) return orders
def cancel_order(self, order_id): params = {'order_id': int(order_id)} try: resp = self.bitfinex_request('/v1/order/cancel', params).json() except ValueError as e: raise ExchangeError('bitfinex', '%s %s while sending to bitfinex %r' % (type(e), str(e), params)) if resp and 'id' in resp and resp['id'] == params['order_id']: return True elif 'message' in resp and resp['message'] == 'Order could not be cancelled.': return True else: return False
def cancel_order(self, oid): params = {'currencyPair': currencyPair, 'orderNumber': oid} try: resp = polo.cancel(currencyPair, orderNumber=oid) except ValueError as e: raise ExchangeError('poloniex', '%s %s while sending to poloniex %r' % (type(e), str(e), params)) if resp and 'success' in resp and resp['success'] == 1: return True elif 'error' in resp and resp['error'] == 'Order could not be cancelled.': return True else: return False
def get_ticker(cls, **kwargs): rawticker = btcny.get_ticker() if 'ticker' in rawticker: ticker = rawticker['ticker'] return create_ticker(bid=ticker['buy'], ask=ticker['sell'], high=ticker['high'], low=ticker['low'], volume=ticker['vol'], last=ticker['last'], timestamp=ticker['date'], currency='CNY') raise ExchangeError('btcchina', 'unable to get ticker')
def bitfinex_request(self, endpoint, params=None): params = params or {} params['request'] = endpoint response = None while response is None: try: response = requests.post(url=BASE_URL + params['request'], headers=self.bitfinex_encode(params), timeout=REQ_TIMEOUT) if "Nonce is too small." in response: response = None except (ConnectionError, Timeout) as e: raise ExchangeError('bitfinex', '%s %s while sending to bitfinex %r' % (type(e), str(e), params)) return response
def huobi_request(self, endpoint, params=None): params = params or {} params['method'] = endpoint params['access_key'] = self.key params['created'] = int(time.time()) params['sign'] = self.huobi_encode(params) if 'secret_key' in params: del params['secret_key'] headers = {'contentType': 'application/x-www-form-urlencoded'} try: response = requests.post(url=BASE_URL, data=params, headers=headers, timeout=REQ_TIMEOUT) except (ConnectionError, Timeout) as e: raise ExchangeError('huobi', '%s error while sending %r' % (str(e), params)) if response.status_code != 200: raise ExchangeError( 'huobi', '%s while sending %r' % (str(response['error_code']), params)) try: resp = json.loads(response.text) except ValueError as e: raise ExchangeError( 'huobi', '%s error while sending %r, ' 'response is: %s' % (type(e), params, response.text)) if 'result' in resp and resp['result'] == 'fail': if resp['code'] in error_codes: raise ExchangeError( 'huobi', '%s while sending %r' % (str(error_codes[resp['code']]), params)) else: raise ExchangeError( 'huobi', '%s while sending %r' % (str(resp), params)) return resp
def create_order(self, amount, price, otype, pair='XXBTZEUR', **kwargs): if BLOCK_ORDERS: return "order blocked" otype = 'buy' if otype == 'bid' else 'sell' if not isinstance(amount, str): amount = str(amount) if not isinstance(price, str): price = str(price) options = {'type': otype, 'volume': amount, 'price': price, 'pair': pair, 'ordertype': 'limit'} options.update(kwargs) resp = self.submit_private_request('AddOrder', options) if 'error' in resp and len(resp['error']) > 0: raise ExchangeError('kraken', 'unable to create order %r for reason %r' % (options, resp['error'])) elif 'result' in resp and 'txid' in resp['result'] and len(resp['result']['txid']) > 0: return str(resp['result']['txid'][0])
def get_open_orders(self, symbol='btc_usd'): params = {'order_id': -1, 'symbol': symbol} resp = self.okcoin_request('order_info.do', params) if resp and 'result' in resp and resp['result']: rawos = resp['orders'] else: raise ExchangeError( 'okcoin', 'unable to get open orders. response was %r' % resp) orders = [] for o in rawos: side = 'ask' if o['type'] == 'sell' else 'bid' orders.append( MyOrder(Money(o['price'], self.fiatcurrency), Money(o['amount']), side, self.name, str(o['order_id']))) return orders
def get_ticker(cls, pair='btc_cny'): try: rawtick = requests.get(BASE_URL + 'ticker', timeout=REQ_TIMEOUT).json() except (ConnectionError, Timeout, ValueError) as e: raise ExchangeError( 'lakebtc', '%s %s while sending get_ticker to lakebtc' % (type(e), str(e))) return create_ticker(bid=rawtick['CNY']['bid'], ask=rawtick['CNY']['ask'], high=rawtick['CNY']['high'], low=rawtick['CNY']['low'], volume=rawtick['CNY']['volume'], last=rawtick['CNY']['last'], timestamp=time.time(), currency='CNY')
def get_transactions(self, limit=None, status=1, current_page=1, page_length=200, symbol='btc_usd'): params = { 'status': status, 'current_page': current_page, 'page_length': page_length, 'symbol': symbol } resp = self.okcoin_request('order_history.do', params) if resp and 'result' in resp and resp['result']: return resp raise ExchangeError( 'okcoin', 'unable to get transactions. response was %r' % resp)
def get_ticker(cls, pair='btc_usd'): try: rawtick = requests.get(BASE_URL + 'ticker.do?symbol=%s' % pair, timeout=REQ_TIMEOUT).json() except (ConnectionError, Timeout, ValueError) as e: raise ExchangeError( 'okcoin', '%s %s while sending get_ticker to okcoin' % (type(e), str(e))) return create_ticker(bid=rawtick['ticker']['buy'], ask=rawtick['ticker']['sell'], high=rawtick['ticker']['high'], low=rawtick['ticker']['low'], volume=rawtick['ticker']['vol'], last=rawtick['ticker']['last'], timestamp=rawtick['date'], currency='USD')
def get_ticker(cls, pair='btc_usd'): try: rawtick = requests.get( 'https://market.huobi.com/staticmarket/ticker_btc_json.js', timeout=REQ_TIMEOUT).json() except (ConnectionError, Timeout, ValueError) as e: raise ExchangeError( 'huobi', '%s %s while sending get_ticker to huobi' % (type(e), str(e))) return create_ticker(bid=rawtick['ticker']['buy'], ask=rawtick['ticker']['sell'], high=rawtick['ticker']['high'], low=rawtick['ticker']['low'], volume=rawtick['ticker']['vol'], last=rawtick['ticker']['last'], timestamp=time.time(), currency='CNY')
def create_order(self, amount, price, otype, symbol='btc_cny'): if BLOCK_ORDERS: return "order blocked" if otype == 'bid': otype = 'buyOrder' elif otype == 'ask': otype = 'sellOrder' else: raise Exception('unknown side %r' % otype) params = { 'params': [ "{:0.2f}".format(float(price)), "{:0.3f}".format(float(amount)), self.fiatcurrency ] } data = self.lakebtc_request(otype, params) if 'id' in data: return str(data['id']) raise ExchangeError( 'lakebtc', 'unable to create order %r response was %r' % (params, data))