def getAllMarkets(limit=None):
    cap = Market()

    if not limit:
        stats = cap.stats()
        limit = stats['active_currencies'] + stats['active_assets']

    return cap.ticker(limit=limit)
Exemple #2
0
def get_market_cap():
    try:
        coinmarketcap = Market()
    except:
        return 'Неполадки на сервере coinmarketcap'
    request = coinmarketcap.stats()
    return 'Market Cap: ' + str(
        round(request['total_market_cap_usd'] / 1000000000, 3)) + ' B'
Exemple #3
0
def get_market():
    try:
        coinmarketcap = Market()
    except:
        return 'Неполадки на сервере coinmarketcap'
    request = coinmarketcap.stats()
    return '*Market Cap:* ' + str(round(request['total_market_cap_usd'] / 1000000000, 3)) + ' B' + '\n' + \
           '24h Vol: ' + str(round(request['total_24h_volume_usd'] / 1000000000, 3)) + ' B' + '\n' + \
           'BTC Dominance: ' + str(round(request['bitcoin_percentage_of_market_cap'], 2)) + '%' + '\n' + \
           'Active currencies: ' + str(int(request['active_currencies']))
Exemple #4
0
    def refresh(self):
        coinmarketcap = Market()
        dict = coinmarketcap.stats()
        rows = []
        for key, value in dict.items():
            rows.append((key, value, 0))

        data = pd.DataFrame(data=rows, columns=['key', 'value', 'index'])
        self.__dataframe = data.pivot(columns='key', values='value', index='index')
        self.__dataframe['insertion_time'] = self. __insertion_time
Exemple #5
0
import urllib.request
from bs4 import BeautifulSoup
from goose3 import Goose

from coinmarketcap import Market
coinmarketcap = Market()
stat = coinmarketcap.ticker(start=0, limit=10)
pv = []
pl = []
pv2 = []
for i in stat:
    pl.append(i["id"])
    pv.append(i["market_cap_usd"])
#print(stat[0]['id'])
#print(pv)
stat1 = coinmarketcap.stats()
bitcoin_per = stat1["bitcoin_percentage_of_market_cap"]
#print(bitcoin_per)
bit = coinmarketcap.ticker('bitcoin')
bit_p = bit[0]["market_cap_usd"]
#print(bit_p)

#print(pv[0].type)

for j in range(len(pv)):
    #print(pv[j])
    pv2.append((float(pv[j]) * float(bitcoin_per)) / float(bit_p))

