def read_from_json(filename: str) -> Union[List, Dict]: ''' reads data from a json file ''' with open(f"{filename}.json", 'r') as json_file: log(LogLevel.INFO, f"Reading from JSON file: '{filename}.json'.") return json.load(json_file)
def _update_tickers(self, balance_tickers: Set[str]) -> None: ''' update `self.coins` with new coins from the account `balance_tickers` ''' self.coins |= balance_tickers write_to_json(list(self.coins), self.coins_filename) log(LogLevel.INFO, f"Updated set of coins to: {self.coins}")
def func(*args, **kwargs): try: response: Response = request_function(*args, **kwargs) if is_success_response(response.status_code): return response.json() raise ClientException(response.json()) except Exception as e: log(LogLevel.ERROR, str(e)) raise e
def update(self): ''' Update the portfolio with new data from binance ''' log(LogLevel.INFO, "Updating Crypto Porfolio.") self._write_spot_balance() self._write_spot_order_history() self._write_refined_spot_trades() self._write_portfolio_summary() log(LogLevel.INFO, "Done with Portfolio update.")
def send_get_request(self, url_endpoint: str, *args, **kwargs) -> Any: ''' send HTTP get request to `urlendpoint`''' log( LogLevel.INFO, f"Sending GET request to: {url_endpoint}. With arguments: args={args} kwargs={kwargs}." ) response = requests.get(url_endpoint, *args, **kwargs) log( LogLevel.INFO, f"Received response from {url_endpoint} with status={response.status_code}: {response.json()}" ) return response
def _write_refined_spot_trades(self) -> None: ''' write refined spot trades to a json file ''' log(LogLevel.INFO, "Starting refinement of spot trades.") for spot_trade in self.spot_order_history: if spot_trade["status"] == "FILLED": self.spot_trades[spot_trade["symbol"]].append(resolve_spot_trade(spot_trade)) write_to_json(self.spot_trades, "spot_trades") log(LogLevel.INFO, "Successfully refined spot trades.")
def write_to_excel(json_object: Union[List, Dict], filename: str, replace_existing: bool = True) -> None: ''' write a json object to an excel file (*.xlsx). ''' if not replace_existing: filename = f"{filename}_{str(timestamp())}" log( LogLevel.INFO, f"Writing to EXCEL file: '{filename}.xlsx' with replace_existing={replace_existing}." ) pd.DataFrame(json_object).to_excel(f"{filename}.xlsx")
def write_to_json(json_object: Union[List, Dict], filename: str, replace_existing: bool = True) -> None: ''' write a json object to a json file. ''' if not replace_existing: filename = f"{filename}_{str(timestamp())}" with open(f"{filename}.json", 'w') as file: log( LogLevel.INFO, f"Writing to JSON file: '{filename}.json' with replace_existing={replace_existing}." ) json.dump(json_object, file, indent=4)
def _write_portfolio_summary(self) -> None: ''' write spot portfolio summary to a json file and an excel file ''' log(LogLevel.INFO, "Creating spot portfolio summary.") portfolio_summary = [] for ticker, trades in self.spot_trades.items(): ticker_summary = create_ticker_summary(ticker.split(self.base_currency)[0], trades) portfolio_summary.append(ticker_summary) portfolio_summary = resolve_portfolio_summary(portfolio_summary, self.spot_balance) write_to_json(portfolio_summary, "spot_portfolio_summary") write_to_excel(portfolio_summary, "spot_portfolio_summary") log(LogLevel.INFO, "Success creating spot portfolio summary.")
def _write_spot_balance(self) -> None: ''' write latest daily snapshots of spot account to json and excel ''' log(LogLevel.INFO, "Starting spot balance update.") spot_balance_payload = binance.get_spot_account_snapshot() latest_spot_balance: Dict[str, Union[int, str, Dict]] = spot_balance_payload["snapshotVos"][-1] self._update_tickers({ balance["asset"] for balance in latest_spot_balance["data"]["balances"] if balance["asset"] != self.base_currency }) self._get_current_ticker_prices() spot_balance: List[Dict[str, Any]] = resolve_spot_balance( latest_spot_balance["data"]["balances"], self.ticker_prices ) self.spot_balance = {balance["symbol"] : balance for balance in spot_balance} filename = "spot_balance" write_to_excel(spot_balance, filename) write_to_json(spot_balance, filename) log(LogLevel.INFO, "Success updating spot balance.")
def _write_spot_order_history(self) -> None: ''' write the spot trade history of symbol pairs to a json file and excel file ''' log(LogLevel.INFO, "Starting spot trade order history update.") for symbol in self.coins: log(LogLevel.INFO, "Fetching spot order history for symbol: ", symbol) symbol_order_history = self.binance.get_all_orders(symbol + self.base_currency) self.spot_order_history.extend(symbol_order_history) format_trade_history(self.spot_order_history) filename = 'spot_order_history' log(LogLevel.INFO, "Fetching old trade order history.") full_trade_history: List[Dict[str, Any]] = read_from_json(filename) reduce_trade_history(full_trade_history, self.spot_order_history) self.spot_order_history = full_trade_history write_to_json(full_trade_history, filename) write_to_excel(full_trade_history, filename) log(LogLevel.INFO, "Success updating spot trade order history.")
from businessLogic import portfolio from businessUtils.switchUtils import Switch from businessUtils.logUtils import LogLevel, log from businessLogic.portfolio import Portfolio if __name__ == '__main__': try: if Switch.check_switch("use_refactored_code"): log(LogLevel.INFO, "Starting Driver... Invoking Portfolio instance...") portfolio = Portfolio() portfolio.update() log(LogLevel.INFO, "Driver destroyed. Exiting ...") else: symbols = ("ETHUSDT", "BTCUSDT", "LINKUSDT", "ADAUSDT", "DOTUSDT", "SXPUSDT", "ENJUSDT", "XRPUSDT", "DOGEUSDT", "AAVEUSDT", "VETUSDT", "MATICUSDT", "LTCUSDT") log(LogLevel.INFO, "Starting driver") portfolio.write_trade_history(symbols) portfolio.write_spot_balance() portfolio.write_portfolio_stats("spot_order_history") portfolio.write_portfolio_summary("portfolio_stats") except Exception as e: log(LogLevel.ERROR, str(e)) raise e