예제 #1
0
def get_account_assets():

    client = Client(
        os.environ["kucoin_key"],
        os.environ["kucoin_secret"],
        os.environ["kucoin_passphrase"],
    )

    balances = client.get_accounts()

    assets = []
    for balance in balances:
        symbol = balance["currency"]
        amount = float(balance["balance"])
        exchange = "kucoin"

        asset = Asset(symbol=symbol, amount=amount, exchange=exchange)

        if int(amount * 1e18) > 0:
            assets.append(asset)

    return assets
#initiates emails
msg = MIMEMultipart()
msg['From'] = MY_ADDRESS
msg['To'] = MY_ADDRESS
msg['Subject'] = "KuCoin Trading Bot"
#exception module
from kucoin.exceptions import KucoinAPIException

#KuCoin API constants
buy_order = client.SIDE_BUY
sell_order = client.SIDE_SELL
stop_loss = client.STOP_LOSS

#retrieves account information and buying power in trading account
accounts = client.get_accounts()
account = pd.DataFrame(accounts)
account = account[(account.type == 'trade')]
trade_hist = client.get_trade_histories('MTV-USDT')
trade_hist = pd.DataFrame(trade_hist)
start_balance = 200.00

#Trade USDT account
buypower = account.loc[account['currency'] == 'USDT', 'available'].values[0]
print(account)
#converts buying power to float and divides by 2 to represent buy size
buypow = float(buypower)
buypowT = buypow / 1.01
buypowT = "{:.2f}".format(buypowT)
#converts buy size back to str for create_market_order
buysize = str(buypowT)
예제 #3
0
    logging.info(
        f'New order: {order["multiple"]}x initial value, {sell_qty:.2f}AMPL @ {price:.2f}USD'
    )
    return client.create_limit_order(symbol=config.market,
                                     side='sell',
                                     price=price,
                                     size=sell_qty,
                                     stop=stop,
                                     stop_price=stop_price)


# cancel previous orders
client.cancel_all_orders()

# total AMPL
balances = client.get_accounts()
AMPL_balances = [
    balance for balance in balances if balance['currency'] == 'AMPL'
]
AMPL_total_qty = sum(float(balance['balance']) for balance in AMPL_balances)
logging.info(f'total balance: {AMPL_total_qty:.2f}')

# AMPL in trading account
AMPL_trading_balance = 0
for AMPL_balance in AMPL_balances:
    if AMPL_balance['type'] == 'trade':
        AMPL_trading_balance = float(AMPL_balance['balance'])
        break
logging.info(f'trading balance: {AMPL_trading_balance:.2f}')