pl.append("Others")
pv2.append(100 - sum(pv2))
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)
Exemple #7
0
class CryptoBot(ChatBot):
    # All the variables related to the new functionalities implemented by the class cryptoBot
    # __defaultCoin is used to know which will be the coin used to report the value of other coins
    # __defaultCurrency is used to know which of the fiat currency is going to be used for reporting
    # __supportedCurrencies will be the list of currencies that coinmarketcap supports in their api
    # __savedStats is where we are going to store all the information about the main stats in the market
    # __savedTickers is where we are going to store all the information related to the coins based on their currency
    # __currencyPerson is where we will store if someone changes their currency and which are they going to use
    # __lastUpdatedStats is the timestamp of the last update in the stats
    # __lastUpdatedTickers is the timestamp of the last update in the tickers
    # __updateInterval is the value in seconds of the minimum amount of time needed to update the stats and tickers again
    __defaultCoin = "BTC"
    __defaultCurrency = "USD"
    __supportedCurrencies = [
        "USD", "AUD", "BRL", "CAD", "CHF", "CNY", "EUR", "GBP", "HKD", "IDR",
        "INR", "JPY", "KRW", "MXN", "RUB"
    ]
    __savedStats = {}
    __savedTickers = {}
    __currencyPerson = {}
    __lastUpdatedStats = {}
    __lastUpdatedTickers = {}
    __updateInterval = None

    # __coinMarketCap is the object created by the coinMarketCap api that will get us all the information from them
    __coinMarketCap = None
    # __exchangerList is the list of exchanger objects that we will use for the functionalities related to the exchangers
    __exchangerList = None

    # Setup of all variables
    def __init__(self,
                 token,
                 superadminid,
                 adminsid=[],
                 exchangers=[],
                 updateInterval=300,
                 debuglevel=0):
        super(CryptoBot, self).__init__(token, superadminid, adminsid,
                                        debuglevel)
        self._debugLevel = debuglevel
        if (self._debugLevel > 0): print "Debug Level: " + str(debuglevel)

        self.__exchangerList = exchangers
        self.__updateInterval = updateInterval
        if (self._debugLevel >= 1):
            print "Update Interval: " + str(updateInterval)

        self.__coinmarketcap = Market()

        for currency in self.__supportedCurrencies:
            if (self._debugLevel >= 1): print "Supported Currency: " + currency
            self.__lastUpdatedStats[currency] = datetime.datetime.min
            self.__lastUpdatedTickers[currency] = datetime.datetime.min
            self.__getStats(currency)
            self.__getTickers(currency)

        if (self._debugLevel >= 1): print "Adding Handlers"
        self._addCommandHandler('currency', self.__setCurrency, pass_args=True)
        self._addCommandHandler('fiatPrice',
                                self.__getPriceFiat,
                                pass_args=True)
        self._addCommandHandler('price', self.__getPriceCoin, pass_args=True)
        self._addCommandHandler('rank', self.__getRank, pass_args=True)
        self._addCommandHandler('marketcap',
                                self.__getMarketCap,
                                pass_args=True)
        self._addCommandHandler('volume', self.__getVolume, pass_args=True)
        self._addCommandHandler('change1h',
                                self.__getChangeLastHour,
                                pass_args=True)
        self._addCommandHandler('change24h',
                                self.__getChangeLastDay,
                                pass_args=True)
        self._addCommandHandler('change7d',
                                self.__getChangeLastSevenDays,
                                pass_args=True)
        self._addCommandHandler('coinInfo', self.__getInfoCoin, pass_args=True)

        self._removeHandler(self._unknownHandler)
        self._addHandler(self._unknownHandler)

        return

    # Functions related to bot functionalities with especific exchangers

    # It will add a new exchanger object to the list of exchangers we already have
    def addExchanger(self, exchanger):
        raise NotImplementedError(
            "You need to implement addExchanger before using it")

    # It will remove an exchanger object from the list of exchangers we have
    def removeExchanger(self, exchanger):
        raise NotImplementedError(
            "You need to implement removeExchanger before using it")

    # Function to change the interval between updates
    def setUpdateInterval(self, interval):
        self.__updateInterval = interval

    # Function to get the interval between updates
    def getUpdateInterval(self):
        return self.__updateInterval

    # Function to set an specific user currency
    def setUserCurrency(self, userid, currency):
        self.__currencyPerson[userid] = currency

    # Function to get a user currency settings
    def getUserCurrency(self, userid):
        return self.__currencyPerson.get(userid) or self.__defaultCurrency

    # Related to bot functiuonalities with any info in the coins

    # Function that will create an alarm in case of a coin prices goes above the price we set
    def setAlertPriceAbove(self, coin, price, person):
        raise NotImplementedError(
            "You need to implement setAlertPriceAbove before using it")

    # Function that will create an alarm in case of a coin prices goes below the price we set
    def setAlertPriceBelow(self, coin, price, person):
        raise NotImplementedError(
            "You need to implement setAlertPriceBelow before using it")

    # Function that will remove an alarm
    def removeAlert(self, alertid, person):
        raise NotImplementedError(
            "You need to implement removeAlert before using it")

    # Information related to coins
    def getStringInfo(self, coins, currency=None, field=None):
        if (currency == None):
            currency = self.__defaultCurrency

        infoString = ""

        if (self._debugLevel >= 1): print "Getting String Info"
        if (self._debugLevel >= 2): print "Field: " + str(field)
        if (self._debugLevel >= 2): print "Coins: " + str(coins)

        for coin in coins:
            info = self.getInfo(coin, currency)
            priceInFiat = self.getPriceInFiat(coin, currency)
            priceInCoin = self.getPriceInCoin(coin)
            marketCap = self.getMarketCap(coin, currency)
            volume = self.getVolume(coin, currency)
            change1h = self.getChangeLastHour(coin)
            change24h = self.getChangeLastDay(coin)
            change7d = self.getChangeLastSevenDays(coin)

            if (self._debugLevel >= 2): print "Info: " + str(info)

            if (info != None):
                infoString += "Name of coin: " + info['name'] + " [" + info[
                    'symbol'] + "]\n"

                if (field == None):
                    infoString += "Rank: " + info['rank'] + "\n\n"
                    infoString += "Price in " + currency + ": " + priceInFiat + "\n"
                    infoString += "Price in " + self.__defaultCoin + ": " + priceInCoin + "\n\n"
                    infoString += "Market Cap in " + currency + ": " + marketCap + "\n"
                    infoString += "24h Volume in " + currency + ": " + volume + "\n\n"
                    infoString += "Change 1h: " + change1h + "\n"
                    infoString += "Change 24h: " + change24h + "\n"
                    infoString += "Change 7d: " + change7d + "\n\n"
                elif (field == CoinField.PRICE_FIAT):
                    infoString += "Price in " + currency + ": " + priceInFiat + "\n\n"
                elif (field == CoinField.PRICE_COIN):
                    infoString += "Price in " + self.__defaultCoin + ": " + priceInCoin + "\n\n"
                elif (field == CoinField.MARKET_CAP):
                    infoString += "Market Cap in " + currency + ": " + marketCap + "\n\n"
                elif (field == CoinField.VOLUME):
                    infoString += "24h Volume in " + currency + ": " + volume + "\n\n"
                elif (field == CoinField.CHANGE_1H):
                    infoString += "Change 1h: " + change1h + "\n\n"
                elif (field == CoinField.CHANGE_24H):
                    infoString += "Change 24h: " + change24h + "\n\n"
                elif (field == CoinField.CHANGE_7D):
                    infoString += "Change 7d: " + change7d + "\n\n"
                elif (field == CoinField.RANK):
                    infoString += "Rank: " + info['rank'] + "\n\n"

        if (self._debugLevel >= 2): print "String Info: \n" + infoString
        return infoString

    # This function will get all the info related to a coin
    def getInfo(self, coin, currency=None):
        if (currency == None):
            currency = self.__defaultCurrency

        coinTicker = None
        tickers = self.__getTickers(currency)

        coin = coin.upper()
        for ticker in tickers:
            if (ticker['symbol'].upper() == coin
                    or ticker['name'].upper() == coin
                    or ticker['id'].upper() == coin):
                coinTicker = ticker

        if (self._debugLevel >= 3): print "Info: " + str(coinTicker)
        return coinTicker

    # The function that will return the price in fiat of certain coin
    def getRank(self, coin):
        currency = self.__defaultCurrency
        coinTicker = self.getInfo(coin, currency)

        if (coinTicker == None):
            return None

        keyRank = "rank"

        if (self._debugLevel >= 2): print "Rank: " + coinTicker[keyRank]
        return coinTicker[keyRank]

    # The function that will return the price in fiat of certain coin
    def getPriceInFiat(self, coin, currency=None):
        if (currency == None):
            currency = self.__defaultCurrency

        coinTicker = self.getInfo(coin, currency)

        if (coinTicker == None):
            return None

        keyPrice = "price_" + currency.lower()

        if (self._debugLevel >= 2): print "PriceFiat: " + coinTicker[keyPrice]
        return coinTicker[keyPrice]

    # The function that will return the price in btc of certain coin
    def getPriceInCoin(self, coin):
        currency = self.__defaultCurrency
        coinTicker = self.getInfo(coin, currency)

        if (coinTicker == None):
            return None

        keyPrice = "price_" + self.__defaultCoin.lower()

        if (self._debugLevel >= 2): print "PriceCoin: " + coinTicker[keyPrice]
        return coinTicker[keyPrice]

    # The function that will return the market cap of certain coin
    def getMarketCap(self, coin, currency=None):
        if (currency == None):
            currency = self.__defaultCurrency

        coinTicker = self.getInfo(coin, currency)

        if (coinTicker == None):
            return None

        keyMarketCap = "market_cap_" + currency.lower()

        if (self._debugLevel >= 2):
            print "Market Cap: " + coinTicker[keyMarketCap]
        return coinTicker[keyMarketCap]

    # The function that will return the last 24h volume of certain coin
    def getVolume(self, coin, currency=None):
        if (currency == None):
            currency = self.__defaultCurrency

        coinTicker = self.getInfo(coin, currency)

        if (coinTicker == None):
            return None

        keyVolume = "24h_volume_" + currency.lower()

        if (self._debugLevel >= 2): print "Volume: " + coinTicker[keyVolume]
        return coinTicker[keyVolume]

    # The function that will return the change in price of the last 24h of certain coin
    def getChangeLastDay(self, coin):
        currency = self.__defaultCurrency
        coinTicker = self.getInfo(coin, currency)

        if (coinTicker == None):
            return None

        keyChange = "percent_change_24h"

        if (self._debugLevel >= 2):
            print "Change 24h: " + coinTicker[keyChange]
        return coinTicker[keyChange]

    # The function that will return the change in price of the last 1h of certain coin
    def getChangeLastHour(self, coin):
        currency = self.__defaultCurrency
        coinTicker = self.getInfo(coin, currency)

        if (coinTicker == None):
            return None

        keyChange = "percent_change_1h"

        if (self._debugLevel >= 2): print "Change 1h: " + coinTicker[keyChange]
        return coinTicker[keyChange]

    # The function that will return the change in price of the last 7d of certain coin
    def getChangeLastSevenDays(self, coin):
        currency = self.__defaultCurrency
        coinTicker = self.getInfo(coin, currency)

        if (coinTicker == None):
            return None

        keyChange = "percent_change_7d"

        if (self._debugLevel >= 2): print "Change 7d: " + coinTicker[keyChange]
        return coinTicker[keyChange]

    # Coinmarketcap function wrapper that will helps us to avoid doing a lot of request to get the stats
    def __getStats(self, currency):
        currentTime = datetime.datetime.now()
        lapsedTime = (currentTime -
                      self.__lastUpdatedStats[currency]).total_seconds()

        if (lapsedTime > self.__updateInterval):
            if (self._debugLevel >= 1): print "Updating Stats for: " + currency
            self.__lastUpdatedStats[currency] = currentTime
            if (currency != self.__defaultCurrency
                    and currency in self.__supportedCurrencies):
                self.__savedStats[currency] = self.__coinmarketcap.stats(
                    convert=currency)
            else:
                self.__savedStats[currency] = self.__coinmarketcap.stats()

        return self.__savedStats[currency]

    # Coinmarketcap function wrapper that will helps us to avoid doing a lot of request to get the tickers
    def __getTickers(self, currency):
        currentTime = datetime.datetime.now()
        lapsedTime = (currentTime -
                      self.__lastUpdatedTickers[currency]).total_seconds()

        if (lapsedTime > self.__updateInterval):
            if (self._debugLevel >= 1):
                print "Updating Ticker for: " + currency
            self.__lastUpdatedTickers[currency] = currentTime
            if (currency != self.__defaultCurrency):
                self.__savedTickers[currency] = self.__coinmarketcap.ticker(
                    convert=currency)
            else:
                self.__savedTickers[currency] = self.__coinmarketcap.ticker()

        return self.__savedTickers[currency]

    # Callback functions that the bot will call after receiving a command
    def __setCurrency(self, bot, update, args):
        chatId = update.message.chat_id
        userId = str(update.message.from_user.id)

        if (self._debugLevel >= 1): print "Set Currency command"
        if (self._debugLevel >= 2): print "Args: " + str(args)

        for currency in args:
            if (self._debugLevel >= 2): print "Arg: " + currency
            if (currency in self.__supportedCurrencies):
                self.setUserCurrency(userId, currency)
                returningMessage = "Your currency now was set to " + currency

        if (self._debugLevel >= 1):
            print "Currency for user " + userId + " set to: " + currency

        bot.send_message(chat_id=chatId, text=returningMessage)

        return

    def __getRank(self, bot, update, args):
        chatId = update.message.chat_id
        userId = str(update.message.from_user.id)
        currency = self.__currencyPerson.get(userId)
        field = CoinField.RANK

        if (self._debugLevel >= 1): print "Get Rank command"
        if (self._debugLevel >= 2): print "Args: " + str(args)

        returningMessage = self.getStringInfo(args, currency, field)

        bot.send_message(chat_id=chatId, text=returningMessage)

        return

    def __getPriceFiat(self, bot, update, args):
        chatId = update.message.chat_id
        userId = str(update.message.from_user.id)
        currency = self.__currencyPerson.get(userId)
        field = CoinField.PRICE_FIAT

        if (self._debugLevel >= 1): print "Get Price Fiat command"
        if (self._debugLevel >= 2): print "Args: " + str(args)

        returningMessage = self.getStringInfo(args, currency, field)

        bot.send_message(chat_id=chatId, text=returningMessage)

        return

    def __getPriceCoin(self, bot, update, args):
        chatId = update.message.chat_id
        userId = str(update.message.from_user.id)
        currency = self.__currencyPerson.get(userId)
        field = CoinField.PRICE_COIN

        if (self._debugLevel >= 1): print "Get Price Coin command"
        if (self._debugLevel >= 2): print "Args: " + str(args)

        returningMessage = self.getStringInfo(args, currency, field)

        bot.send_message(chat_id=chatId, text=returningMessage)

        return

    def __getMarketCap(self, bot, update, args):
        chatId = update.message.chat_id
        userId = str(update.message.from_user.id)
        currency = self.__currencyPerson.get(userId)
        field = CoinField.MARKET_CAP

        if (self._debugLevel >= 1): print "Get Market Cap coomand"
        if (self._debugLevel >= 2): print "Args: " + str(args)

        returningMessage = self.getStringInfo(args, currency, field)

        bot.send_message(chat_id=chatId, text=returningMessage)

        return

    def __getVolume(self, bot, update, args):
        chatId = update.message.chat_id
        userId = str(update.message.from_user.id)
        currency = self.__currencyPerson.get(userId)
        field = CoinField.VOLUME

        if (self._debugLevel >= 1): print "Get Volume command"
        if (self._debugLevel >= 2): print "Args: " + str(args)

        returningMessage = self.getStringInfo(args, currency, field)

        bot.send_message(chat_id=chatId, text=returningMessage)

        return

    def __getChangeLastDay(self, bot, update, args):
        chatId = update.message.chat_id
        userId = str(update.message.from_user.id)
        currency = self.__currencyPerson.get(userId)
        field = CoinField.CHANGE_24H

        if (self._debugLevel >= 1): print "Get Change 24h command"
        if (self._debugLevel >= 2): print "Args: " + str(args)

        returningMessage = self.getStringInfo(args, currency, field)

        bot.send_message(chat_id=chatId, text=returningMessage)

        return

    def __getChangeLastHour(self, bot, update, args):
        chatId = update.message.chat_id
        userId = str(update.message.from_user.id)
        currency = self.__currencyPerson.get(userId)
        field = CoinField.CHANGE_1H

        if (self._debugLevel >= 1): print "Get Change 1h command"
        if (self._debugLevel >= 2): print "Args: " + str(args)

        returningMessage = self.getStringInfo(args, currency, field)

        bot.send_message(chat_id=chatId, text=returningMessage)

        return

    def __getChangeLastSevenDays(self, bot, update, args):
        chatId = update.message.chat_id
        userId = str(update.message.from_user.id)
        currency = self.__currencyPerson.get(userId)
        field = CoinField.CHANGE_7D

        if (self._debugLevel >= 1): print "Get Change 7d command"
        if (self._debugLevel >= 2): print "Args: " + str(args)

        returningMessage = self.getStringInfo(args, currency, field)

        bot.send_message(chat_id=chatId, text=returningMessage)

        return

    def __getInfoCoin(self, bot, update, args):
        chatId = update.message.chat_id
        userId = str(update.message.from_user.id)
        currency = self.__currencyPerson.get(userId)

        if (self._debugLevel >= 1): print "Get Info command"
        if (self._debugLevel >= 2): print "Args: " + str(args)

        returningMessage = self.getStringInfo(args, currency)

        bot.send_message(chat_id=chatId, text=returningMessage)

        return
