def call_cbbook(self, other_args): """Process cbbook command""" coin = self.coin_map_df["Coinbase"] parser = argparse.ArgumentParser( prog="cbbook", add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Get the order book for selected coin", ) _, quotes = coinbase_model.show_available_pairs_for_given_symbol(coin) if len(quotes) < 0: console.print( f"Couldn't find any quoted coins for provided symbol {coin}") parser.add_argument( "--vs", help="Quote currency (what to view coin vs)", dest="vs", type=str, default="USDT" if "USDT" in quotes else quotes[0], choices=quotes, ) ns_parser = parse_known_args_and_warn( parser, other_args, EXPORT_BOTH_RAW_DATA_AND_FIGURES) if ns_parser: pair = f"{coin}-{ns_parser.vs.upper()}" coinbase_view.display_order_book( product_id=pair, export=ns_parser.export, )
def call_stats(self, other_args): """Process stats command""" coin = self.coin_map_df["Binance"] _, quotes = coinbase_model.show_available_pairs_for_given_symbol(coin) parser = argparse.ArgumentParser( prog="stats", add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Display coin stats", ) parser.add_argument( "--vs", help="Quote currency (what to view coin vs)", dest="vs", type=str, default="USDT" if "USDT" in quotes else quotes[0], choices=quotes, ) ns_parser = parse_known_args_and_warn(parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED) if ns_parser: pair = f"{coin}-{ns_parser.vs.upper()}" coinbase_view.display_stats(pair, ns_parser.export)
def load( coin: str, source: str, ) -> Tuple[Union[Optional[str], pycoingecko_model.Coin], Any]: """Load cryptocurrency from given source. Available sources are: CoinGecko, CoinPaprika, Coinbase and Binance. Loading coin from Binance and CoinPaprika means validation if given coins exists in chosen source, if yes then id of the coin is returned as a string. In case of CoinGecko load will return Coin object, if provided coin exists. Coin object has access to different coin information. Parameters ---------- coin: str Coin symbol or id which is checked if exists in chosen data source. source : str Source of the loaded data. CoinGecko, CoinPaprika, or Binance Returns ------- Tuple[Union[str, pycoingecko_model.Coin], Any] - str or Coin object for provided coin - str with source of the loaded data. CoinGecko, CoinPaprika, or Binance """ current_coin = "" # type: Optional[Any] if source == "cg": current_coin = pycoingecko_model.Coin(coin) return current_coin, source if source == "bin": parsed_coin = coin.upper() current_coin, pairs = show_available_pairs_for_given_symbol( parsed_coin) if len(pairs) > 0: print(f"Coin found : {current_coin}\n") else: print(f"Couldn't find coin with symbol {current_coin}\n") return current_coin, source if source == "cp": paprika_coins = get_list_of_coins() paprika_coins_dict = dict(zip(paprika_coins.id, paprika_coins.symbol)) current_coin, _ = coinpaprika_model.validate_coin( coin, paprika_coins_dict) return current_coin, source if source == "cb": coinbase_coin = coin.upper() current_coin, pairs = coinbase_model.show_available_pairs_for_given_symbol( coinbase_coin) if len(pairs) > 0: print(f"Coin found : {current_coin}\n") else: print(f"Couldn't find coin with symbol {current_coin}\n") return current_coin, source return current_coin, None
def call_trades(self, other_args): """Process trades command""" parser = argparse.ArgumentParser( prog="trades", add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Show last trades on Coinbase", ) coin = self.coin_map_df["Coinbase"] _, quotes = coinbase_model.show_available_pairs_for_given_symbol(coin) if len(quotes) < 0: console.print( f"Couldn't find any quoted coins for provided symbol {self.current_coin}" ) parser.add_argument( "--vs", help="Quote currency (what to view coin vs)", dest="vs", type=str, default="USDT" if "USDT" in quotes else quotes[0], choices=quotes, ) parser.add_argument( "--side", help="Side of trade: buy, sell, all", dest="side", type=str, default="all", choices=["all", "buy", "sell"], ) parser.add_argument( "-t", "--top", default=15, dest="top", help="Limit of records", type=check_positive, ) ns_parser = parse_known_args_and_warn(parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED) if ns_parser: pair = f"{coin}-{ns_parser.vs.upper()}" if ns_parser.side.upper() == "all": side = None else: side = ns_parser.side coinbase_view.display_trades(product_id=pair, limit=ns_parser.top, side=side, export=ns_parser.export)
def call_stats(self, other_args): """Process stats command""" _, quotes = coinbase_model.show_available_pairs_for_given_symbol( self.current_coin) parser = argparse.ArgumentParser( prog="stats", add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Display coin stats", ) parser.add_argument( "--vs", help="Quote currency (what to view coin vs)", dest="vs", type=str, default="USDT" if "USDT" in quotes else quotes[0], choices=quotes, ) parser.add_argument( "--export", choices=["csv", "json", "xlsx"], default="", type=str, dest="export", help="Export dataframe data to csv,json,xlsx file", ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return pair = f"{self.current_coin.upper()}-{ns_parser.vs.upper()}" coinbase_view.display_stats(pair, ns_parser.export) except Exception as e: print(e, "\n")
def load( coin: str, source: str = "cp", days: int = 60, vs: str = "usd", interval: str = "1day", should_load_ta_data: bool = False, ): """Load cryptocurrency from given source. Available sources are: CoinGecko, CoinPaprika, Coinbase, Binance and Yahoo Finance Loading coin from Binance and CoinPaprika means validation if given coins exists in chosen source, if yes then id of the coin is returned as a string. In case of CoinGecko load will return Coin object, if provided coin exists. Coin object has access to different coin information. Parameters ---------- coin: str Coin symbol or id which is checked if exists in chosen data source. source : str Source of the loaded data. CoinGecko, CoinPaprika, Yahoo Finance or Binance Returns ------- Tuple[Union[str, pycoingecko_model.Coin], str, str] - str or Coin object for provided coin - str with source of the loaded data. CoinGecko, CoinPaprika, Yahoo Finance or Binance - str with symbol - Dataframe with coin map to different sources """ if source in ("cg", "cp"): if vs not in ("USD", "BTC", "usd", "btc"): console.print( "You can only compare with usd or btc (e.g., --vs usd)\n") return None, None, None, None, None, None if interval != "1day": console.print( "Only daily data is supported for coingecko and coinpaprika (e.g., -i 1day)\n" ) return None, None, None, None, None, None current_coin = "" # type: Optional[Any] coins_map_df = prepare_all_coins_df().set_index("Symbol").dropna(thresh=2) if source == "cg": coingecko = pycoingecko_model.Coin(coin.lower(), True) if not coingecko.symbol: return None, None, None, None, None, None coin_map_df = coins_map_df.loc[coingecko.symbol] coin_map_df = ( coin_map_df.iloc[0] if isinstance(coin_map_df, pd.DataFrame) else coin_map_df ) # TODO: improve to choose the row that matches better; # if it is dataframe, it means that found more than 1 coin if should_load_ta_data: df_prices, currency = load_ta_data( coin_map_df=coin_map_df, source=source, currency=vs, days=days, limit=0, interval=interval, ) return ( str(coingecko), source, coingecko.symbol, coin_map_df, df_prices, currency, ) return ( str(coingecko), source, coingecko.symbol, coin_map_df, None, None, ) if source == "cp": paprika_coins = get_list_of_coins() paprika_coins_dict = dict(zip(paprika_coins.id, paprika_coins.symbol)) current_coin, symbol = coinpaprika_model.validate_coin( coin, paprika_coins_dict) if not symbol: return None, None, None, None, None, None coin_map_df = coins_map_df.loc[symbol.lower( ) if symbol is not None else symbol] coin_map_df = (coin_map_df.iloc[0] if isinstance( coin_map_df, pd.DataFrame) else coin_map_df) if should_load_ta_data: df_prices, currency = load_ta_data( coin_map_df=coin_map_df, source=source, currency=vs, days=days, limit=0, interval=interval, ) return (current_coin, source, symbol, coin_map_df, df_prices, currency) return (current_coin, source, symbol, coin_map_df, None, None) if source == "bin": if vs == "usd": vs = "USDT" if interval not in SOURCES_INTERVALS["bin"]: console.print( "Interval not available on binance. Run command again with one supported (e.g., -i 1day):\n", SOURCES_INTERVALS["bin"], ) return None, None, None, None, None, None # TODO: convert bitcoin to btc before searching pairs parsed_coin = coin.upper() current_coin, pairs = show_available_pairs_for_given_symbol( parsed_coin) if len(pairs) > 0: if vs not in pairs: console.print( "vs specified not supported by binance. Run command again with one supported (e.g., --vs USDT):\n", pairs, ) return None, None, None, None, None, None coin_map_df = coins_map_df.loc[parsed_coin.lower()] coin_map_df = (coin_map_df.iloc[0] if isinstance( coin_map_df, pd.DataFrame) else coin_map_df) # console.print(f"Coin found : {current_coin}\n") if should_load_ta_data: df_prices, currency = load_ta_data( coin_map_df=coin_map_df, source=source, currency=vs, days=0, limit=days, interval=interval, ) return ( current_coin, source, parsed_coin, coin_map_df, df_prices, currency, ) return (current_coin, source, parsed_coin, coin_map_df, None, None) return None, None, None, None, None, None if source == "cb": if vs == "usd": vs = "USDT" if interval not in SOURCES_INTERVALS["cb"]: console.print( "Interval not available on coinbase. Run command again with one supported (e.g., -i 1day):\n", SOURCES_INTERVALS["cb"], ) return None, None, None, None, None, None # TODO: convert bitcoin to btc before searching pairs coinbase_coin = coin.upper() current_coin, pairs = coinbase_model.show_available_pairs_for_given_symbol( coinbase_coin) if vs not in pairs: console.print( "vs specified not supported by coinbase. Run command again with one supported (e.g., --vs USDT):\n", pairs, ) return None, None, None, None, None, None if len(pairs) > 0: # console.print(f"Coin found : {current_coin}\n") coin_map_df = coins_map_df.loc[coin] coin_map_df = (coin_map_df.iloc[0] if isinstance( coin_map_df, pd.DataFrame) else coin_map_df) if should_load_ta_data: df_prices, currency = load_ta_data( coin_map_df=coin_map_df, source=source, currency=vs, days=0, limit=days, interval=interval, ) return (current_coin, source, coin, coin_map_df, df_prices, currency) return (current_coin, source, coin, coin_map_df, None, None) console.print(f"Couldn't find coin with symbol {current_coin}\n") return None, None, None, None, None, None if source == "yf": if vs.upper() not in YF_CURRENCY: console.print( "vs specified not supported by Yahoo Finance. Run command again with one supported (e.g., --vs USD):\n", YF_CURRENCY, ) return None, None, None, None, None, None if interval not in SOURCES_INTERVALS["yf"]: console.print( "Interval not available on YahooFinance. Run command again with one supported (e.g., -i 1day):\n", SOURCES_INTERVALS["yf"], ) return None, None, None, None, None, None # Search coin using crypto symbol coin_map_df_1 = coins_map_df.loc[coins_map_df.index == coin] # Search coin using yfinance id coin_map_df_2 = coins_map_df.loc[coins_map_df.YahooFinance == f"{coin.upper()}-{vs.upper()}"] # Search coin using crypto full name coin_map_df_3 = coins_map_df.loc[coins_map_df.CoinGecko == coin] for _df in [coin_map_df_1, coin_map_df_2, coin_map_df_3]: if not _df.empty: coin_map_df = _df break if coin_map_df.empty: console.print( f"Cannot find {coin} against {vs} on Yahoo finance. Try another source or currency.\n" ) return None, None, None, None, None, None if (coin_map_df["YahooFinance"]).isna().all(): console.print( f"Cannot find {coin} Yahoo finance. Try another source.\n") return None, None, None, None, None, None # Filter for the currency coin_map_df = coin_map_df[ coin_map_df["YahooFinance"].str.upper().str.contains(vs.upper())] coin_map_df = (coin_map_df.iloc[0] if isinstance( coin_map_df, pd.DataFrame) else coin_map_df) if should_load_ta_data: df_prices, currency = load_ta_data( coin_map_df=coin_map_df, source=source, currency=vs, days=days, limit=0, interval=interval, ) return ( coin_map_df["YahooFinance"], source, coin, coin_map_df, df_prices, currency, ) return ( coin_map_df["YahooFinance"], source, coin, coin_map_df, None, None, ) return None, None, None, None, None, None
def call_chart(self, other_args): """Process chart command""" if self.current_coin: parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="chart", description= """Display chart for loaded coin. You can specify currency vs which you want to show chart and also number of days to get data for.""", ) if self.source == "cp": parser.add_argument( "--vs", default="usd", dest="vs", help="Currency to display vs coin", choices=["usd", "btc", "BTC", "USD"], type=str, ) parser.add_argument( "-d", "--days", default=30, dest="days", help="Number of days to get data for", type=check_positive, ) if self.source == "cg": parser.add_argument("--vs", default="usd", dest="vs", help="Currency to display vs coin") parser.add_argument( "-d", "--days", default=30, dest="days", help="Number of days to get data for", ) if self.source == "bin": client = Client(cfg.API_BINANCE_KEY, cfg.API_BINANCE_SECRET) interval_map = { "1day": client.KLINE_INTERVAL_1DAY, "3day": client.KLINE_INTERVAL_3DAY, "1hour": client.KLINE_INTERVAL_1HOUR, "2hour": client.KLINE_INTERVAL_2HOUR, "4hour": client.KLINE_INTERVAL_4HOUR, "6hour": client.KLINE_INTERVAL_6HOUR, "8hour": client.KLINE_INTERVAL_8HOUR, "12hour": client.KLINE_INTERVAL_12HOUR, "1week": client.KLINE_INTERVAL_1WEEK, "1min": client.KLINE_INTERVAL_1MINUTE, "3min": client.KLINE_INTERVAL_3MINUTE, "5min": client.KLINE_INTERVAL_5MINUTE, "15min": client.KLINE_INTERVAL_15MINUTE, "30min": client.KLINE_INTERVAL_30MINUTE, "1month": client.KLINE_INTERVAL_1MONTH, } _, quotes = binance_model.show_available_pairs_for_given_symbol( self.current_coin) parser.add_argument( "--vs", help="Quote currency (what to view coin vs)", dest="vs", type=str, default="USDT", choices=quotes, ) parser.add_argument( "-i", "--interval", help="Interval to get data", choices=list(interval_map.keys()), dest="interval", default="1day", type=str, ) parser.add_argument( "-l", "--limit", dest="limit", default=100, help="Number to get", type=check_positive, ) if self.source == "cb": interval_map = { "1min": 60, "5min": 300, "15min": 900, "1hour": 3600, "6hour": 21600, "24hour": 86400, "1day": 86400, } _, quotes = coinbase_model.show_available_pairs_for_given_symbol( self.current_coin) if len(quotes) < 0: console.print( f"Couldn't find any quoted coins for provided symbol {self.current_coin}" ) return parser.add_argument( "--vs", help="Quote currency (what to view coin vs)", dest="vs", type=str, default="USDT" if "USDT" in quotes else quotes[0], choices=quotes, ) parser.add_argument( "-i", "--interval", help="Interval to get data", choices=list(interval_map.keys()), dest="interval", default="1day", type=str, ) parser.add_argument( "-l", "--limit", dest="limit", default=100, help="Number to get", type=check_positive, ) ns_parser = parse_known_args_and_warn( parser, other_args, EXPORT_BOTH_RAW_DATA_AND_FIGURES) if ns_parser: if self.source in ["bin", "cb"]: limit = ns_parser.limit interval = ns_parser.interval days = 0 else: limit = 0 interval = "1day" days = ns_parser.days plot_chart( coin_map_df=self.coin_map_df, limit=limit, interval=interval, days=days, currency=ns_parser.vs, source=self.source, )
def call_ta(self, other_args): """Process ta command""" # TODO: Play with this to get correct usage if self.current_coin: parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="ta", description= """Loads data for technical analysis. You can specify currency vs which you want to show chart and also number of days to get data for. By default currency: usd and days: 30. E.g. if you loaded in previous step Ethereum and you want to see it's price vs btc in last 90 days range use `ta --vs btc --days 90`""", ) if self.source == "cp": parser.add_argument( "--vs", default="usd", dest="vs", help="Currency to display vs coin", choices=["usd", "btc", "BTC", "USD"], type=str, ) parser.add_argument( "-d", "--days", default=30, dest="days", help="Number of days to get data for", type=check_positive, ) if self.source == "cg": parser.add_argument("--vs", default="usd", dest="vs", help="Currency to display vs coin") parser.add_argument( "-d", "--days", default=30, dest="days", help="Number of days to get data for", ) if self.source == "bin": client = Client(cfg.API_BINANCE_KEY, cfg.API_BINANCE_SECRET) interval_map = { "1day": client.KLINE_INTERVAL_1DAY, "3day": client.KLINE_INTERVAL_3DAY, "1hour": client.KLINE_INTERVAL_1HOUR, "2hour": client.KLINE_INTERVAL_2HOUR, "4hour": client.KLINE_INTERVAL_4HOUR, "6hour": client.KLINE_INTERVAL_6HOUR, "8hour": client.KLINE_INTERVAL_8HOUR, "12hour": client.KLINE_INTERVAL_12HOUR, "1week": client.KLINE_INTERVAL_1WEEK, "1min": client.KLINE_INTERVAL_1MINUTE, "3min": client.KLINE_INTERVAL_3MINUTE, "5min": client.KLINE_INTERVAL_5MINUTE, "15min": client.KLINE_INTERVAL_15MINUTE, "30min": client.KLINE_INTERVAL_30MINUTE, "1month": client.KLINE_INTERVAL_1MONTH, } _, quotes = binance_model.show_available_pairs_for_given_symbol( self.current_coin) parser.add_argument( "--vs", help="Quote currency (what to view coin vs)", dest="vs", type=str, default="USDT", choices=quotes, ) parser.add_argument( "-i", "--interval", help="Interval to get data", choices=list(interval_map.keys()), dest="interval", default="1day", type=str, ) parser.add_argument( "-l", "--limit", dest="limit", default=100, help="Number to get", type=check_positive, ) if self.source == "cb": interval_map = { "1min": 60, "5min": 300, "15min": 900, "1hour": 3600, "6hour": 21600, "24hour": 86400, "1day": 86400, } _, quotes = coinbase_model.show_available_pairs_for_given_symbol( self.current_coin) if len(quotes) < 0: print( f"Couldn't find any quoted coins for provided symbol {self.current_coin}" ) return parser.add_argument( "--vs", help="Quote currency (what to view coin vs)", dest="vs", type=str, default="USDT" if "USDT" in quotes else quotes[0], choices=quotes, ) parser.add_argument( "-i", "--interval", help="Interval to get data", choices=list(interval_map.keys()), dest="interval", default="1day", type=str, ) parser.add_argument( "-l", "--limit", dest="limit", default=100, help="Number to get", type=check_positive, ) if self.source == "cb": interval_map = { "1min": 60, "5min": 300, "15min": 900, "1hour": 3600, "6hour": 21600, "24hour": 86400, "1day": 86400, } _, quotes = coinbase_model.show_available_pairs_for_given_symbol( self.current_coin) if len(quotes) < 0: print( f"Couldn't find any quoted coins for provided symbol {self.current_coin}" ) return parser.add_argument( "--vs", help="Quote currency (what to view coin vs)", dest="vs", type=str, default="USDT" if "USDT" in quotes else quotes[0], choices=quotes, ) parser.add_argument( "-i", "--interval", help="Interval to get data", choices=list(interval_map.keys()), dest="interval", default="1day", type=str, ) parser.add_argument( "-l", "--limit", dest="limit", default=100, help="Number to get", type=check_positive, ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return if self.source in ["bin", "cb"]: limit = ns_parser.limit interval = ns_parser.interval days = 0 else: limit = 0 interval = "1day" days = ns_parser.days self.current_df, self.current_currency = load_ta_data( coin=self.current_coin, source=self.source, currency=ns_parser.vs, days=days, limit=limit, interval=interval, ) except Exception as e: print(e, "\n") if self.current_currency != "" and not self.current_df.empty: try: quit = ta_controller.menu( stock=self.current_df, ticker=self.current_coin, start=self.current_df.index[0], interval="", ) print("") if quit is not None: if quit is True: return quit self.print_help() except (ValueError, KeyError) as e: print(e) else: return else: print( "No coin selected. Use 'load' to load the coin you want to look at.\n" )
def call_trades(self, other_args): """Process trades command""" parser = argparse.ArgumentParser( prog="trades", add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Show last trades on Coinbase", ) _, quotes = coinbase_model.show_available_pairs_for_given_symbol( self.current_coin) if len(quotes) < 0: print( f"Couldn't find any quoted coins for provided symbol {self.current_coin}" ) return parser.add_argument( "--vs", help="Quote currency (what to view coin vs)", dest="vs", type=str, default="USDT" if "USDT" in quotes else quotes[0], choices=quotes, ) parser.add_argument( "--side", help="Side of trade: buy, sell, all", dest="side", type=str, default="all", choices=["all", "buy", "sell"], ) parser.add_argument( "-t", "--top", default=15, dest="top", help="Limit of records", type=check_positive, ) parser.add_argument( "--export", choices=["csv", "json", "xlsx"], default="", type=str, dest="export", help="Export dataframe data to csv,json,xlsx file", ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return pair = f"{self.current_coin.upper()}-{ns_parser.vs.upper()}" if ns_parser.side.upper() == "all": side = None else: side = ns_parser.side coinbase_view.display_trades(product_id=pair, limit=ns_parser.top, side=side, export=ns_parser.export) except Exception as e: print(e, "\n")
def call_book(self, other_args): """Process book command""" if self.current_coin: parser = argparse.ArgumentParser( prog="book", add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Get the order book for selected coin", ) if self.source == "bin": limit_list = [5, 10, 20, 50, 100, 500, 1000, 5000] _, quotes = binance_model.show_available_pairs_for_given_symbol( self.current_coin) parser.add_argument( "-l", "--limit", dest="limit", help="Limit parameter. Adjusts the weight", default=100, type=int, choices=limit_list, ) parser.add_argument( "--vs", help="Quote currency (what to view coin vs)", dest="vs", type=str, default="USDT", choices=quotes, ) if self.source == "cb": _, quotes = coinbase_model.show_available_pairs_for_given_symbol( self.current_coin) if len(quotes) < 0: print( f"Couldn't find any quoted coins for provided symbol {self.current_coin}" ) return parser.add_argument( "--vs", help="Quote currency (what to view coin vs)", dest="vs", type=str, default="USDT" if "USDT" in quotes else quotes[0], choices=quotes, ) parser.add_argument( "--export", choices=["csv", "json", "xlsx"], default="", type=str, dest="export", help="Export dataframe data to csv,json,xlsx file", ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return if self.source == "bin": binance_view.display_order_book( coin=self.current_coin, limit=ns_parser.limit, currency=ns_parser.vs, export=ns_parser.export, ) elif self.source == "cb": pair = f"{self.current_coin.upper()}-{ns_parser.vs.upper()}" coinbase_view.display_order_book( product_id=pair, export=ns_parser.export, ) except Exception as e: print(e, "\n")