Esempio n. 1
0
def get_weights(coins, fiat_currency):
    coinmarketcap = Market()

    market_cap = {}
    for c in coins:
        try:
            listings = coinmarketcap.listings()
            print(listings['data'][0])
            id = [
                item['id'] for item in listings['data'] if item['symbol'] == c
            ][0]
            ticker = coinmarketcap.ticker(id)
            print(ticker)
            market_cap[c] = \
                float(ticker['data']['quotes'][fiat_currency]['market_cap'])
        except HTTPError as e:
            print('caught exception when fetching ticker for {} with name={}'.
                  format(c, coins[c]['name']))
            raise e

    total_market_cap = sum(market_cap.values())

    weights = {}
    for c in coins:
        weights[c] = market_cap[c] / total_market_cap
    print('coin weights:')
    for w in weights:
        print('  {0}: {1:.4f}'.format(w, weights[w]))
    print()
    return weights
Esempio n. 2
0
def get_id_table():
    """Get a dictionary from symbol to id."""
    sym2id = dict()
    id2sym = dict()
    cmc = Market()
    for i, x in enumerate(cmc.listings()["data"]):
        sym2id[x["symbol"]] = x["id"]
        id2sym[x["id"]] = x["symbol"]
    return sym2id, id2sym
Esempio n. 3
0
def get_history_all():
    """Get all history close data."""
    cmc = Market()
    listing = [item['symbol'] for item in cmc.listings()['data']]
    ret = dict()
    for i, x in enumerate(listing):
        scr = CmcScraper(x)
        try:
            header, data = scr.get_data()
            ti = list()
            pr = list()
            for j, xx in enumerate(data):
                if xx[4]:
                    pr.append(xx[4])
                    ti.append(xx[0])
            ret[x] = dict(t=ti, p=pr)
        except Exception:
            print("Invalid coin symbol: {0}".format(x))
        print(i, x)
    return ret
Esempio n. 4
0
def update(event):
    messagebox.showinfo('info',
                        """更新历史数据耗时较久,视网络环境需时20到40分钟,请耐心等待""")
    cmc = Market()
    listing = [item['symbol'] for item in cmc.listings()['data']]
    hist = dict()
    step = 100 / len(listing)
    for i, x in enumerate(listing):
        scr = CmcScraper(x)
        try:
            header, data = scr.get_data()
            ti = list()
            pr = list()
            for j, xx in enumerate(data):
                if xx[4]:
                    pr.append(xx[4])
                    ti.append(xx[0])
            hist[x] = dict(
                t=ti,
                p=pr
            )
        except Exception:
            print("Invalid coin symbol: {0}".format(x))
        print(i, x)
        progress.step(step)
        progress.update()
    sym2id, id2sym = get_id_table()
    outdata = dict(
        history=hist,
        s2i=sym2id,
        i2s=id2sym
    )
    with open("cmc_history.json", "w") as f:
        json.dump(outdata, f)
    update_date()
    messagebox.showinfo('info', "成功更新历史数据")
Esempio n. 5
0
from coinmarketcap import Market