Exemple #8
0
from coinmarketcap import Market
from datetime import datetime
from decimal import Decimal
from blockchain import statistics
import pandas as pd
import requests
coinmarketcap = Market()
cnmc_stats = coinmarketcap.stats(convert='USD')
cnmc_ticker = coinmarketcap.ticker(start=0, limit=1, convert='USD')
# CoinMarketCap DATA
last_updated = datetime.fromtimestamp(
    int(cnmc_ticker['data']['1']['last_updated'])).strftime(
        '%Y-%m-%d %H:%M:%S')
btc_price_cmc = cnmc_ticker['data']['1']['quotes']['USD']['price']
btc_volume_24h_cmc = cnmc_ticker['data']['1']['quotes']['USD']['volume_24h']
btc_market_cap = cnmc_ticker['data']['1']['quotes']['USD']['market_cap']
btc_percent_change_1h = cnmc_ticker['data']['1']['quotes']['USD'][
    'percent_change_1h']
btc_percent_change_24h = cnmc_ticker['data']['1']['quotes']['USD'][
    'percent_change_24h']
btc_percent_change_7d = cnmc_ticker['data']['1']['quotes']['USD'][
    'percent_change_7d']
supply_percentage = Decimal(cnmc_ticker['data']['1']['total_supply'] /
                            cnmc_ticker['data']['1']['max_supply'])
