Python ccxt.exchanges() Examples

The following are 10 code examples of ccxt.exchanges(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ccxt , or try the search function .
Example #1
Source File: ccxt_exchange.py    From catalyst with Apache License 2.0 7 votes vote down vote up
def cancel_order(self, order_param,
                     asset_or_symbol=None, params={}):
        order_id = order_param.id \
            if isinstance(order_param, Order) else order_param

        if asset_or_symbol is None:
            log.debug(
                'order not found in memory, cancelling order might fail '
                'on some exchanges.'
            )
        try:
            symbol = self.get_symbol(asset_or_symbol) \
                if asset_or_symbol is not None else None
            self.api.cancel_order(id=order_id,
                                  symbol=symbol, params=params)

        except (ExchangeError, NetworkError) as e:
            log.warn(
                'unable to cancel order {} / {}: {}'.format(
                    self.name, order_id, e
                )
            )
            raise ExchangeRequestError(error=e) 
Example #2
Source File: ccxt_wrapper.py    From fooltrader with MIT License 5 votes vote down vote up
def fetch_ticks(exchange_str, pairs=None):
    if not pairs:
        df = get_security_list(security_type=SECURITY_TYPE_CRYPTO, exchanges=exchange_str)
        pairs = set(df.loc[:, 'name'].tolist()) & set(CRYPTOCURRENCY_PAIR)
        if not pairs:
            logger.warning("{} not support pair:{}".format(exchange_str, CRYPTOCURRENCY_PAIR))
            return
        else:
            logger.info("{} get tick for paris:{}".format(exchange_str, pairs))

    exchange = eval("ccxt.{}()".format(exchange_str))
    if exchange.has['fetchTrades']:
        # verify one trade at first
        pairs = [pair for pair in pairs if _check_fetch_trades(exchange, pair)]

        logger.info("after check {} get tick for paris:{}".format(exchange_str, pairs))

        while True:

            for pair in pairs:
                trades = exchange.fetch_trades(symbol=pair)

                trade = trades[-1]

                code = pair.replace('/', '-')
                tick = {
                    'securityId': "{}_{}_{}".format("cryptocurrency", exchange_str, code),
                    'code': code,
                    'name': pair,
                    'timestamp': int(trade['timestamp'] / 1000),
                    'id': trade['id'],
                    'price': trade['price'],
                    'volume': trade['amount']
                }
                yield tick

            rate_limit = 5
            time.sleep(rate_limit)

            logger.info("fetch_tickers exchange:{} pairs:{} sleep:{}".format(exchange_str, pairs, rate_limit)) 
Example #3
Source File: ccxt_exchange.py    From catalyst with Apache License 2.0 5 votes vote down vote up
def find_exchanges(features=None, is_authenticated=False):
        ccxt_features = []
        if features is not None:
            for feature in features:
                if not feature.endswith('Bundle'):
                    ccxt_features.append(feature)

        exchange_names = []
        for exchange_name in ccxt.exchanges:
            if is_authenticated:
                exchange_auth = get_exchange_auth(exchange_name)

                has_auth = (exchange_auth['key'] != ''
                            and exchange_auth['secret'] != '')

                if not has_auth:
                    continue

            log.debug('loading exchange: {}'.format(exchange_name))
            exchange = getattr(ccxt, exchange_name)()

            if ccxt_features is None:
                has_feature = True

            else:
                try:
                    has_feature = all(
                        [exchange.has[feature] for feature in ccxt_features]
                    )

                except Exception:
                    has_feature = False

            if has_feature:
                try:
                    log.info('initializing {}'.format(exchange_name))
                    exchange_names.append(exchange_name)

                except Exception as e:
                    log.warn(
                        'unable to initialize exchange {}: {}'.format(
                            exchange_name, e
                        )
                    )

        return exchange_names 
Example #4
Source File: Advanced_Cryptocurrency_Trading_Bot.py    From Cryptocurrency-Trading-Bots-Python-Beginner-Advance with MIT License 5 votes vote down vote up
def diversify():
        #Diversify to do (Diversify will diversify portfolio):
            #Collect Amounts in Wallets (available for trading)
    for exch2 in ccxt.exchanges:
        #Change to incorporate requiring API's keys & phrases (from Keys Python Script)
        exch = getattr (ccxt, exch2) ()
        print(exch.fetchBalance())
    #Diversify into pre-described amounts
        # 50% BTC, 5% Each of 8 next-top coins, 10x 1% of micro-caps
    pass 
Example #5
Source File: conf.py    From crypto-signal with MIT License 4 votes vote down vote up
def __init__(self):
        """Initializes the Configuration class
        """

        with open('defaults.yml', 'r') as config_file:
            default_config = yaml.load(config_file)

        if os.path.isfile('config.yml'):
            with open('config.yml', 'r') as config_file:
                user_config = yaml.load(config_file)
        else:
            user_config = dict()

        if 'settings' in user_config:
            self.settings = {**default_config['settings'], **user_config['settings']}
        else:
            self.settings = default_config['settings']

        if 'notifiers' in user_config:
            self.notifiers = {**default_config['notifiers'], **user_config['notifiers']}
        else:
            self.notifiers = default_config['notifiers']

        if 'indicators' in user_config:
            self.indicators = {**default_config['indicators'], **user_config['indicators']}
        else:
            self.indicators = default_config['indicators']

        if 'informants' in user_config:
            self.informants = {**default_config['informants'], **user_config['informants']}
        else:
            self.informants = default_config['informants']

        if 'crossovers' in user_config:
            self.crossovers = {**default_config['crossovers'], **user_config['crossovers']}
        else:
            self.crossovers = default_config['crossovers']

        if 'exchanges' in user_config:
            self.exchanges = user_config['exchanges']
        else:
            self.exchanges = dict()

        for exchange in ccxt.exchanges:
            if exchange not in self.exchanges:
                self.exchanges[exchange] = {
                    'required': {
                        'enabled': False
                    }
                } 
Example #6
Source File: ccxt_wrapper.py    From fooltrader with MIT License 4 votes vote down vote up
def init_markets(exchanges=CRYPTOCURRENCY_EXCHANGES):
    for exchange_str in set(ccxt.exchanges) & set(exchanges):
        exchange_dir = get_exchange_dir(security_type='cryptocurrency', exchange=exchange_str)

        # 创建交易所目录
        if not os.path.exists(exchange_dir):
            os.makedirs(exchange_dir)

        exchange = eval("ccxt.{}()".format(exchange_str))
        try:
            markets = exchange.fetch_markets()
            df = pd.DataFrame()

            # markets有些为key=symbol的dict,有些为list
            markets_type = type(markets)
            if markets_type != dict and markets_type != list:
                logger.exception("unknown return markets type {}".format(markets_type))
                return

            for market in markets:
                if markets_type == dict:
                    name = market
                    code = name.replace('/', "-")

                if markets_type == list:
                    name = market['symbol']
                    code = name.replace('/', "-")

                security_item = generate_security_item(security_type='cryptocurrency', exchange=exchange_str,
                                                       code=code,
                                                       name=name, list_date=None)

                kdata_dir = get_kdata_dir(security_item)

                if not os.path.exists(kdata_dir):
                    os.makedirs(kdata_dir)

                df = df.append(security_item, ignore_index=True)

                logger.info("init_markets,exchange:{} security:{}".format(exchange_str, security_item))

                if markets_type == dict:
                    security_info = markets[market]

                if markets_type == list:
                    security_info = market

                # 存储数字货币的meta信息
                if security_info:
                    with open(get_security_meta_path(security_type='cryptocurrency', exchange=exchange_str,
                                                     code=code), "w") as f:
                        json.dump(security_info, f, ensure_ascii=False)

            # 存储该交易所的数字货币列表
            if not df.empty:
                df.to_csv(get_security_list_path(security_type='cryptocurrency', exchange=exchange_str),
                          index=False)
            logger.exception("init_markets for {} success".format(exchange_str))
        except Exception as e:
            logger.exception("init_markets for {} failed".format(exchange_str), e) 
Example #7
Source File: ccxt_wrapper.py    From fooltrader with MIT License 4 votes vote down vote up
def fetch_kdata(exchange_str='bitstamp'):
    ccxt_exchange = eval("ccxt.{}()".format(exchange_str))
    if ccxt_exchange.has['fetchOHLCV']:
        for _, security_item in get_security_list(security_type='cryptocurrency', exchanges=[exchange_str]).iterrows():
            try:
                if security_item['name'] not in CRYPTOCURRENCY_PAIR:
                    continue

                start_date, df = get_latest_download_trading_date(security_item)
                # 日K线只抓到昨天
                end_date = pd.Timestamp.today() - pd.DateOffset(1)

                if start_date and (start_date > end_date):
                    logger.info("{} kdata is ok".format(security_item['code']))
                    continue

                try:
                    kdatas = ccxt_exchange.fetch_ohlcv(security_item['name'], timeframe='1d')
                    # for rateLimit
                    time.sleep(5)
                except Exception as e:
                    logger.exception("fetch_kdata for {} {} failed".format(exchange_str, security_item['name']), e)
                    continue

                for kdata in kdatas:
                    timestamp = pd.Timestamp.fromtimestamp(int(kdata[0] / 1000))
                    if is_same_date(timestamp, pd.Timestamp.today()):
                        continue
                    kdata_json = {
                        'timestamp': to_time_str(timestamp),
                        'code': security_item['code'],
                        'name': security_item['name'],
                        'open': kdata[1],
                        'high': kdata[2],
                        'low': kdata[3],
                        'close': kdata[4],
                        'volume': kdata[5],
                        'securityId': security_item['id'],
                        'preClose': None,
                        'change': None,
                        'changePct': None
                    }
                    df = df.append(kdata_json, ignore_index=True)
                if not df.empty:
                    df = df.loc[:, KDATA_COMMON_COL]
                    kdata_df_save(df, get_kdata_path(security_item), calculate_change=True)
                    logger.info(
                        "fetch_kdata for exchange:{} security:{} success".format(exchange_str, security_item['name']))
            except Exception as e:
                logger.info(
                    "fetch_kdata for exchange:{} security:{} failed".format(exchange_str, security_item['name'], e))
    else:
        logger.warning("exchange:{} not support fetchOHLCV".format(exchange_str))


# not used 
Example #8
Source File: ccxt_exchange.py    From catalyst with Apache License 2.0 4 votes vote down vote up
def __init__(self, exchange_name, key,
                 secret, password, quote_currency):
        log.debug(
            'finding {} in CCXT exchanges:\n{}'.format(
                exchange_name, ccxt.exchanges
            )
        )
        try:
            # Making instantiation as explicit as possible for code tracking.
            if exchange_name in SUPPORTED_EXCHANGES:
                exchange_attr = SUPPORTED_EXCHANGES[exchange_name]

            else:
                exchange_attr = getattr(ccxt, exchange_name)

            self.api = exchange_attr({
                'apiKey': key,
                'secret': secret,
                'password': password,
            })
            self.api.enableRateLimit = True

        except Exception:
            raise ExchangeNotFoundError(exchange_name=exchange_name)

        self._symbol_maps = [None, None]

        self.name = exchange_name

        self.quote_currency = quote_currency
        self.transactions = defaultdict(list)

        self.num_candles_limit = 2000
        self.max_requests_per_minute = 60
        self.low_balance_threshold = 0.1
        self.request_cpt = dict()
        self._common_symbols = dict()

        # Operations with retry features
        self.attempts = dict(
            missing_order_attempts=5,
            retry_sleeptime=5,
        )

        self.bundle = ExchangeBundle(self.name)
        self.markets = None
        self._is_init = False 
Example #9
Source File: ccxt_exchange.py    From catalyst with Apache License 2.0 4 votes vote down vote up
def _process_order_fallback(self, order):
        """
        Fallback method for exchanges which do not play nice with
        fetch-my-trades. Apparently, about 60% of exchanges will return
        the correct executed values with this method. Others will support
        fetch-my-trades.

        Parameters
        ----------
        order: Order

        Returns
        -------
        float

        """
        exc_order, price = self.get_order(
            order.id, order.asset, return_price=True
        )
        order.status = exc_order.status
        order.commission = exc_order.commission
        order.filled = exc_order.filled

        transactions = []
        if exc_order.status == ORDER_STATUS.FILLED:
            if order.amount > exc_order.amount:
                log.warn(
                    'executed order amount {} differs '
                    'from original'.format(
                        exc_order.amount, order.amount
                    )
                )

            order.check_triggers(
                price=price,
                dt=exc_order.dt,
            )
            transaction = Transaction(
                asset=order.asset,
                amount=order.amount,
                dt=pd.Timestamp.utcnow(),
                price=price,
                order_id=order.id,
                commission=order.commission,
            )
            transactions.append(transaction)

        return transactions 
Example #10
Source File: ccxt_exchange.py    From catalyst with Apache License 2.0 4 votes vote down vote up
def get_order(self, order_id, asset_or_symbol=None,
                  return_price=False, params={}):
        """Lookup an order based on the order id returned from one of the
        order functions.

        Parameters
        ----------
        order_id : str
            The unique identifier for the order.
        asset_or_symbol: Asset or str
            The asset or the tradingPair symbol of the order.
        return_price: bool
            get the trading price in addition to the order
        params: dict, optional
            Extra parameters to pass to the exchange

        Returns
        -------
        order : Order
            The order object.
        execution_price: float
            The execution price per unit of the order if return_price is True
        """
        if asset_or_symbol is None:
            log.debug(
                'order not found in memory, the request might fail '
                'on some exchanges.'
            )
        try:
            symbol = self.get_symbol(asset_or_symbol) \
                if asset_or_symbol is not None else None
            order_status = self.api.fetch_order(id=order_id,
                                                symbol=symbol,
                                                params=params)
            order, executed_price = self._create_order(order_status)

            if return_price:
                return order, executed_price

            else:
                return order

        except (ExchangeError, NetworkError) as e:
            log.warn(
                'unable to fetch order {} / {}: {}'.format(
                    self.name, order_id, e
                )
            )
            raise ExchangeRequestError(error=e)