class KuCoin: lastTimestamp = None def __init__(self, Config): self.publicKey = Config.getPublicKey() self.secretKey = Config.getSecretKey() self.client = Client(self.publicKey, self.secretKey) def checkKeys(self): try: b = self.client.get_api_keys() if 'code' not in b: # If code is there, it means an error code so wrong. return True #else: # self.errorMessage(b) # return False except (Exception): #TO DO: extract kucoin exception message directly self.errorMessage("KuCoin API error.") return False def getBalance(self, limit=None, page=None): try: jsonD = self.client.get_all_balances() except Exception as e: print("Error getting balance.") return balances = [] for x in jsonD: if x['balance'] != 0.0: balances.append(x) #TO DO, MAKE IT SAME NAMES AS HITBTC for b in balances: for key in b.keys(): if (key == "coinType"): newKey = key.replace("coinType", "currency") b[newKey] = b[key] del b[key] if (key == "balanceStr"): newKey = key.replace("balanceStr", "available") b[newKey] = b[key] del b[key] return balances def getSymbols(self): jsonD = self.client.get_trading_symbols() symbols = [] for x in jsonD: symbols.append(x['symbol']) return symbols def getOrderHistory(self, Config): try: orders = self.client.get_dealt_orders(symbol=Config.getCurrency()) return orders except Exception as e: print("ERROR GETTING ORDER HISTORY:") print(e) return None def getActiveOrders(self, Config): try: orders = self.client.get_active_orders(symbol=Config.getCurrency()) return orders except Exception as e: print("ERROR GETTING ACTIVE ORDERS") print(e) return None def getOrderBook(self, Config, request): try: orders = self.client.get_order_book(Config.getCurrency()) if (request == 'SELL'): return orders['SELL'] if (request == 'BUY'): return orders['BUY'] except Exception as e: print(e) return None def cancelBuyOrders(self, Config): try: cancelAttempt = self.client.cancel_all_orders( Config.getCurrency(), 'BUY') if cancelAttempt is None: return True except Exception as e: print(e) return False def cancelSellOrders(self, Config): try: cancelAttempt = self.client.cancel_all_orders( Config.getCurrency(), 'SELL') if cancelAttempt is None: return True except Exception as e: print(e) return False def cancelOrders(self, Config): try: cancelAttempt = self.client.cancel_all_orders( Config.getCurrency(), 'BUY') cancelAttempt = self.client.cancel_all_orders( Config.getCurrency(), 'SELL') if cancelAttempt is None: return True except Exception as e: print(e) return False def createOrder(self, symbol, side, price, amount): try: #sellPrice = str(round(float(price), 6)) transaction = self.client.create_order(symbol, side.upper(), price, amount) return transaction # returns orderOid except Exception as e: print("Took too long.. mismatch I think??") print(e) def errorMessage(self, b): print( '\n =================== CyrCraft - Errrr Errorrrrrr ======================= \n' ) print(b) print( 'Keys are wrong..\nType 1 to set your keys.. or else any key to go Configuration Menu..' ) print( '\n ======================================================================= \n' )
# list all the coins on KuCoin symbols = client.get_trading_symbols() print("Got a list of trading symbols") #loop through every symbol and work out if you have any trades for row in symbols: # for the current symbol get your dealt orders symbol = row['symbol'] retry = 0 while (retry < maxretries): try: dealtOrders = client.get_dealt_orders(symbol='{0}'.format(symbol)) data = dealtOrders['datas'] break except: retry = retry + 1 # quit if we hit the limit if (retry >= maxretries): raise else: # have a rest for 2 seconds time.sleep(2) print("Trying {0}... you have {1} records".format(symbol, dealtOrders['total'])) #if there are records in data
if (slack_token == ""): slack_token = input("Please enter your Slack Legacy Token: ") client = Client(apiKey, apiSecret) sc = SlackClient(slack_token) while True: try: print("Starting loop at {0}".format(time.strftime(dateformat))) #get my dealt orders retry = 0 while (retry < maxretries): try: dealtOrders = client.get_dealt_orders(since=lastDealsCheck) data = dealtOrders['datas'] break except: retry = retry + 1 # quit if we hit the limit if (retry >= maxretries): raise else: # have a rest for 2 seconds time.sleep(2) print("Found {0} new deals".format(dealtOrders['total'])) # reset the deal time now
class KucoinClient(AbstractClient): def __init__(self, listener): self.exchange = 'kucoin' self.trade_fee = Decimal(0.001) self.client = Client(api_keys.kucoin[0], api_keys.kucoin[1]) super(KucoinClient, self).__init__(listener) self.get_all_balances() def _buy(self, symbol, price, amount): result = self.client.create_buy_order(symbol, price, amount) self.open_orders[symbol] = [str(result['orderOid']), 'BUY', symbol] def _sell(self, symbol, price, amount): result = self.client.create_sell_order(symbol, price, amount) self.open_orders[symbol] = [str(result['orderOid']), 'SELL', symbol] def _cancel(self, symbol): order = self.open_orders.pop(symbol) self.client.cancel_order(order[0], order[1], symbol=order[2]) time.sleep(1) if not self.is_order_fulfilled(order[0]): raise Exception("cancelled order not fulfilled!") def is_order_fulfilled(self, orderOid): try: for data in self.client.get_dealt_orders()['datas']: if data['orderOid'] == orderOid: return True except (KucoinRequestException, KucoinAPIException) as e: print datetime.now(), "[Kucoin] is order fulfilled error", str( e).replace('\r\n', '') self.errors += 1 return False def get_all_balances(self): # Kucoin paginates the coin balances and we can only retrieve 20 coins per page page = 1 while True: try: result = self.client.get_all_balances_paged(limit=20, page=page) for balance in result['datas']: self.coin_balances[str(balance['coinType'])] = Decimal( str(balance['balance']) ) # + Decimal(balance['freezeBalance']) page = result['currPageNo'] + 1 if page > result['pageNos']: break except (KucoinRequestException, KucoinAPIException) as e: print datetime.now(), "[Kucoin] get all balances error:", str( e).replace('\r\n', '') self.errors += 1 break return self.coin_balances # Gets the buy/sell price and amount for one symbol at a time (inefficient). def _market_poll(self): result = {'success': False} result['client'] = self result['timestamp'] = int(time.time() * 1000) result['coinpairs'] = {} threads = [] for symbol in self.exchange_symbols: thread = threading.Thread(target=self._symbol_poll, args=[symbol, result]) thread.start() threads.append(thread) for thread in threads: thread.join() if len(result['coinpairs']) > 0: result['success'] = True return result def _symbol_poll(self, symbol, result): try: data = self.client.get_order_book(symbol, limit=1) if data['BUY'] is not None and data['SELL'] is not None: result['coinpairs'][self._get_arbitrager_coinpair(symbol)] = { 'buy': Decimal(str(data['BUY'][0][0])), 'buyAmount': Decimal(str(data['BUY'][0][1])), 'sell': Decimal(str(data['SELL'][0][0])), 'sellAmount': Decimal(str(data['SELL'][0][1])) } except (KucoinRequestException, KucoinAPIException) as e: print datetime.now(), "[Kucoin] market poll error", str(e).replace( '\r\n', '') self.errors += 1 # Gets the buy/sell price for all the symbols with one query but does not contain buy/sell amount (useless). @DeprecationWarning def market_poll_no_amount(self): threading.Timer(Consts.POLL_INTERVAL, self.market_poll_no_amount).start() timestamp = int(time.time() * 1000) try: coins = self.client.get_trading_symbols() if self.verbose: now = int(time.time() * 1000) print datetime.now( ), "[Kucoin] market_poll took", now - timestamp, "ms." except (KucoinRequestException, KucoinAPIException) as e: print datetime.now(), "[Kucoin] market poll error", str(e).replace( '\r\n', ' ') result = {'success': False} result['client'] = self return result result = {'success': True} result['client'] = self result['timestamp'] = timestamp result['coinpairs'] = {} for coin in coins: symbol = coin['symbol'] if symbol in self.exchange_symbols: result['coinpairs'][self._get_arbitrager_coinpair(symbol)] = { 'buy': Decimal(str(coin['buy'])), 'sell': Decimal(str(coin['sell'])) } # result['timestamp'] = coin['datetime'] if self.callback is None: print result else: self.callback(result)