def function_cmc(): coin = "BTC" coinmarketcap = Pymarketcap(timeout=10) try: cmc_json = coinmarketcap.ticker(coin, convert="EUR") rank = str("Rank : [Rank " + str(cmc_json["data"]["rank"]) + "]\n") if cmc_json["data"]["quotes"]["USD"]["market_cap"] is None: marketcap = "MarketCap : Unknown\n" else: marketcap = str( "MC : " + "$" + "{:,}".format(float(cmc_json["data"]["quotes"]["USD"]["market_cap"])) + "\n") price = str( "Price : ${0:.3f}".format(float(cmc_json["data"]["quotes"]["USD"]["price"])) + " | {0:.3f}€\n".format( float(cmc_json["data"]["quotes"]["EUR"]["price"]))) if cmc_json["data"]["quotes"]["USD"]["percent_change_1h"] is None: change_1 = "1h Swing : Unknown\n" else: change_1 = str("1h Swing : " + str(cmc_json["data"]["quotes"]["USD"]["percent_change_1h"]) + "%\n") if cmc_json["data"]["quotes"]["USD"]["percent_change_24h"] is None: change_24 = "24h Swing : Unknown\n" else: change_24 = str("24h Swing : " + str(cmc_json["data"]["quotes"]["USD"]["percent_change_24h"]) + "%\n") if cmc_json["data"]["quotes"]["USD"]["percent_change_7d"] is None: change_7 = "7 days Swing : Unknown\n" else: change_7 = str("7 days Swing : " + str(cmc_json["data"]["quotes"]["USD"]["percent_change_7d"]) + "%\n") value_mc = "```css\n" + rank + marketcap + price + change_1 + change_24 + change_7 + "```" except TypeError or KeyError: value_mc = "```css\nThis ticker does not exist on Coinmarketcap.\nMaybe you made a typo in the coin's ticker.```" return value_mc
class TestApiCoinmarketcap(unittest.TestCase): """ Tests for Coinmarketcap Api commands. These will fail in the absence of an internet connection or if Coinmarketcap API goes down. """ def setUp(self): self.coinmarketcap = Pymarketcap() def test_symbols(self): actual = self.coinmarketcap.symbols self.assertIs(type(actual), list) self.assertEqual(len(actual) > 0, True) self.assertIs(type(actual[0]), str) def test_ticker(self): actual = self.coinmarketcap.ticker() self.assertIs(type(actual), list) self.assertEqual(len(actual) > 0, True) for tick in actual: self.assertIs(type(tick), dict) actual = self.coinmarketcap.ticker(config.COIN) self.assertIs(type(actual), dict) # With param convert actual = self.coinmarketcap.ticker(config.COIN, convert="EUR") self.assertIs(type(actual), dict) actual = self.coinmarketcap.ticker("ETH", convert="CNY") self.assertIs(type(actual), dict) def test_stats(self): actual = self.coinmarketcap.stats()
async def function_cmc(self, coin): coin = coin.upper() coinmarketcap = Pymarketcap(timeout=10) cmc_json = coinmarketcap.ticker(coin, convert="EUR") rank = str("Rank : [Rank " + str(cmc_json["rank"]) + "]\n") if cmc_json["market_cap_usd"] is None: marketcap = "MarketCap : Unknown\n" else: marketcap = str("MC : " + "$" + "{:,}".format(float(cmc_json["market_cap_usd"])) + "\n") price = str("Price : ${0:.3f}".format(float(cmc_json["price_usd"])) + " | {0:.3f}€\n".format(float(cmc_json["price_eur"]))) if cmc_json["percent_change_1h"] is None: change_1 = "1h Swing : Unknown\n" else: change_1 = str("1h Swing : " + str(cmc_json["percent_change_1h"]) + "%\n") if cmc_json["percent_change_24h"] is None: change_24 = "24h Swing : Unknown\n" else: change_24 = str("24h Swing : " + str(cmc_json["percent_change_24h"]) + "%\n") if cmc_json["percent_change_7d"] is None: change_7 = "7 days Swing : Unknown\n" else: change_7 = str("7 days Swing : " + str(cmc_json["percent_change_7d"]) + "%\n") value_mc = "```css\n" + rank + marketcap + price + change_1 + change_24 + change_7 + "```" self.name = cmc_json["name"] return value_mc
def __init__(self) -> None: try: self._coinmarketcap = Pymarketcap() except BaseException: self._coinmarketcap = None self._pairs = []
def function_cmc(self): coin = self.coin.upper() coinmarketcap = Pymarketcap() cmc_json = coinmarketcap.ticker(coin, convert="EUR") self.price_usd = float(cmc_json["price_usd"]) self.price_eur = float(cmc_json["price_eur"]) self.price_btc = float(cmc_json["price_btc"]) return
def function_cmc(coin): if coin == "": id_coin = "" else: coin = coin.upper() coinmarketcap = Pymarketcap() cmc_json = coinmarketcap.ticker(coin) id_coin = cmc_json["id"] return id_coin
def function_cmc(self, coin): self.coin = coin.upper() coin = coin.upper() coinmarketcap = Pymarketcap() cmc_json = coinmarketcap.ticker(coin, convert="EUR") self.btc_price = cmc_json["price_btc"] self.usd_price = cmc_json["price_usd"] self.eur_price = cmc_json["price_eur"] self.name = cmc_json["name"]
async def function_cmc(self, coin): self.coin = coin.upper() coinmarketcap = Pymarketcap() cmc_json = coinmarketcap.ticker(self.coin, convert="EUR") btc_json = coinmarketcap.ticker(self.coin, convert="BTC") self.price_usd = float(cmc_json["data"]["quotes"]["USD"]["price"]) self.price_eur = float(cmc_json["data"]["quotes"]["EUR"]["price"]) self.price_btc = float(btc_json["data"]["quotes"]["BTC"]["price"]) return
def function_cmc(self, coin): self.coin = coin.upper() coin = coin.upper() coinmarketcap = Pymarketcap() eur_json = coinmarketcap.ticker(coin, convert="EUR") btc_json = coinmarketcap.ticker(coin, convert="BTC") self.btc_price = btc_json["data"]["quotes"]["BTC"]["price"] self.usd_price = eur_json["data"]["quotes"]["USD"]["price"] self.eur_price = eur_json["data"]["quotes"]["EUR"]["price"] self.name = eur_json["data"]["name"]
def function_cmc(self, coin): if coin == "": full_name = self.empty_name else: coin = coin.upper() coinmarketcap = Pymarketcap() cmc_json = coinmarketcap.ticker(coin) ticker = cmc_json["symbol"] name = cmc_json["name"] full_name = name + "%20" + "(" + ticker + ")" return full_name
async def function_btcap(self): coinmarketcap = Pymarketcap() cmc_btc = coinmarketcap.ticker("bitcoin", convert=self.currency) price = str("Price : " + "$" + "{0:.3f}".format(float(cmc_btc["price_usd"])) + " | " + "{0:.3f}".format( float(cmc_btc["price_eur"])) + "€ \n") volume = "24h Volume: " "$ " + "{:,}".format(float(cmc_btc["24h_volume_usd"])) + "\n" change_1 = "24h Swing : " + str(cmc_btc["percent_change_24h"]) + "%\n" change_7 = "7 days Swing : " + str(cmc_btc["percent_change_7d"]) + "%\n\n" value_btc = "```css\n" + price + volume + change_1 + change_7 + "```" return value_btc
def getCoinResult(self): market = Pymarketcap() #Get the KRW Price of Coins cur = market.ticker(convert="KRW") # init Coin's price of up&down of price increaseCoin = 0 decreaseCoin = 0 #Rank from 50 to 100 for i in range(50, 100): #Convert array to Dict to get which I want CurInfo = cur[i] #Get the price and name of the coin which is necessary Price = float(CurInfo['price_krw']) Name = CurInfo['name'] #if file is exist. for avoid error whether file is exist or not if os.path.isfile('./coin_currency/' + Name + '_price.txt'): #get the old one from file PreInfo = open('./coin_currency/' + Name + '_price.txt', 'rt') PrePrice = PreInfo.readline() PrePrice = float(PrePrice) #compare the price if PrePrice > Price: decreaseCoin += 1 elif PrePrice < Price: increaseCoin += 1 #write down the new price to file PreInfo = open('./coin_currency/' + Name + '_price.txt', 'wt') PreInfo.write(str(Price) + '\n') PreInfo.close() else: #For the first execution which don't have coin's priceInfo PreInfo = open('./coin_currency/' + Name + '_price.txt', 'wt') PreInfo.write(str(Price) + '\n') PreInfo.close() #Compare the number of the coin if increaseCoin == 0 and decreaseCoin == 0: result = "EVEN" else: if increaseCoin > decreaseCoin: result = "UP" elif increaseCoin < decreaseCoin: result = "DOWN" return result
def function_cmc(self, coin): coin = coin.upper() coinmarketcap = Pymarketcap() cmc_json = coinmarketcap.ticker(coin, convert="EUR") rank = str("Rank : [Rank " + str(cmc_json["rank"]) + "]\n") marketcap = str("MC : " + "$" + "{:,}".format(float(cmc_json["market_cap_usd"])) + "\n") price = str("Price : " + "$" + "{0:.3f}".format(float(cmc_json["price_usd"])) + " | " + "{0:.3f}".format( float(cmc_json["price_eur"])) + "€ \n") change_1 = str("1h Swing : " + str(cmc_json["percent_change_1h"]) + "%\n") change_24 = str("24h Swing : " + str(cmc_json["percent_change_24h"]) + "%\n") change_7 = str("7 days Swing : " + str(cmc_json["percent_change_7d"]) + "%\n") value_mc = "```css\n" + rank + marketcap + price + change_1 + change_24 + change_7 + "```" self.name = cmc_json["name"] return value_mc
def __init__(self, queue_size=10, progress_bar=True, consumers=10, timeout=15, logger=LOGGER, debug=False, sync=Pymarketcap(), **kwargs): super().__init__(**kwargs) self.timeout = timeout self.logger = logger self.sync = sync # Async queue self.queue_size = queue_size self.connector_limit = self.connector.limit self._responses = [] self.progress_bar = progress_bar self.consumers = consumers self.graphs = type("Graphs", (), {"every_currency": self._every_currency}) self.__start = None self.__end = None if debug: self.logger.setLevel(logging.DEBUG)
def initCoinMarketCap(): global coinmarketcap if not coinmarketcap: coinmarketcap = Pymarketcap() return coinmarketcap
def pymarketcap(): coinmarketcap = Pymarketcap() print("Ranks") print(coinmarketcap.ranks()) print("Tickers") print(coinmarketcap.ticker(limit=10))
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.coinmarketcap = Pymarketcap() self.config = { "COIN": 'BTC', "COIN_NAME": 'bitcoin', "EXCHANGE": 'poloniex', }
def get_cmc_targets(self, max_days): cmc = Pymarketcap() recent = cmc.recently() targets = [] for r in recent: if r['added'] == 'Today': days_old = 0 else: days_old = int(r['added'].replace(' days ago', '')) if days_old < max_days: targets.append({ 'symbol': r['symbol'], 'days_old': days_old, 'volume_24h': r['volume_24h'], 'market_cap': r['market_cap'], }) return targets
def __init__(self): self.coinmarketcap = Pymarketcap() self.bittrex = ccxt.bittrex() #self.poloniex = ccxt.poloniex() self.quadrigacx = ccxt.quadrigacx() self.quadrigacx.userAgent = self.quadrigacx.userAgents['chrome']; self.exchanges = {'Bittrex':self.bittrex,'Quadrigacx':self.quadrigacx,'coinmarketcap':self.coinmarketcap} self.loadMarkets() self.btc = {'name':'BTC','Cmc':{'last': '0', 'current':'0','color':'black','1h':'0','24h':'0','7d':'0'}, 'Bittrex':{'last':'0','currentBTC':'0','lastBTC':'0','current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}, 'Quadrigacx':{'last':'0','currentBTC':'0','lastBTC':'0', 'current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}} self.eth = {'name':'ETH','Cmc': {'last':'0', 'current':'0','color':'black','1h':'0','24h':'0','7d':'0'}, 'Bittrex': {'last':'0','currentBTC':'0','lastBTC':'0', 'current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}, 'Quadrigacx': {'last':'0','currentBTC':'0','lastBTC':'0', 'current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}} self.zec = {'name':'ZEC','Cmc': {'last':'0', 'current':'0','color':'black','1h':'0','24h':'0','7d':'0'}, 'Bittrex': {'last':'0','currentBTC':'0','lastBTC':'0', 'current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}} self.ltc = {'name':'LTC','Cmc': {'last': '0', 'current': '0','color':'black','1h':'0','24h':'0','7d':'0'}, 'Bittrex': {'last':'0','currentBTC':'0','lastBTC':'0', 'current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}, 'Quadrigacx': {'last':'0','currentBTC':'0','lastBTC':'0', 'current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}} self.coins = [self.btc,self.eth,self.zec,self.ltc]
class TestApiCoinmarketcap(unittest.TestCase): """ Tests for Coinmarketcap Api commands. These will fail in the absence of an internet connection or if Coinmarketcap API goes down. """ def __init__(self, *args, **kwargs): super(TestApiCoinmarketcap, self).__init__(*args, **kwargs) self.coinmarketcap = Pymarketcap() self.config = ConfigTest() def tearDown(self): # Prevent TooManyRequestsError time.sleep(.25) def test_symbols(self): actual = self.coinmarketcap.symbols self.assertIs(type(actual), list) self.assertEqual(len(actual) > 0, True) self.assertIs(type(actual[0]), str) def test_ticker(self): actual = self.coinmarketcap.ticker() self.assertIs(type(actual), list) self.assertEqual(len(actual) > 0, True) for tick in actual: self.assertIs(type(tick), dict) actual = self.coinmarketcap.ticker(self.config.COIN) self.assertIs(type(actual), dict) # With param convert actual = self.coinmarketcap.ticker(self.config.COIN, convert="EUR") self.assertIs(type(actual), dict) actual = self.coinmarketcap.ticker("ETH", convert="CNY") self.assertIs(type(actual), dict) def test_stats(self): actual = self.coinmarketcap.stats()
def __init__(self, app): self.app = app self.webhook = "YOUR SLACK WEBHOOK" self.coinmarketcap = Pymarketcap() self.bittrex = ccxt.bittrex() self.poloniex = ccxt.poloniex() self.quadraigacx = ccxt.poloniex() self.exchanges = { 'bittrex': self.bittrex, 'poloniex': self.poloniex, 'quadraigacx': self.quadraigacx, 'coinmarketcap': self.coinmarketcap } self.loadMarkets() self.dispatch_map = { 'showalert': self.showAlert, 'removealert': self.removeAlert, 'alert': self.createAlert, 'topten': self.topten, 'updatecoin': self.updatecoin, 'gainers': self.gainers, 'losers': self.losers, 'symbols': self.symbols } alertFile = Path("alert.p") if alertFile.is_file(): self.alerts = pickle.load(open('alert.p', "rb")) else: self.alerts = [] self.symbols = [] self.timeframe = ['7d', '24h', '1h'] self.symbols = self.coinmarketcap.symbols self.coinmarket_latestinfo = [] self.bittrex_latestinfo = [] self.poloniex_latestinfo = [] self.quadraigacx_latestinfo = [] scheduler = BackgroundScheduler() scheduler.add_job(self.refreshinfo, 'interval', seconds=20) logging.basicConfig() scheduler.start()
def __init__(self, queue_size=10, progress_bar=True, consumers=10, timeout=DEFAULT_TIMEOUT, logger=LOGGER, debug=False, **kwargs): super(AsyncPymarketcap, self).__init__(**kwargs) self.timeout = timeout self.logger = logger self.sync = Pymarketcap() self.queue_size = queue_size self.connector_limit = self.connector.limit self._responses = [] self.progress_bar = progress_bar self.consumers = consumers self.graphs = type("Graphs", (), self._graphs_interface) if debug: self.logger.setLevel(logging.DEBUG)
def get_account_values(username): market = Pymarketcap() account = get_steem_account(username) steem_price = float(market.ticker("steem")["price_usd"]) steem_dollar_price = float(market.ticker("steem-dollars")["price_usd"]) steem_balance = account["balance"] steem_dollar_balance = account["sbd_balance"] savings_balance = account["savings_balance"] steem = float(steem_balance.split(" ")[0]) steem_dollars = float(steem_dollar_balance.split(" ")[0]) savings = float(savings_balance.split(" ")[0]) total_price = steem * steem_price + steem_dollars * steem_dollar_price + savings * steem_price output = { "steem": { "amount": steem, "price_usd": steem * steem_price }, "steem-dollars": { "amount": steem_dollars, "price_usd": steem_dollars * steem_dollar_price }, "savings": { "amount": savings, "price_usd": savings * steem_price }, "total":{ "price_usd": total_price } } response = jsonify(output) response.headers.add('Access-Control-Allow-Origin', '*') return response
def __init__(self): # getcontext().prec = 15 # api_key = 'EcBv9wqxfdWNMhtOI8WbkGb9XwOuITAPxBdljcxv8RYX1H7u2ucC0qokDp2KOWmr' # api_secret = 'i5Y57Gwu8sH9qUE5TbB7zLotm7deTa1D9S8K458LWLXZZzNq5wNAZOHlGJmyjq1s' # kucoin_api_key = '5a64f6a46829d247d237e7bf' # kucoin_api_secret = '93b85f5c-f164-4bea-bd40-3ffda4c03907' self.market_cap = Pymarketcap() # connection = TinyMongoClient() # db = connection.cryptoAnalytics # data = db.arbitrage.find() # arbitrage_data = db.arbitrage.find() # arbitrage_id = arbitrage_data[0]['_id'] slack_token = "xoxp-302678850693-302678850805-302556314308-5b70830e08bc3a0f6895d1f8545f537a" self.slack = Slacker(slack_token) self.exchanges = [ "Poloniex", "Kraken", "HitBTC", "Gemini", "Exmo", #"Yobit", "Cryptopia", "Binance", "OKEX" ] self.to_coins = ["BTC", "ETH", "LTC"] self.Price = cryCompare.Price() self.lowest_price = 10000000000000000000000 self.highest_price = 0 self.exchange1 = None self.exchange2 = None self.movement = None
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for ticker() method""" from pymarketcap.tests import type_test from pymarketcap import Pymarketcap pym = Pymarketcap() def assert_types(res): map_types = { "name": str, "symbol": str, "added": str, "market_cap": str, "price": str, "circulating_supply": str, "volume_24h": str, "percent_change": str } assert isinstance(res, list) for currency in res: assert isinstance(currency, dict) for key, value in currency.items(): type_test(map_types, key, value) def test_types(): assert_types(pym.recently())
def coinMarketCapData(): from pymarketcap import Pymarketcap coinmarketcap = Pymarketcap() symbols = coinmarketcap.symbols # ###### Set initial Date/Time.. Will be setting throughout # In[45]: #Pulls date and time information moment = time.strftime("%Y-%b-%d__%H_%M_%S", time.localtime()) today = pd.Timestamp("today").strftime("%m/%d/%Y") hh = pd.Timestamp("today").strftime("%H") mm = pd.Timestamp("today").strftime("%M") # ###### Coinmarketcap statistics - up to date 1/14/2018 # In[47]: try: stats = coinmarketcap.stats() stats = pd.DataFrame(stats, index=[0]) stats['Date'] = today stats['Hour'] = hh stats['Minute'] = mm stats['Now'] = pd.Timestamp("today") stats.to_csv('Coinmarketcap/boom/stats/stats_' + moment + '.csv', sep=',') print("Look at all those stats 0.o") except: print("*NO STATS GATHERED*") # ###### Coin Data - Updated 1/14/2018 # In[49]: try: from pymarketcap import Pymarketcap coinmarketcap = Pymarketcap() ticker = coinmarketcap.ticker(limit=1500, convert="BTC") ticker = pd.DataFrame(ticker) ticker['Date'] = today ticker['Hour'] = hh ticker['Minute'] = mm ticker['Now'] = pd.Timestamp("today") ticker.to_csv('Coinmarketcap/boom/coins/coins_' + moment + '.csv', sep=',') print("Chaaaa-CHING! The coin data is in") except: print("*NO COINS GATHERED* *YOU ARE LOSING OUT ON BAGS*") # ###### Coin exchange info for each token - Updated 1/14/2018 # In[ ]: for coin2 in symbols: try: from pymarketcap import Pymarketcap coinmarketcap = Pymarketcap() markets = coinmarketcap.markets(coin2) markets = pd.DataFrame(markets['markets']) markets['Date'] = today markets['Hour'] = hh markets['Minute'] = mm markets['Now'] = pd.Timestamp("today") markets.to_csv('Coinmarketcap/boom/markets/markets_' + coin2 + '_' + moment + '.csv', sep=',') except: print("No market data was captured for ", coin2) pass print("I hear the exchange trades from here.. exchange data collected :)") # ###### Gainers and Losers (1h, 24h, 7d) - Updated 1/14/2018 # ###### ******Currently no 7d Gainers being captured****** # ###### New coins - Updated 1/14/2018 # In[102]: #Set date and time today = pd.Timestamp("today").strftime("%m/%d/%Y") hh = pd.Timestamp("today").strftime("%H") mm = pd.Timestamp("today").strftime("%M") moment = time.strftime("%Y-%b-%d__%H_%M_%S", time.localtime()) data = coinmarketcap.recently() data = pd.DataFrame(data) data.head() data['Date'] = today data['Hour'] = hh data['Minute'] = mm data['days_ago'] = data['added'].str.extract('(\d.)', expand=True) data['Now'] = pd.Timestamp("today") data['days_ago'] = data['days_ago'].apply(pd.to_numeric) data['Date_Added'] = data['Now'] - pd.to_timedelta(data['days_ago'], unit='d') data['Date_Added'] = data['Date_Added'].dt.date #Reimport due to naming issues from pymarketcap import Pymarketcap coinmarketcap = Pymarketcap() #Get Market date for new coins for coin2 in data["symbol"]: try: markets = coinmarketcap.markets(coin2) markets = pd.DataFrame(markets['markets']) #add 'Today' 'Hour' and 'minutes' column markets['Date'] = today markets['Hour'] = hh markets['Minute'] = mm markets['Now'] = pd.Timestamp("today") #Save CSV markets.to_csv('Coinmarketcap/boom/markets/new/markerts_' + coin2 + '_' + moment + '.csv', sep=',') print("Market info for new coin", coin2, " captured!") except: print("************ERROR COIN", coin2, "DATA NOT CAPUTRED*************") pass ###Upload datafile data.to_csv('Coinmarketcap/boom/new/new_' + moment + '.csv', sep=',') print("Gotta catch all the new coins!")
def setUp(self): self.coinmarketcap = Pymarketcap()
class TestScraperCoinmarketcap(unittest.TestCase): """ Tests for Coinmarketcap Api commands. These will fail in the absence of an internet connection or if Coinmarketcap API goes down. """ def setUp(self): self.coinmarketcap = Pymarketcap() def test_endpoints(self): from requests import get endpoints = [ 'currencies/%s/' % config.COIN_NAME, 'gainers-losers/', 'currencies/%s/historical-data/'\ % config.COIN_NAME, 'new', 'exchanges/%s/' % config.EXCHANGE, 'exchanges/volume/24-hour/all/' ] base_url = self.coinmarketcap.web_url for e in endpoints: _status_code = get(base_url + e).status_code self.assertEqual(_status_code, 200) def test_markets(self): actual = self.coinmarketcap.markets(config.COIN) value_types = { 'price_usd': Decimal, '24h_volume_usd': int, 'percent_volume': Decimal, 'pair': str, 'exchange': str } self.assertIs(type(actual), list) self.assertIs(len(actual) > 0, True) for source in actual: self.assertIs(type(source), dict) for key, value in source.items(): self.assertIs(type(value), value_types[key]) def test_ranks(self): temps = ['1h', '24h', '7d'] queries = ['gainers', 'losers'] value_types = { 'percent_change': Decimal, '24h_volume_usd': int, 'symbol': str, 'price_usd': Decimal, 'name': str } actual = self.coinmarketcap.ranks() self.assertIs(type(actual), dict) for q, temp in actual.items(): self.assertIn(q, queries) self.assertIs(type(temp), dict) for t, data in temp.items(): self.assertIn(t, temps) self.assertIs(type(data), list) self.assertIs(len(data) > 0, True) for d in data: self.assertIs(type(d), dict) for key, value in d.items(): self.assertIs(type(value), value_types[key]) # Test invalid argument with self.assertRaises(AttributeError): self.coinmarketcap.ranks('8d') def test_historical(self): from datetime import datetime value_types = { 'close': Decimal, 'low': Decimal, 'usd_volume': int, 'open': Decimal, 'usd_market_cap': int, 'high': Decimal, 'date': datetime } actual = self.coinmarketcap.historical(config.COIN, datetime(2017, 9, 30), datetime(2017, 10, 10)) self.assertIs(type(actual), list) for tick in actual: self.assertIs(type(tick), dict) for key, value in tick.items(): self.assertIs(type(value), value_types[key]) def test_recently(self): actual = self.coinmarketcap.recently() value_types = { 'price_usd': Decimal, 'mineable': bool, 'symbol': str, 'usd_market_cap': [str, int], 'circulating_supply': [str, int], 'volume_24h_usd': [str, int], 'days_ago': [str, int], 'name': str } self.assertIs(type(actual), list) for c in actual: self.assertIs(type(c), dict) for key, value in c.items(): if type(value_types[key]) is list: self.assertIn(type(value), value_types[key]) else: self.assertIs(type(value), value_types[key]) def test_exchange(self): actual = self.coinmarketcap.exchange(config.EXCHANGE) value_types = { 'market': str, 'price_usd': Decimal, 'rank': int, 'volume_24h_usd': int, 'name': str, 'perc_volume': Decimal } self.assertIs(type(actual), list) for market in actual: self.assertIs(type(market), dict) for key, value in market.items(): self.assertIs(type(value), value_types[key]) def test_exchanges(self): actual = self.coinmarketcap.exchanges() value_types = { 'market': str, 'price_usd': Decimal, 'rank': int, 'volume_24h_usd': int, 'name': str, 'perc_volume': Decimal, 'perc_change': Decimal } self.assertIs(type(actual), list) for exch in actual: self.assertIs(type(exch), dict) for key, value in exch.items(): if key in ('rank', 'volume_usd'): self.assertIs(type(value), int) elif key == 'name': self.assertIs(type(value), str) elif key == 'markets': self.assertIs(type(value), list) for m in value: self.assertIs(type(m), dict) for _key, _value in m.items(): self.assertIs(type(_value), value_types[_key]) def test_exchange_names(self): actual = self.coinmarketcap.exchange_names self.assertIs(type(actual), list)
class CryptoToFiatConverter(): # Constants SUPPORTED_FIAT = [ "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", "USD" ] def __init__(self) -> None: try: self._coinmarketcap = Pymarketcap() except BaseException: self._coinmarketcap = None self._pairs = [] def convert_amount(self, crypto_amount: float, crypto_symbol: str, fiat_symbol: str) -> float: """ Convert an amount of crypto-currency to fiat :param crypto_amount: amount of crypto-currency to convert :param crypto_symbol: crypto-currency used :param fiat_symbol: fiat to convert to :return: float, value in fiat of the crypto-currency amount """ price = self.get_price(crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol) return float(crypto_amount) * float(price) def get_price(self, crypto_symbol: str, fiat_symbol: str) -> float: """ Return the price of the Crypto-currency in Fiat :param crypto_symbol: Crypto-currency you want to convert (e.g BTC) :param fiat_symbol: FIAT currency you want to convert to (e.g USD) :return: Price in FIAT """ crypto_symbol = crypto_symbol.upper() fiat_symbol = fiat_symbol.upper() # Check if the fiat convertion you want is supported if not self._is_supported_fiat(fiat=fiat_symbol): raise ValueError('The fiat {} is not supported.'.format(fiat_symbol)) # Get the pair that interest us and return the price in fiat for pair in self._pairs: if pair.crypto_symbol == crypto_symbol and pair.fiat_symbol == fiat_symbol: # If the price is expired we refresh it, avoid to call the API all the time if pair.is_expired(): pair.set_price( price=self._find_price( crypto_symbol=pair.crypto_symbol, fiat_symbol=pair.fiat_symbol ) ) # return the last price we have for this pair return pair.price # The pair does not exist, so we create it and return the price return self._add_pair( crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol, price=self._find_price( crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol ) ) def _add_pair(self, crypto_symbol: str, fiat_symbol: str, price: float) -> float: """ :param crypto_symbol: Crypto-currency you want to convert (e.g BTC) :param fiat_symbol: FIAT currency you want to convert to (e.g USD) :return: price in FIAT """ self._pairs.append( CryptoFiat( crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol, price=price ) ) return price def _is_supported_fiat(self, fiat: str) -> bool: """ Check if the FIAT your want to convert to is supported :param fiat: FIAT to check (e.g USD) :return: bool, True supported, False not supported """ fiat = fiat.upper() return fiat in self.SUPPORTED_FIAT def _find_price(self, crypto_symbol: str, fiat_symbol: str) -> float: """ Call CoinMarketCap API to retrieve the price in the FIAT :param crypto_symbol: Crypto-currency you want to convert (e.g BTC) :param fiat_symbol: FIAT currency you want to convert to (e.g USD) :return: float, price of the crypto-currency in Fiat """ # Check if the fiat convertion you want is supported if not self._is_supported_fiat(fiat=fiat_symbol): raise ValueError('The fiat {} is not supported.'.format(fiat_symbol)) try: return float( self._coinmarketcap.ticker( currency=crypto_symbol, convert=fiat_symbol )['price_' + fiat_symbol.lower()] ) except BaseException: return 0.0
#Or iginally Written December 2017 #Setting API Keys from binance.client import Client client = Client("Public Key to be inserted here", "Secret Key to be inserted here") import time import math from pymarketcap import Pymarketcap cmc = Pymarketcap() #Import of pymarketcap has issues upon startup at times, thus the repeated loop of trying to innitiate it is required until it succesfuly initiates while True: try: binance = cmc.exchange('binance') except: pass else: break #-------------------------------------- from binance.enums import * #======================================================= #Constant Variables #----------------- TRX_uptrgtfitprct = 20.0
def __init__(self, *args, **kwargs): super(TestScraperCoinmarketcap, self).__init__(*args, **kwargs) self.coinmarketcap = Pymarketcap()