def get_cmc_top_n() -> pd.DataFrame: """Shows top n coins. [Source: CoinMarketCap] Returns ------- pd.DataFrame Top coin on CoinMarketCap """ cmc = CoinMarketCapAPI(cfg.API_CMC_KEY) ratings = cmc.cryptocurrency_listings_latest().data symbol, rank, price, pchange1d, mkt_cap = [], [], [], [], [] for coin in ratings: symbol.append(coin["symbol"]) rank.append(coin["cmc_rank"]) price.append(coin["quote"]["USD"]["price"]) pchange1d.append(coin["quote"]["USD"]["percent_change_24h"]) mkt_cap.append(coin["quote"]["USD"]["market_cap"] / (10**9)) df = pd.DataFrame(data=[symbol, rank, price, pchange1d, mkt_cap]).transpose() df.columns = [ "Symbol", "CMC_Rank", "Last Price", "1 Day Pct Change", "Market Cap ($B)", ] return df
def get_crypto_price(ticker: str) -> float: cmc = CoinMarketCapAPI(config['cmc_api_key']) crypto_listings = cmc.cryptocurrency_listings_latest().data crypto_price = next((crypto.get('quote', {}).get('USD', {}).get('price') for crypto in crypto_listings if crypto.get('symbol') == ticker), None) if crypto_price is None: raise Exception(f'{ticker} price is None') return float(crypto_price)
class Ticker: def __init__(self): self.ticker = CoinMarketCapAPI(coin_mkt_token) def get_prices(self, *currencies): currencies = ','.join(currencies) updates = {} if currencies: for currency in self.ticker.cryptocurrency_listings_latest( ).data[:2]: updates[currency['symbol']] = { 'price': float(currency['quote']['USD']['price']) } return updates return updates
class CoinMarketCapClient: """ CoinMarketCap client to get the latest top listings sorted by market volume """ def __init__(self, api_key, ignore_list=fiat_list + error_list): # Never invest in fiat self.ignore_list = list(set(ignore_list + fiat_list)) self.client = CoinMarketCapAPI(api_key=api_key) self.latest_listing_response = self.client.cryptocurrency_listings_latest( ) if self.latest_listing_response.status["error_code"] != 0: raise BaseException( "Getting latest listings failed with error code {}".format( self.latest_listing_response.status["error_code"])) self.sorted_listing = sorted(self.latest_listing_response.data, key=lambda x: x["cmc_rank"]) self.sorted_listing = [x["symbol"] for x in self.sorted_listing] self.sorted_listing = list( filter(lambda x: x not in self.ignore_list, self.sorted_listing)) def __getTopK(self, ignore, k): return self.sorted_listing[ignore:k] def getTopK(self, k): return self.__getTopK(0, k) def getLargeCap(self): return self.getTopK(LARGE_CAP) def getMidCap(self): return self.__getTopK(LARGE_CAP, MID_CAP) def getSmallCap(self): return self.__getTopK(MID_CAP, SMALL_CAP)
def get_cmc_top_n(other_args: List[str]): """ Shows top n coins from coinmarketcap.com Parameters ---------- other_args: List[str] Arguments to pass to argparse """ parser = argparse.ArgumentParser( prog="cmc_top_n", add_help=False, description="This gets the top ranked coins from coinmarketcap.com", ) parser.add_argument("-n", default=10, dest="n_to_get", type=int, help="number of coins to display") parser.add_argument( "-s", "--sort", dest="sortby", type=str, help="column to sort data by.", default="CMC_Rank", choices=sort_options, ) parser.add_argument( "--descend", action="store_false", help="Flag to sort in descending order (lowest first)", dest="descend", default=True, ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return cmc = CoinMarketCapAPI(cfg.API_CMC_KEY) ratings = cmc.cryptocurrency_listings_latest().data symbol, rank, price, pchange1d, mkt_cap = [], [], [], [], [] for coin in ratings: symbol.append(coin["symbol"]) rank.append(coin["cmc_rank"]) price.append(coin["quote"]["USD"]["price"]) pchange1d.append(coin["quote"]["USD"]["percent_change_24h"]) mkt_cap.append(coin["quote"]["USD"]["market_cap"] / (10**9)) df = pd.DataFrame( data=[symbol, rank, price, pchange1d, mkt_cap]).transpose() df.columns = [ "Symbol", "CMC_Rank", "Last Price", "1 Day Pct Change", "Market Cap ($B)", ] df = df.sort_values(by=sort_map[ns_parser.sortby], ascending=ns_parser.descend) print( tabulate( df.iloc[:ns_parser.n_to_get, :], headers=df.columns, showindex=False, tablefmt="fancy_grid", floatfmt=".2f", )) print("") except Exception as e: print(e) print("")
import json from pprint import pprint from coinmarketcapapi import CoinMarketCapAPI from private.keys import API_KEYS cmc = CoinMarketCapAPI(API_KEYS['coinmarket']['api_key']) r = cmc.cryptocurrency_listings_latest() latest = [dict(d, prices=d['symbol']) for d in r.data] pprint(r.data) with open('../../public/dummy_data/cmc_latest.json', 'w') as f: f.write(json.dumps(r.data)) # r2 = cmc.cryptocurrency_quotes_historical(interval='daily', count=7) # # pprint(r2.data) # # with open('../../public/dummy_data/cmc_quotes_historical.json', 'w') as f: # f.write(json.dumps(r2.data))
from coinmarketcapapi import CoinMarketCapAPI, CoinMarketCapAPIError import json import numpy as np APIKEY = "2b660bde-a5ee-4ea6-b3f5-f7ff33e83685" cmc = CoinMarketCapAPI(APIKEY) #r = cmc.cryptocurrency_info(symbol='BTC') response = cmc.cryptocurrency_listings_latest() latest = list(response.data) arr = [] for crypto in list(latest): quote = crypto['quote']['USD'] liste = [ crypto['name'], float(quote['percent_change_1h']), float(quote['percent_change_24h']), float(quote['percent_change_7d']) ] arr.append(liste) ''' plus rapide de convertir la liste en array ''' np_arr = np.array(arr, dtype='object') """for crypto in list(latest): print(crypto['id'],crypto['name'],crypto['quote'])""" """ {'price': 31844.873093123057, 'volume_24h': 18276287717.518513, 'percent_change_1h': 0.37411178, 'percent_change_24h': 1.4830346, 'percent_change_7d': -5.76745594, 'percent_change_30d': -15.65053106, 'percent_change_60d': -18.20391267, 'percent_change_90d': -44.1877872, 'market_cap': 597399851781.7104, 'last_updated': '2021-07-18T12:05:02.000Z' """ b = np_arr[np.argsort(np_arr[:, 1])]