def get_coins_higher_price(number_coins: int = 200): """ Get the coins with the currently higher price :param number_coins: the number of coins you want to include :return: a dict with all the info about the coins with higher price """ coins_dict = cryptocompare.get_coin_list(format=False) coins_names_list = list(coins_dict.keys()) chunk_coins = np.array_split( coins_names_list, 200) # due to limits I have to split the coins in 200 parts prices_in_USD = {} print('Getting cripto currencies prices:') for chunk in tqdm(chunk_coins): try: chunk_prices = cryptocompare.get_price(coin=list(chunk), curr='USD') chunk_dict_one_level = {} for cripto in chunk_prices: chunk_dict_one_level[cripto] = chunk_prices[cripto]['USD'] prices_in_USD.update(chunk_dict_one_level) except Exception as e: print(e) sorted_criptos = dict( sorted(prices_in_USD.items(), key=lambda item: item[1])) final_criptos = list(sorted_criptos.keys())[-number_coins:] final_dict = {} for money in final_criptos: if money in coins_dict: final_dict[money] = coins_dict[money] return final_dict
def getCrycptoCurrencyList(): try: list_ = cryptocompare.get_coin_list(format=False) print(type(list_)) print(list_) list_string = json.dumps(list_) cr_list_json = json.loads((list_string)) print(type(cr_list_json)) print(cr_list_json) CrCurrencyList = [] for key, value in sorted(cr_list_json.items()): if key in crc_list: print(key) print(value) CrCurrencyList.append( CrCurrency(name=value['CoinName'], symbol=value['Symbol'], url=value['Url'], image_url=value['ImageUrl'])) for cr in CrCurrencyList: print(cr) return jsonify({'status': 'success'}, json.dumps([ob.__dict__ for ob in CrCurrencyList])) except Exception as e: return jsonify({'status': 'failed'})
def loadPriceData(): coin_list = crt.get_coin_list() keys = list(coin_list.keys()) coin_data = {} for keyIndex in range(len(keys)): if not coin_list[keys[keyIndex]]['Rating']['Weiss']['Rating']: del coin_list[keys[keyIndex]] else: price_list = crt.get_price(keys[keyIndex], currency='USD', full=True) if price_list: coin_data.update(price_list['RAW']) keyIndex = keyIndex + 1 for k in coin_data.keys(): coin_data[k] = coin_data[k]['USD'] coin_data = pd.DataFrame.from_dict(coin_data, orient='index') return coin_data[[ 'FROMSYMBOL', 'PRICE', 'MKTCAP', 'VOLUME24HOURTO', 'SUPPLY', 'IMAGEURL' ]]
def show_coin_price(coin): if coin not in cryptocompare.get_coin_list(format=True): print('Désolé, cette crypto n\'existe pas !') return False coin_price = cryptocompare.get_price(coin, full=False, curr='USD') print('1 {coin} = {coin_price} $'.format( coin=coin, coin_price=coin_price[coin]['USD']))
def syncMarkets(): # Fetch top 25 print("Beginning marketcap sync") orderedCoinList = [] full_list = cryptocompare.get_coin_list() # Get list of all coins row_ct = 0 with open('./MarketCaps.csv', 'w', newline='\n') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for symbol in list(full_list): row_ct += 1 try: marketData = cryptocompare.get_price(symbol, 'USD', full=True)['RAW'] data = [ 0, symbol, marketData[symbol]['USD']['MKTCAP'], marketData[symbol]['USD']['PRICE'], marketData[symbol]['USD']['VOLUME24HOUR'], marketData[symbol]['USD']['SUPPLY'], marketData[symbol]['USD']['CHANGEPCT24HOUR'], str(datetime.datetime.now()) ] writer.writerow(data) print("{}. Data inserted for {}".format(row_ct, symbol), end='\r') except Exception as inst: # print(inst) pass # Connect to the MySQL database db = MySQLdb.connect(host='127.0.0.1', user='******', passwd='pass', db='Blockfund', local_infile=1) # Check if connection was successful if (not db): # Terminate print("Connection unsuccessful") return -1 else: try: cursor = db.cursor() loadTableSQL = "LOAD DATA LOCAL INFILE '~/workspace/Blockfund_test/Application/db/MarketCaps.csv' INTO TABLE marketcaps FIELDS OPTIONALLY ENCLOSED BY '\"' TERMINATED BY ',' LINES TERMINATED BY '\n' (PK,symbol, marketcap, price, volume24hr, supply, percentchange24hr, @date) SET DATE = STR_TO_DATE(@DATE, '%Y-%m-%d %H:%i:%s');" cursor.execute("START TRANSACTION;") cursor.execute("Truncate table marketcaps;") cursor.execute( loadTableSQL) # Getting warnings here but the uploads look ok cursor.execute("COMMIT;") except Exception as e: print("Error loading marketcaps: {}".format(e)) print("Marketcaps loaded") return True
def loadCoinData(): coin_list = crt.get_coin_list() keys = list(coin_list.keys()) for keyIndex in range(len(keys)): if not coin_list[keys[keyIndex]]['Rating']['Weiss']['Rating']: del coin_list[keys[keyIndex]] coin_list = pd.DataFrame().from_dict(coin_list, orient='index') return coin_list[['Name', 'CoinName', 'Rating']]
def get_coin_list(): coin_dict = cryptocompare.get_coin_list() coins = [] for key, coin_data in coin_dict.items(): id = int(coin_data[coin_property.ID]) code = coin_data[coin_property.NAME] name = coin_data[coin_property.FULL_NAME] sortOrder = int(coin_data[coin_property.SORT_ORDER]) coin = Coin(id, code.lower(), name.lower(), sortOrder) coins.append(coin) sorted_coins = sorted(coins, key=lambda x: x.sortOrder) return sorted_coins
def async_update_supported_coins(self): """Starts a celery async task to update supported coins""" self.update_state(state='RUNNING', meta={'current': 0, 'total': 100}) coins_list = cryptocompare.get_coin_list(False) new_coins = 0 updated = 0 length = len(coins_list) print_counter = 0 for idx, coin_key in enumerate(coins_list): item = coins_list.get(coin_key) try: _id = int(item.get("Id")) except ValueError: continue try: coin: Coin = Coin.objects.get(cc_id=_id) updated += 1 except Coin.DoesNotExist: coin = Coin() coin.cc_id = _id new_coins += 1 coin.img_url = item.get('ImageUrl', '') coin.name = item.get('Name', '') coin.symbol = item.get('Symbol', '') coin.coin_name = item.get('CoinName', '') coin.full_name = item.get('FullName', '') coin.save() percent_done = int((idx + 1) / length * 100) self.update_state( state='RUNNING', meta={ 'current': percent_done, 'total': 100 }) print_counter += 1 if print_counter is 30: print("Status: {}%".format(percent_done)) print_counter = 0 print("new: {} updated: {}".format(new_coins, updated)) self.update_state(state='SUCCESS', meta={'current': 100, 'total': 100})
def Coins_Init(modeladmin, request, queryset): A = getCoinList() CoinNameList = A['CoinName'] coins = cryptocompare.get_coin_list(format=True) print(coins) for x in coins: if Entire_Shares.objects.filter(Share_Code=x, Share_Category=1): coin = Entire_Shares.objects.get(Share_Code=x, Share_Category=1) coin.Share_Name = CoinNameList[x] coin.save() else: Entire_Shares.objects.create( Share_Code=x, Share_Category=1, Share_Name=x, Is_feasible=True )
def choisir(): choice = int( input( "1 - Lister les crypto-monnaies\n2 - Chercher la crypto-monnaie dont vous voulez connaitre le prix\nChoix : " )) if choice == 1: list_crypto = cryptocompare.get_coin_list(format=True) for crypto in list_crypto: print(crypto) elif choice == 2: cryptosearch = input( "Entrer l'identifiant de la crypto-monnaie dont vous voulez connaitre le prix\nChoix : " ) devise = input("Entrer la devise désirée (USD ou EUR)\nChoix : ") prix = cryptocompare.get_price(cryptosearch, curr=devise, full=True) print("Prix pour la monnaie " + cryptosearch + " : " + str(prix['RAW'][cryptosearch][devise]['PRICE'])) print('---------------------------------------') else: print('---------------------------------------') print("Merci de rentrer seulement 1 ou 2") print('---------------------------------------')
#!/usr/bin/env python3.5 #-*- coding: utf-8 -*- import cryptocompare while True: curr = ['USD'] inp = input( "\nBonjour veuillez choisir votre fonctionalitée \nEntrez : \n 1: Liste des cryptomonnaies\n 2: Prix de la cryptomonnaie désirée\n 3: Quitter le programme\n> " ) if inp == '1': crypto_list = cryptocompare.get_coin_list(format=True) for liste in crypto_list: print(liste) elif inp == '2': mon = input("Entrez le nom de votre cryptomonnaie:\n") print(cryptocompare.get_price(mon, curr)) elif inp == '3': exit() else: print("Une Erreur est survenue veuillez réessayer")
#!/usr/bin/env python import cryptocompare import datetime import time coins = ['BTC', 'ETH', 'XMR', 'NEO'] currencies = ['EUR', 'USD', 'GBP'] print('================== COIN LIST =====================') print(cryptocompare.get_coin_list()) print(cryptocompare.get_coin_list(True)) print('===================== PRICE ======================') print(cryptocompare.get_price(coins[0])) print(cryptocompare.get_price(coins[1], curr='USD')) print(cryptocompare.get_price(coins[2], curr=['EUR', 'USD', 'GBP'])) print(cryptocompare.get_price(coins[2], full=True)) print(cryptocompare.get_price(coins[0], curr='USD', full=True)) print(cryptocompare.get_price(coins[1], curr=['EUR', 'USD', 'GBP'], full=True)) print('==================================================') print(cryptocompare.get_price(coins)) print(cryptocompare.get_price(coins, curr='USD')) print(cryptocompare.get_price(coins, curr=['EUR', 'USD', 'GBP'])) print('==================== HIST PRICE ==================') print(cryptocompare.get_historical_price(coins[0])) print(cryptocompare.get_historical_price(coins[0], curr='USD')) print(cryptocompare.get_historical_price(coins[1], curr=['EUR', 'USD', 'GBP'])) print(
def fullBackloadBySymbolandCurrency(symbol, currency): start_time = time.time() coin_list = cryptocompare.get_coin_list(format=False) print("Symbol: {}, Id: {}".format(symbol, coin_list[symbol]['Id'])) snapshot = cryptocompare.get_snapshotbyid(coin_list[symbol]['Id']) # Get start date for API from the snapshot list then convert to MYSQL date format start_date = datetime.datetime.strptime( snapshot['Data']['General']['StartDate'], '%d/%m/%Y').strftime('%Y-%m-%d') print(snapshot['Data']['General']['StartDate'] ) # Get ICO date, or whatever they consider a start date # if snapshot['Data']['General']['StartDate'] < '01/01/2000': print("Invalid date range, skipping") logging.warning( "Invalid date range for {}, supposed start date: {}".format( symbol, snapshot['Data']['General']['StartDate'])) return False db = MySQLdb.connect(host='127.0.0.1', user='******', passwd='pass', db='Backload', local_infile=1) # Check if connection was successful if (db): # Carry out normal procedure print("Connection successful") else: # Terminate print("Connection unsuccessful") logging.warning( "Database connection error. Symbol: {}, StartDate: {}".format( symbol, snapshot['Data']['General']['StartDate'])) return -1 cursor = db.cursor() #print("SELECT CALENDAR_DATE from DimDate where CALENDAR_DATE >= CAST('{}' AS DATE) AND CALENDAR_DATE < date(now()) order by CALENDAR_DATE limit 10;".format(start_date)) result_ct = cursor.execute( "SELECT CALENDAR_DATE from DimDate where CALENDAR_DATE >= CAST('{}' AS DATE) AND CALENDAR_DATE < date(now()) order by CALENDAR_DATE;" .format(start_date)) results = list(cursor.fetchall()) print("{} days to load.".format(len(results))) row_ct = 0 if len(results) > 0: if cryptocompare.get_historical_price( symbol, currency, datetime.datetime.combine( results[0][0], datetime.datetime.min.time())) == None: with open('allcoins/nodatacurrency.csv', 'a', newline='\n') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) writer.writerow("No data returned for: {} - {}".format( symbol, currency)) return True with open("allcoins/" + symbol + currency + '_' + 'loadHistoricalDailyPrices.csv', 'a', newline='\n') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for row in results: row_ct += 1 time.sleep( 0.5) # Slow down the API calls so as to not get banned. historical_date = datetime.datetime.combine( row[0], datetime.datetime.min.time() ) # Ugggh, did I make this column date instead of datetime? This is a quick fix until I fix the db datatype for attempt in range( 5): # Try to reconnect 5 times if we can't connect try: historical_price = cryptocompare.get_historical_price( symbol, currency, historical_date) except: print("Retrying API Call...") historical_price = cryptocompare.get_historical_price( symbol, currency, historical_date) else: break else: print( "Backloading failed, API calls got denied. Exiting...") return False print('{} rows inserted!'.format(row_ct), end='\r') try: writer.writerow([ 0, historical_date, historical_price[symbol][currency] ]) except: logging.warning( "Writerow error - Symbol: {}, Currency: {}, historicaldate: {}, historical_price: {}" .format(symbol, currency, historical_date, historical_price)) return False else: print("{} - {} backload complete.".format(symbol, currency)) elapsed_time = time.time() - start_time print("{}: {} rows inserted in {}s.\nAPI call frequency: {}".format( symbol, row_ct, elapsed_time, float(elapsed_time) / float(row_ct))) print("(If call frequency exceeds 1.67 they will ban the IP)") # Now create the db tables and load them from CSV try: createTableSQL = "CREATE TABLE {}{}_closingprice (`PK` int(11) NOT NULL AUTO_INCREMENT,`date` datetime DEFAULT NULL,`{}` double DEFAULT NULL, PRIMARY KEY (`PK`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;".format( symbol.lower().replace("*", ""), currency.lower(), currency) result_ct = cursor.execute(createTableSQL) loadTableSQL = "LOAD DATA LOCAL INFILE '~/workspace/Random/allcoins/{}{}_loadHistoricalDailyPrices.csv' INTO TABLE {}{}_closingprice FIELDS OPTIONALLY ENCLOSED BY '\"' TERMINATED BY ',' LINES TERMINATED BY '\n' (PK,@DATE,USD) SET DATE = STR_TO_DATE(@DATE, '%Y-%m-%d %H:%i:%s');".format( symbol, currency, symbol.lower(), currency.lower()) cursor.execute("START TRANSACTION;") cursor.execute( loadTableSQL) # Getting warnings here but the uploads look ok cursor.execute("COMMIT;") except Exception as e: print("Create or load table error:\n{}".format(e)) return True
#!/usr/bin/python3.5 #-*- coding: utf-8 -*- import cryptocompare as crypt #pip3 install -U lazyme from lazyme.string import color_print #On affiche toutes les cryptomonnaies sous forme d'une liste monnaies = crypt.get_coin_list() for key in monnaies: color_print(key, color='green') #on peut aussi faire print(key, end=', ') pour éviter le saut de ligne print('######################################################') print(' ------------------------------------------------------') color_print('|Saisie le nom de la cryptomonnaie que tu veux ou alors|', color='red') color_print('| saisie list pour les afficher toutes ! |', color='red') print(' ------------------------------------------------------') print('######################################################') #boucle permettant la demande de crypto à afficher, qui se break si l'on écrit quit while 1 : entree = input('Saisie un des noms de la liste ou quit pour arréter ! ') if entree!='quit': price = crypt.get_price(entree)
generalstats = ['CoinName'] facebookstats = ['Points', 'likes', 'talking_about'] cryptocomparestats = ['Points', 'Followers', 'PageViews', 'PageViewsSplit'] repostats = ['stars', 'language', 'forks', 'subscribers', 'open_total_issues'] # master dictionary for all important stats masterstats = {} masterstats['Reddit'] = redditstats masterstats['Twitter'] = twitterstats masterstats['General'] = generalstats masterstats['Facebook'] = facebookstats masterstats['CryptoCompare'] = cryptocomparestats masterstats['Repo'] = repostats # cryptocompare raw data coinlist = cryptocompare.get_coin_list() print('finished getting list of coins') # dict of coin ids; format -> {coin: id} symbol_id_dict = { 'BTC': 1182, 'ETH': 7605, 'LTC': 3808, 'XRP': 5031, 'ETC': 5324, 'ZIL': 716725, 'DASH': 3807, 'SC': 13072, 'XMR': 5038, 'NEO': 27368, 'BAT': 107672
client.get_symbol_info('BTC') cryptocompare.get_historical_price_hour('BTC', curr='USD') datetime.datetime.fromtimestamp(1551193200) cryptocompare.get_coin_list(format=False) datetime.datetime.fromtimestamp(1551186000000/1000.0) opportunities[mkt] #order = client.create_test_order( # symbol=mkt, # side=SIDE_BUY, # type=ORDER_TYPE_LIMIT, # timeInForce=TIME_IN_FORCE_GTC,
def test_get_coin_list(self): res = cryptocompare.get_coin_list() self.assertEqual(type(res), dict, "expected dict") self.assertTrue(len(res.keys()) > 0, "expected data")
def test_get_coin_list_format(self): res = cryptocompare.get_coin_list(True) self.assertEqual(type(res), list, "expected list") self.assertTrue(len(res) > 0, "expected data")
#!/usr/bin/env python3.5 #-*- coding: utf-8 -*- import cryptocompare while True: print("Que voulez-vous savoir ? \n") print(" \n") print("1) Valeur d'une crypto-monnaie \n") print("2) Liste des crypto-monnaies \n") print("3) Quitter \n") user_question = input('>>> ') if (user_question.startswith('1')): print('Quelle crypto-monnaie en Euro, voulez-vous? \n') user_value = input('>>> ') print(cryptocompare.get_price(user_value, curr='EUR')) elif (user_question.startswith('2')): for list_crypto in cryptocompare.get_coin_list(format=True): print(list_crypto) elif (user_question.startswith('3')): print("A bientôt \n") exit() else: print("Répondez par '1', '2' ou '3' \n")
from typing import Optional import cryptocompare from great_expectations.core.expectation_configuration import ExpectationConfiguration from great_expectations.execution_engine import PandasExecutionEngine from great_expectations.expectations.expectation import ColumnMapExpectation from great_expectations.expectations.metrics import ( ColumnMapMetricProvider, column_condition_partial, ) CRYPTO_TICKER_LIST = list(cryptocompare.get_coin_list(format=False).keys()) # This method compares a string to the valid cryptocurrency ticker. def is_valid_crypto_ticker(ticker: str) -> bool: return ticker in CRYPTO_TICKER_LIST # This class defines a Metric to support your Expectation. # For most ColumnMapExpectations, the main business logic for calculation will live in this class. class ColumnValuesToBeValidCryptoTicker(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_crypto_ticker" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column, **kwargs): return column.apply(lambda x: is_valid_crypto_ticker(x))
def test_get_coin_list(self): res = cryptocompare.get_coin_list() self.assertTrue(len(res) > 0, "expected data") self.assertEqual(res['ETH']['CoinName'], 'Ethereum')
def show_coin_list(): coin_list = cryptocompare.get_coin_list(format=True) for coin in coin_list: print(coin)
#!/usr/bin/env python3.5 #-*- codding: utf-8 -*- #Jérémy ROBIN B2b import cryptocompare global found found = False listeCrypto = cryptocompare.get_coin_list(format=True) def triCrypto(coinSelected): for coin in listeCrypto: if coinSelected == coin: prix = cryptocompare.get_price(coin) found = True print(">> Prix d'un " + coin + " " + str(prix[coin]['EUR']) + " EUR") if (found == False): print('Veuillez entré une crypto dans la liste') def Liste(liste): count = 0 for i in liste: print(i) #Core Liste(listeCrypto)
def get_crypto_list(): return [e for e in cryptocompare.get_coin_list(format=False)]
import cryptocompare while True: choix = input( "Appuyez sur 'L' pour afficher la liste de cryptomonnaie, sinon, Ecrivez le nom de la Cryptomonnaie que vous voulez afficher (BTC, EUR, ETH etc...), appuyez sur 'x' pour quitter : " ) if choix == 'L': print(cryptocompare.get_coin_list(format=True)) elif choix == 'x': break else: currency = cryptocompare.get_price(choix) print(currency)
def get_coin_list(self): list = cryptocompare.get_coin_list(format=False) return list
def test_coin_list(self): lst = cryptocompare.get_coin_list() self.assertTrue('BTC' in lst.keys()) lst = cryptocompare.get_coin_list(True) self.assertTrue('BTC' in lst)
print(cryptocompare.get_historical_price_hour(coins[0], curr='USD', limit=2, exchange='Coinbase', quiet=False)) print(cryptocompare.get_historical_price_hour(coins[0], curr='USD', limit=2, exchange='Kraken', quiet=True)) print(cryptocompare.get_historical_price_hour(coins[0], curr='USD', limit=5, timestamp=1572375600, exchange='Coinbase', quiet=False)) print('================== hacked PRICE DAY ================') print(cryptocompare.get_historical_price_day(coins[0])) print(cryptocompare.get_historical_price_day(coins[0], curr='USD')) print(cryptocompare.get_historical_price_day(coins[1], curr=['EUR','USD','GBP'], quiet=False)) print(cryptocompare.get_historical_price_day(coins[1], curr=['EUR','USD','GBP'], quiet=True)) print(cryptocompare.get_historical_price_day(coins[0], curr='USD', limit=1, quiet=False)) print(cryptocompare.get_historical_price_day(coins[0], curr='USD', limit=1, exchange='Coinbase', quiet=False)) print(cryptocompare.get_historical_price_day(coins[0], curr='USD', limit=1, exchange='Kraken', quiet=False)) print('================== COIN LIST =====================') response, err = cryptocompare.get_coin_list() print(response) response, err = cryptocompare.get_coin_list(True) print(response) print('===================== PRICE ======================') print(cryptocompare.get_price(coins[0])) print(cryptocompare.get_price(coins[1], curr='USD')) print(cryptocompare.get_price(coins[2], curr=['EUR','USD','GBP'])) print(cryptocompare.get_price(coins[2], full=True)) print(cryptocompare.get_price(coins[0], curr='USD', full=True)) print(cryptocompare.get_price(coins[1], curr=['EUR','USD','GBP'], full=True)) print('==================================================') print(cryptocompare.get_price(coins)) print(cryptocompare.get_price(coins, curr='USD'))