def get_coin_price(coin_code, currency_code): """ Returning the current btc/eth price for specified currency """ data = cryptocompare.get_price(coin_code, currency_code) return data[coin_code][currency_code]
#!/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")
def get_bitcoin_price(self): price = cryptocompare.get_price('BTC', curr='USD')['BTC']['USD'] formated = str(price)[0:2] + " " + str(price)[2::] + "$" returns = self.calculate_return(self.bitcoin_init, price) return [formated, returns]
#!/usr/bin/env python3.5 #-*- coding: utf-8 -*- import cryptocompare crypto = '' print(cryptocompare.get_coin_list(format=False)) while crypto != 'exit': crypto = input( 'De quelle cryptomonnaie souhaitez-vous connaitre le prix ? ') print(cryptocompare.get_price(crypto))
#pip install cryptocompare import cryptocompare btc = cryptocompare.get_price('BTC') print(btc)
def get_dogecoin_price(self): price = cryptocompare.get_price("DOGE", curr='USD')['DOGE']['USD'] formated = str(price) + "$" returns = self.calculate_return(self.dogecoin_init, price) return [formated, returns]
def test_get_price_defaults(self): res = cryptocompare.get_price('BTC') self.assertIsNotNone(res[coins[0]]) self.assertTrue( float(res[coins[0]][cryptocompare.DEFAULT_CURRENCY]) > 0)
def Handle_CryptoCurrency(scd, RD_id, gapSeed): if gapSeed == 'N/A': gapSeed = '0' gapSeed = int(gapSeed) RD_row = RD_Related_To_Shares.objects.get(id=RD_id) currentPrice = cryptocompare.get_price(scd, 'USD') #('BTC') yesterday = date.today() - timedelta(1) #yesterday = datetime.strftime(datetime.now() - timedelta(1), '%Y:%m:%d') yesterday = yesterday.strftime('%Y:%m:%d') yestList = yesterday.split(':') y = int(yestList[0]) m = int(yestList[1]) d = int(yestList[2]) yesterdayPrice = cryptocompare.get_historical_price(scd, 'USD', timestamp=datetime( y, m, d)) currentPrice = currentPrice[scd]['USD'] yesterdayPrice = yesterdayPrice[scd]['USD'] hPrice = currentPrice - yesterdayPrice excgR = MarketStatus.exchRate() hPrice = hPrice * excgR currentPrice = currentPrice * excgR #initQuant = currentPrice #QuantMado = "61;62;63;64;65;66;67;68;69;" #QuantMaSu = "71;72;73;74;75;76;77;78;79;" q = [] if gapSeed < 2: gapSeed = 2 for i in range(0, 18): rn = random.randrange(0, gapSeed) rn = rn / 15000000 q.append("{0:.4f}".format(rn)) currentPrice = int(currentPrice) length = len(str(currentPrice)) divider = length - 5 if divider < 0: divider = 0 fixer = pow(10, -divider) currentPrice = int(fixer * currentPrice) temp = currentPrice / fixer currentPrice = temp dict = { 'scd': scd, '10': currentPrice, '15': 1, '11': hPrice, '61': q[0], '62': q[1], '63': q[2], '64': q[3], '65': q[4], '66': q[5], '67': q[6], '68': q[7], '69': q[8], '71': q[9], '72': q[10], '73': q[11], '74': q[12], '75': q[13], '76': q[14], '77': q[15], '78': q[16], '79': q[17] } RD_row.RDDictString = json.dumps(dict) RD_row.Should_be_updated_now = False RD_row.save() return
# -*- coding: utf-8 -*- """ Created on Tue May 14 09:45:38 2019 @author: Jeffrey """ """ Be sure to download this papckage first.... pip install cryptocompare """ import cryptocompare #Gathers all the prices and prints themin thier top 20 rank from 5/16/19 print("Below are the top 20 coins according to Coinbase...") BTCprice = cryptocompare.get_price('BTC', curr='USD', full=False) print('1: ', BTCprice) ETHprice = cryptocompare.get_price('ETH', curr='USD', full=False) print('2: ', ETHprice) XRPprice = cryptocompare.get_price('XRP', curr='USD', full=False) print('3: ', XRPprice) BCHprice = cryptocompare.get_price('BCH', curr='USD', full=False) print('4: ', BCHprice) LTCprice = cryptocompare.get_price('LTC', curr='USD', full=False)
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')) 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']))
import cryptocompare btc_inr = cryptocompare.get_price("BTC", currency="INR") print(btc_inr) doge_inr = cryptocompare.get_price("DOGE", currency="INR") print(doge_inr) ethereum_inr = cryptocompare.get_price("ETH", currency="INR") print(ethereum_inr) litecoin_inr = cryptocompare.get_price("LTC", currency="INR") print(litecoin_inr) Stellar_inr = cryptocompare.get_price("XLM", currency="INR") print(Stellar_inr)
while True: print(" ** Which one Do you want?") print("\n ** 1.My IP **") print(" ** 2.BTC Price **") print(" ** 3.Whois **") print(" ** 4.MailBomber **") print(" ** 5.DDoser **") print(" ** 0.Exit **") men = int(input(" ))=>> ")) if men == 1: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) print(" ** Your ip :", s.getsockname()[0]) s.close() elif men == 2: btc = cryptocompare.get_price('BTC', currency='USD')["BTC"]["USD"] print(" ** Price =", btc, "$") elif men == 3: print(" ** Enter the website :") site = input(" ))=>> ") w = whois.whois(site) print(w) elif men == 4: server = input(' ** MailServer 1.Gmail/2.Yahoo: ') user = input(' ** Email: ') passwd = getpass.getpass(' ** Password: '******'\n ** To: ') body = input(' ** Message: ') total = int(input(' ** Number of send: ')) if server == 'gmail' or '1' or 'Gmail': smtp_server = 'smtp.gmail.com'
#!/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")
def get_price(crypto): if crypto.upper() in get_crypto_list(): return cryptocompare.get_price( 'BTC', curr='USD', full=True)['RAW'][crypto.upper()]['USD']['PRICE'] return ""
def test_get_price_against_currency(self): res = cryptocompare.get_price(coins[0], currencies=currencies[0]) self.assertIsNotNone(res[coins[0]]) self.assertIsNotNone(res[coins[0]][currencies[0]]) self.assertTrue(float(res[coins[0]][currencies[0]]) > 0)
def getvalue(coin): getvalue = cryptocompare.get_price(coin, curr='USD', full=False) getvalue = getvalue[coin].get('USD') print(getvalue) return getvalue
def crypto(update, context): new_message.new_message(update) with open('config.yaml', 'r') as f: config = yaml.full_load(f) apikey = config['CRYPTO']['API_KEY'] if enable_check.enable_check(__name__): return def changepct(time): if len(context.args) >= 2: currency1 = context.args[1] else: currency1 = "BTC" if len(context.args) == 3: currency2 = context.args[2] else: currency2 = "USD" url = f"https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?CMC_PRO_API_KEY={apikey}&symbol={currency1.upper()}&convert={currency2.upper()}" r = requests.get(url) msg = r.json()['data'][currency1.upper()]['quote'][ currency2.upper()][f'percent_change_{time[:-1]}'] if msg > 0.01 or msg < -0.01: msg = round(msg, 2) if msg > 0.0: msg = f"+{msg}" return msg # crypto % change for past 24h, 7d, 30d if len(context.args) >= 1 and context.args[0] in ['24h%', '7d%', '30d%']: msg = changepct(context.args[0]) context.bot.send_message(chat_id=update.message.chat_id, text=f'{msg}%') # /crypto 24h btc elif len(context.args) >= 1 and context.args[0] == "24h": if len(context.args) >= 2: currency1 = context.args[1] else: currency1 = "BTC" if len(context.args) == 3: currency2 = context.args[2] else: currency2 = "USD" try: symbol = currency.symbol(currency2, native=False) except: symbol = "" avg = cryptocompare.get_avg(currency1, currency=currency2) msg = avg['CHANGE24HOUR'] if msg > 0.01 or msg < -0.01: msg = round(msg, 2) if msg > 0.0: msg = f"+{msg}" context.bot.send_message(chat_id=update.message.chat_id, text=f"{msg}{symbol}") # /crypto btc eur elif len(context.args) >= 1: currency1 = context.args[0].upper() if len(context.args) == 2: currency2 = context.args[1].upper() else: currency2 = "USD" try: symbol = currency.symbol(currency2, native=False) except: symbol = '' price = cryptocompare.get_price(currency1, currency=currency2, full=False) if price: context.bot.send_message( chat_id=update.message.chat_id, text=f"{symbol}{price[currency1][currency2]}") else: context.bot.send_message(chat_id=update.message.chat_id, text=f"Sorry, can\'t find {currency1}") return elif not context.args or len(context.args) > 3: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/crypto <btc,eth,xmr,etc>`') return
def treat_real(coin, v): v = v.replace(coin, u'') v = v.replace(u'$', u'') v = v.replace(u',', u'') return v if __name__ == '__main__': assert len(sys.argv) == 2 db = sqlite3.connect(sys.argv[1]) cursor = db.cursor() cycle = 0 while True: query = get_price(COIN_LIST, full=True) if query is not None: timestamp = time.time() tables = query['RAW'] for coin, d in tables.items(): cmd = "INSERT INTO %s VALUES(" % coin cmd += "%s," % str(timestamp) for key in DB_TABLE_ORDER[1:]: v = d[u'USD'][key] if isinstance(v, str): cmd += "'%s'" % str(v) else: cmd += "%s" % str(v) if key != DB_TABLE_ORDER[-1]: cmd += ",\n" cmd += ");"
async def bat(ctx): price = cryptocompare.get_price('BAT', 'EUR') await ctx.send(price['BAT']['EUR'], "€")
def get_historical(self, coin, time_step, nod, end=datetime.now(), columns=['close'], currency="USD", add_this_moment_price=False): """ :param: coin: It should be symbol. e.x 'BTC' :param: time_step: It can be 'day' for price history in last days, 'hour' for ... and 'min' for ... :param: nod: Number of dates. Actually number of rows in returned dataframe(Except when add_this_moment_price is True) :param: end: Default is today date. But can pass a date to recive data from nod days before end to end day :param: columns: A list of columns from ['high', 'low', 'open', 'volumefrom', 'volumeto', 'close']. And if it is 'OHLC', columns will be consideres as ['open', 'high', 'low', 'close']. :param: add_this_moment_price: Only works when columns=['close']. Adds this moment's price to dataframe. :param: currency: currency unit :returns: A dataframe with index of time laps and columns passed """ if columns == "OHLC": #Famous open, high, low, close dataframe for candle bars columns = ['open', 'high', 'low', 'close'] if columns == "OHLCV": columns = ['open', 'high', 'low', 'close', 'volumeto'] if time_step == "day": data = cc.get_historical_price_day(coin, currency, limit=nod, toTs=end) elif time_step == "hour": data = cc.get_historical_price_hour(coin, currency, limit=nod, toTs=end) elif time_step == "min": data = cc.get_historical_price_minute(coin, currency, limit=nod, toTs=end) else: raise ValueError( "Only 'day', 'hour' and 'min' are valid as time_stamp") df = pd.DataFrame.from_dict( data) #converting json like recived data to a pandas df index = [datetime.fromtimestamp(tstamp) for tstamp in df.time] dates = [t + timedelta(seconds=510 * 60 - 21) for t in index] # Converting timelaps to Tehran time zone df.index = dates if add_this_moment_price: if columns == ['close'] and time_step == "min": #Adding this moment's price to tail price = cc.get_price(coin, currency)[coin][currency] t = datetime.now() now_df = pd.DataFrame({"close": price}, index=[t]) df = df.append(now_df) else: raise ValueError( "add_this_moment_price will only work when dataframe is a price table and time_step is 'min'" ) return df[columns]
def get_price(from_coins: [str, list], to_coins: [str, list]): compare = cryptocompare.get_price(from_coins, to_coins) return compare
def get_litecoin_price(self): price = cryptocompare.get_price("LTC", curr='USD')['LTC']['USD'] formated = str(price) + "$" returns = self.calculate_return(self.litecoin_init, price) return [formated, returns]
def startTrading(): # adjustable variables ticker = "BTC" coinsToBuy = 5 buyingFrequency = 3 # in seconds totalRuntime = 3600 # in seconds startingCashReserve = 10000000 # tracking variables cash = startingCashReserve coinsOwned = 0 timeSpent = 0 previousPrice = cryptocompare.get_price(ticker, curr="USD", full=False)['BTC']['USD'] valueOfInvestment = 0 costOfInvestment = 0 unrealizedGains = 0 profit = 0 openingPrice = cryptocompare.get_price(ticker, curr="USD", full=False)['BTC']['USD'] closingPrice = 0 startTime = datetime.now().strftime("%m/%d/%Y %H:%M:%S") # graphing data prices = [] profitOrLoss = [] percentPriceChange = [] while (timeSpent < totalRuntime): time.sleep(buyingFrequency) currentPrice = cryptocompare.get_price(ticker, curr="USD", full=False)['BTC']['USD'] # if share price increases or remains the same, buy more # only calculated profits if buying, otherwise record as unrealized gains if (currentPrice >= previousPrice): cash -= coinsToBuy * currentPrice coinsOwned += coinsToBuy costOfInvestment += coinsToBuy * currentPrice valueOfInvestment = coinsOwned * currentPrice unrealizedGains += valueOfInvestment - costOfInvestment # profit += valueOfInvestment - costOfInvestment timeSpent += buyingFrequency # if share price decreases, sell all shares # convert unrealized gains into profits / loss if (currentPrice < previousPrice): valueOfInvestment = coinsOwned * currentPrice profit += valueOfInvestment - costOfInvestment # reset tracking variables unrealizedGains = 0 costOfInvestment = 0 valueOfInvestment = 0 coinsOwned = 0 timeSpent += buyingFrequency prices.append(currentPrice) profitOrLoss.append(profit) percentPriceChange.append( ((currentPrice - previousPrice) / previousPrice) * 100) previousPrice = currentPrice # calculate current net income & shares owned print("Current Price: $" + str(currentPrice)) print("Value of Investment: $" + str(valueOfInvestment)) print("Cost of Posistion: $" + str(costOfInvestment)) print("Profit: $" + str(profit)) print("Coins Owned: " + str(coinsOwned)) print("*****************\n") # close posistion at end of trading cash = cash + (coinsOwned * currentPrice) coinsOwned = 0 timeSpent += buyingFrequency closingPrice = currentPrice closingTime = datetime.now().strftime("%m/%d/%Y %H:%M:%S") totalPercentPriceChange = (((closingPrice - openingPrice) / openingPrice) * 100) truncatedTotalPercentPriceChange = '%.4f' % (totalPercentPriceChange) # calculate final profit/loss print("Opening Price: $" + str(openingPrice)) print("Closing Price: $" + str(closingPrice)) print("Stock Price Change: " + str(totalPercentPriceChange)) print("Profit / Loss: $" + str(profit)) # write results to appropriate txt file tradeDetails = [ startTime, closingTime, ticker, openingPrice, closingPrice, truncatedTotalPercentPriceChange, buyingFrequency, totalRuntime, coinsToBuy, profit ] writeTradeDetails(tradeDetails) writeGraphingDetails(prices, profitOrLoss, percentPriceChange) return prices, profitOrLoss, percentPriceChange
def test_get_price_full(self): price = cryptocompare.get_price('ETH', full=True) self.assertIn('RAW', price) self.assertIn('ETH', price['RAW']) self.assertIn('EUR', price['RAW']['ETH']) self.assertIn('PRICE', price['RAW']['ETH']['EUR'])
def of(self, instr): data = cryptocompare.get_price(instr, curr='USD') return Decimal(data[instr]['USD'])
def get_price(self): return cryptocompare.get_price(self.name, curr=self.curr)[self.name][self.curr]
import cryptocompare import io import ipfshttpclient import matplotlib.pyplot as plt import pytest import qrcode import os app = Flask(__name__) babel = Babel(app) translator = Translator() app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False test_address = os.environ.get('TEST_ADDRESS') private_key = os.environ.get('PRIVATE_KEY') web3 = Web3(Web3.HTTPProvider(os.environ.get('ROPSTEN_URL'))) valorUDC = cryptocompare.get_price('ETH').get('ETH').get('EUR') init_db() app.secret_key = os.environ.get("PRIVATE_KEY") app.config["PRIVATE_KEY"] = app.secret_key oauth = OAuth(app) google = oauth.register( name='google', client_id=os.environ.get('GOOGLE_CLIENT_ID'), client_secret=os.environ.get('GOOGLE_CLIENT_SECRET'), access_token_url='https://accounts.google.com/o/oauth2/token', access_token_params=None, authorize_url='https://accounts.google.com/o/oauth2/auth', authorize_params=None, api_base_url='https://www.googleapis.com/oauth2/v1/', userinfo_endpoint='https://openidconnect.googleapis.com/v1/userinfo',
def get_usd_crypto_price(coin): usd_crypto_price = str(cryptocompare.get_price( coin, currency='USD')).strip('{}:') f = usd_crypto_price.split(' ') usd_price = f[2] return usd_price
def get_balance(test_address): web3 = Web3(Web3.HTTPProvider(os.environ.get('ROPSTEN_URL'))) balance = web3.eth.getBalance(test_address) valorUDC = cryptocompare.get_price('ETH').get('ETH').get('EUR') balancefloat = float(web3.fromWei(balance, "ether")) * valorUDC return balancefloat
app.tokenContract = 0 app.crowdContract = 0 app.wallet = 0 app.cap = 0 app.goal = 0 app.cloTime = 0 app.balances = {} app.name = '' accounts = [] for i in range(10): accounts.append(w3.eth.accounts[i]) app.name_accounts = ['Producer','Collaborator 1', 'Collaborator 2', 'Investor 1', 'Investor 2',\ 'Investor 3', 'Investor 4', 'Consumer 1', 'Consumer 2', 'Consumer 3'] app.accounts = {app.name_accounts[i]: accounts[i] for i in range(10)} exchange_rate = cryptocompare.get_price('ETH', curr='USD')['ETH'][ 'USD'] # used to have real time eth/dollar exchange rate ## FUNCTIONS # Convert from usual date-time format to unix one which is read by the MovBitCrowdsale contract def convertToUnix(s): date, time = s.split(" ") day, month, year = date.split("/") hour, minute = time.split(":") return int(datetime.datetime(int(year),int(month),int(day),\ int(hour), int(minute)).timestamp()) # Convert from unix date-time format to usal one def convertToDate(s): timestamp = datetime.datetime.fromtimestamp(int(s))
import cryptocompare btc = cryptocompare.get_price('BTC', currency='BRL') print(btc) # RESULTADO {'BTC': {'BRL': 314056.13}} doge = cryptocompare.get_price('DOGE', currency='BRL') print(doge) # RESULTADO {'DOGE': {'BRL': 1.828}}