btc_dominance = cnmc_stats['data']['bitcoin_percentage_of_market_cap']
total_market_cap = cnmc_stats['data']['quotes']['USD']['total_market_cap']

# Crypto Whale MARKET INFRO - Twitter
# Blockchain Data
stats = statistics.get()
btc_trade_volume = stats.trade_volume_btc
class CoinMarket:
    """Handles CoinMarketCap API features"""
    def __init__(self):
        """
        Initiates CoinMarket

        @param bot - discord bot object
        """
        self.market = Market()

    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, currency="", fiat="", load_all=False):
        """
        Fetches the currency data based on the desired currency

        @param currency - the cryptocurrency to search for (i.e. 'bitcoin',
                          'ethereum')
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @param load_all - True: load all cryptocurrencies
                          False: don't load all cryptocurrencies
        @return - currency data
        """
        try:
            if load_all:
                return self.market.ticker(start=0, limit=0)
            return self.market.ticker(currency, 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 find currency: `{}`. Check "
                                    "if this currency is valid and also check "
                                    "for spelling errors: {}".format(
                                        currency, str(e)))

    def _format_currency_data(self, data, eth_price, 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['percent_change_24h'] is not None:
                if float(data['percent_change_24h']) >= 0:
                    hour_trend = SMALL_GREEN_TRIANGLE
                else:
                    hour_trend = SMALL_RED_TRIANGLE
                    isPositivePercent = False
            header = "__**#{}. {} ({})**__ {}".format(data['rank'],
                                                      data['name'],
                                                      data['symbol'],
                                                      hour_trend)
            converted_price = float(
                price.convert(float(data['price_usd']), '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['market_cap_usd'] is None:
                formatted_market_cap = 'Unknown'
            else:
                converted_market_cap = price.convert(
                    float(data['market_cap_usd']), 'USD', fiat)
            if fiat in fiat_suffix:
                formatted_price = '**{} {}**'.format(converted_price,
                                                     fiat_currencies[fiat])
                if data['market_cap_usd'] is not None:
                    formatted_market_cap = '**{:,} {}**'.format(
                        int(converted_market_cap), fiat_currencies[fiat])
            else:
                formatted_price = '**{}{}**'.format(fiat_currencies[fiat],
                                                    converted_price)
                if data['market_cap_usd'] is not None:
                    formatted_market_cap = '**{}{:,}**'.format(
                        fiat_currencies[fiat], int(converted_market_cap))
            if (data['available_supply'] is None):
                available_supply = 'Unknown'
            else:
                available_supply = '**{:,}**'.format(
                    int(float(data['available_supply'])))
            if single_search:
                available_supply += '\n'
            percent_change_1h = '**{}%**'.format(data['percent_change_1h'])
            percent_change_24h = '**{}%**'.format(data['percent_change_24h'])
            percent_change_7d = '**{}%**'.format(data['percent_change_7d'])
            formatted_data = ("{}\n"
                              "Price ({}): {}\n"
                              "Price (BTC): **{}**\n"
                              "Price (ETH): **{}**\n"
                              "Market Cap ({}): {}\n"
                              "Available 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, available_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_currency(self, acronym_list, currency, fiat):
        """
        Obtains the data of the specified currency and returns them.

        @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:
                try:
                    data = self.fetch_currency_data(
                        acronym_list[currency.upper()], fiat)[0]
                except CurrencyException:
                    formatted_data = acronym_list[currency.upper()]
                    return formatted_data, isPositivePercent
            else:
                data = self.fetch_currency_data(currency, fiat)[0]
            formatted_data, isPositivePercent = self._format_currency_data(
                data, fiat)
            return formatted_data, isPositivePercent
        except CurrencyException as e:
            raise
        except FiatException as e:
            raise
        except Exception as e:
            raise CoinMarketException(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
            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, eth_price, fiat)
            return formatted_data, isPositivePercent
        except CurrencyException as e:
            raise
        except FiatException as e:
            raise
        except Exception as e:
            raise CoinMarketException(e)

    def fetch_coinmarket_stats(self, fiat=''):
        """
        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['total_market_cap_usd'] is None):
                formatted_stats += "Total Market Cap (USD): Unknown"
            else:
                converted_price = int(
                    c.convert(float(stats['total_market_cap_usd']), '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)
            formatted_stats += "Bitcoin Percentage of Market: **{:,}%**\n".format(
                stats['bitcoin_percentage_of_market_cap'])
            formatted_stats += "Active Markets: **{:,}**\n".format(
                stats['active_markets'])
            formatted_stats += "Active Currencies: **{:,}**\n".format(
                stats['active_currencies'])
            formatted_stats += "Active Assets: **{:,}**\n".format(
                stats['active_assets'])

            return formatted_stats
        except Exception as e:
            raise CoinMarketException("Failed to format data: `{}`".format(e))

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

        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - formatted market stats
        """
        try:
            fiat = self.fiat_check(fiat)
            stats = self.fetch_coinmarket_stats(fiat)
            formatted_stats = self._format_coinmarket_stats(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_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_multiple_currency(self, acronym_list, currency_list, fiat):
        """
        Returns updated info of multiple coin stats
        @param acronym_list - list of cryptocurrency acronyms
        @param currency_list - list of cryptocurrencies
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - formatted cryptocurrency data
        """
        try:
            fiat = self.fiat_check(fiat)
            formatted_data = ''
            data_list = []
            for currency in currency_list:
                if acronym_list is not None:
                    if currency.upper() in acronym_list:
                        data_list.append(
                            self.fetch_currency_data(
                                acronym_list[currency.upper()], fiat)[0])
                    else:
                        data_list.append(
                            self.fetch_currency_data(currency, fiat)[0])
                else:
                    data_list.append(
                        self.fetch_currency_data(currency, fiat)[0])
            data_list.sort(key=lambda x: int(x['rank']))
            for data in data_list:
                formatted_data += self._format_currency_data(
                    data, fiat, False)[0] + '\n'
            return formatted_data
        except CurrencyException as e:
            raise
        except FiatException 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:
                    raise CurrencyException("Invalid currency: `{}`"
                                            "".format(currency))
            data_list.sort(key=lambda x: int(x['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 = 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)))
class CoinMarket:
    """Handles CoinMarketCap API features"""
    def __init__(self):
        """
        Initiates CoinMarket

        @param bot - discord bot object
        """
        self.market = Market()

    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()
        if fiat is not "USD":
            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, currency="", fiat="", load_all=False):
        """
        Fetches the currency data based on the desired currency

        @param currency - the cryptocurrency to search for (i.e. 'bitcoin',
                          'ethereum')
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @param load_all - True: load all cryptocurrencies
                          False: don't load all cryptocurrencies
        @return - currency data
        """
        try:
            if load_all:
                return self.market.ticker(start=0, limit=0)
            return self.market.ticker(currency, convert=fiat)
        except Exception as e:
            raise CurrencyException("Failed to find currency: `{}`. Check "
                                    "if this currency is valid and also check "
                                    "for spelling errors.".format(currency))

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

        @param currency - the cryptocurrency to search for (i.e. 'bitcoin',
                          'ethereum')
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - formatted currency data
        """
        try:
            price = CurrencyConverter()
            isPositivePercent = True
            formatted_data = ''
            hour_trend = ''
            if float(data['percent_change_1h']) >= 0:
                hour_trend = '<:small_green_triangle:396586561413578752>'
            else:
                hour_trend = ':small_red_triangle_down:'
                isPositivePercent = False

            formatted_data += '__**#{}. {} ({})**__ {}\n'.format(
                data['rank'], data['name'], data['symbol'], hour_trend)
            if fiat is not "USD":
                converted_price = float(
                    price.convert(float(data['price_usd']), 'USD', fiat))
            converted_price = "{:,.6f}".format(converted_price).rstrip('0')
            if converted_price.endswith('.'):
                converted_price = converted_price.replace('.', '')
            if fiat in fiat_suffix:
                formatted_data += 'Price ({}): **{} {}**\n'.format(
                    fiat, converted_price, fiat_currencies[fiat])
            else:
                formatted_data += 'Price ({}): **{}{}**\n'.format(
                    fiat, fiat_currencies[fiat], converted_price)
            formatted_data += 'Price (BTC): **{:,}**\n'.format(
                float(data['price_btc']))
            if (data['market_cap_usd'] is None):
                formatted_data += 'Market Cap ({}): Unknown\n'.format(fiat)
            else:
                converted_price = float(
                    price.convert(float(data['market_cap_usd']), 'USD', fiat))
                formatted_data += 'Market Cap ({}): **${:,}**\n'.format(
                    fiat, converted_price)
            if (data['available_supply'] is None):
                formatted_data += 'Available Supply: Unknown\n'
            else:
                formatted_data += 'Available Supply: **{:,}**\n'.format(
                    float(data['available_supply']))
            formatted_data += 'Percent Change (1H): **{}%**\n'.format(
                data['percent_change_1h'])
            formatted_data += 'Percent Change (24H): **{}%**\n'.format(
                data['percent_change_24h'])
            formatted_data += 'Percent Change (7D): **{}%**\n'.format(
                data['percent_change_7d'])

            return formatted_data, isPositivePercent
        except Exception as e:
            raise CoinMarketException("Failed to format data: {}".format(e))

    def get_currency(self, acronym_list, currency, fiat):
        """
        Obtains the data of the specified currency and returns them.

        @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:
                try:
                    data = self.fetch_currency_data(
                        acronym_list[currency.upper()], fiat)[0]
                except CurrencyException:
                    formatted_data = acronym_list[currency.upper()]
                    return formatted_data, isPositivePercent
            else:
                data = self.fetch_currency_data(currency, fiat)[0]
            formatted_data, isPositivePercent = self._format_currency_data(
                data, fiat)
            return formatted_data, isPositivePercent
        except CurrencyException as e:
            raise
        except FiatException as e:
            raise
        except Exception as e:
            raise CoinMarketException(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
            if currency not in market_list:
                raise CurrencyException(
                    "Invalid currency: `{}`".format(currency))
            data = market_list[currency]
            formatted_data, isPositivePercent = self._format_currency_data(
                data, fiat)
            return formatted_data, isPositivePercent
        except CurrencyException as e:
            raise
        except FiatException as e:
            raise
        except Exception as e:
            raise CoinMarketException(e)

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

        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - market stats
        """
        try:
            return self.market.stats(convert=fiat)
        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['total_market_cap_usd'] is None):
                formatted_stats += "Total Market Cap (USD): Unknown"
            else:
                if fiat is not "USD":
                    converted_price = c.convert(
                        float(stats['total_market_cap_usd']), '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)
            formatted_stats += "Bitcoin Percentage of Market: **{:,}%**\n".format(
                stats['bitcoin_percentage_of_market_cap'])
            formatted_stats += "Active Markets: **{:,}**\n".format(
                stats['active_markets'])
            formatted_stats += "Active Currencies: **{:,}**\n".format(
                stats['active_currencies'])
            formatted_stats += "Active Assets: **{:,}**\n".format(
                stats['active_assets'])

            return formatted_stats
        except Exception as e:
            raise CoinMarketException("Failed to format data: `{}`".format(e))

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

        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - formatted market stats
        """
        try:
            fiat = self.fiat_check(fiat)
            stats = self.fetch_coinmarket_stats(fiat)
            formatted_stats = self._format_coinmarket_stats(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_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_multiple_currency(self, acronym_list, currency_list, fiat):
        """
        Returns updated info of multiple coin stats
        @param acronym_list - list of cryptocurrency acronyms
        @param currency_list - list of cryptocurrencies
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - formatted cryptocurrency data
        """
        try:
            fiat = self.fiat_check(fiat)
            formatted_data = ''
            data_list = []
            for currency in currency_list:
                if acronym_list is not None:
                    if currency.upper() in acronym_list:
                        data_list.append(
                            self.fetch_currency_data(
                                acronym_list[currency.upper()], fiat)[0])
                    else:
                        data_list.append(
                            self.fetch_currency_data(currency, fiat)[0])
                else:
                    data_list.append(
                        self.fetch_currency_data(currency, fiat)[0])
            data_list.sort(key=lambda x: int(x['rank']))
            for data in data_list:
                formatted_data += self._format_currency_data(data,
                                                             fiat)[0] + '\n'
            return formatted_data
        except CurrencyException as e:
            raise
        except FiatException as e:
            raise
        except Exception as e:
            raise CoinMarketException(e)

    def get_current_multiple_currency(self, market_list, acronym_list,
                                      currency_list, fiat):
        """
        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 currency_list - list of cryptocurrencies to retrieve
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - list of formatted cryptocurrency data
        """
        try:
            fiat = self.fiat_check(fiat)
            formatted_data = []
            data_list = []
            result_msg = ''
            for currency in currency_list:
                try:
                    if currency.upper() in acronym_list:
                        currency = acronym_list[currency.upper()]
                        if "Duplicate" in currency:
                            return currency
                    data_list.append(market_list[currency])
                except:
                    raise CurrencyException(
                        "Invalid currency: `{}`".format(currency))
            data_list.sort(key=lambda x: int(x['rank']))
            for data in data_list:
                formatted_msg = self._format_currency_data(data, fiat)[0]
                if len(result_msg + formatted_msg) < 2000:
                    result_msg += formatted_msg + '\n'
                else:
                    formatted_data.append(result_msg)
                    result_msg = '{}'.format(formatted_msg)
            formatted_data.append(result_msg)
            return formatted_data
        except CurrencyException as e:
            raise
        except FiatException as e:
            raise
        except Exception as e:
            raise CoinMarketException(e)
Exemple #11
0
class CoinMarket:
    """
    Handles CoinMarketCap API features
    """
    def __init__(self):
        """
        Initiates CoinMarket

        @param bot - discord bot object
        """
        self.market = Market()

    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):
        """
        Formats price under the desired fiat

        @param price - price to format
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - formatted price under fiat
        """
        ucase_fiat = fiat.upper()
        if ucase_fiat in fiat_suffix:
            formatted_fiat = "{:,.2f} {}".format(float(price),
                                                 fiat_currencies[ucase_fiat])
        else:
            formatted_fiat = "{}{:,.2f}".format(fiat_currencies[ucase_fiat],
                                                float(price))
        return formatted_fiat

    def load_all_acronyms(self):
        """
        Loads all available acronyms for cryptocurrencies

        @return - all cryptocurrency acronyms
        """
        try:
            acronym_list = {}
            duplicate_count = 0
            data = self.fetch_currency_data(load_all=True)
            for currency in data:
                if currency['symbol'] in acronym_list:
                    duplicate_count += 1
                    logger.warning(
                        "Found duplicate acronym. Creating seperate "
                        "separate definition...")
                    if currency['symbol'] not in acronym_list[
                            currency['symbol']]:
                        acronym_list[currency['symbol'] +
                                     str(1)] = acronym_list[currency['symbol']]
                        acronym_list[currency['symbol']] = (
                            "Duplicate acronyms "
                            "found. Possible "
                            "searches are:\n"
                            "{}1 ({})\n".format(
                                currency['symbol'],
                                acronym_list[currency['symbol']]))
                    dupe_acronym = re.search('\\d+',
                                             acronym_list[currency['symbol']])
                    dupe_num = str(
                        int(dupe_acronym.group(len(dupe_acronym.group()) -
                                               1)) + 1)
                    dupe_key = currency['symbol'] + dupe_num
                    acronym_list[dupe_key] = currency['id']
                    acronym_list[currency['symbol']] = (
                        acronym_list[currency['symbol']] +
                        "{} ({})".format(dupe_key, currency['id']))
                    dupe_msg = "Created duplicate acronym: {} ({})".format(
                        dupe_key, currency['id'])
                    logger.info(dupe_msg)
                else:
                    acronym_list[currency['symbol']] = currency['id']
            return acronym_list, duplicate_count
        except Exception as e:
            raise CoinMarketException(
                "Failed to load all acronyms: {}".format(e))

    def fetch_currency_data(self, currency="", fiat="", load_all=False):
        """
        Fetches the currency data based on the desired currency

        @param currency - the cryptocurrency to search for (i.e. 'bitcoin',
                          'ethereum')
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @param load_all - True: load all cryptocurrencies
                          False: don't load all cryptocurrencies
        @return - currency data
        """
        try:
            if load_all:
                return self.market.ticker(currency, start=0, limit=0)
            return self.market.ticker(currency, convert=fiat)
        except Exception:
            raise CurrencyException("Failed to find currency: `{}`. Check "
                                    "if this currency is valid and also check "
                                    "for spelling errors.".format(currency))

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

        @param currency - the cryptocurrency to search for (i.e. 'bitcoin',
                          'ethereum')
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - formatted currency data
        """
        try:
            isPositivePercent = True
            formatted_data = ''
            hour_trend = ''
            if float(data['percent_change_1h']) >= 0:
                hour_trend = ':arrow_upper_right:'
            else:
                hour_trend = ':arrow_lower_right:'
                isPositivePercent = False

            formatted_data += '__**#{}. {} ({})**__ {}\n'.format(
                data['rank'], data['name'], data['symbol'], hour_trend)
            if fiat in fiat_suffix:
                formatted_data += 'Price ({}): **{:,} {}**\n'.format(
                    fiat, float(data['price_{}'.format(fiat.lower())]),
                    fiat_currencies[fiat])
            else:
                formatted_data += 'Price ({}): **{}{:,}**\n'.format(
                    fiat, fiat_currencies[fiat],
                    float(data['price_{}'.format(fiat.lower())]))
            formatted_data += 'Price (BTC): **{:,}**\n'.format(
                float(data['price_btc']))
            if (data['market_cap_usd'] is None):
                formatted_data += 'Market Cap (USD): Unknown\n'
            else:
                formatted_data += 'Market Cap (USD): **${:,}**\n'.format(
                    float(data['market_cap_usd']))
            if (data['available_supply'] is None):
                formatted_data += 'Available Supply: Unknown\n'
            else:
                formatted_data += 'Available Supply: **{:,}**\n'.format(
                    float(data['available_supply']))
            formatted_data += 'Percent Change (1H): **{}%**\n'.format(
                data['percent_change_1h'])
            formatted_data += 'Percent Change (24H): **{}%**\n'.format(
                data['percent_change_24h'])
            formatted_data += 'Percent Change (7D): **{}%**\n'.format(
                data['percent_change_7d'])

            return formatted_data, isPositivePercent
        except Exception as e:
            raise CoinMarketException("Failed to format data: {}".format(e))

    async def get_currency(self, acronym_list, currency, fiat):
        """
        Obtains the data of the specified currency and returns them.

        @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:
                try:
                    data = self.fetch_currency_data(
                        acronym_list[currency.upper()], fiat)[0]
                except CurrencyException:
                    formatted_data = acronym_list[currency.upper()]
                    return formatted_data, isPositivePercent
            else:
                data = self.fetch_currency_data(currency, fiat)[0]
            formatted_data, isPositivePercent = self._format_currency_data(
                data, fiat)
            return formatted_data, isPositivePercent
        except CurrencyException as e:
            raise
        except FiatException as e:
            raise
        except Exception as e:
            raise CoinMarketException(e)

    def _fetch_coinmarket_stats(self, fiat):
        """
        Fetches the coinmarket stats

        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - market stats
        """
        try:
            return self.market.stats(convert=fiat)
        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:
            formatted_stats = ''
            if (stats['total_market_cap_usd'] is None):
                formatted_stats += "Total Market Cap (USD): Unknown"
            else:
                if fiat in fiat_suffix:
                    formatted_stats += "Total Market Cap ({}): **{:,} {}**\n".format(
                        fiat,
                        float(stats['total_market_cap_{}'.format(
                            fiat.lower())]), fiat_currencies[fiat])
                else:
                    formatted_stats += "Total Market Cap ({}): **{}{:,}**\n".format(
                        fiat, fiat_currencies[fiat],
                        float(stats['total_market_cap_{}'.format(
                            fiat.lower())]))
            formatted_stats += "Bitcoin Percentage of Market: **{:,}%**\n".format(
                stats['bitcoin_percentage_of_market_cap'])
            formatted_stats += "Active Markets: **{:,}**\n".format(
                stats['active_markets'])
            formatted_stats += "Active Currencies: **{:,}**\n".format(
                stats['active_currencies'])
            formatted_stats += "Active Assets: **{:,}**\n".format(
                stats['active_assets'])

            return formatted_stats
        except Exception as e:
            raise CoinMarketException("Failed to format data: `{}`".format(e))

    async def get_stats(self, fiat):
        """
        Returns the market stats

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

    async def get_multiple_currency(self, acronym_list, currency_list, fiat):
        """
        Returns updated info of multiple coin stats

        @param acronym_list - list of cryptocurrency acronyms
        @param currency_list - list of cryptocurrencies
        @param fiat - desired fiat currency (i.e. 'EUR', 'USD')
        @return - formatted cryptocurrency data
        """
        try:
            fiat = self.fiat_check(fiat)
            formatted_data = ''
            data_list = []
            for currency in currency_list:
                if acronym_list is not None:
                    if currency.upper() in acronym_list:
                        data_list.append(
                            self.fetch_currency_data(
                                acronym_list[currency.upper()], fiat)[0])
                    else:
                        data_list.append(
                            self.fetch_currency_data(currency, fiat)[0])
                else:
                    data_list.append(
                        self.fetch_currency_data(currency, fiat)[0])
            data_list.sort(key=lambda x: int(x['rank']))
            for data in data_list:
                formatted_data += self._format_currency_data(data,
                                                             fiat)[0] + '\n'
            return formatted_data
        except CurrencyException as e:
            raise
        except FiatException as e:
            raise
        except Exception as e:
            raise CoinMarketException(e)
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)))
Exemple #13
0
def getCoinMarket():
    coinmarketcap = Market()
    while True:
        print coinmarketcap.stats()
        print coinmarketcap.ticker(limit=4, convert='EUR')
        time.sleep(1)  # Delays for 5 seconds. You can also use a float value.
Exemple #14
0
# author: Christian Urcuqui
# Date: 22 october 2018
# this code allows us to use APIs from different sources in order to know the value of the different crypto monies
import requests
from coinmarketcap import Market

coinmarketcap = Market()

print(coinmarketcap.stats())

print(coinmarketcap.ticker("steem"))