def test_failed_get_token_price(self): # Arrange responses.add( responses.GET, 'https://api.coingecko.com/api/v3/simple/token_price/ethereum?include_market_cap=true&include_24hr_vol=true&include_last_updated_at=true&contract_addresses=0xB8c77482e45F1F44dE1745F52C74426C631bDD52&vs_currencies=bnb', status=404) exception = HTTPError("HTTP Error") # Act Assert with pytest.raises(HTTPError) as HE: CoinGeckoAPI().get_token_price( 'ethereum', '0xB8c77482e45F1F44dE1745F52C74426C631bDD52', 'bnb', include_market_cap='true', include_24hr_vol='true', include_last_updated_at='true')
def test_get_coin_info_from_contract_address_by_id(self): # Arrange json_response = { 'id': '0x', 'symbol': 'zrx', 'name': '0x', 'block_time_in_minutes': 0, 'categories': ['Protocol'], 'localization': { 'en': '0x', 'es': '0x', 'de': '0x', 'nl': '0x', 'pt': '0x', 'fr': '0x', 'it': '0x', 'hu': '0x', 'ro': '0x', 'sv': '0x', 'pl': '0x', 'id': '0x', 'zh': '0x协议', 'zh-tw': '0x協議', 'ja': 'ロエックス', 'ko': '제로엑스', 'ru': '0x', 'ar': '0x', 'th': '0x', 'vi': '0x', 'tr': '0x' } } responses.add( responses.GET, 'https://api.coingecko.com/api/v3/coins/ethereum/contract/0x0D8775F648430679A709E98d2b0Cb6250d2887EF', json=json_response, status=200) # Act response = CoinGeckoAPI().get_coin_info_from_contract_address_by_id( id='ethereum', contract_address='0x0D8775F648430679A709E98d2b0Cb6250d2887EF') ## Assert assert response == json_response
def ethTop150(token_map): cg = CoinGeckoAPI() out_file = {} data_lst = list() notFound = 0 #token_map["Ethereum Token Name"] = token_map["Ethereum Token Name"].lower() token_map['symbol_lower'] = token_map.apply( lambda row: row['Avalanche Token Symbol'].lower(), axis=1) found = 0 page = 1 while found < 150: result = cg.get_coins_markets('usd', per_page=250, page=page, order='market_cap_desc') for i in range(len(result)): #print(result[i]) #breakpoint() row = token_map[token_map["symbol_lower"] == result[i] ['symbol'].lower()] #if result[i]['symbol'].lower() == 'mkr': # breakpoint() if len(row.index) == 0: notFound += 1 elif len(row.index) > 1: print("Collision for symbol", result[i]['symbol']) else: found += 1 data = {} data['address'] = row.iloc[0]['Ethereum Token Address'] data['name'] = row.iloc[0]['Ethereum Token Name'] data['symbol'] = row.iloc[0]['Ethereum Token Symbol'] data['imageUri'] = HOSTED_URL + LOGOS_OUT_DIR + '/' + row.iloc[ 0]['Avalanche Token Address'] + '/logo.png' data['resourceId'] = '0x' + row.iloc[0]['Resource ID'] data_lst.append(data) if found == 150: break page += 1 out_file['data'] = data_lst #breakpoint() with open(ETH_CONFIG_150, 'w') as json_file: json.dump(out_file, json_file, indent=4) print("Not found:", notFound)
def __init__(self, builder): config = load_config() self.cg = CoinGeckoAPI() self.source_unit = builder.get_object('source_unit') self.conv_unit = builder.get_object('conv_unit') self.source_amount = builder.get_object('source_amount') self.conv_result = builder.get_object('conv_result') self.time_update = builder.get_object('time_update') self.crypto_completion = builder.get_object('crypto_completion') self.currency_completion = builder.get_object('currency_completion') self.radio_api = builder.get_object('radio_api') self.api_rate = builder.get_object('api_rate') self.custom_rate = builder.get_object('custom_rate') self.current_crypto = config['cryptocurrency'] self.current_currency = config['vs_currency'] self.source = 'api' self.current_rate = None self.auto_update = True self.inverted_rates = False self.crypto_ids = load_supported_cryptos() self.currencies = load_supported_vs_currencies() self.source_unit.set_text(self.current_crypto) self.conv_unit.set_text(self.current_currency) if self.crypto_ids is None or self.currencies is None: # Download the config files directly from the API update_conf_files(self) else: # Updating the UI with the config values populate_completion(self.crypto_completion, self.crypto_ids) populate_completion(self.currency_completion, self.currencies) # Update the config files in a background thread ConfigUpdater(self) # Get and display the data received from the API self.updateValues() self.updateRate() # Start the auto-updater in the background with 10s interval GLib.timeout_add(interval=10000, function=self.updateValues)
def get_coins(top: int = 250, category: str = ""): """Get N coins from CoinGecko [Source: CoinGecko] Parameters ---------- top: int Number of top coins to grab from CoinGecko Returns ------- pandas.DataFrame N coins """ client = CoinGeckoAPI() df = pd.DataFrame() if top <= 250: kwargs = { "vs_currency": "usd", "order": "market_cap_desc", "per_page": top, "sparkline": False, "price_change_percentage": "1h,24h,7d,14d,30d,200d,1y", } if category: kwargs["category"] = category data = client.get_coins_markets(**kwargs) df = df.append(pd.DataFrame(data), ignore_index=True) else: p = 1 while top > 0: kwargs = { "vs_currency": "usd", "order": "market_cap_desc", "per_page": top, "sparkline": False, "price_change_percentage": "1h,24h,7d,14d,30d,200d,1y", "page": p, } if category: kwargs["category"] = category data = client.get_coins_markets(**kwargs) df = df.append(pd.DataFrame(data), ignore_index=True) top -= 250 p += 1 return df
def calculate_greeks( df: pd.DataFrame, ) -> typing.Tuple[pd.DataFrame, typing.Dict[str, float], typing.Dict[str, float]]: """we apply the greeks on each row over the dataframe""" # pricing API cg = CoinGeckoAPI() # lambdas for getting IV and current price of underlying f_vol = lambda x: math.sqrt(x.functions.impliedVolRate().call()) f_pri = lambda x: cg.get_price(ids=x, vs_currencies="usd")[x]["usd"] price_wbtc, price_eth = f_pri("bitcoin"), f_pri("ethereum") # append constants to df as cols df = df.assign( underlying_price=np.where( df["symbol"] == "WBTC", price_wbtc, price_eth, ), volatility=np.where( df["symbol"] == "WBTC", f_vol(abi_stuff.wbtc_contract), f_vol(abi_stuff.eth_contract), ), ) df_greeks = df.apply(mibian_bs, axis=1) df = pd.concat([df, df_greeks], axis=1) underlying_prices = { "WBTC": price_wbtc, "ETH": price_eth, } # instead of doing this every time a user interacts with the calculator we do it once # and cache until repull of data writetoken_totbal = { "WBTC": abi_stuff.writewbtc_contract.functions.totalSupply().call(), "ETH": abi_stuff.writeeth_contract.functions.totalSupply().call(), } return df, underlying_prices, writetoken_totbal
def __init__(self, inID, inSymbol, inEntryPrice, inEntryAmount, date='-', dbID=''): self.cg = CoinGeckoAPI() self.coin_id = inID self.symbol = inSymbol self.entry_price = inEntryPrice self.entry_amount = inEntryAmount self.current_price = self.get_price() self.current_value = self.get_cur_val() self.pl = self.get_PL() self.pl_percent = self.get_PL_Percent() self.date = date self.dbID = dbID
def pricegrab(addressfromdiscord, currencyfromdiscord): cg = CoinGeckoAPI() bsc = BscScan("ABZ3YV2I961GK1HJDPXN7GUQB6WIPEWUWU") # key in quotation marks global example2 global sfmwalletbalanceincurfinal global curpriceformat address = addressfromdiscord currencyvs = currencyfromdiscord.lower() example = int(bsc.get_acc_balance_by_token_contract_address(contract_address="0x8076c74c5e3f5852037f31ff0093eeb8c8add8d3", address=address)) example2 = example * 0.000000001 example4 = cg.get_price(ids="safemoon", vs_currencies=currencyvs) curprice = (example4["safemoon"][currencyvs]) curpriceformat = format(curprice, 'f') sfmwalletbalanceincurfinal = int(float(curprice) * example2) - (float(curprice) * example2 / 10)
def _get_live_data(self): if settings.TEST_NET: return self.default_data_if_empty cg = CoinGeckoAPI() response = cg.get_price( ids="burst", vs_currencies=["usd", "btc"], include_market_cap="true", include_24hr_change="true", )["burst"] return ExchangeData( price_usd=response["usd"], price_btc=response["btc"], market_cap_usd=response["usd_market_cap"], percent_change_24h=response["usd_24h_change"], )
def valor_eth(moeda: str = 'BRL', moeda2="USD"): cg = CoinGeckoAPI() IST = pytz.timezone('Brazil/East') agora = datetime.now(IST) data = agora.strftime("%d/%m/%y") hora = agora.strftime("%H:%M") data_fo = ":calendar_spiral: Em {} às {}".format(data, hora) result = cg.get_price(ids='ethereum', vs_currencies='{}'.format(moeda), include_24hr_change='true') moeda_valor = result['ethereum'][moeda.lower()] moeda_24_hrs = result['ethereum']['{}_24h_change'.format(moeda.lower())] moeda_fo = float("%.2f" % moeda_24_hrs) if moeda_fo > 0: frase3 = ":chart_with_upwards_trend: 24h: {}%".format(moeda_fo) elif moeda_fo < 0: frase3 = ":chart_with_downwards_trend: 24h: {}%".format(moeda_fo) formatado = list(str(moeda_valor)) formatado.insert(1, '.') moeda_valor = "".join(formatado) troca_ponto = moeda_valor.rfind(".") moeda_valor = moeda_valor[:troca_ponto] + "," + moeda_valor[troca_ponto + 1:] frase = ":flag_br: R$ {}".format(moeda_valor) ###### result = cg.get_price(ids='ethereum', vs_currencies='{}'.format(moeda2)) moeda_valor2 = result['ethereum'][moeda2.lower()] formatado2 = list(str(moeda_valor2)) formatado2.insert(1, '.') moeda_valor2 = "".join(formatado2) troca_ponto = moeda_valor2.rfind(".") moeda_valor2 = moeda_valor2[:troca_ponto] + "," + moeda_valor2[ troca_ponto + 1:] frase2 = ":flag_us: $ {}".format(moeda_valor2) return "Valor atual do Ethereum:money_with_wings:" + '\n' + '\n' + frase + '\n' + frase2 + '\n' + '\n' + frase3 + '\n' + '\n' + data_fo
def test_get_get_coin_ticker_by_id(self): # Arrange bitcoin_json_sample = { 'name': 'Bitcoin', 'tickers': [{ 'base': 'BTC', 'target': 'USDT', 'market': { 'name': 'BW.com', 'identifier': 'bw', 'has_trading_incentive': False }, 'last': 7963.0, ' volume': 93428.7568, 'converted_last': { 'btc': 0.99993976, 'eth': 31.711347, 'usd': 7979.23 }, 'converted_volume': { 'btc': 93423, 'eth': 2962752, 'usd': 745489919 }, ' bid_ask_spread_percentage': 0.111969, 'timestamp': '2019-05-24T11:20:14+00:00', 'is_anomaly': False, 'is_stale': False, 'trade_url': 'https://www.bw.com/trade/btc_us dt', 'coin_id': 'bitcoin' }] } responses.add(responses.GET, 'https://api.coingecko.com/api/v3/coins/bitcoin/tickers', json=bitcoin_json_sample, status=200) # Act response = CoinGeckoAPI().get_coin_ticker_by_id('bitcoin') ## Assert assert response == bitcoin_json_sample
def __init__(self): self.isServiceAvailable = True signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.logging = error_reporting.Client() self.cache1 = Cache(ttl=5) self.cache2 = Cache(ttl=5) self.coinGecko = CoinGeckoAPI() self.lastBitcoinQuote = { "quotePrice": [0], "quoteVolume": None, "ticker": Ticker("BTCUSD", "BTCUSD", "BTC", "USD", "BTC/USD", hasParts=False), "exchange": None, "timestamp": time.time() } try: rawData = self.coinGecko.get_coin_by_id(id="bitcoin", localization="false", tickers=False, market_data=True, community_data=False, developer_data=False) self.lastBitcoinQuote["quotePrice"] = [ rawData["market_data"]["current_price"]["usd"] ] self.lastBitcoinQuote["quoteVolume"] = rawData["market_data"][ "total_volume"]["usd"] except: pass context = zmq.Context.instance() self.socket = context.socket(zmq.ROUTER) self.socket.bind("tcp://*:6900") print("[Startup]: Quote Server is online")
def test_get_coin_history_by_id(self): # Arrange history_json_sample = { "id": "bitcoin", "symbol": "btc", "name": "Bitcoin", "localization": { "en": "Bitcoin", "es": "Bitcoin", "de": "Bitcoin", "nl": "Bitcoin", "pt": "Bitcoin", "fr": "Bitcoin", "it": "Bitcoin", "hu": "Bitcoin", "ro": "Bitcoin", "sv": "Bitcoin", "pl": "Bitcoin", "id": "Bitcoin", "zh": "比特币", "zh-tw": "比特幣", "ja": "ビットコイン", "ko": "비트코인", "ru": "биткоина", "ar": "بيتكوين", "th": "บิตคอยน์", "vi": "Bitcoin", "tr": "Bitcoin" } } responses.add( responses.GET, 'https://api.coingecko.com/api/v3/coins/bitcoin/history?date=27-08-2018', json=history_json_sample, status=200) # Act response = CoinGeckoAPI().get_coin_history_by_id( 'bitcoin', '27-08-2018') ## Assert assert response == history_json_sample
def get_trending_coins() -> pd.DataFrame: """Returns trending coins [Source: CoinGecko] Parameters ---------- Returns ------- pandas.DataFrame: Trending Coins """ client = CoinGeckoAPI() data = client.get_search_trending() coins = data["coins"] df = pd.DataFrame(columns=["Symbol", "Name", "Market Cap Rank"]) for i, coin in enumerate(coins): coin = coin["item"] df.loc[i] = [coin["id"], coin["name"], coin["market_cap_rank"]] return df
def test_get_coins_list(self): # Arrange coins_json_sample = [{ "id": "bitcoin", "symbol": "btc", "name": "Bitcoin" }, { "id": "litecoin", "symbol": "ltc", "name": "Litecoin" }, { "id": "auroracoin", "symbol": "aur", "name": "Auroracoin" }, { "id": "peercoin", "symbol": "ppc", "name": "Peercoin" }, { "id": "dogecoin", "symbol": "doge", "name": "Dogecoin" }, { "id": "nxt", "symbol": "nxt", "name": "NXT" }, { "id": "omni", "symbol": "omni", "name": "Omni (Mastercoin)" }] responses.add(responses.GET, 'https://api.coingecko.com/api/v3/coins/list', json=coins_json_sample, status=200) # Act response = CoinGeckoAPI().get_coins_list() ## Assert assert response == coins_json_sample
def update_conf_files(handler): # Fetch all the supported cryptos from CoinGecko and saves them using JSON cg = CoinGeckoAPI() data = cg.get_coins_list() vs_currencies = cg.get_supported_vs_currencies() supported_cryptos = {d['symbol']: d['id'] for d in data} with open('conf/supported_cryptos.json', 'w') as json_file: json.dump(supported_cryptos, json_file) with open('conf/supported_vs_currencies.json', 'w') as json_file: json.dump(vs_currencies, json_file) # Update the values loaded from previous config file handler.crypto_ids = supported_cryptos handler.currencies = sorted([vsc.upper() for vsc in vs_currencies]) populate_completion(handler.crypto_completion, handler.crypto_ids) populate_completion(handler.currency_completion, handler.currencies)
def query_coingecko_asset_price(self, asset: str, timestamp: datetime, fiat: str = "usd"): asset = self.get_gecko_token_name(asset) logger.debug("Requesting price of {} at {}".format(asset, timestamp)) if asset == "euro": return self.query_coingecko_asset_price("tether", timestamp, fiat="eur") else: cg = CoinGeckoAPI() data = cg.get_coin_history_by_id( asset, timestamp.strftime("%d-%m-%Y %H:%M:%S"), localization='false') price = data["market_data"]["current_price"][fiat] logger.debug("{} is {} at {}".format(asset, price, timestamp)) return float(price)
def get_coins_for_given_exchange(exchange_id: str = "binance", page: int = 1) -> dict: """Helper method to get all coins available on binance exchange [Source: CoinGecko] Parameters ---------- exchange_id: str id of exchange page: int number of page. One page contains 100 records Returns ------- dict dictionary with all trading pairs on binance """ client = CoinGeckoAPI() binance_coins = client.get_exchanges_tickers_by_id(id=exchange_id, page=page) return binance_coins["tickers"]
def get_finance_products() -> pd.DataFrame: """Get list of financial products from CoinGecko API Returns ------- pandas.DataFrame Rank, Platform, Identifier, Supply_Rate, Borrow_Rate """ client = CoinGeckoAPI() df = pd.DataFrame( client.get_finance_products(per_page=250), columns=[ "platform", "identifier", "supply_rate_percentage", "borrow_rate_percentage", ], ) df.columns = ["Platform", "Identifier", "Supply_Rate", "Borrow_Rate"] create_df_index(df, "Rank") return df
def get_top_crypto_categories( sort_filter: str = SORT_VALUES[0]) -> pd.DataFrame: """Returns top crypto categories [Source: CoinGecko] Returns ------- pandas.DataFrame Rank, Name, Change_1h, Change_7d, Market_Cap, Volume_24h,Coins, Url """ if sort_filter in SORT_VALUES: client = CoinGeckoAPI() data = client.get_coins_categories() df = pd.DataFrame(data) del df["id"] del df["content"] del df["updated_at"] df["top_3_coins"] = df["top_3_coins"].apply(coin_formatter) df.columns = [ replace_underscores_in_column_names(col) if isinstance(col, str) else col for col in df.columns ] return df return pd.DataFrame()
def test_get_exchanges_id_name_list(self): # Arrange json_response = [{ 'id': 'abcc', 'name': 'ABCC' }, { 'id': 'acx', 'name': 'ACX' }, { 'id': 'airswap', 'name': 'AirSwap' }] responses.add(responses.GET, 'https://api.coingecko.com/api/v3/exchanges/list', json=json_response, status=200) # Act response = CoinGeckoAPI().get_exchanges_id_name_list() ## Assert assert response == json_response
def test_get_supported_vs_currencies(self): # Arrange coins_json_sample = [ 'btc', 'eth', 'ltc', 'bch', 'bnb', 'eos', 'xrp', 'xlm', 'usd', 'aed', 'ars', 'aud', 'bdt', 'bhd', 'bmd', 'brl', 'cad', 'chf', 'clp', 'cny', 'czk', 'dkk', 'eur', 'gbp', 'hkd', 'huf', 'idr', 'ils', 'inr', 'jpy', 'krw', 'kwd', 'lkr', 'mmk', 'mxn', 'myr', 'nok', 'nzd', 'php', 'pkr', 'pln', 'rub', 'sar', 'sek', 'sgd', 'thb', 'try', 'twd', 'uah', 'vef', 'vnd', 'zar', 'xdr', 'xag', 'xau' ] responses.add( responses.GET, 'https://api.coingecko.com/api/v3/simple/supported_vs_currencies', json=coins_json_sample, status=200) # Act response = CoinGeckoAPI().get_supported_vs_currencies() ## Assert assert response == coins_json_sample
def test_get_coin_market_chart_by_id(self): # Arrange json_response = { "prices": [[1535373899623, 6756.942910425894], [1535374183927, 6696.894541693875], [1535374496401, 6689.990513793263], [1535374779118, 6668.291007556478], [1535375102688, 6703.7499879964], [1535375384209, 6706.898948451269]] } responses.add( responses.GET, 'https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=1', json=json_response, status=200) # Act response = CoinGeckoAPI().get_coin_market_chart_by_id( 'bitcoin', 'usd', 1) ## Assert assert response == json_response
def grab_assets_BTC_value(): cg = CoinGeckoAPI() assets = [ 'ethereum', 'ripple', 'eos', 'litecoin', 'bitcoin-cash', 'binancecoin', 'cardano', 'stellar', 'tron', 'bitcoin-cash-sv', 'monero', 'iota', 'dash' ] # 'holotoken', 'true-usd', 'omisego', 'qtum', 'lisk', 'decred', 'chainlink', '0x', # 'bitcoin-gold', 'zilliqa', 'bitcoin-diamond', 'augur', 'icon', # 'usd-coin', 'ethereum', 'dogecoin', 'tezos', 'vechain', 'waves', 'ontology', 'zcash', 'ripple', 'eos', # 'litecoin', 'bitcoin-cash', 'tether', 'stellar', 'tron', 'binancecoin', 'bitcoin-cash-sv', 'cardano', # 'monero', 'iota', 'dash', 'maker', 'neo', 'ethereum-classic', 'nem' btc_asstet_list = [] for btcvalue in assets: simple_price = cg.get_price(ids=btcvalue, vs_currencies='btc') btc_asstet_dataframe = df(simple_price) #btc_asstet_list.append(simple_price) return btc_asstet_dataframe
def get_global_defi_info() -> pd.DataFrame: """Get global statistics about Decentralized Finances [Source: CoinGecko] Returns ------- pandas.DataFrame Metric, Value """ client = CoinGeckoAPI() results = client.get_global_decentralized_finance_defi() for key, value in results.items(): try: results[key] = round(float(value), 4) except (ValueError, TypeError): pass df = pd.Series(results).reset_index() df.columns = ["Metric", "Value"] df["Metric"] = df["Metric"].apply( lambda x: replace_underscores_in_column_names(x) if isinstance(x, str) else x) return df
def fetch_df(): cg = CoinGeckoAPI() top_n = 200 #n_days_ago = 50 time_now = int(time.time()) time_delta = 91 * 24 * 60 * 60 df_r = pd.DataFrame() for i, coin in enumerate(cg.get_coins_markets(vs_currency="usd")[:top_n]): coin_id = coin["id"] chart = cg.get_coin_market_chart_range_by_id( coin_id, vs_currency="usd", from_timestamp=time_now - time_delta, to_timestamp=time_now) df = pd.DataFrame(chart["prices"], columns=["time", "price"]) df['time'] = pd.to_datetime(df['time'],unit='ms') df["time_delta"] = df.time - df.iloc[0].time df.set_index("time_delta", inplace=True) df["%s" % coin_id] = np.log(df.price) - np.log(df.iloc[0].price) df.drop(columns=["time", "price"], inplace=True) df = df.iloc[1:] df = df.transpose() df_r = df_r.append(df) print(i, coin_id) time.sleep(.15) print(df_r) print() print(df_r.idxmax(axis = 0)) return df_r
def test_get_coins_markets(self): # Arrange markets_json_sample = [{ "id": "bitcoin", "symbol": "btc", "name": "Bitcoin", "image": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1510040391", "current_price": 7015.11823787848, "market_cap": 120934444800.105, "market_cap_rank": 1, "total_volume": 6121170828.21792, "high_24h": 7054.21193531031, "low_24h": 6668.29100755648, "price_change_24h": "299.72373285508", "price_change_percentage_24h": "4.46323343521924", "market_cap_change_24h": "5197755386.983", "market_cap_change_percentage_24h": "4.4910178555649", "circulating_supply": "17236100.0", "ath": 19665.3949272416, "ath_change_percentage": -64.2200698307594, "ath_date": "2017-12-16T00:00:00.000Z", "roi": 0, "last_updated": "2018-08-28T12:12:53.390Z" }] responses.add( responses.GET, 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd', json=markets_json_sample, status=200) # Act response = CoinGeckoAPI().get_coins_markets('usd') ## Assert assert response == markets_json_sample
def get_coin_pair_data(exclude=[], include_exchanges=[], include_coins=[]): cg = CoinGeckoAPI() coins = [] if (include_coins == []): coins = cg.get_coins_list() random.shuffle(coins) else: coins = include_coins coin_data = [] for coin in coins: print("Getting coin: " + coin["id"]) try: market_data = cg.get_coin_by_id(coin['id'])['tickers'] pairs_data = [] for i in market_data: market = i['market']['name'] price = float(i['converted_last']['usd']) volume = float(i['converted_volume']['usd']) info = { 'market': market, 'price': price, 'target': i['target'], 'volume': volume } if len(include_exchanges) == 0: if market not in exclude: pairs_data.append(info) else: if market in include_exchanges: pairs_data.append(info) coin_data.append({'name': i['base'], 'market data': pairs_data}) except Exception as e: print("ERROR:") print(e) continue return (coin_data)
def test_get_coin_status_updates_by_id(self): # Arrange json_response = [{ 'description': 'Travala.com Partners with Litecoin Foundation to Champion Crypto Payments. \r\n#TravelWithLitecoin www.travala.com/litecoin\r\n\r\nRead the full announcement here: bit.ly/2LumY3b', 'category': 'general', 'created_at': '2019-05-14T13:56:43.282Z', 'user': '******', 'user_title': 'Operations Director', 'pin': False, 'project': { 'type': 'Coin', 'id': 'litecoin', 'name': 'Litecoin', 'symbol': 'ltc', 'image': { 'thumb': 'https://assets.coingecko.com/coins/images/2/thumb/litecoin.png?1547033580', 'small': 'https://assets.coingecko.com/coins/images/2/small/litecoin.png?1547033580', 'large': 'https://assets.coingecko.com/coins/images/2/large/litecoin.png?1547033580' } } }] responses.add( responses.GET, 'https://api.coingecko.com/api/v3/coins/litecoin/status_updates', json=json_response, status=200) # Act response = CoinGeckoAPI().get_coin_status_updates_by_id('litecoin') ## Assert assert response == json_response
def get_data_from_remote(symbol, interval, start, end): error_msg = f"{symbol}-{interval}-{start}-{end}" try: cg = CoinGeckoAPI() data = cg.get_coin_market_chart_by_id(id=symbol, vs_currency="usd", days="max") _resp = pd.DataFrame(columns=["date"] + list(data.keys())) _resp["date"] = [ dt.fromtimestamp(mktime(time.localtime(x[0] / 1000))) for x in data["prices"] ] for key in data.keys(): _resp[key] = [x[1] for x in data[key]] _resp["date"] = pd.to_datetime(_resp["date"]) _resp["date"] = [x.date() for x in _resp["date"]] _resp = _resp[(_resp["date"] < pd.to_datetime(end).date()) & (_resp["date"] > pd.to_datetime(start).date())] if _resp.shape[0] != 0: _resp = _resp.reset_index() if isinstance(_resp, pd.DataFrame): return _resp.reset_index() except Exception as e: logger.warning(f"{error_msg}:{e}")