coinmarketcap = Market()
alllistings = coinmarketcap.listings()
#print(alllistings)
getbtcprice = coinmarketcap.ticker(start=1, limit=1, convert='INR')
#print(getbtcprice)
getpricebyid = coinmarketcap.ticker(1, convert='INR')
#print(getpricebyid)
getoverallstats = coinmarketcap.stats(convert='INR')
#print(getoverallstats)
Esempio n. 6
0
class CoinmarketcapHelper:

    __DATA_FOLDER = './data'
    __CACHE_MINUTES = 30
    __FIRST_PRICE = False

    def __init__(self,
                 convert_currency='USD',
                 data_folder=__DATA_FOLDER,
                 cache_minutes=__CACHE_MINUTES,
                 first_price=__FIRST_PRICE):
        self.first_price = first_price
        self.tickers = OrderedDict()
        self.symbols = OrderedDict()
        self.convert_currency = convert_currency.upper()
        self.tickers_path = f'{data_folder}/tickers/coinmarketcap_tickers_{self.convert_currency}.json'
        self.symbols_aliases_path = f'{data_folder}/coinmarketcap_symbols_aliases.json'
        self.coins_aliases_path = f'{data_folder}/coinmarketcap_coins_aliases.json'
        self.symbols_path = f'{data_folder}/coinmarketcap_symbols.json'
        self.symbols_conflicting_path = f'{data_folder}/coinmarketcap_symbols_conflicting.json'
        os.makedirs(os.path.dirname(self.tickers_path), exist_ok=True)
        self.coinmarketcap = Market()
        self._initialize(cache_minutes)

        self.symbols_aliases = self._load_dict_from_json(
            self.symbols_aliases_path)
        self.coins_aliases = self._load_dict_from_json(self.coins_aliases_path)

    def _initialize(self, cache_minutes=__CACHE_MINUTES):
        """Load tickers json or if it's missing or older than `cache_minutes`, re-download it"""
        download_tickers = True
        if os.path.exists(self.tickers_path):
            logging.debug(f'File {self.tickers_path} exists')
            date_now = time.time()
            file_date = os.path.getmtime(self.tickers_path)
            file_seconds_old = date_now - file_date
            # This will make sure that the file will be loaded if it was saved within 1 hour
            if file_seconds_old < cache_minutes * 60:
                logging.debug(f'File {self.tickers_path} is cached already.')
                self.tickers = json.load(open(self.tickers_path))
                download_tickers = False

        if download_tickers:
            listings = self.coinmarketcap.listings()
            total_listings = listings['metadata']['num_cryptocurrencies']
            hundreds = ceil(total_listings / 100)
            logging.debug(
                f'Downloading {total_listings} tickers with {hundreds} API calls...'
            )
            tickers = OrderedDict()
            for i in range(hundreds):
                start_rank = i * 100 + 1
                logging.debug(
                    f'Downloading from rank {start_rank} to {start_rank + 99}...'
                )
                partial_tickers = self.coinmarketcap.ticker(
                    start=start_rank, limit=100, convert=self.convert_currency)
                tickers.update(partial_tickers['data'])

            self._process_tickers(tickers)
            with open(self.tickers_path, 'w') as f:
                f.write(json.dumps(self.tickers, indent=2))
            logging.debug(f'Downloading tickers: done.')
            self.tickers = tickers

        if self.symbols == {}:
            self.symbols = json.load(open(self.symbols_path))

    def _process_tickers(self, tickers):
        """
        Create a dictionary of info (name + id) by symbol, save it as json (for caching purposes, to be loaded at each
        initialization) and save also conflicting symbols (used by several cyptocurrencies)
        """
        non_unique_symbols = OrderedDict()
        symbols_ranked = OrderedDict()
        for ticker in tickers.values():
            # Add to tickers dictionary (key = coinmarketcap id)
            id = ticker['id']
            self.tickers[id] = ticker

            # Add symbol_info (name + id) to symbols dictionary
            symbol = ticker['symbol']
            symbol_info = self._convert_to_symbol_info(ticker)
            symbol_ranked = symbols_ranked.get(symbol)
            # If the symbol is found, it means that this is a non unique symbol
            if symbol_ranked is not None:
                # If it's not found this dict, then we add a list of 2 elements (first crypto and this crypto)
                if non_unique_symbols.get(symbol) is None:
                    non_unique_symbols[symbol] = [
                        symbol_ranked, symbol_info[1]
                    ]
                else:
                    non_unique_symbols[symbol].append(symbol_info[1])

                if not isinstance(symbol_ranked, list):
                    symbol_ranked = [symbol_ranked]
                symbol_ranked.append(symbol_info[1])
                symbols_ranked[symbol] = symbol_ranked
            else:
                symbols_ranked[symbol] = symbol_info[1]

        # Save symbols sorted alphabetically
        self.symbols = OrderedDict(
            sorted(symbols_ranked.items(), key=lambda t: t[0]))
        with open(self.symbols_path, 'w') as f:
            f.write(json.dumps(self.symbols, indent=2))

        # Save non unique symbols sorted alphabetically
        non_unique_symbols_sorted = OrderedDict(
            sorted(non_unique_symbols.items(), key=lambda t: t[0]))
        if len(non_unique_symbols) > 0:
            with open(self.symbols_conflicting_path, 'w') as f:
                f.write(json.dumps(non_unique_symbols_sorted, indent=2))
            logging.debug('The following symbols are not unique: ' +
                          ','.join(sorted(non_unique_symbols_sorted)))

    @staticmethod
    def _load_dict_from_json(json_path):
        if os.path.exists(json_path):
            return json.load(open(json_path))
        else:
            return {}

    @staticmethod
    def _convert_to_symbol_info(ticker):
        """Convert a ticker to symbol_info by extracting symbol, name and id"""
        id = ticker['id']
        name = ticker['name']
        symbol = ticker['symbol']
        result = [symbol, {'name': name, 'id': id}]
        return result

    def _get_symbol_info(self, symbol):
        """Get symbol info, `None` if the symbol is not found, or a list if many coins use the same symbol"""
        symbol = symbol.upper()
        alias = self.symbols_aliases.get(symbol)
        symbol_info = self.symbols.get(alias or symbol)
        if symbol_info is None:
            logging.error(
                f'Currency {symbol} not found in our coinmarketcap list.')
            return None
        return symbol_info

    def _get_ticker_price(self, ticker):
        return float(ticker['quotes'][self.convert_currency]['price'])

    def get_coin_id(self, symbol):
        """Get symbol id, `None` is the symbol is not found, or a list if many coins use the same symbol"""
        currency_info = self._get_symbol_info(symbol)
        if currency_info is None:
            return None

        if isinstance(currency_info, list):
            return currency_info

        return currency_info['id']

    def get_price(self, symbol, get_first=None):
        """
        Get price by symbol

        :param symbol: coin symbol, e.g. BTC, ETH, LTC
        :param get_first: if true, if a symbol is used by several coins, it will return the price of the first coin,
        else it will return a list of symbol_info (coin id and name) including also the price
        :return: None, a price or a list of symbol_info with price
        """
        get_first = get_first or self.first_price

        currency_id = self.get_coin_id(symbol)
        if currency_id is None:
            return None

        if not isinstance(currency_id, list):
            ticker = self.tickers[str(currency_id)]
            return self._get_ticker_price(ticker)
        else:
            if get_first:
                ticker = self.tickers[str(currency_id[0]['id'])]
                return self._get_ticker_price(ticker)
            else:
                for currency_info in currency_id:
                    currency_info_id = currency_info['id']
                    ticker = self.tickers[str(currency_info_id)]
                    price = self._get_ticker_price(ticker)
                    currency_info.update({'price': price})
                return currency_id

    def get_symbol_by_name(self, name):
        """Get symbol by coin name"""
        alias = self.coins_aliases.get(name.lower())
        search_name = (alias or name).lower()
        result = None
        for symbol, symbol_info in self.symbols.items():
            if not isinstance(symbol_info, list):
                symbol_info = [symbol_info]

            for info in symbol_info:
                if info['name'].lower() == search_name:
                    result = symbol
                    break
        return result
    def run(self):
        context = zmq.Context()
        sub = context.socket(zmq.SUB)
        sub.connect(f"tcp://{self.addr}:{self.be}")
        sub.setsockopt(zmq.SUBSCRIBE, b'info')

        publisher = context.socket(zmq.PUB)
        publisher.bind(f"tcp://{self.addr}:{self.fe}")

        coinmarketcap = Market()
        cmc_ = coinmarketcap.listings()

        for i in cmc_['data']:
            if i['symbol'] not in self.cmc_list:
                self.cmc_list[i['symbol']] = {
                    "name": i['name'],
                    "id": i['id'],
                }
        while True:

            # -------------------------------------
            # process info
            # -------------------------------------
            try:
                rcv = sub.recv(flags=zmq.NOBLOCK)
            except zmq.Again as e:
                pass
            else:

                topic, payload = rcv.split(b'@', 1)
                payload = json.loads(payload)
                exchange = payload['exchange']

                # ----------------------------------------------------------------------
                # Add coins from exchange_info to local dict self.marketcup['marketcup']
                # ----------------------------------------------------------------------

                if exchange not in self.marketcup:
                    self.marketcup[exchange] = {}

                for i in payload['active_symbols']:
                    target, market = i.split('/')
                    # -------------------------------
                    # marketcup by exchange
                    # -------------------------------
                    if target not in self.marketcup[exchange]:
                        self.marketcup[exchange][target] = {}

                    if target not in self.marketcup['marketcup']:
                        self.marketcup['marketcup'][target] = {}

                        if target in self.cmc_list:
                            self.marketcup['marketcup'][
                                target] = self.cmc_list[target]

            # ---------------------------------------------------
            #  Request update from CoinMarketCum every x minutes
            # ---------------------------------------------------
            if datetime.datetime.now() > self.next_cmc_update:
                if len(self.marketcup['marketcup']) > 0:
                    self.next_cmc_update = datetime.datetime.now(
                    ) + datetime.timedelta(minutes=CMC_TICK_TIMER)

                for key, value in self.marketcup['marketcup'].items():
                    if 'id' in value.keys(
                    ):  # Если такой коин есть на маркет кап

                        try:
                            cmc_tick = coinmarketcap.ticker(value['id'],
                                                            convert='USD')
                        except Exception as e:
                            print(self.name, e)
                        else:
                            if self.update_coin(key, cmc_tick['data']):
                                subscribe_str = f"cmc-{key}@"
                                publisher.send_string(
                                    subscribe_str + json.dumps(
                                        self.marketcup['marketcup'][key]))
                                #print('updte for:',subscribe_str)

                    sleep(1.5)
            # -------------------------------------
            #  Push collected CMC every X seconds
            # -------------------------------------
            if datetime.datetime.now() > self.next_cmc_push_timer:
                self.next_cmc_push_timer = datetime.datetime.now(
                ) + datetime.timedelta(seconds=CMC_PUSH_TIMER)

                for i_coin in self.marketcup['marketcup'].keys():
                    if 'last_updated' in self.marketcup['marketcup'][
                            i_coin].keys():
                        subscribe_str = f"cmc-{i_coin}@"
                        publisher.send_string(
                            subscribe_str +
                            json.dumps(self.marketcup['marketcup'][i_coin]))
                        #print(self.name, i_coin, subscribe_str, self.marketcup['marketcup'][i_coin])

            sleep(0.1)
