'ybvMtTm4PeOGT0bJ5CrQugI5Wpdi2OcvaIoB0wAD462lekazGP0wRirDXL5kIbJM') # bclient = BinanceClient('EDSFRPjwir0HhT4oZhCUHace2wIVxtqKpmdtpjla47Dxlp07WRoRCAVVrtKjEXso', 'V6JY4yWcPbhMleYUWacgItMaECdxY0TcDW1mD3SZZje8pwYFepnjlzRcUabCwQxX') # In[4]: # KUCOIN currencies = client.get_currencies() orders = client.get_buy_orders('ETH-BTC', limit=50) sellorders = client.get_sell_orders('ETH-BTC', limit=50) # account balance userFee = 0.002 # accountBalanceKucoin = 0.0009027 * (1 - userFee)# 0.0009145 * (1 - userFee) accountBalanceKucoinBTC = (float( client.get_coin_balance('BTC')['balance'])) * (1 - userFee) FixedAccountBalanceKucoin = 0.0018 accountBalanceKucoin = (float( client.get_coin_balance('ETH')['balance'])) * (1 - userFee) # In[5]: # BINANCE depth = bclient.get_order_book(symbol='ETHBTC') # In[6]: print(orders) print(sellorders) print(depth)
class KucoinApi(PyexAPI): """kucoin API interface. """ logger = logging.getLogger() def __init__(self, api_server: str, api_key: str, secret_key: str, timeout: float, requests_params=None): assert (isinstance(api_server, str)) assert (isinstance(api_key, str)) assert (isinstance(secret_key, str)) assert (isinstance(timeout, float)) self.api_server = api_server self.api_key = api_key self.secret_key = secret_key self.timeout = timeout self.client = Client(api_key, secret_key) def get_markets(self): return self.client.get_trading_markets() def ticker(self, pair: str): assert (isinstance(pair, str)) return self.client.get_tick(pair) def get_balances(self): return self.client.get_all_balances() def get_fiat_balance(self, fiat: str): assert (isinstance(fiat, str)) return self.client.get_total_balance(fiat) def get_balance(self, coin: str): assert (isinstance(coin, str)) return self.client.get_coin_balance(coin) def get_coin_info(self, coin: str): assert (isinstance(coin, str)) return self.client.get_coin_info(coin) def get_user_info(self): return self.client.get_user() def order_book(self, pair: str, limit=None): assert (isinstance(pair, str)) return self.client.get_order_book(pair, limit) def get_orders(self, pair: str) -> List[Order]: assert (isinstance(pair, str)) orders = self.client.get_active_orders(pair) sell_orders = list( map(lambda item: Order.from_list(item, pair, True), orders[self.client.SIDE_SELL])) buy_orders = list( map(lambda item: Order.from_list(item, pair, False), orders[self.client.SIDE_BUY])) return sell_orders + buy_orders def place_order(self, pair: str, is_sell: bool, price: Wad, amount: Wad) -> str: assert (isinstance(pair, str)) assert (isinstance(is_sell, bool)) assert (isinstance(price, Wad)) assert (isinstance(amount, Wad)) side = self.client.SIDE_SELL if is_sell else self.client.SIDE_BUY self.logger.info(f"Placing order ({side}, amount {amount} of {pair}," f" price {price})...") result = self.client.create_order(pair, side, price, amount) order_id = result['orderOid'] self.logger.info(f"Placed order as #{order_id}") return order_id def cancel_order(self, order_id: str, is_sell: bool, pair: str): assert (isinstance(order_id, str)) assert (isinstance(is_sell, bool)) assert (isinstance(pair, str)) side = self.client.SIDE_SELL if is_sell else self.client.SIDE_BUY self.logger.info(f"Cancelling order #{order_id} of type {side}...") try: self.client.cancel_order(order_id, side, pair) self.logger.info(f"Canceled order #{order_id}...") return True except Exception as e: self.logger.error(f"Failed to cancel order #{order_id}... {e}") return False def get_trades(self, pair: str, page_number: int = 1) -> List[Trade]: assert (isinstance(pair, str)) assert (isinstance(page_number, int)) page_number = page_number - 1 limit = 100 result = self.client.get_symbol_dealt_orders(pair, page_number, limit) return list( map(lambda item: Trade.from_dict(pair, item), result['datas'])) def get_all_trades(self, pair: str, page_number: int = 1) -> List[Trade]: assert (isinstance(pair, str)) assert (page_number == 1) result = self.client.get_recent_orders(pair, 50) return list(map(lambda item: Trade.from_list(pair, item), result))
class KucoinWrapper(BaseExchangeWrapper): INTERVAL_MAP = { CandleTicks.one_minute : Client.RESOLUTION_1MINUTE, CandleTicks.five_minutes : Client.RESOLUTION_5MINUTES, CandleTicks.thirty_minutes : Client.RESOLUTION_30MINUTES, CandleTicks.one_hour : Client.RESOLUTION_1HOUR, CandleTicks.one_day : Client.RESOLUTION_1DAY, } TIME_SINCE_MAP = { CandleTicks.one_minute : "1 hour ago", CandleTicks.five_minutes : "5 hours ago", CandleTicks.thirty_minutes : "26 hours ago", CandleTicks.one_hour : "52 hours ago", CandleTicks.one_day : "60 days ago", } ORDER_TYPE_MAPPINGS = { 'BUY' : OrderType.limit_buy, 'SELL' : OrderType.limit_sell, } def __init__(self, api_key, api_secret): BaseExchangeWrapper.__init__(self) self._handle = Client(api_key, api_secret) self._filters = {} self._load_markets() def _perform_request(self, request_lambda): try: return request_lambda() except KucoinAPIException as ex: raise ExchangeAPIException('Failed to perform request: {0}'.format(ex.message)) def _load_currencies(self): result = self._perform_request(lambda: self._handle.get_coin_list()) for coin in result: self.add_currency( Currency( coin['coin'], coin['name'], coin['confirmationCount'], coin['withdrawFeeRate'] # check if this is right ) ) def _load_markets(self): self._load_currencies() result = self._perform_request(lambda: self._handle.get_trading_symbols()) for market in result: self.add_market(market['coinTypePair'], market['coinType']) def _make_symbol(self, base_currency_code, market_currency_code): return '{0}-{1}'.format(market_currency_code, base_currency_code) def _process_paged_request(self, make_request, callback): page = 1 limit = 50 data = self._perform_request(lambda: make_request(limit=limit, page=page)) while len(data['datas']) > 0: for entry in data['datas']: callback(entry) page += 1 data = make_request(limit=limit, page=page) def get_market_state(self, base_currency_code, market_currency_code): symbol = self._make_symbol(base_currency_code, market_currency_code) data = self._perform_request(lambda: self._handle.get_tick(symbol)) return MarketState(data['sell'], data['buy'], data['lastDealPrice']) def get_orderbook(self, base_currency_code, market_currency_code): symbol = self._make_symbol(base_currency_code, market_currency_code) data = self._perform_request(lambda: self._handle.get_order_book(symbol)) buy_orderbook = Orderbook() sell_orderbook = Orderbook() for item in data['BUY']: buy_orderbook.add_order(Order(item[0], item[1])) for item in data['SELL']: sell_orderbook.add_order(Order(item[0], item[1])) return (buy_orderbook, sell_orderbook) def get_candles(self, base_currency_code, market_currency_code, interval, limit): symbol = self._make_symbol(base_currency_code, market_currency_code) since = KucoinWrapper.TIME_SINCE_MAP[interval] kucoin_interval = KucoinWrapper.INTERVAL_MAP[interval] data = self._perform_request( lambda: self._handle.get_historical_klines_tv(symbol, kucoin_interval, since) ) output = [] for i in data: output.append(Candle( i[3], # Low i[2], # High i[1], # Open i[4], # Close dateparser.parse(str(i[0])) )) return output def get_wallets(self): output = [] self._process_paged_request( self._handle.get_all_balances, lambda entry: output.append(Wallet( entry['coinType'], entry['balance'], entry['balance'] - entry['freezeBalance'], entry['freezeBalance'] )) ) return output def get_wallet(self, currency_code): self.check_valid_currency(currency_code) data = self._perform_request(lambda: self._handle.get_coin_balance(currency_code)) return Wallet( self._currencies[currency_code], data['balance'], data['balance'] - data['freezeBalance'], data['freezeBalance'] ) def get_deposit_history(self, currency_code): request = lambda limit, page: self._handle.get_deposits( currency_code, limit=limit, page=page ) output = [] self._process_paged_request( request, lambda entry: output.append(Transfer( self._currencies[entry['coinType']], entry['amount'], entry['outerWalletTxid'], # is this right? 1 if entry['status'] == 'FINISHED' else 0, 0, # cost entry['status'] == 'CANCEL', dataparser.parse(str(entry['createdAt'])) )) ) return output def get_withdrawal_history(self, currency_code): request = lambda limit, page: self._handle.get_withdrawals( currency_code, limit=limit, page=page ) output = [] self._process_paged_request( request, lambda entry: output.append(Transfer( self._currencies[entry['coinType']], entry['amount'], entry['outerWalletTxid'], # is this right? 0, entry['fee'], entry['status'] == 'CANCEL', dataparser.parse(str(entry['createdAt'])) )) ) return output def get_open_orders(self): raise ExchangeAPIException('Not implemented') def get_order_history(self): output = [] self._process_paged_request( self._handle.get_dealt_orders, lambda entry: output.append(TradeOrder( data['orderOid'], self._currencies[base_currency], self._currencies[market_currency], None, # Date open dateparser.parse(str(data['createdAt'])), data['amount'], 0, # Amount remaining data['dealPrice'], data['dealPrice'], KucoinWrapper.ORDER_TYPE_MAPPINGS[data['direction']] )) ) return output def buy(self, base_currency_code, market_currency_code, amount, rate): symbol = self._make_symbol(base_currency_code, market_currency_code) result = self._perform_request(lambda: self._handle.create_buy_order(symbol, rate, amount)) return result['orderOid'] def sell(self, base_currency_code, market_currency_code, amount, rate): symbol = self._make_symbol(base_currency_code, market_currency_code) result = self._perform_request(lambda: self._handle.create_sell_order(symbol, rate, amount)) return result['orderOid'] def cancel_order(self, base_currency_code, market_currency_code, order_id): self._perform_request(lambda: self._handle.cancel_order(order_id, None)) def withdraw(self, currency_code, amount, address, address_tag): if address_tag: raise ExchangeAPIException('Address tag not supported') self._perform_request( lambda: self._handle.create_withdrawal(currency_code, amount, address) ) def get_deposit_address(self, currency_code): result = self._perform_request(lambda: self._handle.get_deposit_address(currency_code)) return CryptoAddress( currency_code, result['address'], None ) def transfers_needs_asset(self): return True
rpx_amount = .005 / rpx_eth_ask print 'Buying RPX...' client.create_buy_order('RPX-ETH', rpx_eth_ask, rpx_amount) wait_until_filled('RPX-ETH') print 'Selling RPX...' client.create_sell_order('RPX-BTC', rpx_btc_bid, rpx_amount) wait_until_filled('RPX-BTC') print 'Buying ETH...' client.create_buy_order('ETH-BTC', eth_btc_ask, rpx_amount * rpx_btc_bid / eth_btc_ask) wait_until_filled('ETH-BTC') # IF RPX is cheaper in BTC elif (rpx_eth_bid * eth_btc_bid) / rpx_btc_ask > 1.003: print 'Trade started...' print 'Selling ETH...' client.create_sell_order('ETH-BTC', eth_btc_bid, 0.005) wait_until_filled('ETH-BTC') print 'Buying RPX...' btc_balance = client.get_coin_balance('BTC')['balance'] client.create_buy_order('RPX-BTC', rpx_btc_ask, btc_balance / rpx_btc_ask) wait_until_filled('RPX-BTC') print 'Selling RPX...' rpx_balance = client.get_coin_balance('RPX')['balance'] client.create_sell_order('RPX-ETH', rpx_eth_bid, rpx_balance) wait_until_filled('RPX-ETH') else: print 'Waiting for arb opportunity...'
checkTime = time.time() * 1000 logging.info("BaseTime: " + str(checkTime)) if (isWithinChecktime(get_last_buy_order(completedBuyOrders), checkTime, checkInterval)): logging.info("Order executed within " + str(checkInterval) + "...getting price") price = (get_order_price(completedBuyOrders)) logging.info("Last buy price: " + str(price)) if (isWithinChecktime(get_last_sell_order(completedSellOrders), checkTime, checkInterval)): logging.info("Order executed within " + str(checkInterval) + "...getting price") price = (get_order_price(completedSellOrders)) logging.info("Last sell price: " + str(price)) openOrders = (client.get_active_orders(tokenPair)) balance = client.get_coin_balance(currency) balance = (float(balance['balanceStr']) + float(extCoinBalance)) buyAmount = determine_buy_amount(balance) buyPrice = determine_initial_buy_price(price) logging.info("setting buy of " + str(buyAmount) + " at " + str(buyPrice)) logging.info( client.create_buy_order(tokenPair, buyPrice, buyAmount)) sellAmount = determine_sell_amount(balance) sellPrice = determine_initial_sell_price(price) logging.info("setting sell of " + str(sellAmount) + " at " + str(sellPrice)) logging.info( client.create_sell_order(tokenPair, sellPrice, sellAmount)) else: logging.info("No orders present...setting to ticker price")