async def main():
    exchange = cro.Exchange()
    account = cro.Account(from_env=True)
    coins = (await account.get_balance()).keys()
    pairs = await exchange.get_pairs()
    
    with (SRC_PATH / 'pairs.py').open('w') as f:
        f.writelines([
            "from .structs import Pair\n\n",
        ] + [
            f'{pair.name} = Pair("{pair.name}", '
            f'price_precision={pair.price_precision}, '
            f'quantity_precision={pair.quantity_precision})\n'
            for pair in sorted(pairs, key=lambda p: p.name)
        ] + [
            "\n",
            ALL_TEMPLATE.format(class_name='Pair')
        ])

    with (SRC_PATH / 'coins.py').open('w') as f:
        f.writelines([
            "from .structs import Coin\n\n",
        ] + [
            f'{coin.name} = Coin("{coin.name}")\n'
            for coin in sorted(coins, key=lambda c: c.name)
        ] + [
            "\n",
            ALL_TEMPLATE.format(class_name='Coin')
        ])
Beispiel #2
0
async def sell():
    account = cro.Account(api_key=api_key, api_secret=api_secret)
    data = await account.get_balance()
    cro_balance = data[cro.Coin(name="CRO")].available
    print(f'CRO balance {math.floor(cro_balance)}')
    if cro_balance > threshold:
        exchange = cro.Exchange()
        price = await exchange.get_price(cro.pairs.CRO_USDT)
        print(f'CRO price {price}')
        result = await account.create_order(pair=pair,
                                            side=cro.OrderSide.SELL,
                                            type_=cro.OrderType.MARKET,
                                            quantity=math.floor(cro_balance))
        print(result)
Beispiel #3
0
    def __init__(self, config=None):
        self.exchange = config['corecito_exchange']
        self.api_key = config['api_key']
        self.api_secret = config['api_secret']
        self.core_number = config['core_number']
        self.min_price_stop = config[
            'min_price_stop'] if 'min_price_stop' in config else None
        self.max_price_stop = config[
            'max_price_stop'] if 'max_price_stop' in config else None
        self.min_core_number_increase_percentage = config[
            'min_core_number_increase_percentage']
        self.max_core_number_increase_percentage = config[
            'max_core_number_increase_percentage']
        self.min_core_number_decrease_percentage = config[
            'min_core_number_decrease_percentage']
        self.max_core_number_decrease_percentage = config[
            'max_core_number_decrease_percentage']
        self.is_fiat = config['is_fiat']

        if self.exchange == 'crypto.com':
            self.account = cro.Account(api_key=self.api_key,
                                       api_secret=self.api_secret)
            self.cro_exchange = cro.Exchange()
            self.base_currency = config['cryptocom_base_currency']
            self.core_number_currency = config[
                'cryptocom_core_number_currency']
            self.pair = eval('cro.pairs.' + config['cryptocom_trading_pair'])
            self.pair_name = self.pair.name.replace('_', '/')
            self.cro_coin_base_currency = eval(
                'cro.coins.' + config['cryptocom_base_currency'])
            self.cro_coin_core_number_currency = eval(
                'cro.coins.' + config['cryptocom_core_number_currency'])
            self.max_decimals_buy = config['cryptocom_max_decimals_buy']
            self.max_decimals_sell = config['cryptocom_max_decimals_sell']
        elif self.exchange == 'binance':
            binance = Binance(public_key=self.api_key,
                              secret_key=self.api_secret,
                              sync=True)
            self.account = binance.b
            self.pair = config['binance_trading_pair']
            self.pair_name = self.pair.replace('_', '/')
            self.base_currency = config['binance_base_currency']
            self.core_number_currency = config['binance_core_number_currency']
            self.max_decimals_buy = config['binance_max_decimals_buy']
            self.max_decimals_sell = config['binance_max_decimals_sell']

        if not self.account:
            raise Exception(
                'Could not connect to the exchange account with provided keys!'
            )
Beispiel #4
0
import cryptocom.exchange as cdc
from utils import db
from config import exchangeCredentials

EXCHANGE = cdc.Exchange()
ACCOUNT = cdc.Account(**exchangeCredentials["CDC"])


def createPair(c1, c2):
    return cdc.structs.Pair(name=f"{c1}_{c2}",
                            price_precision=16,
                            quantity_precision=16)


async def getPrice(**kwargs) -> float:
    """ Get price """
    price = await EXCHANGE.get_price(createPair(kwargs["c1"], kwargs["c2"]))
    return price