def getMarket(nrOfPositions):

    coinmarketcap = Market()
    linstings = coinmarketcap.listings()
    ticker = coinmarketcap.ticker(start=0, limit=nrOfPositions, convert='USD')
    return ticker
Esempio n. 9
0
class CoinMarket:
    """Handles CoinMarketCap API features"""
    def __init__(self, api_key):
        """
        Initiates CoinMarket
        """
        self.market = Market(api_key)

    def fiat_check(self, fiat):
        """
        Checks if fiat is valid. If invalid, raise FiatException error.

        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - uppercase fiat
        """
        if fiat is not fiat.upper():
            fiat = fiat.upper()
        if fiat not in fiat_currencies:
            error_msg = "This fiat currency is not supported: `{}`".format(
                fiat)
            raise FiatException(error_msg)
        return fiat

    def format_price(self, price, fiat, symbol=True):
        """
        Formats price under the desired fiat

        @param price - price to format
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @param symbol - if True add currency symbol to fiat
                        if False symbol will not be added
        @return - formatted price under fiat
        """
        c = CurrencyConverter()
        ucase_fiat = fiat.upper()
        price = float(c.convert(float(price), "USD", fiat))
        if symbol:
            if ucase_fiat in fiat_suffix:
                formatted_fiat = "{:,.6f} {}".format(
                    float(price), fiat_currencies[ucase_fiat])
            else:
                formatted_fiat = "{}{:,.6f}".format(
                    fiat_currencies[ucase_fiat], float(price))
        else:
            formatted_fiat = str(price)
        formatted_fiat = formatted_fiat.rstrip('0')
        if formatted_fiat.endswith('.'):
            formatted_fiat = formatted_fiat.replace('.', '')
        return formatted_fiat

    def fetch_currency_data(self, fiat="USD"):
        """
        Fetches all cryptocurrency data

        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - currency data
        """
        try:
            return self.market.listings(limit=5000, convert=fiat)
        except RequestException as e:
            logger.error("Failed to retrieve data - "
                         "Connection error: {}".format(str(e)))
            return None
        except Exception as e:
            raise CurrencyException(
                "Failed to fetch all cryptocurrencies: `{}`".format(str(e)))

    def _format_currency_data(self, data, fiat, single_search=True):
        """
        Formats the data fetched

        @param currency - the cryptocurrency to search for (i.e. 'bitcoin',
                          'ethereum')
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @param single_search - separate more lines if True
        @return - formatted currency data
        """
        try:
            price = CurrencyConverter()
            isPositivePercent = True
            formatted_data = ''
            hour_trend = ''
            if data['quote']['USD']['percent_change_24h'] is not None:
                if float(data['quote']['USD']['percent_change_24h']) >= 0:
                    hour_trend = SMALL_GREEN_TRIANGLE
                else:
                    hour_trend = SMALL_RED_TRIANGLE
                    isPositivePercent = False
            header = "[__**#{}. {} ({})**__ {}](https://coinmarketcap.com/currencies/{})".format(
                data['cmc_rank'], data['name'], data['symbol'], hour_trend,
                data['slug'])
            converted_price = float(
                price.convert(float(data['quote']['USD']['price']), 'USD',
                              fiat))
            converted_price = "{:,.6f}".format(converted_price).rstrip('0')
            if converted_price.endswith('.'):
                converted_price = converted_price.replace('.', '')
            # formatted_btc = '{:,.8f}'.format(float(data['price_btc'])).rstrip('0')
            # if formatted_btc.endswith('.'):
            #     formatted_btc = formatted_btc.replace('.', '')
            # eth_price = eth_price.rstrip('.')
            # if single_search:
            #     eth_price += '\n'
            if data['quote']['USD']['market_cap'] is None:
                formatted_market_cap = 'Unknown'
            else:
                converted_market_cap = price.convert(
                    float(data['quote']['USD']['market_cap']), 'USD', fiat)
            if data['quote']['USD']['volume_24h'] is None:
                formatted_volume_24h = 'Unknown'
            else:
                converted_volume_24h = price.convert(
                    float(data['quote']['USD']['volume_24h']), 'USD', fiat)
            if fiat in fiat_suffix:
                formatted_price = '**{} {}**'.format(converted_price,
                                                     fiat_currencies[fiat])
                if data['quote']['USD']['market_cap'] is not None:
                    formatted_market_cap = '**{:,} {}**'.format(
                        int(converted_market_cap), fiat_currencies[fiat])
                if data['quote']['USD']['volume_24h'] is not None:
                    formatted_volume_24h = '**{:,} {}**'.format(
                        int(converted_volume_24h), fiat_currencies[fiat])
            else:
                formatted_price = '**{}{}**'.format(fiat_currencies[fiat],
                                                    converted_price)
                if data['quote']['USD']['market_cap'] is not None:
                    formatted_market_cap = '**{}{:,}**'.format(
                        fiat_currencies[fiat], int(converted_market_cap))
                if data['quote']['USD']['volume_24h'] is not None:
                    formatted_volume_24h = '**{}{:,}**'.format(
                        fiat_currencies[fiat], int(converted_volume_24h))
            if (data['circulating_supply'] is None):
                circulating_supply = 'Unknown'
            else:
                circulating_supply = '**{:,}**'.format(
                    int(float(data['circulating_supply'])))
            if (data['max_supply'] is None):
                max_supply = 'Unknown'
            else:
                max_supply = '**{:,}**'.format(int(float(data['max_supply'])))
            if single_search:
                formatted_volume_24h += '\n'
                max_supply += '\n'
            percent_change_1h = '**{}%**'.format(
                data['quote']['USD']['percent_change_1h'])
            percent_change_24h = '**{}%**'.format(
                data['quote']['USD']['percent_change_24h'])
            percent_change_7d = '**{}%**'.format(
                data['quote']['USD']['percent_change_7d'])
            formatted_data = (
                "{}\n"
                "Price ({}): {}\n"
                # "Price (BTC): **{}**\n"
                # "Price (ETH): **{}**\n"
                "Market Cap ({}): {}\n"
                "Volume 24h ({}): {}\n"
                "Circulating Supply: {}\n"
                "Max Supply: {}\n"
                "Percent Change (1H): {}\n"
                "Percent Change (24H): {}\n"
                "Percent Change (7D): {}\n"
                "".format(
                    header,
                    fiat,
                    formatted_price,
                    # formatted_btc,
                    # eth_price,
                    fiat,
                    formatted_market_cap,
                    fiat,
                    formatted_volume_24h,
                    circulating_supply,
                    max_supply,
                    percent_change_1h,
                    percent_change_24h,
                    percent_change_7d))
            return formatted_data, isPositivePercent
        except Exception as e:
            raise CoinMarketException("Failed to format data ({}): {}".format(
                data['name'], e))

    def get_current_currency(self, market_list, acronym_list, currency, fiat):
        """
        Obtains the data of the specified currency and returns them using
        the current updated market list

        @param market_list - list of entire crypto market
        @param acronym_list - list of cryptocurrency acronyms
        @param currency - the cryptocurrency to search for (i.e. 'bitcoin',
                          'ethereum')
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        """
        try:
            isPositivePercent = False
            fiat = self.fiat_check(fiat)
            if currency.upper() in acronym_list:
                currency = acronym_list[currency.upper()]
                if "Duplicate" in currency:
                    return currency, isPositivePercent, None
            if currency not in market_list:
                raise CurrencyException(
                    "Invalid currency: `{}`".format(currency))
            data = market_list[currency]
            # eth_price = self.get_converted_coin_amt(market_list, currency, ETHEREUM, 1)
            formatted_data, isPositivePercent = self._format_currency_data(
                data, fiat)
            id_number = market_list[currency]['id']
            return formatted_data, isPositivePercent, id_number
        except CurrencyException as e:
            raise
        except FiatException as e:
            raise
        except Exception as e:
            raise CoinMarketException(e)

    def fetch_coinmarket_stats(self, fiat="USD"):
        """
        Fetches the coinmarket stats

        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - market stats
        """
        try:
            return self.market.stats(convert=fiat)
        except RequestException as e:
            logger.error("Failed to retrieve data - "
                         "Connection error: {}".format(str(e)))
            return None
        except Exception as e:
            raise MarketStatsException(
                "Unable to retrieve crypto market stats "
                "at this time.")

    def _format_coinmarket_stats(self, stats, fiat):
        """
        Receives and formats coinmarket stats

        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - formatted stats
        """
        try:
            c = CurrencyConverter()
            formatted_stats = ''
            if stats['data']['quote']['USD']['total_market_cap'] is None:
                formatted_stats += "Total Market Cap (USD): Unknown"
            else:
                converted_price = int(
                    c.convert(
                        float(
                            stats['data']['quote']['USD']['total_market_cap']),
                        'USD', fiat))
                if fiat in fiat_suffix:
                    formatted_stats += "Total Market Cap ({}): **{:,} {}**\n".format(
                        fiat, converted_price, fiat_currencies[fiat])
                else:
                    formatted_stats += "Total Market Cap ({}): **{}{:,}**\n".format(
                        fiat, fiat_currencies[fiat], converted_price)
            if stats['data']['quote']['USD']['total_volume_24h'] is None:
                formatted_stats += "Total Volume 24h (USD): Unknown"
            else:
                converted_price = int(
                    c.convert(
                        float(
                            stats['data']['quote']['USD']['total_volume_24h']),
                        'USD', fiat))
                if fiat in fiat_suffix:
                    formatted_stats += "Total Volume 24h ({}): **{:,} {}**\n".format(
                        fiat, converted_price, fiat_currencies[fiat])
                else:
                    formatted_stats += "Total Volume 24h ({}): **{}{:,}**\n".format(
                        fiat, fiat_currencies[fiat], converted_price)
            formatted_stats += "Bitcoin Dominance: **{}%**\n".format(
                stats['data']['btc_dominance'])
            formatted_stats += "Ethereum Dominance: **{}%**\n".format(
                stats['data']['eth_dominance'])
            formatted_stats += "Active Exchanges: **{:,}**\n".format(
                stats['data']['active_exchanges'])
            formatted_stats += "Active Currencies: **{:,}**\n".format(
                stats['data']['active_cryptocurrencies'])
            return formatted_stats
        except Exception as e:
            raise CoinMarketException("Failed to format data: `{}`".format(e))

    def get_current_stats(self, market_stats, fiat):
        """
        Returns the market stats

        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - formatted market stats
        """
        try:
            fiat = self.fiat_check(fiat)
            formatted_stats = self._format_coinmarket_stats(market_stats, fiat)
            return formatted_stats
        except FiatException as e:
            raise
        except MarketStatsException as e:
            raise
        except Exception as e:
            raise CoinMarketException(e)

    def get_current_multiple_currency(self,
                                      market_list,
                                      acronym_list,
                                      currency_list,
                                      fiat,
                                      cached_data=None):
        """
        Returns updated info of multiple coin stats using the current
        updated market list
        @param market_list - list of entire crypto market
        @param acronym_list - list of cryptocurrency acronyms
        @param cached_data - a cache of formatted cryptocurrency data
        @param currency_list - list of cryptocurrencies to retrieve
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - list of formatted cryptocurrency data
        """
        try:
            formatted_data = []
            data_list = []
            result_msg = ''
            for currency in currency_list:
                try:
                    if acronym_list is not None:
                        if currency.upper() in acronym_list:
                            currency = acronym_list[currency.upper()]
                            if "Duplicate" in currency:
                                return [[currency]]
                        if market_list[currency] not in data_list:
                            data_list.append(market_list[currency])
                    else:
                        if market_list[currency] not in data_list:
                            data_list.append(market_list[currency])
                except Exception as e:
                    raise CurrencyException("Invalid currency: `{}`"
                                            "".format(currency))
            data_list.sort(key=lambda x: int(x['cmc_rank']))
            for data in data_list:
                # eth_price = self.get_converted_coin_amt(market_list,
                #                                         data['id'],
                #                                         ETHEREUM,
                #                                         1)
                if cached_data is None:
                    formatted_msg = self._format_currency_data(
                        data,
                        # eth_price,
                        fiat,
                        False)[0]
                else:
                    if cached_data:
                        if fiat not in cached_data:
                            cached_data[fiat] = {}
                        if data['id'] not in cached_data[fiat]:
                            formatted_msg = self._format_currency_data(
                                data,
                                # eth_price,
                                fiat,
                                False)[0]
                            cached_data[fiat][data['id']] = formatted_msg
                        else:
                            formatted_msg = cached_data[fiat][data['id']]
                    else:
                        formatted_msg = self._format_currency_data(
                            data,
                            # eth_price,
                            fiat,
                            False)[0]
                        if fiat not in cached_data:
                            cached_data[fiat] = {}
                        if data['id'] not in cached_data[fiat]:
                            cached_data[fiat][data['id']] = formatted_msg
                if len(result_msg) + len(formatted_msg) < 2000:
                    result_msg += "{}\n".format(formatted_msg)
                else:
                    formatted_data.append(result_msg)
                    result_msg = "{}\n".format(formatted_msg)
            formatted_data.append(result_msg)
            return formatted_data, cached_data
        except CurrencyException as e:
            raise
        except FiatException as e:
            raise
        except Exception as e:
            raise CoinMarketException(e)

    def get_converted_coin_amt(self, market_list, currency1, currency2,
                               currency_amt):
        """
        Converts coin to coin based on btc price
        """
        try:
            price_btc1 = float(market_list[currency1]['price_btc'])
            price_btc2 = float(market_list[currency2]['price_btc'])
            btc_amt = float("{:.8f}".format(currency_amt * price_btc1))
            converted_amt = "{:.8f}".format(btc_amt / price_btc2).rstrip('0')
            return converted_amt
        except Exception as e:
            print("Failed to convert coin. See error.log.")
            logger.error("Exception: {}".format(str(e)))
