def compare_actual_market_prices(base, quote, amount_in_eur, clients): """ Compares actual price for given base amount in EUR """ amount_in_eur = amount_in_eur / price.get_current_price(base, 'EUR')[base]['EUR'] cols = ['pair'] for client in clients: cols += [client.describe()['name'] + ' buy', client.describe()['name'] + ' sell'] df = pd.DataFrame(columns=cols) pair = base + '/' + quote row = {} row['pair'] = pair for client in clients: try: buy_price, sell_price = calc_market_price(base, quote, amount_in_eur, client) except ExchangeError: print('error') continue row[client.describe()['name'] + ' buy'] = buy_price row[client.describe()['name'] + ' sell'] = sell_price df = df.append(row, ignore_index=True) return df
def gen_crypto_data(item_id): result = MySQL(item_id).searchTweetsByHour() fsym = item_id.upper() price_data = price.get_current_price( fsym, 'USD', e='all', try_conversion=True, full=True, format='raw')[fsym]['USD'] result['price'] = price_data['PRICE'] result['coin_supply'] = price_data['SUPPLY'] result['market_cap'] = price_data['MKTCAP'] result['velocity'] = result['price'] * \ result['coin_supply'] / result['market_cap'] result['high'] = 0 result['low'] = float("inf") result['volume_sold'] = 0 for data in price.get_historical_data( fsym, 'USD', 'minute', aggregate=10, limit=6): result['high'] = data['high'] if data['high'] > result['high'] else result['high'] result['low'] = data['low'] if data['low'] < result['low'] else result['low'] result['volume_sold'] += data['volumeto'] file_path = './out/' + fsym + '_crypto.xlsx' if not os.path.isfile(file_path): wb = Workbook() ws = wb.active ws.append(['price', 'high', 'low', 'volume_sold', 'coin_supply', 'market_cap', 'velocity', 'amount_hour', 'amount_avg', 'amount_spike', 'sentiment_hour', 'sentiment_avg', 'sentiment_spike']) wb.save(file_path) else: wb = load_workbook(file_path) ws = wb.active ws.append([time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), result['price'], result['high'], result['low'], result['volume_sold'], result['coin_supply'], result['market_cap'], result['velocity'], result['amount_hour'], result['amount_avg'], result['amount_spike'], result['sentiment_hour'], result['sentiment_avg'], result['sentiment_spike']]) wb.save(file_path) return result
def get_coin_price(self, coin, unit): symbol = coin.symbol res = cryptocompy_price.get_current_price(symbol, unit, full=True) infos = res[symbol][unit] price, high, low = self.prices_from_res_infos(infos) return CurrencyPrice(coin, price, low, high)
def get_single_price(base, quote, exchange, ret_float=False): """ Get price of a single pair. Will check both directions (e.g. BTC-LTC and LTC-BTC). :param base: base curr (or quote if reversed) :param quote: quote curr (or base if reversed) :param exchange: exchange str :param ret_float: optionally return price as float :return: returns price as dict """ assert (isinstance(base, str) and isinstance(quote, str)), 'Single pair only' p = price.get_current_price(base, quote, e=exchange) if 'Type' in p: p = price.get_current_price(quote, base, e=exchange) if 'Type' in p: raise PairNotListedError('{}-{} pair (or reverse) not listed on {}'.format(base, quote, exchange)) p = {base: {quote: 1/p[quote][base]}} return p if not ret_float else p[base][quote]
def get_coins_prices(self, coins, unit): symbols = [coin.symbol for coin in coins] res = cryptocompy_price.get_current_price(symbols, unit, full=True) for symbol, info in res.items(): price, high, low = self.prices_from_res_infos(info[unit]) coin = [c for c in coins if c.symbol == symbol] yield CurrencyPrice(coin[0], price, low, high)
def test_get_current_price_inputs(fsim, tsim): prices = price.get_current_price(fsim, tsim) assert "BTC" in prices.keys() btc_prices = prices['BTC'] assert 'USD' in btc_prices.keys()
def test_get_display_current_price(): res = price.get_current_price("BTC", "USD", full=True, format='display') assert res['BTC']['USD'] btc_price = res['BTC']['USD'] assert btc_price['PRICE'] == '$ 6,591.28' assert btc_price['LASTUPDATE'] == 'Just now' assert btc_price['MKTCAP'] == '$ 114.01 B'
def get_rate(currency="USD"): """ Return price of 1 currency in ETH :param currency: currency to convert to :return: conversion rate from currency to ETH """ if currency is None: return None factor_dict = price.get_current_price("ETH", currency) factor = factor_dict["ETH"][currency] return 1.0 / factor
def compare_two_exchanges(base, quote, e1, e2): """ Compares one or more pair prices for 2 exchanges. """ if isinstance(base, str) and isinstance(quote, str): ex1 = get_single_price(base, quote, e1) ex2 = get_single_price(base, quote, e2) else: ex1 = price.get_current_price(base, quote, e=e1) ex2 = price.get_current_price(base, quote, e=e2) if 'Type' in ex1 or 'Type' in ex2: raise PairNotListedError('One or more pairs not listed in both exchanges') df = pd.DataFrame(columns=['Pair', e1, e2, '% diff']) for b in ex1: for q in ex1[b]: row = { 'Pair': b + '-' + q, e1: ex1[b][q], e2: ex2[b][q], '% diff': 100 * (ex1[b][q]/ex2[b][q] - 1) } df = df.append(row, ignore_index=True) return df
def update_cc_prices(): cryptocoins = ['ETH', 'BTC'] currencies = ['EUR', 'USD'] response = price.get_current_price(cryptocoins, currencies) channel_layer = get_channel_layer() for cryptocoin in cryptocoins: for currency in currencies: latest_price = response[cryptocoin][currency] ticker_code = cryptocoin + currency if cache.get(ticker_code) != latest_price: cache.set(ticker_code, response[cryptocoin][currency]) async_to_sync(channel_layer.group_send)(ticker_code, { 'type': 'price_update', 'price': latest_price, })
def test_get_full_current_price(): res = price.get_current_price("BTC", "USD", full=True) assert res['BTC']['USD'] btc_price = res['BTC']['USD'] assert btc_price['TYPE'] == '5' assert btc_price['MARKET'] == 'CCCAGG' assert btc_price['FROMSYMBOL'] == 'BTC' assert btc_price['TOSYMBOL'] == 'USD' assert btc_price['FLAGS'] == '4' assert btc_price['PRICE'] == 6593.57 assert btc_price['LASTUPDATE'] == 1538255360 assert btc_price['LASTVOLUME'] == 0.01861566 assert btc_price['LASTVOLUMETO'] == 122.3979645 assert btc_price['LASTTRADEID'] == '51692673' assert btc_price['VOLUMEDAY'] == 34753.13910881231 assert btc_price['VOLUMEDAYTO'] == 228196363.20126274 assert btc_price['VOLUME24HOUR'] == 36811.604030178525 assert btc_price['VOLUME24HOURTO'] == 241927684.9410378 assert btc_price['OPENDAY'] == 6635.4 assert btc_price['HIGHDAY'] == 6635.42 assert btc_price['LOWDAY'] == 6474.23 assert btc_price['OPEN24HOUR'] == 6652.5 assert btc_price['HIGH24HOUR'] == 6663.43 assert btc_price['LOW24HOUR'] == 6472.26 assert btc_price['LASTMARKET'] == 'Coinbase' assert btc_price['CHANGE24HOUR'] == -58.93000000000029 assert btc_price['CHANGEPCT24HOUR'] == -0.8858323938369078 assert btc_price['CHANGEDAY'] == -41.82999999999993 assert btc_price['CHANGEPCTDAY'] == -0.6304066069867669 assert btc_price['SUPPLY'] == 17295637 assert btc_price['MKTCAP'] == 114039993254.09 assert btc_price['TOTALVOLUME24H'] == 183347.3560109875 assert btc_price['TOTALVOLUME24HTO'] == 1208121423.1291404
def get_price(cryptocurrency, currency): prices_crypto = price.get_current_price(cryptocurrency, [currency], e='all', try_conversion=True, full=False, format='raw') return prices_crypto.get(cryptocurrency).get(currency)
from cryptocompy import price bitcoin = price.get_current_price("BTC", ["EUR"]) litecoin = price.get_current_price("LTC", ["EUR"]) zcash = price.get_current_price("ZEC", ["EUR"]) print("H τιμή του bitcoin ειναι:", bitcoin['BTC']['EUR']) print("H τιμή του litecoin ειναι:", litecoin['LTC']['EUR']) print("H τιμή του zcash ειναι:", zcash['ZEC']['EUR'])
def fetch_coin(coin, fiat): r = price.get_current_price(coin, fiat) return r[coin][fiat]
from cryptocompy import price import pprint value = price.get_current_price(["BTC", "LTC", 'ZEC'], 'EUR') pprint.pprint(value, width=1)
pip install cryptocompy from cryptocompy import price price = price.get_current_price(["BTC", "LTC", "ZEC"], ["EUR"])
def get_value(): dace1 = price.get_current_price("BTC", "EUR") return dace1["BTC"]["EUR"]
def get_current_price(coin): p = price.get_current_price(coin, "USD") return p[coin]["USD"]
def get_total_balance(clients, gbp_only=False, wallets=None, funds_invested=None): """ Analyses balance of funds across one or more exchanges. Note: Prices for small coins like IOTA and XRB are currently incorrect on cryptocompare. :param clients: Dict of ccxt authenticated clients with exchange names as keys :param wallets: optional dict of coins held in private wallets (e.g. {'BTC': 1.1, 'LTC': 0.02}) :param gbp_only: optionally return GBP values only :param funds_invested: optionally input GBP invested for profit calculation :return: DataFrame of balance """ eur2gbp = CurrencyRates().get_rate('EUR', 'GBP') pd.set_option('expand_frame_repr', False) pd.options.display.float_format = '{:.2f}'.format # build df columns from currencies df_cols = ['Exchange'] totals = {} coins = set() for ex in clients: totals_raw = clients[ex].fetch_balance()['total'] totals[ex] = {} for curr in totals_raw: if totals_raw[curr] > 0.01: totals[ex][curr] = totals_raw[curr] for curr in totals[ex]: if curr not in FIAT: coins.add(curr) # add wallets totals['Wallets'] = {} for curr in wallets: totals['Wallets'][curr] = wallets[curr] coins.add(curr) df_cols += list(coins) + ['EUR', 'GBP', 'Total (GBP)'] df = pd.DataFrame(columns=df_cols) avg_prices = price.get_current_price([c for c in coins if c != 'BTC'], 'BTC') btc2gbp = price.get_current_price('BTC', 'GBP')['BTC']['GBP'] # print(avg_prices) # print(btc2gbp) # build row values for each exchange for ex in totals: row = {} total_gbp = 0 for col in df: if col == 'Exchange': row['Exchange'] = ex elif col in totals[ex]: row[col] = totals[ex][col] if col == 'EUR': total_gbp += row[col] * eur2gbp elif col == 'GBP': total_gbp += row[col] elif col == 'BTC': total_gbp += row[col] * btc2gbp else: total_gbp += row[col] * avg_prices[col]['BTC'] * btc2gbp else: row[col] = 0. row['Total (GBP)'] = total_gbp df = df.append(row, ignore_index=True) # total all exchanges in each curr and GBP row_totals = {} row_gbp_totals = {} for col in df_cols: if col == 'Exchange': row_totals['Exchange'] = 'Total' row_gbp_totals['Exchange'] = 'Total (GBP)' else: row_totals[col] = sum(df[col].values) if col == 'EUR': row_gbp_totals[col] = row_totals[col] * eur2gbp elif col == 'GBP' or col == 'Total (GBP)': row_gbp_totals[col] = row_totals[col] elif col == 'BTC': row_gbp_totals[col] = row_totals[col] * btc2gbp else: row_gbp_totals[ col] = row_totals[col] * avg_prices[col]['BTC'] * btc2gbp df = df.append(row_totals, ignore_index=True) df = df.append(row_gbp_totals, ignore_index=True) # add percentage of funds stored in each exchange perc_col = [] for i, row in df.iterrows(): if row['Exchange'] != 'Total': perc_col.append(100 * row['Total (GBP)'] / df['Total (GBP)'].values[-1]) perc_col.append(100) df['%'] = perc_col # add percentage of funds in each curr perc_row = {} for col in df_cols: if col == 'Exchange': perc_row[col] = '%' else: perc_row[ col] = 100 * df[col].values[-1] / df['Total (GBP)'].values[-1] perc_row['%'] = 100 df = df.append(perc_row, ignore_index=True) # formatting and sorting df = df.loc[:, (df > 1).any(axis=0)] # delete columns with less than £1 in df = df[:-3].sort_values(by='%', ascending=False).reset_index(drop=True).append( df[-3:], ignore_index=True) df = pd.concat([ df.iloc[:, 0], df.iloc[:, 1:-3].sort_values( by=len(df) - 1, ascending=False, axis=1), df.iloc[:, -3:] ], axis=1) print(df) # profit calc if funds_invested is not None: current_value = df['Total (GBP)'].values[-2] profit = current_value - funds_invested profitperc = 100 * profit / funds_invested print( '\nInvested: £{:.2f}, Current Value: £{:.2f}, Profit: £{:.2f}, {:+.2f}%' .format(funds_invested, current_value, profit, profitperc)) if gbp_only: return df[['Exchange', 'Total (GBP)']][:-2] else: return df
import json from cryptocompy import price import datetime import time import numpy import matplotlib.pyplot as plt '''cryptocurrencies market data streaming''' BTC_volume = [0] BTC_time = [0] ETH_volume = [] XRP_volume = [] starttime = time.time() while True: #import cryptocurrency market volume coin_data = price.get_current_price(["BTC", "ETH", "XRP"], ["USD"], full=True) BTC_volume.append((coin_data['BTC']['USD']['LASTVOLUME'])) #get time from data BTC_LASTUPDATE = (coin_data['BTC']['USD']['LASTUPDATE']) BTC_time_form = datetime.datetime.fromtimestamp(BTC_LASTUPDATE).strftime( '%H%M') BTC_time.append(int(BTC_time_form)) time.sleep(60.0 - ((time.time() - starttime) % 60.0)) print(BTC_volume) print(BTC_time)