async def marketOrder(**kwargs):
    if kwargs["marketOrder"] == "buy":
        order_id = await ACCOUNT.buy_market(createPair(kwargs["c1"],
                                                       kwargs["c2"]),
                                            spend=kwargs["qty"])
        db.insert_db(
            "INSERT INTO morder(ORDER_ID, EXCHANGE, TYPE, C1, C2, QUANTITY) values(?,?,?,?,?,?)",
            rows=[(order_id, "cdc", "buy", kwargs["c1"], kwargs["c2"],
                   kwargs["qty"])])
        return order_id
    elif kwargs["marketOrder"] == "sell":
def exchange() -> cro.Exchange:
    return cro.Exchange()
Beispiel #6
0
async def exchange() -> cro.Exchange:
    ex = cro.Exchange()
    await ex.sync_pairs()
    return ex
Beispiel #7
0
async def main():
    iteration = 0
    opportunities175 = 0
    opportunities120 = 0
    config = get_config()
    logger = setupLogger('logfile.log')

    #Crypto.com API setup
    cdc_exchange = cro.Exchange()
    cdc_account = cro.Account(api_key=config['cdc_api_key'],
                              api_secret=config['cdc_api_secret'])
    cdc_pair = eval('cro.pairs.' + config['cdc_trading_pair'])

    # Kraken API setup
    krk_exchange = krakenex.API(key=config['krk_api_key'],
                                secret=config['krk_api_secret'])

    # Binance API setup
    binance = Binance(public_key=config['bnb_api_key'],
                      secret_key=config['bnb_api_secret'],
                      sync=True)
    bnb_exchange = binance.b

    while True:
        try:
            iteration += 1
            print(f'------------ Iteration {iteration} ------------')
            # Check Balances
            # cdc_coin_base_currency = eval('cro.coins.' + config['cdc_base_currency'])
            # cdc_target_currency = eval('cro.coins.' + config['cdc_target_currency'])
            # cdc_balances = await cdc_account.get_balance()
            # Crypto.com: Get my base currency balance
            # cdc_base_currency_balance = cdc_balances[cdc_coin_base_currency]
            # cdc_base_currency_available = cdc_base_currency_balance.available
            # Get my Target currency balance
            # cdc_target_currency_balance = cdc_balances[cdc_target_currency]
            # EXAMPLE BTC_balance:Balance(total=0.04140678, available=3.243e-05, in_orders=0.04137435, in_stake=0, coin=Coin(name='BTC'))
            # logger.info(f"Crypto.com's Balances\n(Base) {config['cdc_base_currency']} balance:{cdc_base_currency_balance} \n(Target) {config['cdc_target_currency']} balance:{cdc_target_currency_balance}\n\n")

            # Kraken: Get my base currency balance
            krk_balance = krk_exchange.query_private('Balance')
            krk_base_currency_available = 0
            if config['krk_base_currency'] in krk_balance['result']:
                krk_base_currency_available = krk_balance['result'][
                    config['krk_base_currency']]
            # Kraken: Get my target currency balance
            krk_target_currency_available = 0
            if config['krk_target_currency'] in krk_balance['result']:
                krk_target_currency_available = krk_balance['result'][
                    config['krk_target_currency']]
            logger.info(
                f"Kraken's Balances\n(Base) {config['krk_base_currency']} balance:{krk_base_currency_available} \n(Target) {config['krk_target_currency']} balance:{krk_target_currency_available}\n"
            )

            # Binance: Get my base currency balance
            bnb_btc_balance_result = bnb_exchange.get_asset_balance(
                asset=config['bnb_base_currency'])
            if bnb_btc_balance_result:
                bnb_btc_balance = float(bnb_btc_balance_result['free'])
            else:
                bnb_btc_balance = 0.0
            logger.info(
                f"Binance's Balances\nBTC balance:{bnb_btc_balance} \n")

            # Check target currency price differences in exchanges
            # Crypto.com target currency ticker
            # cdc_tickers = await cdc_exchange.get_tickers()
            # cdc_ticker = cdc_tickers[cdc_pair]
            # cdc_buy_price = cdc_ticker.buy_price
            # cdc_sell_price = cdc_ticker.sell_price
            # cdc_high = cdc_ticker.high
            # cdc_low = cdc_ticker.low
            # logger.info(f'\nCRYPTO.COM => Market {cdc_pair.name}\nbuy price: {cdc_buy_price} - sell price: {cdc_sell_price} <> low: {cdc_low} - high: {cdc_high}\n\n')

            # Kraken trading pair ticker
            krk_tickers = krk_exchange.query_public(
                "Ticker", {'pair': config['krk_trading_pair']
                           })['result'][config['krk_trading_pair']]
            krk_buy_price = krk_tickers['b'][0]
            krk_sell_price = krk_tickers['a'][0]
            krk_high = krk_tickers['h'][0]
            krk_low = krk_tickers['l'][0]
            logger.info(
                f"\nKRAKEN => Market {config['krk_trading_pair']}\nbuy price: {krk_buy_price} - sell price: {krk_sell_price} <> low: {krk_low} - high: {krk_high}\n"
            )

            # Binance trading pair ticker
            bnb_tickers = bnb_exchange.get_orderbook_tickers()
            bnb_ticker = next(item for item in bnb_tickers
                              if item['symbol'] == config['bnb_trading_pair'])
            bnb_buy_price = bnb_ticker['bidPrice']
            bnb_sell_price = bnb_ticker['askPrice']
            logger.info(
                f"\nBINANCE => Market {config['bnb_trading_pair']}\nbuy price: {bnb_buy_price} - sell price: {bnb_sell_price}\n"
            )

            buy_prices = {'krk': krk_buy_price, 'bnb': bnb_buy_price}
            # buy_prices = {'cdc': cdc_buy_price, 'krk': krk_buy_price, 'bnb': bnb_buy_price}
            max_buy_price_key = max(buy_prices, key=buy_prices.get)
            max_buy_price = buy_prices[max_buy_price_key]
            sell_prices = {'krk': krk_sell_price, 'bnb': bnb_sell_price}
            # sell_prices = {'cdc': cdc_sell_price, 'krk': krk_sell_price, 'bnb': bnb_sell_price}
            min_sell_price_key = min(sell_prices, key=sell_prices.get)
            min_sell_price = sell_prices[min_sell_price_key]
            logger.info(
                f"Max buy price -> {max_buy_price_key} = {max_buy_price}")
            logger.info(
                f"Min sell price -> {min_sell_price_key} = {min_sell_price}")
            logger.info(
                f"Max(buy price) - Min(sell price) = {float(max_buy_price) - float(min_sell_price)}\n"
            )

            diff = (float(max_buy_price) - float(min_sell_price))
            if diff >= 175.0:
                opportunities175 += 1
                if max_buy_price_key == 'bnb' and min_sell_price_key == 'krk' and not config[
                        'safe_mode_on']:
                    try:
                        # Market order to buy XRP with BTC in Binance
                        result = bnb_exchange.order_market_buy(
                            symbol=config['bnb_buy_trading_pair'],
                            quoteOrderQty=bnb_btc_balance)
                        if result:
                            if result['status'] != "FILLED":
                                raise Exception(
                                    "Could not sell BTC for XRP in Binance: {}"
                                    .format(result))
                        else:
                            raise Exception(
                                "Could not sell BTC for XRP in Binance. 'result' is empty!"
                            )
                        logger.info(result)

                        # Market order to buy the same amount of BTC with EUR in Kraken
                        result = krk_exchange.query_private(
                            'AddOrder', {
                                'pair': config['krk_buy_trading_pair'],
                                'type': 'buy',
                                'ordertype': 'market',
                                'oflags': 'fciq',
                                'volume': bnb_btc_balance
                            })
                        if result['error']:
                            raise Exception(
                                "Could not perform 'AddOrder' of type 'buy' in Kraken"
                            )
                        logger.info(result)

                        # In Binance: Send XRP to Kraken
                        # First get XRP balance
                        bnb_xrp_balance_result = bnb_exchange.get_asset_balance(
                            asset=config['bnb_base_currency'])
                        if bnb_xrp_balance_result:
                            bnb_xrp_balance = float(
                                bnb_xrp_balance_result['free'])
                        else:
                            bnb_xrp_balance = 0.0
                        logger.info(
                            f"Binance's Balances\nXRP balance:{bnb_xrp_balance} \n"
                        )
                        # Send XRP from Binance to Kraken
                        result = bnb_exchange.withdraw(
                            asset='XRP',
                            address=config['krk_xrp_address'],
                            addressTag=config['krk_xrp_address_tag'],
                            amount=bnb_xrp_balance)
                        if result:
                            if not result['success']:
                                raise Exception("Could not send XRP to Kraken")
                        else:
                            raise Exception("Could not send XRP to Kraken")
                        logger.info(result)

                        # In Kraken: buy XRP with BTC
                        # First get BTC Balance
                        krk_balance = krk_exchange.query_private('Balance')
                        krk_base_currency_available = 0
                        if config['krk_base_currency'] in krk_balance[
                                'result']:
                            krk_base_currency_available = krk_balance[
                                'result'][config['krk_base_currency']]
                        krk_tickers = krk_exchange.query_public(
                            "Ticker",
                            {'pair': config['krk_buy_trading_pair_step2']
                             })['result'][config['krk_buy_trading_pair_step2']]
                        krk_buy_price = krk_tickers['b'][0]
                        krk_xrp_volume = round(
                            float(krk_base_currency_available) /
                            float(krk_buy_price), 8)

                        result = krk_exchange.query_private(
                            'AddOrder', {
                                'pair': config['krk_buy_trading_pair_step2'],
                                'type': 'buy',
                                'ordertype': 'market',
                                'oflags': 'fciq',
                                'volume': krk_xrp_volume
                            })
                        if result['error']:
                            raise Exception(
                                "Could not buy XRP with BTC in Kraken: {}".
                                format(result['error']))
                        logger.info(result)

                        #  Send XRP amount from Kraken to Binance
                        krk_balance = krk_exchange.query_private('Balance')
                        krk_xrp_volume = 0
                        if 'XXRP' in krk_balance['result']:
                            krk_xrp_volume = krk_balance['result']['XXRP']
                        result = krk_exchange.query_private(
                            'Withdraw', {
                                'asset': 'XXRP',
                                'key': config['krk_bnb_xrp_address_key'],
                                'amount': krk_xrp_volume
                            })

                        # Wait until withdrawals are complete (should be max 4 mins for XRP transfers)
                        # Give withdrawals some time to do their thing
                        await asyncio.sleep(10)
                        tries = 0
                        waiting = True
                        while tries < 50 and waiting:
                            tries = +1
                            # Get XRP balance in Kraken
                            krk_balance = krk_exchange.query_private('Balance')
                            krk_xrp_volume_from_bnb = 0
                            if 'XXRP' in krk_balance['result']:
                                krk_xrp_volume_from_bnb = krk_balance[
                                    'result']['XXRP']
                            # Get XRP balance in Binance
                            bnb_xrp_balance_result = bnb_exchange.get_asset_balance(
                                asset='XRP')
                            if bnb_xrp_balance_result:
                                bnb_xrp_balance_from_krk = float(
                                    bnb_xrp_balance_result['free'])
                            else:
                                bnb_xrp_balance_from_krk = 0.0
                            Waiting = (krk_xrp_volume_from_bnb +
                                       100.0) > bnb_xrp_balance and (
                                           bnb_xrp_balance_from_krk +
                                           100.0) > krk_xrp_volume
                            await asyncio.sleep(10)

                        # in Binance sell XRP to buy BTC
                        bnb_xrp_balance_result = bnb_exchange.get_asset_balance(
                            asset='XRP')
                        if bnb_xrp_balance_result:
                            bnb_xrp_balance = float(
                                bnb_xrp_balance_result['free'])
                        else:
                            bnb_xrp_balance = 0.0
                        # bnb_xrp_balance = round(bnb_xrp_balance, 3)
                        logger.info(
                            f"Binance's Balances\nXRP balance:{bnb_xrp_balance} \n"
                        )

                        # Market order to buy XRP with BTC in Binance
                        result = bnb_exchange.order_market_sell(
                            symbol=config['bnb_buy_trading_pair'],
                            quantity=int(bnb_xrp_balance))
                        if result:
                            if result['status'] != "FILLED":
                                raise Exception(
                                    "Could not sell BTC for XRP in Binance: {}"
                                    .format(result))
                        else:
                            raise Exception(
                                "Could not sell BTC for XRP in Binance")
                        logger.info(result)

                        # In Kraken: sell XRP to buy EUR
                        krk_balance = krk_exchange.query_private('Balance')
                        krk_xrp_volume = 0
                        if 'XXRP' in krk_balance['result']:
                            krk_xrp_volume = krk_balance['result']['XXRP']
                        result = krk_exchange.query_private(
                            'AddOrder', {
                                'pair': config['krk_buy_trading_pair_step3'],
                                'type': 'sell',
                                'ordertype': 'market',
                                'oflags': 'fciq',
                                'volume': krk_xrp_volume
                            })
                        if result['error']:
                            raise Exception(
                                "Could not buy BTC with EUR in Kraken: {}".
                                format(result))
                        logger.info(result)
                    except Exception as e:
                        logger.info(traceback.format_exc())
                        logger.info(
                            "\nException occurred -> '{}'. Waiting for next iteration... ({} seconds)\n\n\n"
                            .format(e, config['seconds_between_iterations']))

            elif 120.0 <= diff < 175.0:
                opportunities120 += 1

            opportunities = {
                'Opportunities175': opportunities175,
                'Opportunities120': opportunities120
            }

            for key, value in opportunities.items():
                logger.info(f'{key} = {value}')

            print(f'------------ Iteration {iteration} ------------\n')
            if config['test_mode_on']:
                await asyncio.sleep(1)
                break
            else:
                # Wait given seconds until next poll
                logger.info(
                    "Waiting for next iteration... ({} seconds)\n\n\n".format(
                        config['seconds_between_iterations']))
                await asyncio.sleep(config['seconds_between_iterations'])
        except Exception as e:
            # Network issue(s) occurred (most probably). Jumping to next iteration
            logger.info(
                "Exception occurred -> '{}'. Waiting for next iteration... ({} seconds)\n\n\n"
                .format(e, config['seconds_between_iterations']))
            await asyncio.sleep(config['seconds_between_iterations'])