#Need to get absolute path for the cron job fdir = os.path.abspath(os.path.dirname(__file__)) load_dotenv(Path(os.path.join(fdir, '.env'))) API_KEY = os.getenv("ETHERSCAN_API") INFURA_KEY = os.getenv("INFURA_KEY") CONSUMER_KEY = os.getenv("CONSUMER_KEY") CONSUMER_SECRET = os.getenv("CONSUMER_SECRET") ACCESS_TOKEN = os.getenv("ACCESS_TOKEN") ACCESS_TOKEN_SECRET = os.getenv("ACCESS_TOKEN_SECRET") abi = open(os.path.join(fdir, 'abi.json'), 'r').read() cg = CoinGeckoAPI() w3 = Web3( Web3.WebsocketProvider(f'wss://mainnet.infura.io/ws/v3/{INFURA_KEY}')) fromBlock = 0 totalEth = float(0) totalDai = float(0) tweetMessage = '24 hour transaction activity:\n' def build_message(tx_times, amount, token): global tweetMessage if token == 'DAI' and float(amount) * tx_times > 1500: emoji = "🌪🌪🌪" elif token == 'ETH' and float(amount) * tx_times > 7:
from pycoingecko import CoinGeckoAPI cg = CoinGeckoAPI() bitcoin_price = cg.get_coin_ticker_by_id( 'bitcoin', exchange_ids='binance')['tickers'][0]['last'] print(bitcoin_price)
class DetailProcessor(object): coinGecko = CoinGeckoAPI() 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.cache = Cache() context = zmq.Context.instance() self.socket = context.socket(zmq.ROUTER) self.socket.bind("tcp://*:6900") print("[Startup]: Detail Server is online") def exit_gracefully(self): print("[Startup]: Detail Server is exiting") self.socket.close() self.isServiceAvailable = False def run(self): while self.isServiceAvailable: try: response = None, None origin, delimeter, clientId, service, request = self.socket.recv_multipart( ) request = pickle.loads(zlib.decompress(request)) if request.timestamp + 30 < time.time(): continue if service == b"detail": response = self.request_detail(request) except (KeyboardInterrupt, SystemExit): return except Exception: print(traceback.format_exc()) if os.environ["PRODUCTION_MODE"]: self.logging.report_exception() finally: try: self.socket.send_multipart([ origin, delimeter, zlib.compress(pickle.dumps(response, -1)) ]) except: pass def request_detail(self, request): payload, tradeMessage, updatedTradeMessage = None, None, None for platform in request.platforms: request.set_current(platform=platform) hashCode = hash(request.requests[platform]) fromCache = False if request.can_cache() and self.cache.has(hashCode): payload, updatedQuoteMessage = self.cache.get(hashCode), None fromCache = True elif platform == "CoinGecko": payload, updatedQuoteMessage = self.request_coingecko_details( request) if payload is not None: if request.can_cache() and not fromCache: self.cache.set(hashCode, payload) if request.authorId != 401328409499664394 and request.requests[ platform].ticker.base is not None: database.document("dataserver/statistics/{}/{}".format( platform, str(uuid.uuid4()))).set({ "timestamp": time.time(), "authorId": str(request.authorId), "ticker": { "base": request.requests[platform].ticker.base, "quote": request.requests[platform].ticker.quote, "id": request.requests[platform].ticker.id, "bias": request.parserBias }, "exchange": None if request.requests[platform].exchange is None else request.requests[platform].exchange.id }) return payload, updatedTradeMessage elif updatedTradeMessage is not None: tradeMessage = updatedTradeMessage return None, tradeMessage def request_coingecko_details(self, request): ticker = request.get_ticker() try: try: rawData = self.coinGecko.get_coin_by_id(id=ticker.symbol, localization="false", tickers=False, market_data=True, community_data=True, developer_data=True) except: return None, None payload = { "name": "{} ({})".format(rawData["name"], ticker.base), "rank": rawData["market_data"]["market_cap_rank"], "image": rawData["image"]["large"], "marketcap": "" if rawData["market_data"]["market_cap"] is None else rawData["market_data"]["market_cap"].get("usd", ""), "volume": None if rawData["market_data"]["total_volume"] is None else rawData["market_data"]["total_volume"].get("usd"), "supply": { "total": None if rawData["market_data"]["total_supply"] is None else rawData["market_data"]["total_supply"], "circulating": None if rawData["market_data"]["circulating_supply"] is None else rawData["market_data"]["circulating_supply"] }, "score": { "developer": rawData["developer_score"], "community": rawData["community_score"], "liquidity": rawData["liquidity_score"], "public interest": rawData["public_interest_score"] }, "price": { "current": rawData["market_data"]["current_price"].get("usd"), "ath": rawData["market_data"]["ath"].get("usd"), "atl": rawData["market_data"]["atl"].get("usd") }, "change": { "past day": rawData["market_data"] ["price_change_percentage_24h_in_currency"].get("usd"), "past month": rawData["market_data"] ["price_change_percentage_30d_in_currency"].get("usd"), "past year": rawData["market_data"] ["price_change_percentage_1y_in_currency"].get("usd") }, "sourceText": "from CoinGecko", "platform": "CoinGecko", } return payload, None except Exception: print(traceback.format_exc()) if os.environ["PRODUCTION_MODE"]: self.logging.report_exception() return None, None
class Coin: """Coin class, it holds loaded coin""" def __init__(self, symbol: str, load_from_api: bool = False): self.client = CoinGeckoAPI() if load_from_api: self._coin_list = self.client.get_coins_list() else: self._coin_list = read_file_data("coingecko_coins.json") self.coin_symbol, self.symbol = self._validate_coin(symbol) if self.coin_symbol: self.coin: Dict[Any, Any] = self._get_coin_info() def __str__(self): return f"{self.coin_symbol}" def _validate_coin( self, search_coin: str) -> Tuple[Optional[Any], Optional[Any]]: """Validate if given coin symbol or id exists in list of available coins on CoinGecko. If yes it returns coin id. [Source: CoinGecko] Parameters ---------- symbol: str Either coin symbol or coin id Returns ------- Tuple[str, str] - str with coin - str with symbol """ coin = None symbol = None for dct in self._coin_list: if search_coin.lower() in [ dct["id"], dct["symbol"], ]: coin = dct.get("id") symbol = dct.get("symbol") return coin, symbol raise ValueError( f"Could not find coin with the given id: {search_coin}\n") def coin_list(self) -> list: """List all available coins [Source: CoinGecko] Returns ------- list list of all available coin ids """ return [token.get("id") for token in self._coin_list] def _get_coin_info(self) -> dict: """Helper method which fetch the coin information by id from CoinGecko API like: (name, price, market, ... including exchange tickers) [Source: CoinGecko] Returns ------- dict Coin information """ params = dict(localization="false", tickers="false", sparkline=True) return self.client.get_coin_by_id(self.coin_symbol, **params) def _get_links(self) -> Dict: """Helper method that extracts links from coin [Source: CoinGecko] Returns ------- dict Links related to coin """ return self.coin.get("links", {}) @property def get_repositories(self) -> Optional[Any]: """Get list of all repositories for given coin [Source: CoinGecko] Returns ------- list Repositories related to coin """ return self._get_links().get("repos_url") @property def get_developers_data(self) -> pd.DataFrame: """Get coin development data from GitHub or BitBucket like: number of pull requests, contributor etc [Source: CoinGecko] Returns ------- pandas.DataFrame Developers Data Columns: Metric, Value """ dev = self.coin.get("developer_data", {}) useless_keys = ( "code_additions_deletions_4_weeks", "last_4_weeks_commit_activity_series", ) remove_keys(useless_keys, dev) df = pd.Series(dev).to_frame().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[df["Value"].notna()] @property def get_blockchain_explorers(self) -> Union[pd.DataFrame, Any]: """Get list of URLs to blockchain explorers for given coin. [Source: CoinGecko] Returns ------- pandas.DataFrame Blockchain Explorers Columns: Metric, Value """ blockchain = self._get_links().get("blockchain_site") if blockchain: dct = filter_list(blockchain) df = pd.Series(dct).to_frame().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[df["Value"].notna()] return None @property def get_social_media(self) -> pd.DataFrame: """Get list of URLs to social media like twitter, facebook, reddit... [Source: CoinGecko] Returns ------- pandas.DataFrame Urls to social media Columns: Metric, Value """ social_dct = {} links = self._get_links() for (channel) in CHANNELS.keys(): # pylint: disable=consider-iterating-dictionary) if channel in links: value = links.get(channel, "") if channel == "twitter_screen_name": value = "https://twitter.com/" + value elif channel == "bitcointalk_thread_identifier" and value is not None: value = f"https://bitcointalk.org/index.php?topic={value}" social_dct[channel] = value social_dct["discord"] = find_discord(links.get("chat_url")) dct = rename_columns_in_dct(social_dct, CHANNELS) df = pd.Series(dct).to_frame().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[df["Value"].notna()] @property def get_websites(self) -> pd.DataFrame: """Get list of URLs to websites like homepage of coin, forum. [Source: CoinGecko] Returns ------- pandas.DataFrame Urls to website, homepage, forum Columns: Metric, Value """ websites_dct = {} links = self._get_links() sites = ["homepage", "official_forum_url", "announcement_url"] for site in sites: websites_dct[site] = filter_list(links.get(site)) df = pd.Series(websites_dct).to_frame().reset_index() df.columns = ["Metric", "Value"] df["Value"] = df["Value"].apply(lambda x: ",".join(x)) df["Metric"] = df["Metric"].apply( lambda x: replace_underscores_in_column_names(x) if isinstance(x, str) else x) return df[df["Value"].notna()] @property def get_categories(self) -> Union[Dict[Any, Any], List[Any]]: """Coins categories. [Source: CoinGecko] Returns ------- list/dict Coin categories """ return self.coin.get("categories", {}) def _get_base_market_data_info(self) -> dict: """Helper method that fetches all the base market/price information about given coin. [Source: CoinGecko] Returns ------- dict All market related information for given coin """ market_dct = {} market_data = self.coin.get("market_data", {}) for stat in [ "total_supply", "max_supply", "circulating_supply", "price_change_percentage_24h", "price_change_percentage_7d", "price_change_percentage_30d", ]: market_dct[stat] = market_data.get(stat) prices = create_dictionary_with_prefixes(["current_price"], market_data, DENOMINATION) market_dct.update(prices) return market_dct @property def get_base_info(self) -> pd.DataFrame: """Get all the base information about given coin. [Source: CoinGecko] Returns ------- pandas.DataFrame Base information about coin """ regx = r'<a href="(.+?)">|</a>' results = {} for attr in BASE_INFO: info_obj = self.coin.get(attr, {}) if attr == "description": info_obj = info_obj.get("en") info_obj = re.sub(regx, "", info_obj) info_obj = re.sub(r"\r\n\r\n", " ", info_obj) results[attr] = info_obj results.update(self._get_base_market_data_info()) df = pd.Series(results).to_frame().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[df["Value"].notna()] @property def get_market_data(self) -> pd.DataFrame: """Get all the base market information about given coin. [Source: CoinGecko] Returns ------- pandas.DataFrame Base market information about coin Metric,Value """ market_data = self.coin.get("market_data", {}) market_columns_denominated = [ "market_cap", "fully_diluted_valuation", "total_volume", "high_24h", "low_24h", ] denominated_data = create_dictionary_with_prefixes( market_columns_denominated, market_data, DENOMINATION) market_single_columns = [ "market_cap_rank", "total_supply", "max_supply", "circulating_supply", "price_change_percentage_24h", "price_change_percentage_7d", "price_change_percentage_30d", "price_change_percentage_60d", "price_change_percentage_1y", "market_cap_change_24h", ] single_stats = {} for col in market_single_columns: single_stats[col] = market_data.get(col) single_stats.update(denominated_data) try: single_stats["circulating_supply_to_total_supply_ratio"] = ( single_stats["circulating_supply"] / single_stats["total_supply"]) except (ZeroDivisionError, TypeError) as e: console.print(e) df = pd.Series(single_stats).to_frame().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[df["Value"].notna()] def get_all_time_high(self, currency: str = "usd") -> pd.DataFrame: """Get all time high data for given coin. [Source: CoinGecko] Returns ------- pandas.DataFrame All time high price data Metric,Value """ market_data = self.coin.get("market_data", {}) if market_data == {}: return pd.DataFrame() ath_columns = [ "current_price", "ath", "ath_date", "ath_change_percentage", ] results = {} for column in ath_columns: results[column] = market_data[column].get(currency) df = pd.Series(results).to_frame().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) df["Metric"] = df["Metric"].apply( lambda x: x.replace("Ath", "All Time High")) df["Metric"] = df["Metric"] + f" {currency.upper()}" return df[df["Value"].notna()] def get_all_time_low(self, currency: str = "usd") -> pd.DataFrame: """Get all time low data for given coin. [Source: CoinGecko] Returns ------- pandas.DataFrame All time low price data Metric,Value """ market_data = self.coin.get("market_data", {}) if market_data == {}: return pd.DataFrame() ath_columns = [ "current_price", "atl", "atl_date", "atl_change_percentage", ] results = {} for column in ath_columns: results[column] = market_data[column].get(currency) df = pd.Series(results).to_frame().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) df["Metric"] = df["Metric"].apply( lambda x: x.replace("Atl", "All Time Low")) df["Metric"] = df["Metric"] + f" {currency.upper()}" return df[df["Value"].notna()] @property def get_scores(self) -> pd.DataFrame: """Get different kind of scores for given coin. [Source: CoinGecko] Returns ------- pandas.DataFrame Social, community, sentiment scores for coin Metric,Value """ score_columns = [ "coingecko_rank", "coingecko_score", "developer_score", "community_score", "liquidity_score", "sentiment_votes_up_percentage", "sentiment_votes_down_percentage", "public_interest_score", "community_data", "public_interest_stats", ] single_stats = {col: self.coin.get(col) for col in score_columns[:-2]} nested_stats = {} for col in score_columns[-2:]: _dct = self.coin.get(col, {}) for k, _ in _dct.items(): nested_stats[k] = _dct.get(k, {}) single_stats.update(nested_stats) df = pd.Series(single_stats).reset_index() df.replace({0: ""}, inplace=True) df = df.fillna("") df.columns = ["Metric", "Value"] # pylint: disable=unsupported-assignment-operation df["Metric"] = df["Metric"].apply( lambda x: replace_underscores_in_column_names(x) if isinstance(x, str) else x) return df[df["Value"].notna()] def get_coin_market_chart(self, vs_currency: str = "usd", days: int = 30, **kwargs: Any) -> pd.DataFrame: """Get prices for given coin. [Source: CoinGecko] Parameters ---------- vs_currency: str currency vs which display data days: int number of days to display the data kwargs Returns ------- pandas.DataFrame Prices for given coin Columns: time, price, currency """ prices = self.client.get_coin_market_chart_by_id( self.coin_symbol, vs_currency, days, **kwargs) prices = prices["prices"] df = pd.DataFrame(data=prices, columns=["time", "price"]) df["time"] = pd.to_datetime(df.time, unit="ms") df = df.set_index("time") df["currency"] = vs_currency return df def get_ohlc(self, vs_currency: str = "usd", days: int = 90) -> pd.DataFrame: """Get Open, High, Low, Close prices for given coin. [Source: CoinGecko] Parameters ---------- vs_currency: str currency vs which display data days: int number of days to display the data on from (1/7/14/30/90/180/365, max) Returns ------- pandas.DataFrame OHLC data for coin Columns: time, price, currency """ prices = self.client.get_coin_ohlc_by_id(self.coin_symbol, vs_currency, days) df = pd.DataFrame(data=prices, columns=["time", "open", "high", "low", "close"]) df["time"] = pd.to_datetime(df.time, unit="ms") df = df.set_index("time") df["currency"] = vs_currency return df
!pip install pycoingecko #importing all the important modules import numpy import sys numpy.set_printoptions(threshold=sys.maxsize) import pandas as pd from pycoingecko import CoinGeckoAPI coin=CoinGeckoAPI() crypto=input("enter name of the cryptocurrency\n") cur=input("enter currency in the form of three letter notation\n")#enter the currency in which you want to see the price of the crypto curency in for eg. Usd,INR,EUR etc. days=input("enter days\n") BTC=coin.get_coin_market_chart_by_id(id=crypto,vs_currency=cur,days=days) ch=int(input('Enter appropriate choice\n1.Price real-time stats\n2.Market cap stats\n3.Total net values stats\n')) if ch==1: #prices stats BTC_Data=pd.DataFrame(BTC['prices'],columns=['Timestamp','Price']) # more organisation using date_time BTC_Data['Date']=pd.to_datetime(BTC_Data['Timestamp'],unit='ms') #to print all the rows pd.set_option("display.max_rows", len(BTC['prices'])) print(BTC_Data) elif ch==2: # market caps stats BTC_m=pd.DataFrame(BTC['market_caps'],columns=['Time stamp','market cap']) BTC_m['Date']=pd.to_datetime(BTC_m['Timestamp'],unit='ms') #to print all the rows pd.set_option("display.max_rows", len(BTC['market_caps'])) print(BTC_m) else: # Total values stats BTC_t=pd.DataFrame(BTC['total_value'],columns=['Time stamp','Total value'])
def execute(self, bot, update, args): try: data = CoinGeckoAPI().get_coin_by_id(con.CG_ID) except Exception as e: error = f"{emo.ERROR} Could not retrieve price" update.message.reply_text(error) logging.error(e) self.notify(e) return if not data: update.message.reply_text(f"{emo.ERROR} Could not retrieve data") return name = data["name"] symbol = data["symbol"].upper() rank_mc = data["market_cap_rank"] rank_cg = data["coingecko_rank"] cs = int(float(data['market_data']['circulating_supply'])) sup_c = f"{utl.format(cs)} {symbol}" if data["market_data"]["total_supply"]: ts = int(float(data["market_data"]["total_supply"])) sup_t = f"{utl.format(ts)} {symbol}" else: sup_t = "N/A" usd = data["market_data"]["current_price"]["usd"] eur = data["market_data"]["current_price"]["eur"] btc = data["market_data"]["current_price"]["btc"] eth = data["market_data"]["current_price"]["eth"] p_usd = utl.format(usd, force_length=True) p_eur = utl.format(eur, force_length=True, template=p_usd) p_btc = utl.format(btc, force_length=True, template=p_usd) p_eth = utl.format(eth, force_length=True, template=p_usd) p_usd = "{:>12}".format(p_usd) p_eur = "{:>12}".format(p_eur) p_btc = "{:>12}".format(p_btc) p_eth = "{:>12}".format(p_eth) v_24h = utl.format( int(float(data["market_data"]["total_volume"]["usd"]))) m_cap = utl.format(int(float( data["market_data"]["market_cap"]["usd"]))) if data["market_data"]["price_change_percentage_1h_in_currency"]: c_1h = data["market_data"][ "price_change_percentage_1h_in_currency"]["usd"] c1h = utl.format(float(c_1h), decimals=2, force_length=True) h1 = "{:>10}".format(f"{c1h}%") else: h1 = "{:>10}".format("N/A") if data["market_data"]["price_change_percentage_24h_in_currency"]: c_1d = data["market_data"][ "price_change_percentage_24h_in_currency"]["usd"] c1d = utl.format(float(c_1d), decimals=2, force_length=True) d1 = "{:>10}".format(f"{c1d}%") else: d1 = "{:>10}".format("N/A") if data["market_data"]["price_change_percentage_7d_in_currency"]: c_1w = data["market_data"][ "price_change_percentage_7d_in_currency"]["usd"] c1w = utl.format(float(c_1w), decimals=2, force_length=True) w1 = "{:>10}".format(f"{c1w}%") else: w1 = "{:>10}".format("N/A") if data["market_data"]["price_change_percentage_30d_in_currency"]: c_1m = data["market_data"][ "price_change_percentage_30d_in_currency"]["usd"] c1m = utl.format(float(c_1m), decimals=2, force_length=True) m1 = "{:>10}".format(f"{c1m}%") else: m1 = "{:>10}".format("N/A") if data["market_data"]["price_change_percentage_1y_in_currency"]: c_1y = data["market_data"][ "price_change_percentage_1y_in_currency"]["usd"] c1y = utl.format(float(c_1y), decimals=2, force_length=True) y1 = "{:>10}".format(f"{c1y}%") else: y1 = "{:>10}".format("N/A") msg = f"{name} ({symbol})\n\n" \ f"USD {p_usd}\n" \ f"EUR {p_eur}\n" \ f"BTC {p_btc}\n" \ f"ETH {p_eth}\n\n" \ f"Hour {h1}\n" \ f"Day {d1}\n" \ f"Week {w1}\n" \ f"Month {m1}\n" \ f"Year {y1}\n\n" \ f"Market Cap Rank: {rank_mc}\n" \ f"Coin Gecko Rank: {rank_cg}\n\n" \ f"Volume 24h: {v_24h} USD\n" \ f"Market Cap: {m_cap} USD\n" \ f"Circ. Supp: {sup_c}\n" \ f"Total Supp: {sup_t}\n\n" cg_link = f"👉 https://idena.today 👈" update.message.reply_text(text=f"`{msg}`{cg_link}", parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, quote=False)
import telebot import requests from pycoingecko import CoinGeckoAPI import urllib.request from pprint import pprint from html_table_parser.parser import HTMLTableParser with open('.git/token', 'r') as file: tokens = list(file) cg = CoinGeckoAPI() bot_token = tokens[0].strip() weather_token = tokens[1].strip() bot = telebot.TeleBot(bot_token) currency = cg.get_price(ids='bittorrent-2,cardano,tron', vs_currencies='usd', include_24hr_change='true') keyboard1 = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True).add( 'Погода', 'Курсы криптовалют', 'Стоимость топлива') keyboard2 = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True).add( 'BitTorrent', 'Tron', 'Cardano') @bot.message_handler(commands=['start']) def start_message(message): bot.send_message(message.chat.id, 'Доступные функции: \n\t• прогноз погоды в Светлогорске ' '\n\t• информация о стоимости криптовалют' '\n\t• стоимость топлива', reply_markup=keyboard1)
DEFAULT_JSON = { "coin": "", "coin_sym": "", "coin_id": "", "last_price": 0, "table": { "position_size": [], "price": [] }, "total_purchased": 0, "avg_price": 0, "cost": 0.0, "pnl": 0.0, "per_change": 0.0 } CG = CoinGeckoAPI() # region file ops def save(fname, data): # save table save_file(os.path.join(SAVE_DIR, fname), data) def load(fname): # load table otherwise load empty table if fname: try: data = load_file(os.path.join(SAVE_DIR, fname)) return data
for row in reader: if row: datetimes.append( datetime.datetime.fromisoformat(row[0]).timestamp()) dna.append(float(row[1])) datetimes = array(datetimes, dtype=float) dna = array(dna, dtype=float) print("%a\n%a" % (datetimes, dna)) coef = polyfit(datetimes, dna, 1) p = poly1d(coef) print(p) cg = CoinGeckoAPI() dna_price = cg.get_price(ids="idena", vs_currencies=["usd", "gbp"])["idena"] dna_per_day = coef[ 0] * 60 * 60 * 24 # gradient is in units dna/second, so multiply to get dna/day print("DNA/day: %.4f. $%.2f/day, £%.2f/day." % (dna_per_day, dna_per_day * dna_price["usd"], dna_per_day * dna_price["gbp"])) xlabel("Datetime") ylabel("DNA") plot(datetimes, dna, "x", label="Data") plot(datetimes, dna, label="Data") x = linspace(min(datetimes), max(datetimes), 1000) plot(x, p(x), label="Best fit")
from pycoingecko import CoinGeckoAPI from pprint import pprint import argparse cg = CoinGeckoAPI() def parse_arguments(): # create the top-level parser parser = argparse.ArgumentParser(prog=__file__) # parser.add_argument("--foo", action="store_true", help="foo help") subparsers = parser.add_subparsers(help="sub-command help") # create portfolio sub command parser_portfolio = subparsers.add_parser("portfolio", help="Portfolio Help") parser_portfolio.add_argument("set", help="Set your portfolio", dest="set_portfolio") args = parser.parse_args() pprint(args) return args def sanitize_number(num): num = round(num, 2) billions = 0 millions = 0 if num >= 1000000000: while num >= 1000000000: num -= 1000000000
"7d": "?time=d7", "14d": "?time=d14", "30d": "?time=d30", "60d": "?time=d60", "1y": "?time=y1", } CATEGORIES = { "trending": 0, "most_voted": 1, "positive_sentiment": 2, "recently_added": 3, "most_visited": 4, } client = CoinGeckoAPI() def get_gainers_or_losers(period="1h", typ="gainers") -> pd.DataFrame: """Scrape data about top gainers - coins which gain the most in given period and top losers - coins that lost the most in given period of time. Parameters ---------- period: str One from [1h, 24h, 7d, 14d, 30d, 60d, 1y] typ: str Either "gainers" or "losers" Returns ------- pandas.DataFrame
class CoinStats(): def __init__(self, coin, last_price = None): if last_price is None: self.last_price = 0.0 else: self.last_price = last_price self.coin = coin self.current_price = 0.0 self.time_offset = -14400 # EST offset self.cg = CoinGeckoAPI() self.last_time = self.current_time() self.day_no = self.set_day() def get_price(self): doge_info = self.cg.get_price(ids=self.coin, vs_currencies='usd') return doge_info[self.coin]['usd'] def get_prices(self): price_info = self.cg.get_price(ids=self.coin, vs_currencies='usd') prices = [] for coin in self.coin: prices.append(price_info[coin]['usd']) return prices def check_price(self): try: self.current_price = self.get_price() if (self.current_price != self.last_price): if (self.current_time() < self.last_time): # if new day, rename file self.day_no = self.set_day() self.last_time = self.current_time() self.append_to_file() self.last_price = self.current_price return True except KeyboardInterrupt: sys.exit(0) except: pass return False def set_day(self): day_offset = 105-18733 # didn't feel like actually figuring it out offset for: days since Jan 1st 2021 day_no = math.floor((time.time()+self.time_offset)/86400) + day_offset self.price_file = "../{}_price_history/".format(self.coin)+str(day_no)+".csv" return day_no def current_time(self): return ((time.time()+self.time_offset) % 86400) def append_to_file(self): f = open(self.price_file, "a") f.write(str(self.last_time)+","+str(self.current_price)+"\n") f.close() def plot_data(self, filename_csv): csv_file = open(filename_csv) csv_data = csv.reader(csv_file) x = [] y = [] for row in csv_data: x.append(float(row[0])) y.append(float(row[1])) plot.plotXvY(x, y)
class CoinGecko: def __init__(self): """ All free data and no API key necessary 200 api calls/ min """ self.api = CoinGeckoAPI() def get_price(self, symbols: List[str], currency="usd", print_error=True) -> float: resp = self.api.get_price(symbols, vs_currencies=currency) assert isinstance(symbols, list) if not resp: # got an empty response ... if print_error: print("No response. Please check the accuracy of your symbols and currencies.") print(self.__find_coin_id(symbols[0], self.get_all_coin_ids())) return None return resp def get_current_coin_price(self, symbols: List[str], currency='usd') -> str: """ A wrapper function for 'python cli.py coin ...' :param symbols: :param currency: :return: """ resp = self.api.get_price(symbols, vs_currencies=currency, print_error=False) assert isinstance(symbols, list) assert len(symbols) == 1 s = "" if not resp: # bad coin name s += "No response. Please check the accuracy of your symbols.\n" s += self.__find_coin_id(symbols[0], self.get_all_coin_ids()) return s elif not resp[symbols[0]]: # empty response s += "No response. Please check the accuracy of your currencies.\n" s += self.__find_currency_id(currency, self.get_supported_vs_currencies()) return s else: s += f"Current price of {symbols[0]} vs {currency} is: {resp[symbols[0]][currency]}" return s def get_historical_data(self, symbol: str, days: int, currency='usd') -> pd.DataFrame: """ By default, returns the the data in 1 hour time segments """ assert isinstance(symbol, list) try: resp = self.api.get_coin_market_chart_by_id(symbol, currency, days) except ValueError as e: print(self.__find_coin_id(symbol[0], self.get_coins_list())) return None else: df = pd.DataFrame(columns=['price', 'marketCap', 'volume', 'time']) for i in range(len(resp['prices'])): timestamp = datetime.fromtimestamp(resp['prices'][i][0] / 1000) df = df.append({ 'price': resp['prices'][i][1], 'marketCap': resp['market_caps'][i][1], 'volume': resp['total_volumes'][i][1], 'time': timestamp.isoformat() }, ignore_index=True) df = df.sort_values(by='time', ascending=False) df = df.reset_index(drop=True) return df def get_supported_vs_currencies(self): """ Returns the currencies that cryptos can be compared to . like 'usd' """ return self.api.get_supported_vs_currencies() def get_coins_list(self): """ Returns all the available crypto coins that are available """ return self.api.get_coins_list() def get_all_coin_ids(self) -> set: """IDs are what must be used to get information from pycoingecko""" coins = self.get_coins_list() return set([coin['id'] for coin in coins]) def __find_coin_id(self, wrongName, allIds): suggestion = min_edit_dist(wrongName, allIds) return f"No data found for symbol '{wrongName}'\n\n Did you mean '{suggestion}'?" def __find_currency_id(self, wrongCurr, allCurrs): suggestion = min_edit_dist(wrongCurr, allCurrs) return f"No data found for currency '{wrongCurr}'\n\n Did you mean '{suggestion}'?"
def __init__(self): """ All free data and no API key necessary 200 api calls/ min """ self.api = CoinGeckoAPI()
from pycoingecko import CoinGeckoAPI import MongoDBUtils cg = CoinGeckoAPI() # test = cg.get_coin_market_chart_by_id("bitcoin", vs_currency="usd", days= "max") mongo = MongoDBUtils.MongoUtils() mongo.connect() # mongo.connectToCollectino("dev","btc_hist") mongo.collection.insert_one(test) TICKERS = ['LINK', 'BTC', 'XLM', 'ZRX', 'ZEC', 'XTZ', 'XRP', 'REP', 'OXT', 'OMG' , 'MKR', 'LTC', 'KNC', 'ETH', 'ETC', 'EOS', 'DASH', 'DAI', 'COMP', 'BCH', 'BAT', 'ATOM'] TICKERS = [x.lower() for x in TICKERS] symbols = cg.get_coins_list() for i in symbols: if i["symbol"] in TICKERS: data = cg.get_coin_market_chart_by_id(i["id"], vs_currency="usd", days= "max") mongo.connectToCollectino("dev",i["id"]) timestamps = [] for i in data["prices"]: timestamps.append(i[0]) #data['timestamps'] = timestamps returnedData = {} for key in data: returnedData[key] = [] for entry in data[key]: returnedData[key].append(entry[1])
import serial import time from pycoingecko import CoinGeckoAPI cg = CoinGeckoAPI() lastInfo = cg.get_price(ids='dogecoin', vs_currencies='gbp') lastPrice = 0 sleepTime = 10 s = serial.Serial() s.port = 'COM3' s.baudrate = 9600 s.open() def parse(): # print("after parsing") preparse = cg.get_price(ids='dogecoin', vs_currencies='gbp') # print(preparse) split = str(preparse).split("'") # print(split) priceA = str(split[4]).split("}") # print("a" + str(priceA)) priceB = str(split[4]).split(": ") # print("b" + str(priceB)) name = split[1] priceC = priceB[1] size = len(priceC)
class Application(wx.Frame): def __init__(self, parent, title, pos, size): super(Application, self).__init__(parent, title=title, pos=pos, size=size) self.InitUI() self.Centre() # load data self.cg = CoinGeckoAPI() self.Layout() self.Update() def InitUI(self): panel = wx.Panel(self) font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(15) self.grid_count_row = 1 self.grid_count_col = 1 sizer = wx.GridBagSizer(7, 5) text1 = wx.StaticText(panel, label="Scrape data from coingecko api") sizer.Add(text1, pos=(0, 0), span=(1, 3), flag=wx.LEFT|wx.CENTER, border=15) line = wx.StaticLine(panel) sizer.Add(line, pos=(1, 0), span=(1, 6), flag=wx.EXPAND|wx.CENTER, border=10) # input time st1 = wx.StaticText(panel, label='Time (in days)', size=(150, 30)) st1.SetFont(font) sizer.Add(st1, pos=(2, 0), flag=wx.LEFT|wx.EXPAND|wx.CENTER,border=15) time_input_options = ["1h", "24h", "7d", "14d", "30d", "200d", "1y"] self.price_change_percentage = wx.ComboBox(panel, value=time_input_options[0], choices = time_input_options, size=(200, 30)) sizer.Add(self.price_change_percentage, pos=(2, 1), span=(1, 3), flag=wx.CENTER|wx.EXPAND, border=5) btn1 = wx.Button(panel, label='Check', size=(70, 30)) sizer.Add(btn1, pos=(2, 5),flag=wx.RIGHT|wx.CENTER, border=5) btn1.Bind(wx.EVT_BUTTON, self.check) btn2 = wx.Button(panel, label='Update', size=(70, 30)) sizer.Add(btn2, pos=(3, 5),flag=wx.RIGHT|wx.CENTER, border=5) btn2.Bind(wx.EVT_BUTTON, self.update) cal_options = [ "Decreased more than", "Increased more than"] self.cal_combo = wx.ComboBox(panel ,value=cal_options[1] ,choices = cal_options, size=(150, 30)) sizer.Add(self.cal_combo, pos=(3, 0),flag=wx.LEFT|wx.EXPAND|wx.CENTER, border=15) self.change_percentage = wx.TextCtrl(panel, value="0.5", size=(150, 30)) sizer.Add(self.change_percentage, pos=(3, 1), flag=wx.CENTER|wx.EXPAND, border=5) st2 = wx.StaticText(panel, label='%', size=(30, 30)) st2.SetFont(font) sizer.Add(st2, pos=(3, 2), flag=wx.LEFT|wx.CENTER,border=5) line2 = wx.StaticLine(panel) sizer.Add(line2, pos=(4, 0), span=(0, 6), flag=wx.EXPAND|wx.CENTER, border=10) st3 = wx.StaticText(panel, label='Result:', size=(150, 30)) st3.SetFont(font) sizer.Add(st3, pos=(5, 0), flag=wx.LEFT|wx.EXPAND|wx.CENTER,border=15) self.grid = wx.grid.Grid(panel, size=(1000, 300)) self.grid.AutoSizeColumns(setAsMin=True) self.grid.CreateGrid(100,12) sizer.Add(self.grid, pos=(6, 0), span=(0, 6), flag=wx.EXPAND|wx.CENTER, border=10) panel.SetSizer(sizer) sizer.Fit(self) def check(self, event): df_coins = pd.DataFrame(self.cg.get_coins()) coin_list = df_coins["id"].tolist() req1_field = self.price_change_percentage.GetValue() print(req1_field) req2_field = "price_change_percentage_%s_in_currency" % (req1_field) percent = float(self.change_percentage.GetValue()) data = self.cg.get_coins_markets(ids=coin_list, vs_currency="usd", price_change_percentage=req1_field) df_requested_data = pd.DataFrame(data) if(self.cal_combo.GetValue() == "Increased more than"): df_requested_data = df_requested_data.loc[(df_requested_data[req2_field] > percent)] else: df_requested_data = df_requested_data.loc[(df_requested_data[req2_field] < percent)] # print(df_requested_data[['id', req2_field]]) self.df_to_list(df_requested_data[['id', req2_field]]) def df_to_list(self,df): print(df) self.clear_grid() self.grid_count_row, self.grid_count_col = df.shape print(self.grid_count_row) if (self.grid_count_row <= 1 or self.grid_count_col <= 1): return for x in range(len(df.columns.values)): self.grid.SetCellValue(0,x, str(df.columns.values[x])) self.grid.SetCellFont(0,x, wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD)) self.grid.SetCellBackgroundColour(0,x, "light blue") self.grid.SetColSize(x, 300) row_indx = 1 for index, row in df.iterrows(): for col in range(0, self.grid_count_col): self.grid.SetCellValue(row_indx, col, str(row[col])) row_indx +=1 self.grid.ForceRefresh() def clear_grid(self): """ remove all data """ for row in range(0,self.grid_count_row): for col in range(0,self.grid_count_col): self.grid.SetCellValue(row, col, "") self.grid.ForceRefresh() def update(self, event): self.clear_grid() self.grid.ForceRefresh()
from pycoingecko import CoinGeckoAPI cg = CoinGeckoAPI() print("This shows the coin's market data.") id = input("Enter the coin name - ") data = cg.get_coin_by_id(id)['market_data'] print(id + 'coin current rank = ' + str(data['market_cap_rank']))
from flask import Flask from flask_pymongo import PyMongo from pycoingecko import CoinGeckoAPI import datetime, threading app = Flask(__name__) app.config["MONGO_URI"] = "mongodb://localhost:27017/betsite_db" mongo = PyMongo(app) users = mongo.db.user forecasts = mongo.db.forecasts timerruns = mongo.db.timerrun coingecko = CoinGeckoAPI() def readybet(): listid = [] casts = forecasts.find() for count in casts: if count['count'] > 1 and count['activate'] == True: listid.append(count['id']) return listid def timebet(): listsec = [] for id in readybet(): dateone = datetime.datetime.now() getcast = forecasts.find_one({'id': id})
from datetime import datetime from typing import Union import pandas as pd from pycoingecko import CoinGeckoAPI from data_sources.helpers import print_red """https://pypi.org/project/pycoingecko/""" coin_gecko = CoinGeckoAPI() def get_price(cg_id: str) -> Union[None, float]: try: return coin_gecko.get_price(cg_id, 'usd')[cg_id]['usd'] except Exception as Arguments: print_red(f"Unsucessful call in coin_gecko.get_price: {Arguments}") return None def get_historic_prices(cg_id: str, since: datetime, till: datetime) -> Union[None, pd.Series]: try: response = coin_gecko.get_coin_market_chart_range_by_id( cg_id, 'usd', int(since.timestamp()), int(till.timestamp())) return pd.Series({ datetime.fromtimestamp(item[0] / 1000, tz=since.tzinfo): item[1] for item in response['prices'] }) except Exception as Arguments: print_red(
class discord_bot: # api instance cg = CoinGeckoAPI() es = etherscan.Client( api_key=bot_ids.etherscan_api_key, cache_expire_after=5, ) # logging.basicConfig(filename="log.log", level=logging.INFO) global the_coin_list the_coin_list = copy.deepcopy(cg.get_coins_list()) # functions to gather btc, eth, and any coins price def btc_status(self): price_data = self.cg.get_price(ids='bitcoin', vs_currencies='usd') price = price_data['bitcoin']['usd'] if price != None: price = round(price, 2) price = "{:,}".format(price) response = "Bitcoin - $" + str(price) # logging.info("Logged BTC price at " + str(datetime.now())) return response else: # logging.warning("Error from CoinGecko at: " + str(datetime.now())) return "CoinGecko Error" def eth_status(self): price_data = self.cg.get_price(ids='Ethereum', vs_currencies='usd') price = price_data['ethereum']['usd'] if price != None: price = round(price, 2) price = "{:,}".format(price) response = "Ethereum: $" + str(price) # logging.info("Logged ETH price at " + str(datetime.now())) return response else: # logging.warning("Error from CoinGecko at: " + str(datetime.now())) return "Coingecko Errors" def get_coin_price(self, coin_name): coin_label = "" coin_name = coin_name.lower() coin_label = self.check_coin(coin_name) if self.check_coin(coin_name) != "": price_data = self.cg.get_price(ids=coin_label, vs_currencies='usd', include_24hr_change='true', include_market_cap='true') price = price_data[coin_label]['usd'] if price != None: if float(price) < 0.001: price = round(price, 5) elif float(price) < 0.01: price = round(price, 4) else: price = round(price, 3) price = "{:,}".format(price) percent_change = price_data[coin_label]['usd_24h_change'] if percent_change != None: percent_change = str(round(percent_change, 2)) + "%" else: percent_change = None market_cap = price_data[coin_label]['usd_market_cap'] market_cap = round(market_cap, 2) market_cap = self.check_large(market_cap) if market_cap != "Not Found": mc = "$" + market_cap else: mc = market_cap # market_cap = "{:,}".format(market_cap) coin_name = self.change_cap(coin_name) # embedResponse = discord.Embed(title=coin_name + " Info", color=0xFF8C00) embedResponse = discord.Embed(title=coin_name + "'s" + " Stats", color=0xFF8C00) embedResponse.add_field( name="Price", value="[" + "$" + str(price) + "](https://www.coingecko.com/en/coins/" + coin_label + ")", inline=False) embedResponse.add_field(name="Percent Change (24hr)", value=str(percent_change), inline=False) embedResponse.add_field(name="Market Cap", value=mc, inline=False) embedResponse.set_footer(text="Powered by cryptobot.info") response1 = "```" + coin_name + "'s price: $" + str( price) + "\n" + "Percent Change (24h): " + str( percent_change) + "%" + "\n" + "Market Cap: $" + str( market_cap) + "```" # response2 = "```" + coin_name + "'s price: $" + str(price) + ", " + "Percent Change (24h): " + str(percent_change) + "%" + "\n" + "Market Cap: $" + str(market_cap) + "```" return embedResponse return "" # retreive data and create candle chart of any coin def get_line_chart(self, coin_name, coin_name2, num_days, type): #all code that includes type 2 is for chart one currency against another #coin label work coin_label = "" coin_name = coin_name.lower() coin_label = self.check_coin(coin_name) #coin label 2 work if type == 2: coin_label2 = "" coin_name2 = coin_name2.lower() coin_label2 = self.check_coin(coin_name2) #checking if num days is valid temp = str(num_days) if not temp.isdigit(): temp = temp.lower() if temp != "max": return False if self.check_coin(coin_name) != "": charts = self.cg.get_coin_market_chart_by_id(id=coin_label, vs_currency='usd', days=num_days) if type == 2: charts2 = self.cg.get_coin_market_chart_by_id( id=coin_label2, vs_currency='usd', days=num_days) plt.close() x_vals = [] y_vals = [] count = 0 open, close, high, low, volume = [], [], [], [], [] min = len(charts["prices"]) if type == 2: if min > len(charts2["prices"]): min = len(charts2["prices"]) for point in charts['prices']: if count == 0: time_conv = datetime.utcfromtimestamp( point[0] / 1000).strftime('%Y-%m-%d') time1 = datetime.utcfromtimestamp( point[0] / 1000).strftime('%Y-%m-%d %H:%M:%S') if count == 1: time2 = datetime.utcfromtimestamp( point[0] / 1000).strftime('%Y-%m-%d %H:%M:%S') if count == min - 1: time_end = datetime.utcfromtimestamp( point[0] / 1000).strftime('%Y-%m-%d') x_vals.append(time_conv) y_vals.append(point[1]) volume.append(1) count += 1 if count == min: break if type == 2: count = 0 for point in charts2['prices']: if count == min: break y_vals[count] = y_vals[count] / point[1] count += 1 open = y_vals close = y_vals high = y_vals low = y_vals period = len(open) frequency = "" if num_days == "1": frequency = "5min" elif num_days != "max" and (int(num_days) <= 90 and int(num_days) > 1): frequency = "1H" else: frequency = "4D" dti = pd.date_range(start=time_conv, end=time_end, periods=period) # print(dti2) # dti = pd.date_range(time_conv, periods=period, freq=frequency) ohlc = { "opens": open, "highs": high, "lows": low, "closes": close, "volumes": volume } ohlc = pd.DataFrame(data=ohlc, index=dti) ohlc.columns = ['Open', 'High', 'Low', 'Close', 'Volume' ] #these two lines solved the dataframe problem ohlc.index.name = "Date" # plot and make it look good percent_change = ( (close[len(close) - 1] - close[0]) / close[0]) * 100 percent_change = round(percent_change, 2) changed, days = "", "" # change title based on days if num_days == "1": days = "the past 24 hours" elif num_days == "MAX" or num_days == "max": days = "Within Lifetime" else: days = "Past " + num_days + " Days" # change title based on percent if percent_change > 0: changed = "+" else: changed = "" percent_change = "{:,}".format( percent_change ) # had to do it here because this converts it to a string, need it as a int above # title = "\n" + "\n" + coin_label + "'s price " + changed + percent_change + "% within " + days coin_label = self.change_cap(coin_label) title1 = "\n" + "\n" + coin_label + " " + changed + percent_change + "% - " + days if type == 2: coin_label2 = self.change_cap(coin_name2.lower()) title1 = "\n" + "\n" + coin_label + "/" + coin_label2 + " " + changed + percent_change + "% - " + days mc = mpf.make_marketcolors( up='tab:blue', down='tab:red', wick={ 'up': 'blue', 'down': 'red' }, volume='tab:green', ) edited_style = mpf.make_mpf_style(gridstyle='-', facecolor="lightgray", gridcolor="white", edgecolor="black", base_mpl_style="classic", marketcolors=mc) if type == 1: fig, axlist = mpf.plot(ohlc, type='line', title=title1, figratio=(30, 20), ylabel='Price - USD', style=edited_style, returnfig=True) ax1 = axlist[0] # ax1.yaxis.set_major_formatter(tick.FormatStrFormatter('%.8f')) ax1.yaxis.set_major_formatter( tick.FuncFormatter(reformat_large_tick_values)) fig.savefig('chart.png') else: fig, axlist = mpf.plot(ohlc, type='line', title=title1, figratio=(16, 10), ylabel=coin_label + "/" + coin_label2, style=edited_style, returnfig=True) ax1 = axlist[0] # ax1.yaxis.set_major_formatter(tick.FormatStrFormatter('%.8f')) ax1.yaxis.set_major_formatter( tick.FuncFormatter(reformat_large_tick_values)) fig.savefig('chart.png') return "" else: return "error" def get_tvl_chart(self, coin_name, coin_name2, num_days, type): #coin label work coin_label = "" coin_name = coin_name.lower() coin_label = self.check_coin(coin_name) #coin label 2 work valid_intervals = ["1w", "1m", "3m", "1y", "all", "max"] check_int = False num_days = num_days.lower() for interval in valid_intervals: if num_days == interval: check_int = True if not check_int: error_days = "```Command Error: Wrong number of days: Only can input '1w','1m','3m','1y','all','max'```" return error_days if type == 2: coin_label2 = "" coin_name2 = coin_name2.lower() coin_label2 = self.check_coin(coin_name2) if self.check_coin(coin_name) != "": link = "https://data-api.defipulse.com/api/v1/defipulse/api/GetHistory?api-key=" + bot_ids.defipulse_api_key + "&project=" + coin_name + "&period=" + num_days response = requests.get(link) output = response.json() y_vals = [] x_vals = [] count = 0 min = len(output) volume = [] for one_int in output: time_conv = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(one_int["timestamp"])) x_vals.append(time_conv) y_vals.append(one_int["tvlUSD"]) volume.append(1) count += 1 # check to see if the data is reversed if x_vals[0] > x_vals[1]: # reverse lists x_vals = x_vals[::-1] y_vals = y_vals[::-1] plt.close() open, close, high, low = y_vals, y_vals, y_vals, y_vals period = len(open) frequency = "" # if num_days == "1": # frequency = "5min" # elif num_days != "max" and (int(num_days) <= 90 and int(num_days) > 1): # frequency = "1H" # else: # frequency = "4D" dti = pd.date_range(start=x_vals[0], end=x_vals[len(x_vals) - 1], periods=period) # print(dti2) # dti = pd.date_range(time_conv, periods=period, freq=frequency) ohlc = { "opens": open, "highs": high, "lows": low, "closes": close, "volumes": volume } ohlc = pd.DataFrame(data=ohlc, index=dti) ohlc.columns = ['Open', 'High', 'Low', 'Close', 'Volume' ] #these two lines solved the dataframe problem ohlc.index.name = "Date" # plot and make it look good percent_change = ( (close[len(close) - 1] - close[0]) / close[0]) * 100 percent_change = round(percent_change, 2) changed, days = "", "" # change title based on days # if num_days == "1": # days = "the past 24 hours" # elif num_days == "MAX" or num_days == "max": # days = "Within Lifetime" # else: # days = "Past " + num_days + " Days" # # change title based on percent # if percent_change > 0: # changed = "+" # else: # changed = "" percent_change = "{:,}".format( percent_change ) # had to do it here because this converts it to a string, need it as a int above # title = "\n" + "\n" + coin_label + "'s price " + changed + percent_change + "% within " + days coin_label = self.change_cap(coin_label) title1 = "\n" + "\n" + coin_label + " " + "Historcal TVL: " + percent_change + "% - " + "Past " + num_days if type == 2: coin_label2 = self.change_cap(coin_name2.lower()) title1 = "\n" + "\n" + coin_label + "/" + coin_label2 + " " + changed + percent_change + "% - " + days mc = mpf.make_marketcolors( up='tab:blue', down='tab:red', wick={ 'up': 'blue', 'down': 'red' }, volume='tab:green', ) edited_style = mpf.make_mpf_style(gridstyle='-', gridcolor="white", edgecolor="black", base_mpl_style="nightclouds", marketcolors=mc) # edited_style = mpf.make_mpf_style(gridstyle = '-', facecolor = "black", gridcolor = "white", edgecolor = "black", base_mpl_style = "classic", marketcolors=mc) if type == 1: fig, axlist = mpf.plot(ohlc, type='line', title=title1, figratio=(16, 10), ylabel='Price - USD ($)', style="nightclouds", returnfig=True) ax1 = axlist[0] # ax1.yaxis.set_major_formatter(tick.FormatStrFormatter('%.8f')) ax1.yaxis.set_major_formatter( tick.FuncFormatter(reformat_large_tick_values)) fig.savefig('ctvl.png') else: mpf.plot(ohlc, type='line', title=title1, figratio=(16, 10), ylabel=coin_label + "/" + coin_label2, style=edited_style, savefig="ctvl.png") return "" else: return "error" # retreive data and create candle chart of any coin def get_candle_chart(self, coin_name, num_days): # used the below links for the mpf libraries # https://github.com/matplotlib/mplfinance#usage # https://github.com/matplotlib/mplfinance/blob/master/examples/styles.ipynb #coin label work coin_label = "" coin_label = self.check_coin(coin_name) #checking if num days is valid valid_days = ["1", "7", "14", "30", "90", "180", "365", "MAX", "max"] check = False error_days = "```Command Error: Wrong number of days: Only can input '1','7','14','30','90','180','365','MAX'```" for day in valid_days: if num_days == day: check = True if check == False: return error_days if self.check_coin(coin_name) != "": candles = self.cg.get_coin_ohlc_by_id(id=coin_label, vs_currency='usd', days=num_days) plt.close() date_arr, year, month, day, hour, open, high, low, close, volume = [], [], [], [], [], [], [], [], [], [] count = 0 time_conv = "" for point in candles: # convert to standard date and time, parse and add them into arrays if count == 0: time_conv = datetime.utcfromtimestamp( point[0] / 1000).strftime('%Y-%m-%d') if count == 0: time1 = datetime.utcfromtimestamp( point[0] / 1000).strftime('%Y-%m-%d %H:%M:%S') if count == 1: time2 = datetime.utcfromtimestamp( point[0] / 1000).strftime('%Y-%m-%d %H:%M:%S') if count == len(candles) - 1: time_end = datetime.utcfromtimestamp( point[0] / 1000).strftime('%Y-%m-%d') # parse and add in the OHLC vectors open.append(point[1]) high.append(point[2]) low.append(point[3]) close.append(point[4]) volume.append(1) count += 1 # create the date and dataframe period = len(open) frequency = "" if num_days == "1": frequency = "30min" elif num_days == "7" or num_days == "14" or num_days == "30": frequency = "4H" else: frequency = "4D" dti = pd.date_range(start=time_conv, end=time_end, periods=period) # dti = pd.date_range(time_conv, periods=period, freq=frequency) ohlc = { "opens": open, "highs": high, "lows": low, "closes": close, "volumes": volume } ohlc = pd.DataFrame(data=ohlc, index=dti) ohlc.columns = ['Open', 'High', 'Low', 'Close', 'Volume' ] #these two lines solved the dataframe problem ohlc.index.name = "Date" # plot and make it look good percent_change = ( (close[len(close) - 1] - close[0]) / close[0]) * 100 percent_change = round(percent_change, 2) changed, days = "", "" # change title based on days if num_days == "1": days = "the past 24 hours" elif num_days == "MAX" or num_days == "max": days = "Within Lifetime" else: days = "Past " + num_days + " Days" # change title based on percent if percent_change > 0: changed = "+" else: changed = "" percent_change = "{:,}".format( percent_change ) # had to do it here because this converts it to a string, need it as a int above # title = "\n" + "\n" + coin_label + "'s price " + changed + percent_change + "% within " + days coin_label = self.change_cap(coin_label) title1 = "\n" + "\n" + coin_label + " " + changed + percent_change + "% - " + days mc = mpf.make_marketcolors( up='tab:blue', down='tab:red', wick={ 'up': 'blue', 'down': 'red' }, volume='tab:green', ) edited_style = mpf.make_mpf_style(gridstyle='-', facecolor="lightgray", gridcolor="white", edgecolor="black", base_mpl_style="classic", marketcolors=mc) mpf.plot(ohlc, type='candle', title=title1, figratio=(16, 10), ylabel='Price - USD', style=edited_style, savefig="candle.png") return "" else: return "error" # function to get the ath, atl, and/or the range of the coin def get_all_time(self, symbol, coin_name): coin = "" coin = self.check_coin(coin_name) if coin == "": return "e" # get market data market_data = self.cg.get_coin_by_id(id=coin) ath = market_data["market_data"]["ath"]["usd"] atl = market_data["market_data"]["atl"]["usd"] # change the coin name capitalization coin_final = self.change_cap(coin) # then deduce based on type of prompt if symbol == "H": if ath != None and ath != "": ath = "{:,}".format(ath) embedResponse = discord.Embed(color=0xFF8C00) embedResponse.add_field(name=coin_final + " ATH", value="$" + str(ath), inline=False) return embedResponse else: return "e" elif symbol == "L": if atl != None and atl != "": atl = "{:,}".format(atl) embedResponse = discord.Embed(color=0xFF8C00) embedResponse.add_field(name=coin_final + " ATL", value="$" + str(atl), inline=False) return embedResponse else: return "e" elif symbol == "R": if ath != None and atl != None and ath != "" and atl != "": # get ath and atl prices ath = "{:,}".format(ath) atl = "{:,}".format(atl) # get current price price_data = self.cg.get_price(ids=coin, vs_currencies='usd', include_24hr_change='true', include_market_cap='true') price = price_data[coin]['usd'] if price != None: if float(price) < 0.001: price = round(price, 5) elif float(price) < 0.01: price = round(price, 4) else: price = round(price, 3) # format price for commas price = "{:,}".format(price) embedResponse = discord.Embed(title=coin_final + " Range", color=0x0000ff) embedResponse.add_field(name="All Time Low", value="$" + str(atl), inline=True) embedResponse.add_field(name="Current Price", value="$" + str(price), inline=True) embedResponse.add_field(name="All Time High", value="$" + str(ath), inline=True) embedResponse.set_footer(text="Powered by cryptobot.info") return embedResponse else: return "e" else: return "e" # get an image of a coin def get_image(self, coin_name): coin = "" coin = self.check_coin(coin_name) if coin == "": return "e" # get coin image data output = self.cg.get_coin_by_id(id=coin) image_url = image_cg = output["image"]["small"] # change the coin name capitalization coin_final = self.change_cap(coin) # take image and save as png req = requests.get(image_url, headers={'User-Agent': 'Mozilla/5.0'}) # webpage = urlopen(req).read() file = open("image.png", "wb") file.write(req.content) file.close() return coin_final def get_conversion(self, num, first, second): first_coin = "" second_coin = "" first_coin = self.check_coin(first) second_coin = self.check_coin(second) # check if the coin names are valid if first_coin == "" or second_coin == "": return "e" # retreive price data about the coins first_data = self.cg.get_price(ids=first_coin, vs_currencies='usd') first_price = first_data[first_coin]['usd'] if first_data != None: second_data = self.cg.get_price(ids=second_coin, vs_currencies='usd') second_price = second_data[second_coin]['usd'] if second_data != None: # convert to proper cap. first = self.change_cap(first) second = self.change_cap(second) conv_num = float(num) * (first_price / second_price) conversion = self.round_num(conv_num) conversion = self.check_large(conversion) num = self.check_large(int(num)) embedResponse = discord.Embed(color=0x7A2F8F) embedResponse.add_field( name=first + " to " + second + " Conversion", value=str(num) + " " + first + " = " + str(conversion) + " " + second, inline=False) embedResponse.set_footer(text="Powered by cryptobot.info") return embedResponse else: embedResponse = discord.Embed(color=0x7A2F8F) embedResponse.add_field(name="Error", value="No data from CoinGecko", inline=False) return embedResponse return embedResponse def get_supply(self, coin): coin_name = "" coin_name = self.check_coin(coin) # check if the coin names are valid if coin_name == "": return "e" data = self.cg.get_coin_by_id(id=coin_name) csupply = data["market_data"]["circulating_supply"] tsupply = data["market_data"]["total_supply"] msupply = data["market_data"]["max_supply"] coin_name = self.change_cap(coin_name) csupply = self.check_large(csupply) tsupply = self.check_large(tsupply) msupply = self.check_large(msupply) embedResponse = discord.Embed(title=coin_name + "'s" + " Supply", color=0x00C09A) embedResponse.add_field(name="Circulating", value=csupply, inline=False) embedResponse.add_field(name="Total", value=tsupply, inline=False) embedResponse.add_field(name="Max", value=msupply, inline=False) embedResponse.set_footer(text="Powered by cryptobot.info") return embedResponse # find trending coins on coingecko def get_trending(self): numbering = range(1, 8) output = "" trendy = self.cg.get_search_trending() count = 0 for x in trendy["coins"]: output += str(numbering[count]) + ") " + x['item']['name'] + "\n" count += 1 embedResponse = discord.Embed(color=0x0099E1) embedResponse.add_field(name="Top Trending Coins on CoinGecko", value=output) embedResponse.set_footer(text="Powered by cryptobot.info") return embedResponse # find trending coins on coingecko def get_rekt(self): count = 0 # link = "https://data-api.defipulse.com/api/v1/rekto/api/top10?api-key=" + bot_ids.defipulse_api_key # link = "https://api.rek.to/api/top10?api-key=" + bot_ids.defipulse_api_key # response = requests.get(link) # output = response.json() # ids, amounts = "", "" # for idiot in output["top10"]: # if count < 5: # ids += str(idiot["id"]) + "\n" # amounts += "$" + str(self.check_large(idiot["value_usd"])) + "\n" # # amounts += str(self.check_large(int(idiot["value_usd"]))) + "\n" # count += 1 # embedResponse = discord.Embed(title="Top 5 Rekts (Past 24hrs)", color=0x6d37da) # embedResponse.add_field(name = "Rekted Amount (USD)", value = amounts) # embedResponse.add_field(name = "The Rekt-ed", value = ids) embedResponse = discord.Embed(title="Error with API", color=0x6d37da) embedResponse.add_field( name="Depreciated", value="Defipulse deprecated the Rekt API endpoints") return embedResponse def get_mcap_to_tvl_ratio(self, coin): coin_name = "" coin_name = self.check_coin(coin) # check if the coin names are valid if coin_name == "": return "e" data = self.cg.get_coin_by_id(id=coin_name) ratio = data["market_data"]["mcap_to_tvl_ratio"] coin_name = self.change_cap(coin_name) embedResponse = discord.Embed(color=0xF8C300) embedResponse.add_field(name=coin_name + " Mcap to TVL Ratio", value=str(ratio), inline=False) embedResponse.set_footer(text="Powered by cryptobot.info") return embedResponse def get_tvl(self, coin): coin_name = "" coin_name = self.check_coin(coin) # check if the coin names are valid if coin_name == "": return "e" data = self.cg.get_coin_by_id(id=coin_name) try: tvl = data["market_data"]["total_value_locked"]["usd"] tvl = self.check_large(tvl) except: tvl = "None" coin_name = self.change_cap(coin_name) embedResponse = discord.Embed(color=0xF8C300) embedResponse.add_field(name=coin_name + " TVL", value=str(tvl), inline=False) embedResponse.set_footer(text="Powered by cryptobot.info") return embedResponse def get_gmr(self): options = webdriver.ChromeOptions() options.headless = True options.add_argument('--headless') options.add_argument('--disable-gpu') options.add_argument("window-size=1024,768") options.add_argument("--no-sandbox") driver = webdriver.Chrome( executable_path="/root/cryptobot/chromedriver", options=options) driver.get( "https://www.lookintobitcoin.com/charts/golden-ratio-multiplier/") driver.execute_script("window.scrollTo(0, 260)") sleep(5) screenshot = driver.save_screenshot("grm.png") img = Image.open("grm.png") width, height = img.size img = img.crop((50, 0, width - 10, height - 200)) img = img.save("grm.png", format="png") driver.quit() def get_mvrv(self): options = webdriver.ChromeOptions() options.headless = True options.add_argument('--headless') options.add_argument('--disable-gpu') options.add_argument("window-size=1024,768") options.add_argument("--no-sandbox") driver = webdriver.Chrome( executable_path="/root/cryptobot/chromedriver", options=options) driver.get("https://www.lookintobitcoin.com/charts/mvrv-zscore/") driver.execute_script("window.scrollTo(0, 290)") sleep(5) screenshot = driver.save_screenshot("mvrv.png") img = Image.open("mvrv.png") width, height = img.size img = img.crop((0, 0, width - 10, height - 205)) img = img.save("mvrv.png", format="png") driver.quit() # The Puell Multiple Chart def get_puell(self): options = webdriver.ChromeOptions() options.headless = True options.add_argument('--headless') options.add_argument('--disable-gpu') options.add_argument("window-size=1024,768") options.add_argument("--no-sandbox") driver = webdriver.Chrome( executable_path="/root/cryptobot/chromedriver", options=options) driver.get("https://www.lookintobitcoin.com/charts/puell-multiple/") driver.execute_script("window.scrollTo(0, 300)") sleep(5) screenshot = driver.save_screenshot("puell.png") img = Image.open("puell.png") width, height = img.size img = img.crop((10, 0, width - 10, height - 220)) img = img.save("puell.png", format="png") driver.quit() # The Pi Cycle Top Indicator def get_pi(self): options = webdriver.ChromeOptions() options.headless = True options.add_argument('--headless') options.add_argument('--disable-gpu') options.add_argument("window-size=1024,768") options.add_argument("--no-sandbox") driver = webdriver.Chrome( executable_path="/root/cryptobot/chromedriver", options=options) driver.get( "https://www.lookintobitcoin.com/charts/pi-cycle-top-indicator/") driver.execute_script("window.scrollTo(0, 270)") sleep(5) screenshot = driver.save_screenshot("picycle.png") img = Image.open("picycle.png") width, height = img.size img = img.crop((10, 0, width - 10, height - 205)) img = img.save("picycle.png", format="png") driver.quit() def get_ds(self): options = webdriver.ChromeOptions() options.headless = True options.add_argument('--headless') options.add_argument('--disable-gpu') options.add_argument("window-size=1024,768") options.add_argument("--no-sandbox") driver = webdriver.Chrome( executable_path="/root/cryptobot/chromedriver", options=options) driver.get("https://www.defisocks.com/#/") last_height = driver.execute_script( "return document.body.scrollHeight") for i in range(0, 2): # Scroll down to bottom if i == 1: driver.execute_script("window.scrollTo(0, 3350);") # Wait to load page sleep(4) # Calculate new scroll height and compare with last scroll height new_height = driver.execute_script( "return document.body.scrollHeight") if new_height == last_height: break last_height = new_height screenshot = driver.save_screenshot("ds.png") img = Image.open("ds.png") width, height = img.size img = img.crop((320, 125, width - 340, height - 100)) img = img.save("ds.png", format="png") driver.quit() def get_defisocks(self): results = self.es.get_token_transactions( contract_address="0x9d942bd31169ed25a1ca78c776dab92de104e50e") return results # functions to check coins, names, and size # round numbers correctly, sig figs for <1, rounding for >1 def round_num(self, num): if num < 1: temp = num count = 1 while temp < 1: temp *= 10 count += 1 return round(num, count) else: return round(num, 2) def check_coin(self, coin_name): coin_label = "" coin_name = coin_name.lower() if coin_name == "uni": coin_name = "uniswap" elif coin_name == "rbc": coin_name = "rubic" elif coin_name == "comp" or coin_name == "compound": coin_name = "compound-governance-token" elif coin_name == "graph" or coin_name == "thegraph": coin_name = "the-graph" for coin in the_coin_list: if coin['id'] == coin_name or coin['symbol'] == coin_name: if coin['symbol'] == coin_name: coin_label = coin['id'] else: coin_label = coin_name return coin_label return coin_label #find a better way of doing this instead of recopying the function def change_cap(self, coin_name): coin_label = "" coin_name = coin_name.lower() for coin in the_coin_list: if coin['id'] == coin_name or coin['symbol'] == coin_name: if coin['symbol'] == coin_name: coin_label = coin_name.upper() else: coin_label = coin_name.lower() coin_label = coin_label.capitalize() return coin_label return coin_label def check_large(self, num): #there are better ways but atm, its not important num = float(num) # check to see if num exists or less than 999, if so no need to compress if num == None: return "None" if num < 999: print("in here") return num if num == 0: return "Not Found" #start compressing letter = "" if num >= 1000000: letter = " M" num /= 1000000 if (num >= 1000): letter = " B" num /= 1000 if (num >= 1000): letter = " T" num /= 1000 num = round(num, 2) if letter == "": num = "{:,}".format(num) return str(num) + letter def get_events(self): news = self.cg.get_events(country_code='US', type="Eventf", page=10, upcoming_events_only=False, from_date="2019-01-01", to_date="2020-10-02") return news['data'] def get_list_exchanges(self): ex = self.cg.get_exchanges_list() response = "```List of Exchanges: " + "\n" for i in range(len(ex)): response += ex[i]['id'] + ", " response += "```" return response def get_global_data(self): print(self.cg.get_coins_markets(vs_currency='USD')) def get_global_defi_data(self): coin_label = "" news = self.cg.get_global_decentralized_finance_defi() def_mc = news['defi_market_cap'] def_mc = float(def_mc) def_mc = round(def_mc, 2) def_mc = "{:,}".format(def_mc) response = "```Defi Market Cap: $" + str(def_mc) + "\n" der = news['defi_to_eth_ratio'] der = float(der) der = round(der, 2) response += "Defi To Eth Ratio: " + str(der) + "\n" defi_dom = news['defi_dominance'] defi_dom = float(defi_dom) defi_dom = round(defi_dom, 2) response += "Defi Dominance: " + str(defi_dom) + "%" + "\n" tdc = news['top_coin_name'] tdcmc = news['top_coin_defi_dominance'] tdcmc = float(tdcmc) tdcmc = round(tdcmc, 2) response += "Top Defi Coin: " + tdc + "\n" + "Top Defi Coin Dominance: " + str( tdcmc) + "%" + "\n```" return response def gas(self): wei = self.es.get_gas_price() gwei = wei / 1000000000 gwei = round(gwei, 2) avg_gas = 21000 price_data = self.cg.get_price(ids="ethereum", vs_currencies='usd') eth_price = price_data["ethereum"]['usd'] eth_price = round(eth_price, 3) usd_amount = (avg_gas * gwei / 1000000000) * eth_price usd_amount = round(usd_amount, 2) embedResponse = discord.Embed(title="Gas Price", color=0x0000ff) embedResponse.add_field(name="Gwei Price", value=str(gwei), inline=False) embedResponse.add_field(name="USD Price (avg trxn)", value="$" + str(usd_amount), inline=False) return embedResponse def future(self): response = "BAND is a shitcoin [I'm not changing this Shi]" return response def error(self): embedResponse = discord.Embed(color=0xF93A2F) embedResponse.add_field(name="Error", value="Not a valid command/coin", inline=False) return embedResponse def find_member(self, bot, gld, mem_id): found_mem = None for guild in bot.guilds: if guild.name == gld: break members = '\n - '.join([member.name for member in guild.members]) ids = [member.id for member in guild.members] for member in guild.members: if member.id == mem_id: return member def get_servers(self, bot): all = "" counter = 1 for guild in bot.guilds: mem_count = guild.member_count all += "Server " + str(counter) + ": " + str( guild.name) + " (Size: " + str(mem_count) + ")" + "\n" counter += 1 return all def help(self): help_info = "```CryptoBot gives you sends live updates of " + \ "any cryptocurrency!" + "\n" + "\n" + \ "Commands:" + "\n" + "\n" + \ " Price Command: ![coin symbol/name], '!btc' or '!bitcoin' - retreive price information about a coin" + "\n" + "\n" + \ " Chart Command: '!chart btc 5' <chart> <coin> <num days> - retreive the line chart of a coin, only support USD as of now (ex: !chart link 30)" + "\n" + "\n" + \ " Chart Command: '!chart btc 5' <chart> <coin1> <coin2> <num days> - retreive the line chart of two coins coupled (ex: !chart link btc 30)" + "\n" + "\n" + \ " Candle Command: '!candle btc 5' <chart> <coin_name/symbol> <num days>, "\ "days has to be one of these:" + "\n" + " '1','7','14','30','90','180','365','MAX' - retreive the candle chart of a coin" + "\n" + "\n" + \ " Suggestion Command: !suggestion or !suggestions do this' <suggestion> <message> - send a suggestion for the bot" + "\n" + "\n" + \ " Gas Command: '!gas' - get information about gwei prices" + "\n" + "\n" + \ " Convert Command: '!convert <num> <coin1> <coin2>' - get conversion rate of num of coin1 in number of coin2 (ex: !convert 1000 usdc btc)" + "\n" + "\n" + \ " Global Defi Stats Command: '!global-defi' - get global information about defi" + "\n" + "\n" + \ " Top Trending Coins Command: '!trendy - get the top trending coins on CoinGecko" + "\n" + "\n" + \ " Supply Command: '!supply <coin> - get the circulating and maximum supply of a coin" + "\n" + "\n" + \ " Golden Ratio Multiple Indicator (BTC) (Unavailable): '!grm-chart" + "\n" + "\n" + \ " Puell Multiple Indicator (BTC) (Unavailable): '!puell-chart" + "\n" + "\n" + \ " MVRV Z-Score Indicator (BTC) (Unavailable): '!mvrv-chart" + "\n" + "\n" + \ " PI Cycle Top Indicator (BTC) (Unavailable): '!pi-chart" + "\n" + "\n" + \ " ATH, ATL, Range Commands: '!ath [coin], !atl [coin], !range [coin]" + "\n" + "\n" + \ " Image Command: '!image [coin]" + "\n" + "\n" + \ " TVL Command: '!tvl [coin]" + "\n" + "\n" + \ " Mcap to TVL Ratio Command: '!tvl-ratio [coin]" + "\n" + "\n" + \ " Defisocks (Unavailable): '!defisocks" + "\n" + "\n" + \ " ATH, ATL, Range: '!ath [coin], !atl [coin], !range [coin]" + "\n" + "\n" + \ "Credits to CoinGecko® and Etherscan® for their free APIs!```" return help_info
class CoinData: """Gathers all relevant data from the CoinGecko API, and returns it to the app pages.""" def __init__(self) -> None: self.info = CoinGeckoAPI() def get_coin_by_ticker(self, coin_ticker): """A lookup that is used in case the user passes a coin's ticker into the form. Coins are only accessible via the API by their id, but users may pass in a ticker instead. This method handles that situation.""" names = { coin['symbol']: coin['id'] for coin in self.info.get_coins_list() } return names.get(coin_ticker.lower(), coin_ticker) def get_all_coin_data(self, logos): """This method returns the relevant data for all coins in the top 25 coins ranked by market cap.""" top_coins = [] for idx, item in enumerate( self.info.get_coins_markets('usd')[:TOP_COINS], start=1): coin = Coin(rank=idx, logo=logos[idx - 1], name=item['id'].title(), price=item['current_price'], market_cap=item['market_cap'], volume=item['total_volume'], change=item['price_change_24h'], percent_change=round( item['price_change_percentage_24h'], 2)) top_coins.append(coin) return top_coins def single_coin_data(self, coin): """This method gathers all the relevant data for a single coin that the user may search for.""" try: data = self.info.get_coin_by_id(coin.lower()) id = data['id'].title() symbol = data['symbol'].upper() link1 = data['links']['homepage'][0] link2 = data['links']['blockchain_site'][0] image = data['image']['small'] market_cap_rank = data['market_cap_rank'] price_data = self.info.get_coins_markets('usd')[market_cap_rank - 1] ath = '$' + str(data['market_data']['ath']['usd']) price = price_data['current_price'] mcap = price_data['market_cap'] volume = price_data['total_volume'] return SingleCoin(id=id, symbol=symbol, link1=link1, link2=link2, image=image, market_cap_rank=market_cap_rank, ath=ath, price=price, mcap=mcap, volume=volume) except TypeError: pass def single_coin_exchanges(self, coin): """Gathers all relevant exchange data for a single coin.""" exchange_info = [] Exchanges = namedtuple('Exchanges', 'name volume') data = self.info.get_coin_by_id(coin.lower())['tickers'] names = [ name['market']['name'] for name in data if name['target'] == 'USDT' ] volumes = [ round(vol['volume'], 2) for vol in data if vol['target'] == 'USDT' ] for i in range(TOP_EXCHANGES): exchange = Exchanges(name=names[i], volume=volumes[i]) exchange_info.append(exchange) return exchange_info def portfolio_coins(self, user): """Gets all of the data for a user's coins to display on the portfolio page.""" coin_list = [] user_coins = PortfolioHoldings.objects.filter(person=user) for coin in user_coins.iterator(): name = self.get_coin_by_ticker(coin.coin_ticker) image = self.single_coin_data(name).image coin = CoinSet(ticker=coin.coin_ticker, amount=coin.number_of_coins, usd=coin.amount_in_usd, image=image) coin_list.append(coin) return coin_list
def get_coin_potential_returns( main_coin: str, vs: Union[str, None] = None, top: Union[int, None] = None, price: Union[int, None] = None, ) -> pd.DataFrame: """Fetch data to calculate potential returns of a certain coin. [Source: CoinGecko] Parameters ---------- main_coin : str Coin loaded to check potential returns for (e.g., algorand) vs : str | None Coin to compare main_coin with (e.g., bitcoin) top : int | None Number of coins with highest market cap to compare main_coin with (e.g., 5) price Target price of main_coin to check potential returns (e.g., 5) Returns ------- pd.DataFrame Potential returns data Columns: Coin, Current Price, Target Coin, Potential Price, Potential Market Cap ($), Change (%) """ client = CoinGeckoAPI() COLUMNS = [ "Coin", "Current Price ($)", "Current Market Cap ($)", "Target Coin", "Potential Price ($)", "Potential Market Cap ($)", "Change (%)", ] if top and top > 0: # user wants to compare with top coins data = client.get_price( ids=f"{main_coin}", vs_currencies="usd", include_market_cap=True, include_24hr_vol=False, include_24hr_change=False, include_last_updated_at=False, ) top_coins_data = client.get_coins_markets(vs_currency="usd", per_page=top, order="market_cap_desc") main_coin_data = data[main_coin] diff_arr = [] for coin in top_coins_data: market_cap_difference_percentage = calc_change( coin["market_cap"], main_coin_data["usd_market_cap"]) future_price = main_coin_data["usd"] * ( 1 + market_cap_difference_percentage / 100) diff_arr.append([ main_coin, main_coin_data["usd"], main_coin_data["usd_market_cap"], coin["id"], future_price, coin["market_cap"], market_cap_difference_percentage, ]) return pd.DataFrame( data=diff_arr, columns=COLUMNS, ) if vs: # user passed a coin data = client.get_price( ids=f"{main_coin},{vs}", vs_currencies="usd", include_market_cap=True, include_24hr_vol=False, include_24hr_change=False, include_last_updated_at=False, ) main_coin_data = data[main_coin] vs_coin_data = data[vs] if main_coin_data and vs_coin_data: market_cap_difference_percentage = calc_change( vs_coin_data["usd_market_cap"], main_coin_data["usd_market_cap"]) future_price = main_coin_data["usd"] * ( 1 + market_cap_difference_percentage / 100) return pd.DataFrame( data=[[ main_coin, main_coin_data["usd"], main_coin_data["usd_market_cap"], vs, future_price, vs_coin_data["usd_market_cap"], market_cap_difference_percentage, ]], columns=COLUMNS, ) if price and price > 0: # user passed a price data = client.get_price( ids=main_coin, vs_currencies="usd", include_market_cap=True, include_24hr_vol=False, include_24hr_change=False, include_last_updated_at=False, ) main_coin_data = data[main_coin] if main_coin_data: final_market_cap = (main_coin_data["usd_market_cap"] * price / main_coin_data["usd"]) market_cap_difference_percentage = calc_change( final_market_cap, main_coin_data["usd_market_cap"]) future_price = main_coin_data["usd"] * ( 1 + market_cap_difference_percentage / 100) return pd.DataFrame( data=[[ main_coin, main_coin_data["usd"], main_coin_data["usd_market_cap"], "", future_price, final_market_cap, market_cap_difference_percentage, ]], columns=COLUMNS, ) return pd.DataFrame()
def __init__(self) -> None: self.info = CoinGeckoAPI()
from pycoingecko import CoinGeckoAPI import pandas as pd import matplotlib.pyplot as plt import plotly.graph_objects as go """ Request for a JSON expressed as a dictionary of nested lists with price, market cap and total volumes, which contain the unix timestamp and price at that time """ cg = CoinGeckoAPI() bitcoin_data = cg.get_coin_market_chart_by_id(id='bitcoin', vs_currency='usd', days=30) bitcoin_price_data = bitcoin_data['prices'] data = pd.DataFrame(bitcoin_price_data, columns=['TimeStamp', 'Price']) data['Date'] = pd.to_datetime(data['TimeStamp'], unit='ms') print(data) candlestick_data = data.groupby(data.Date.dt.date).agg( {'Price': ['min', 'max', 'first', 'last']}) print(candlestick_data) fig = go.Figure(data=[ go.Candlestick(x=candlestick_data.index, open=candlestick_data['Price']['first'], high=candlestick_data['Price']['max'], low=candlestick_data['Price']['min'], close=candlestick_data['Price']['last']) ]) fig.update_layout(xaxis_rangeslider_visible=False,
#!/usr/bin/python #the program provides the file table_coins_list.csv which contains the list of coins IDs in coingecko from pycoingecko import CoinGeckoAPI cg = CoinGeckoAPI() import sys import csv import time coins_list = cg.get_coins_list() with open('table_coins_list.csv', 'wt') as fh: csvobj = csv.DictWriter(fh, fieldnames=list(coins_list[0].keys())) csvobj.writeheader() csvobj.writerows(coins_list)
def get_prices(ids, vs_currencies="usd"): cg = CoinGeckoAPI() prices = cg.get_price(ids=ids, vs_currencies=vs_currencies) return prices
class CurrencyBot: URLS = { 'btc': 'https://exmo.me/ru/trade/BTC_RUB', 'ltc': 'https://exmo.me/ru/trade/LTC_RUB', 'bch': 'https://exmo.me/ru/trade/BCH_RUB', 'eth': 'https://exmo.me/ru/trade/ETH_RUB', } CURR_MSGS = { 'BitCoin': 'BitCoin (BTC)', 'LitCoin': 'LitCoin (LTC)', 'EXMOCoin': 'EXMO (₽)', 'Etherium': 'Etherium (ETH)', 'BitCoinCash': 'BitCoinCash (BCH)', } def __init__(self): import coinaddr self.cg = CoinGeckoAPI() self.btc_currency = 0 self.ltc_currency = 0 self.bch_currency = 0 self.eth_currency = 0 self.exmo_currency = 1 self.last_cur_update = None self.last_cur_update = self.update_all_currencies() self.coinaddr = coinaddr def adress_is_valid(self, address): print( address, 'ADDRESS CHECKOUT ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' ) try: address = bytes(address, 'ascii') if self.coinaddr.validate('btc', address): return True except Exception: try: if self.coinaddr.validate('ltc', address): return True except Exception: try: if self.coinaddr.validate('bch', address): return True except Exception: try: if self.coinaddr.validate('eth', address): return True except Exception: return False def update_all_currencies(self): if self.last_cur_update is None or time_is_come( str(self.last_cur_update)): self.btc_currency = self.cg.get_price('bitcoin', 'rub')['bitcoin']['rub'] self.ltc_currency = self.cg.get_price('litecoin', 'rub')['litecoin']['rub'] self.bch_currency = self.cg.get_price('bitcoin-cash', 'rub')['bitcoin-cash']['rub'] self.eth_currency = self.cg.get_price('ethereum', 'rub')['ethereum']['rub'] return datetime.now() def get_btc(self): return self.btc_currency def get_ltc(self): return self.ltc_currency def get_bch(self): return self.bch_currency def get_eth(self): return self.eth_currency def get_curr_by_key(self, key): price = 'NaN' if key == 'Bitcoin': price = self.btc_currency if key == 'LiteCoin': price = self.ltc_currency if key == 'Bitcoin Cash': price = self.bch_currency if key == 'Ethereum': price = self.eth_currency if key == 'ExmoRUB': price = self.exmo_currency return price def print(self): print(self.btc_currency) print(self.ltc_currency) print(self.bch_currency) print(self.eth_currency)
import threading from time import sleep import webbrowser import random import os import uuid import pyperclip try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse from pycoingecko import CoinGeckoAPI from win32com.shell import shell, shellcon version='20' cg = CoinGeckoAPI() s = requests.session() f_stop = threading.Event() try: api_key = json.load(open('auth.json','r'))['key'] except: api_key = '' try: api_secret = json.load(open('auth.json','r'))['secret'] except: api_secret = '' def f(f_stop): check_stops() if not f_stop.is_set():
from pycoingecko import CoinGeckoAPI cg = CoinGeckoAPI() # btc_price = cg.get_price(ids='bitcoin', vs_currencies='usd') # {'bitcoin': {'usd': 9186.89}} # btc_price # multi_price = cg.get_price(ids='bitcoin,litecoin,ethereum', vs_currencies='usd') # multi_price # usd_price = cg.get_price(ids='bitcoin', vs_currencies='usd', include_market_cap='true', include_24hr_vol='true', include_24hr_change='true', include_last_updated_at='true') # usd_price # coin_list = cg.get_coins_list() # coin_list # for item in coin_markets: # print("Symbol: {} Name: {} Id: {}\n".format(item['symbol'],item['name'],item['id'])) # For Coin markets: # { # "id": "bitcoin", # "symbol": "btc", # "name": "Bitcoin", # "image": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579", # "current_price": 9186.79, # "market_cap": 169480345274, # "market_cap_rank": 1, # "total_volume": 16054018229, # "high_24h": 9218.76, # "low_24h": 9106.67, # "price_change_24h": 28.71,