Esempio n. 10
0
from coinmarketcap import Market

coinmarketcap = Market()
coinmarketcap.listings()
{
    "cached":
    false,
    "data": [{
        "symbol": "BTC",
        "website_slug": "bitcoin",
        "id": 1,
        "name": "Bitcoin"
    }, {
        "symbol": "LTC",
        "website_slug": "litecoin",
        "id": 2,
        "name": "Litecoin"
    }, {
        "symbol": "NMC",
        "website_slug": "namecoin",
        "id": 3,
        "name": "Namecoin"
    }, ...],
    "metadata": {
        "timestamp": 1525776852,
        "num_cryptocurrencies": 1597,
        "error": null
    }
}
Esempio n. 11
0
class Strategy:
    def __init__(self, exchange=None, **kwargs):
        print('Strategy initializing...')
        self.exchange = exchange if exchange else DEFAULT_EXCHANGE
        self.type = ROLLBACK
        self.purchase_different_coins = 4  # 3-10 recommended
        self.drop_range_to_buy_pct = range(-40, -10)
        self.deposit_threshold_pct = 50
        self.capitalization_threshold_usd = float(20000000.0)  # > 30 billions recommended
        self.market_volume_threshold_usd_24h = 500000
        self.your_margin_pct = 5
        self.market = Market()
        self.drops = None
        self.suitable_coins_marketcap = {}
        self.suitable_tickers = []
        self.coins_listing = {item['symbol']: {'id': item['id'], 'name': item['name']} for item in self.market.listings()['data']}
        self.crypto_only = False  # include tokens, ico etc.
        self.currencies = None
        self.profit_policy = HALF_REINVEST
        for key in kwargs:
            if hasattr(self, key):
                setattr(self, key, kwargs[key])

    def fetch_currencies(self):
        curs = self.exchange.fetch_currencies()
        if self.crypto_only:
            curs = dict((k + '/' + BASE_TICKER, v) for k, v in curs.items() if v['type'] == 'crypto')
        else:
            curs = dict((k + '/' + BASE_TICKER, v) for k, v in curs.items())
        self.currencies = curs

    def fetch_suitable_coins(self):
        self.fetch_currencies()
        try:
            tickers = self.exchange.fetch_tickers()
        except:
            tickers = {}
        self.drops = {pair: data for pair, data in tickers.items()
                      if pair.endswith(BASE_TICKER)
                      and data['percentage'] is not None
                      and int(data['percentage']) in self.drop_range_to_buy_pct
                      and pair in self.currencies}
        if self.market:
            for pair, market_data in self.drops.items():
                ticker = pair.split('/')[0]
                if ticker in self.coins_listing:
                    market_cap_id = self.coins_listing[ticker]['id']
                    if bool(market_cap_id):
                        market_data = self.market.ticker(market_cap_id, convert=USD)['data']['quotes'][USD]
                        capital = market_data['market_cap']
                        if isinstance(capital, float):
                            if capital >= self.capitalization_threshold_usd:
                                    print(ticker, self.coins_listing[ticker]['name'], capital)
                                    self.suitable_coins_marketcap[ticker] = capital
                else:
                    print('Capitalization is unknown: {}... pass'.format(ticker))
                if len(self.suitable_coins_marketcap) > 0:
                    scm = self.suitable_coins_marketcap
                    self.suitable_tickers = sorted(scm, key=scm.get, reverse=True)[:self.purchase_different_coins]
