From 5f9ef3ddeee7e27f68e0ff5f20f171a181e3d069 Mon Sep 17 00:00:00 2001 From: Jamie Date: Fri, 30 Apr 2021 22:49:30 -0400 Subject: [PATCH] add order book command --- README.md | 6 +- .../cryptocurrency/binance_model.py | 85 ++++++++++++++++--- .../cryptocurrency/binance_view.py | 43 ++++++++++ .../cryptocurrency/crypto_controller.py | 27 +++++- .../cryptocurrency/pycoingecko_view.py | 23 +++-- 5 files changed, 163 insertions(+), 21 deletions(-) create mode 100644 gamestonk_terminal/cryptocurrency/binance_view.py diff --git a/README.md b/README.md index 2809b6a6025..ac56f9069c9 100644 --- a/README.md +++ b/README.md @@ -225,10 +225,14 @@ These are the ones where a key is necessary: * Tradier: https://developer.tradier.com/getting_started * Oanda API: https://developer.oanda.com * CoinMarketCap API: https://coinmarketcap.com/api/ + * Binance: https://binance.us When these are obtained, don't forget to update [config_terminal.py](/gamestonk_terminal/config_terminal.py). -Alternatively, you can also set them to the following environment variables: GT_API_KEY_ALPHAVANTAGE, GT_API_KEY_FINANCIALMODELINGPREP, GT_API_KEY_QUANDL, GT_API_REDDIT_CLIENT_ID, GT_API_REDDIT_CLIENT_SECRET, GT_API_REDDIT_USERNAME, GT_API_REDDIT_USER_AGENT, GT_API_REDDIT_PASSWORD, GT_API_TWITTER_KEY, GT_API_TWITTER_SECRET_KEY, GT_API_TWITTER_BEARER_TOKEN, GT_API_POLYGON_KEY, GT_FRED_API_KEY, GT_API_NEWS_TOKEN, GT_OANDA_TOKEN, GT_OANDA_ACCOUNT, GT_TRADIER_TOKEN, GT_CMC_API_KEY. +Alternatively, you can also set them to the following environment variables: GT_API_KEY_ALPHAVANTAGE, GT_API_KEY_FINANCIALMODELINGPREP, +GT_API_KEY_QUANDL, GT_API_REDDIT_CLIENT_ID, GT_API_REDDIT_CLIENT_SECRET, GT_API_REDDIT_USERNAME, GT_API_REDDIT_USER_AGENT, GT_API_REDDIT_PASSWORD, +GT_API_TWITTER_KEY, GT_API_TWITTER_SECRET_KEY, GT_API_TWITTER_BEARER_TOKEN, GT_API_POLYGON_KEY, GT_FRED_API_KEY, +GT_API_NEWS_TOKEN, GT_OANDA_TOKEN, GT_OANDA_ACCOUNT, GT_TRADIER_TOKEN, GT_CMC_API_KEY, GT_BINANCE_API_KEY, GT_BINANCE_SECRET_KEY. Example: ``` diff --git a/gamestonk_terminal/cryptocurrency/binance_model.py b/gamestonk_terminal/cryptocurrency/binance_model.py index 44b8ecd5f4e..148d8c6a59d 100644 --- a/gamestonk_terminal/cryptocurrency/binance_model.py +++ b/gamestonk_terminal/cryptocurrency/binance_model.py @@ -3,21 +3,84 @@ __docformat__ = "numpy" import argparse from typing import List +import matplotlib.pyplot as plt +import numpy as np from binance.client import Client +from gamestonk_terminal.main_helper import parse_known_args_and_warn +from gamestonk_terminal.config_terminal import BINANCE_API_KEY, BINANCE_SECRET_KEY +from gamestonk_terminal.cryptocurrency.binance_view import plot_order_book -def order_book(coin:str, other_args:List[str]): - """Get order book for currency""" - pass -def recent_trades(coin:str, other_args:List[str]): - """Get recent trades for currency""" - pass +def order_book(coin: str, other_args: List[str]): + """ + Get order book for currency + Parameters + ---------- + coin: str + Coin to get order book for + other_args: List[str] + Argparse arguments + + Returns + ------- + + """ + client = Client(BINANCE_API_KEY, BINANCE_SECRET_KEY) + order_book = client.get_order_book(symbol=coin) + bids = np.asarray(order_book["bids"], dtype=float) + asks = np.asarray(order_book["asks"], dtype=float) + bids = np.insert(bids, 2, bids[:, 1].cumsum(), axis=1) + asks = np.insert(asks, 2, np.flipud(asks[:, 1]).cumsum(), axis=1) + plot_order_book(bids, asks, coin) + + +def recent_trades(coin: str, other_args: List[str]): + """ + Get recent trades for currency + Parameters + ---------- + coin: str + Coin to get recent trades for + other_args: List[str] + Argparse arguments + + Returns + ------- + + """ -def candles(coin:str, other_args:List[str]): - """Get order book for currency""" pass -def balance(coin:str, other_args:List[str]): - """Get order book for currency""" - pass \ No newline at end of file +def candles(coin: str, other_args: List[str]): + """ + Get klines/candles for coin + Parameters + ---------- + coin: str + Coin to get symbol of + other_args: List[str] + Argparse arguments + + Returns + ------- + + """ + pass + + +def balance(coin: str, other_args: List[str]): + """ + Get accont holdings for asset + Parameters + ---------- + coin: str + Coin to get holdings of + other_args : List[str] + Argparse arguments + + Returns + ------- + + """ + pass diff --git a/gamestonk_terminal/cryptocurrency/binance_view.py b/gamestonk_terminal/cryptocurrency/binance_view.py new file mode 100644 index 00000000000..da8ccd3a4c2 --- /dev/null +++ b/gamestonk_terminal/cryptocurrency/binance_view.py @@ -0,0 +1,43 @@ +"""Binance view functions""" +__docformat__ = "numpy" + +import numpy as np +import matplotlib.pyplot as plt +from gamestonk_terminal.main_helper import plot_autoscale +from gamestonk_terminal.config_plot import PLOT_DPI +from gamestonk_terminal.feature_flags import USE_ION as ion + + +def plot_order_book(bids: np.array, asks: np.array, coin: str): + """ + Plots Bid/Ask + Parameters + ---------- + bids : np.array + array of bids with columns: price, size, cumulative size + asks : np.array + array of asks with columns: price, size, cumulative size + coin : str + Coin being plotted + + Returns + ------- + + """ + + _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) + ax.plot(bids[:, 0], bids[:, 2], "g", label="bids") + ax.fill_between(bids[:, 0], bids[:, 2], color="g", alpha=0.4) + ax.plot(asks[:, 0], asks[:, 2], "r", label="asks") + ax.fill_between(asks[:, 0], asks[:, 2], color="r", alpha=0.4) + plt.grid(b=True, which="major", color="#666666", linestyle="-") + plt.minorticks_on() + plt.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2) + plt.legend(loc=0) + plt.xlabel("Price") + plt.ylabel("Size (Coins) ") + plt.title(f"Order Book for {coin}") + # if ion: + # plt.ion() + plt.show() + print("") diff --git a/gamestonk_terminal/cryptocurrency/crypto_controller.py b/gamestonk_terminal/cryptocurrency/crypto_controller.py index afeabb8cae8..e95633d8fdb 100644 --- a/gamestonk_terminal/cryptocurrency/crypto_controller.py +++ b/gamestonk_terminal/cryptocurrency/crypto_controller.py @@ -29,6 +29,7 @@ class CryptoController: "trades", "candle", "balance", + "add", ] def __init__(self): @@ -57,6 +58,7 @@ class CryptoController: print(" top view top coins from coinmarketcap") print("") print("Binance:") + print(" add add coin as current") print(" book get order book") print(" trades get recent trades") print(" candle get klines/candles and plot") @@ -92,9 +94,11 @@ class CryptoController: return True def call_load(self, other_args): + """Load command - get df from gecko""" self.current_coin, self.current_df = pycoingecko_view.load(other_args) def call_view(self, other_args): + """View command - plot loaded coin""" if self.current_coin: pycoingecko_view.view(self.current_coin, self.current_df, other_args) @@ -103,13 +107,32 @@ class CryptoController: print("") def call_trend(self, _): + """Trend command - show top 7 gecko coins""" pycoingecko_view.trend() def call_top(self, other_args): + """Top command - get top n coins from coinmarketcap""" cmc_view.get_cmc_top_n(other_args) - def call_book(self,other_args): - binance_model.order_book(other_args) + def call_book(self, other_args): + """Book command - get order book from binance""" + binance_model.order_book(self.current_coin, other_args) + + def call_trades(self, other_args): + """Trades command - get recent trades from binance""" + binance_model.recent_trades(self.current_coin, other_args) + + def call_candle(self, other_args): + """Candle command - show candle chart from binance""" + binance_model.candles(self.current_coin, other_args) + + def call_balance(self, other_args): + """Balance command - check current holdings of coin in binance""" + binance_model.balance(self.current_coin, other_args) + + def call_add(self, _): + self.current_coin = input("Coin?").upper() + def menu(): crypto_controller = CryptoController() diff --git a/gamestonk_terminal/cryptocurrency/pycoingecko_view.py b/gamestonk_terminal/cryptocurrency/pycoingecko_view.py index 03f335467d5..bb042a60432 100644 --- a/gamestonk_terminal/cryptocurrency/pycoingecko_view.py +++ b/gamestonk_terminal/cryptocurrency/pycoingecko_view.py @@ -137,22 +137,31 @@ def view(coin: str, prices: pd.DataFrame, other_args: List[str]): print(e) print("") + def trend(): """Prints top 7 coins from pycoingecko""" cg = CoinGeckoAPI() trending = cg.get_search_trending()["coins"] name, symbol, price, rank = [], [], [], [] for coin in trending: - name.append( coin["item"]["name"] ) - symbol.append( coin["item"]["symbol"] ) + name.append(coin["item"]["name"]) + symbol.append(coin["item"]["symbol"]) coin_id = coin["item"]["id"] - price.append( cg.get_price(coin_id, vs_currencies="USD")[coin_id]["usd"]) - rank.append( coin["item"]["market_cap_rank"] ) + price.append(cg.get_price(coin_id, vs_currencies="USD")[coin_id]["usd"]) + rank.append(coin["item"]["market_cap_rank"]) df = pd.DataFrame() - df["name"]= name + df["name"] = name df["symbol"] = symbol df["last_price"] = price df["market_cap_rank"] = rank - print( tabulate(df, headers=df.columns, floatfmt = ".2f", showindex=False, tablefmt="fancy_grid")) - print("") \ No newline at end of file + print( + tabulate( + df, + headers=df.columns, + floatfmt=".2f", + showindex=False, + tablefmt="fancy_grid", + ) + ) + print("")