# Checking that AMPL in trading account is sufficient
예제 #4
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
예제 #5
0
async def parser(message):
    config.read('config.ini')
    binance_key = config['Binance']['binance_key']
    binance_sec = config['Binance']['binance_sec']
    kucoin_key = config['Kucoin']['kucoin_key']
    kucoin_sec = config['Kucoin']['kucoin_sec']
    kucoin_api_pass = config['Kucoin']['kucoin_api_pass']
    coinmarketcap_apikey = config['API']['coinmarketcap_apikey']
    blockfrost_apikey = config['API']['blockfrost_apikey']
    ada_address = config['Addresses']['ada_address']
    bnb_address = config['Addresses']['bnb_address']
    total = []
    USDT = 0.
    RUB = 0.
    # * Getting coins info from Binance
    try:
        client = binance.Client(binance_key, binance_sec)
        await client.load()
        accinfo = await client.fetch_account_information(receive_window=None)
        for coin in accinfo['balances']:
            if coin['asset'] == "USDT":
                USDT += float(coin['free'])
            elif coin['asset'] == "RUB":
                RUB += float(coin['free'])
            else:
                amount = float(coin['free'])
                ticker = coin['asset'] + "USDT"
                if amount > 0.000001:
                    print(ticker[:-4] + f" amount: {amount}")
                    coin.pop('locked')
                    coin['amount'] = float(coin.pop('free'))
                    total.append(coin)
        await client.close()
    except:
        print("Wrong Binance credentials.")
        bot.send_message(message.chat.id,
                         "You entered wrong Binance credentials.")

    # * Getting the amount of ADA on Yoroi
    link_cardano = "https://cardano-mainnet.blockfrost.io/api/v0/addresses/"
    headers = {'project_id': blockfrost_apikey}

    session = Session()
    session.headers.update(headers)
    try:
        response = session.get(link_cardano + ada_address)
        data = json.loads(response.text)
    except (ConnectionError, Timeout, TooManyRedirects) as e:
        print(e)
    try:
        ada_amount = float(data['amount'][0]['quantity'])
    except:
        ada_amount = 0
        bot.send_message(
            message.chat.id,
            "You entered wrong ADA address or Blockfrost API key.")
    if ada_amount > 1e+6:
        ada_amount /= 1e+6
    print(f"Found {ada_amount} ADA in Cardano Wallet")

    if not any(d['asset'] == 'ADA' for d in total):
        total.append({'asset': 'ADA', 'amount': ada_amount})
    else:
        for x in total:
            if x['asset'] == 'ADA':
                x['amount'] += ada_amount

    # * Getting the coins from BNB Wallet

    bnb_api_link = "https://dex.binance.org/api/v1/account/"

    response = urlopen(bnb_api_link + bnb_address)
    data_json = (json.loads(response.read()))['balances']
    for coin in data_json:
        amount = float(coin['free'])
        ticker = coin['symbol']
        if "CBB" in ticker:
            ticker = ticker[:-4]
        if amount > 0.000001:
            if not any(d['asset'] == ticker for d in total):
                total.append({'asset': ticker, 'amount': amount})
                print(
                    f"creating {ticker} with {amount} in total | From BNB Wallet"
                )
            else:
                for coin in total:
                    if coin['asset'] == ticker:
                        coin['amount'] += amount
                        print(
                            f"adding to {ticker} {amount} in total | From BNB Wallet"
                        )
                        break

    # *Getting coins from Kucoin
    try:
        client = Client(kucoin_key, kucoin_sec, kucoin_api_pass)
        kucoininfo = client.get_accounts()
        for coin in kucoininfo:
            if coin['type'] != 'trade':
                continue
            amount = float(coin['balance'])
            ticker = coin['currency']
            if amount > 0.000001 and ticker != "USDT":
                if not any(d['asset'] == ticker for d in total):
                    total.append({'asset': ticker, 'amount': amount})
                    print(
                        f"creating {ticker} with {amount} in total | From Kucoin"
                    )
                else:
                    for coin in total:
                        if coin['asset'] == ticker:
                            coin['amount'] += amount
                            print(
                                f"adding to {ticker} {amount} in total | From Kucoin"
                            )
                            break
    except:
        print("Wrong Kucoin credentials.")
        bot.send_message(message.chat.id,
                         "You entered wrong Kucoin credentials.")

    try:
        coinmarketcap_url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest"
        alltickers = ""
        for coin in total:
            alltickers += (coin['asset'] + ",")
        alltickers = alltickers[:-1]
        parameters = {'symbol': alltickers}
        headers = {
            'Accepts': 'application/json',
            'X-CMC_PRO_API_KEY': coinmarketcap_apikey,
        }
        session = Session()
        session.headers.update(headers)
        response = session.get(coinmarketcap_url, params=parameters)
        data = json.loads(response.text)
        print("Got prices from Coinmarketcap")
        for coin in total:
            ticker = coin['asset']
            coin['price'] = data['data'][ticker]['quote']['USD']['price']
            coin['value_in_USD'] = coin['price'] * coin['amount']
        total = [
            i for i in total
            if not (i['value_in_USD'] < include_with_value_higher_than)
        ]
        total = sorted(total, key=itemgetter('value_in_USD'), reverse=True)

        balance = 0.
        for coin in total:
            balance += coin['value_in_USD']
        balance += USDT + (RUB / 74)
        balance = round(balance, 2)
        reply_msg = "*Total balance is " + str(balance) + " $*" + "\n\n"
        reply_msg += "*In coins:*\n"
        for coin in total:
            if coin['amount'] >= 1:
                amount = str(round(coin['amount'], 2))
            else:
                amount = str(round(coin['amount'], 6))
            reply_msg += coin['asset'] + ": " + amount + " | " + \
                str(round(coin['value_in_USD'], 2)) + " $\n"
        reply_msg += "\n*In fiat:*\n" + str(round(USDT, 2)) + " $\n"
        if RUB != 0:
            reply_msg += str(round(RUB, 2)) + " ₽\n"

        bot.reply_to(message, reply_msg, parse_mode='Markdown')
    except:
        print("Wrong API key for Coinmarketcap")
        bot.send_message(message.chat.id,
                         "You entered wrong Coinmarketcap API key.")
예제 #6
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))