예제 #1
0
class Kucoin:
    def __init__(self):
        self.client = Client(s.KUCOIN_API_KEY, s.KUCOIN_API_SECRET,
                             s.KUCOIN_API_PASSPHRASE)

    def get_ticker(self, symbol):
        _symbol = "-".join(symbol)

        try:
            item = self.client.get_ticker(_symbol)
        except (KucoinAPIException, Exception) as err:
            raise ValueError(str(err))

        try:
            item.update(self.client.get_24hr_stats(_symbol))
        except (KucoinAPIException, Exception) as err:
            raise ValueError(str(err))

        item.update(ticker=symbol[0])
        return item
예제 #2
0
class KUCoin():

    global client
    global api_key
    global api_secret
    global api_pasphrase
    global balance_percent
    global pair
    global base_coin

    def __init__(self, balance_percent_value, coin_name):
        #api_key = '602e39d9a2644e0006e7e2c2'
        #603e5c8473b5c50006582528
        db = DB()

        config = db.connection.all()

        self.api_key = config[0]['api_key']
        #api_secret = '2db4483e-2a76-4c2c-b533-f64a80a25c6d'
        self.api_secret = config[0]['api_secret']
        self.api_passphrase = config[0]['api_pass']
        #, sandbox=True
        self.client = Client(self.api_key, self.api_secret,
                             self.api_passphrase)

        self.base_coin = config[1]['base_coin']
        self.balance_percent = balance_percent_value

        self.pair = coin_name + "-" + self.base_coin

    def getcurprice(self, pair):
        ticker = self.client.get_ticker(pair)
        return float(ticker['price'])

    def getAccounts(self, ):
        accounts = self.client.get_accounts()
        return accounts

    def get_max_position_available(self, currency, pair):
        accounts = self.getAccounts()

        for account in accounts:
            if account['currency'] == currency:
                balance = account['balance']
                break

        price = self.getcurprice(pair)

        to_use = (float(balance) * self.balance_percent) / 100

        decide_position_to_use = to_use / price

        return decide_position_to_use

    def create_sell_order(self, pair, quantity, price):

        order = self.client.create_limit_order(pair, Client.SIDE_SELL, price,
                                               quantity)
        print(order)
        return order

    def create_market_order(self):
        maxquantity = 0.0
        try:
            maxquantity = round(
                0.9 *
                self.get_max_position_available(self.base_coin, self.pair))
            if maxquantity > 0.0:
                # place a market buy order
                order = self.client.create_market_order(pair,
                                                        Client.SIDE_BUY,
                                                        size=maxquantity)
                print("Done")
                if not order['orderId']:
                    return "No Order Created Yet"
                else:
                    return "Max quantity " + str(
                        maxquantity) + "for Current Pair " + pair

        except KucoinAPIException as e:
            return e.message
예제 #3
0
class KucoinApi(PyexAPI):
    """kucoin API interface.
    """

    logger = logging.getLogger()

    def __init__(self,
                 api_server: str,
                 api_key: str,
                 secret_key: str,
                 api_passphrase: str,
                 timeout: float,
                 requests_params=None):
        assert (isinstance(api_server, str))
        assert (isinstance(api_key, str))
        assert (isinstance(secret_key, str))
        assert (isinstance(api_passphrase, 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, api_passphrase)

    def get_symbols(self):
        return self.client.get_symbols()

    def ticker(self, pair: str):
        assert (isinstance(pair, str))
        return self.client.get_ticker(pair)

    def get_balances(self):
        return self.client.get_accounts()

    def get_coin_info(self, coin: str):
        assert (isinstance(coin, str))
        return self.client.get_currency(coin)

    def order_book(self, pair: str, limit=None):
        assert (isinstance(pair, str))
        return self.client.get_order_book(pair)

    def get_orders(self, pair: str) -> List[Order]:
        assert (isinstance(pair, str))

        orders = self.client.get_orders(pair, 'active')

        return list(
            map(lambda item: Order.to_order(item, pair), orders['items']))

    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_limit_order(pair, side, str(price),
                                                str(amount))
        order_id = result['orderId']

        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)
            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_fills(symbol=pair,
                                       page=page_number,
                                       page_size=limit)

        return list(
            map(lambda item: Trade.from_dict(pair, item), result['items']))

    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_trade_histories(pair)

        return list(map(lambda item: Trade.from_list(pair, item), result))