Esempio n. 12
0
"""Module responsible for quoting prices, executing trades and monitoring open positions.
Right now only works with Bittrex but will be expanded to support Binance

"""
import json
from bittrex.bittrex import Bittrex
my_bittrex = Bittrex(None, None)

from coinmarketcap import Market

cmc = Market()
listings = cmc.listings()['data']

# count = listings['metadata']['num_cryptocurrencies']


def getCurrency(symbol):
    result = getexists(symbol)
    if result is not None:
        return cmc.ticker(result)['data']


def quote(symbol):
    result = getexists(symbol)
    if result is not None:
        return cmc.ticker(result)['data']['quotes']['USD']['price']


def getexists(symbol):
    for listing in listings:
        if listing['symbol'] == symbol:
Esempio n. 13
0
'''
(int) start - return results from rank [start] and above (default is 1)
(int) limit - return a maximum of [limit] results (default is 100; max is 100)
(string) convert - return pricing info in terms of another currency. Valid fiat
currency values are: "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR",
"GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", 
"PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR" 
Valid cryptocurrency values are: "BTC", "ETH" "XRP", "LTC", and "BCH"
'''

from coinmarketcap import Market

coinmarketcap = Market()

all_coin_list = coinmarketcap.listings()

coin_data = coinmarketcap.ticker(start=0, limit=200, convert='INR')

print(coin_data)