X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=store.py;h=32c41211050c83d97c554e84ae29d188c457f3e0;hb=3a15ffc79ea84e5ec6200545bcbf11fc6c1c6564;hp=45a52339dc688bb9311451c476ec149b23f09a5f;hpb=a0dcf4e0978331709da164fb0e29ae008b90fc88;p=perso%2FImmae%2FProjets%2FCryptomonnaies%2FCryptoportfolio%2FTrader.git diff --git a/store.py b/store.py index 45a5233..32c4121 100644 --- a/store.py +++ b/store.py @@ -7,6 +7,7 @@ import datetime import inspect from json import JSONDecodeError from simplejson.errors import JSONDecodeError as SimpleJSONDecodeError +import dbs __all__ = ["Portfolio", "BalanceStore", "ReportStore", "TradeStore"] @@ -17,6 +18,7 @@ class ReportStore: self.print_logs = [] self.logs = [] + self.redis_status = [] self.no_http_dup = no_http_dup self.last_http = None @@ -46,6 +48,10 @@ class ReportStore: self.logs.append(hash_) return hash_ + def add_redis_status(self, hash_): + self.redis_status.append(hash_) + return hash_ + @staticmethod def default_json_serial(obj): if isinstance(obj, (datetime.datetime, datetime.date)): @@ -63,6 +69,13 @@ class ReportStore: json.dumps(log, default=self.default_json_serial, indent=" ") ) + def to_json_redis(self): + for log in (x.copy() for x in self.redis_status): + yield ( + log.pop("type"), + json.dumps(log, default=self.default_json_serial) + ) + def set_verbose(self, verbose_print): self.verbose_print = verbose_print @@ -86,19 +99,35 @@ class ReportStore: "args": args, }) - def log_balances(self, tag=None): + def log_balances(self, tag=None, checkpoint=None, tickers=None, + ticker_currency=None, compute_value=None, type=None): self.print_log("[Balance]") for currency, balance in self.market.balances.all.items(): self.print_log("\t{}".format(balance)) - self.add_log({ - "type": "balance", - "tag": tag, - "balances": self.market.balances.as_json() - }) + log = { + "type": "balance", + "tag": tag, + "checkpoint": checkpoint, + "balances": self.market.balances.as_json() + } + + if tickers is not None: + log["tickers"] = self._ticker_hash(tickers, ticker_currency, + compute_value, type) + + self.add_log(log.copy()) + self.add_redis_status(log) def log_tickers(self, amounts, other_currency, compute_value, type): + log = self._ticker_hash(amounts, other_currency, compute_value, + type) + log["type"] = "tickers" + + self.add_log(log) + + def _ticker_hash(self, amounts, other_currency, compute_value, type): values = {} rates = {} if callable(compute_value): @@ -107,15 +136,14 @@ class ReportStore: for currency, amount in amounts.items(): values[currency] = amount.as_json()["value"] rates[currency] = amount.rate - self.add_log({ - "type": "tickers", - "compute_value": compute_value, - "balance_type": type, - "currency": other_currency, - "balances": values, - "rates": rates, - "total": sum(amounts.values()).as_json()["value"] - }) + return { + "compute_value": compute_value, + "balance_type": type, + "currency": other_currency, + "balances": values, + "rates": rates, + "total": sum(amounts.values()).as_json()["value"] + } def log_dispatch(self, amount, amounts, liquidity, repartition): self.add_log({ @@ -211,6 +239,7 @@ class ReportStore: "body": body, "headers": headers, "status": response.status_code, + "duration": response.elapsed.total_seconds(), "response": None, "response_same_as": self.last_http["date"] }) @@ -222,6 +251,7 @@ class ReportStore: "body": body, "headers": headers, "status": response.status_code, + "duration": response.elapsed.total_seconds(), "response": response.text, "response_same_as": None, }) @@ -274,13 +304,26 @@ class BalanceStore: compute_value, type) return amounts - def fetch_balances(self, tag=None): + def fetch_balances(self, tag=None, add_portfolio=False, + checkpoint=None, log_tickers=False, add_usdt=False, + ticker_currency="BTC", ticker_compute_value="average", ticker_type="total"): all_balances = self.market.ccxt.fetch_all_balances() for currency, balance in all_balances.items(): if balance["exchange_total"] != 0 or balance["margin_total"] != 0 or \ currency in self.all: self.all[currency] = portfolio.Balance(currency, balance) - self.market.report.log_balances(tag=tag) + if add_portfolio: + for currency in Portfolio.repartition(from_cache=True): + self.all.setdefault(currency, portfolio.Balance(currency, {})) + if add_usdt: + self.all.setdefault("USDT", portfolio.Balance("USDT", {})) + if log_tickers: + tickers = self.in_currency(ticker_currency, compute_value=ticker_compute_value, type=ticker_type) + self.market.report.log_balances(tag=tag, checkpoint=checkpoint, + tickers=tickers, ticker_currency=ticker_currency, + compute_value=ticker_compute_value, type=ticker_type) + else: + self.market.report.log_balances(tag=tag, checkpoint=checkpoint) def dispatch_assets(self, amount, liquidity="medium", repartition=None): if repartition is None: @@ -473,7 +516,9 @@ class Portfolio: cls.get_cryptoportfolio(refetch=True) @classmethod - def repartition(cls, liquidity="medium"): + def repartition(cls, liquidity="medium", from_cache=False): + if from_cache: + cls.retrieve_cryptoportfolio() cls.get_cryptoportfolio() liquidities = cls.liquidities.get(liquidity) return liquidities[cls.last_date.get()] @@ -495,11 +540,38 @@ class Portfolio: try: cls.data.set(r.json(parse_int=D, parse_float=D)) cls.parse_cryptoportfolio() + cls.store_cryptoportfolio() except (JSONDecodeError, SimpleJSONDecodeError): cls.data.set(None) cls.last_date.set(None) cls.liquidities.set({}) + @classmethod + def retrieve_cryptoportfolio(cls): + if dbs.redis_connected(): + repartition = dbs.redis.get("/cryptoportfolio/repartition/latest") + date = dbs.redis.get("/cryptoportfolio/repartition/date") + if date is not None and repartition is not None: + date = datetime.datetime.strptime(date.decode(), "%Y-%m-%d") + repartition = json.loads(repartition, parse_int=D, parse_float=D) + repartition = { k: { date: v } for k, v in repartition.items() } + + cls.data.set("") + cls.last_date.set(date) + cls.liquidities.set(repartition) + + @classmethod + def store_cryptoportfolio(cls): + if dbs.redis_connected(): + hash_ = {} + for liquidity, repartitions in cls.liquidities.items(): + hash_[liquidity] = repartitions[cls.last_date.get()] + dump = json.dumps(hash_) + key = "/cryptoportfolio/repartition/latest" + dbs.redis.set(key, dump) + key = "/cryptoportfolio/repartition/date" + dbs.redis.set(key, cls.last_date.date().isoformat()) + @classmethod def parse_cryptoportfolio(cls): def filter_weights(weight_hash):