X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=store.py;h=2b5c18a1a1a65eb241af2677d322195a5202d18d;hb=90d7423eec074a0ed0af680c223180f8d7e1d4e6;hp=a7aad22d9fcab3933307df21f7974497ba996f61;hpb=18167a3c502e9d61828067c3f6e56b5182584249;p=perso%2FImmae%2FProjets%2FCryptomonnaies%2FCryptoportfolio%2FTrader.git diff --git a/store.py b/store.py index a7aad22..2b5c18a 100644 --- a/store.py +++ b/store.py @@ -1,68 +1,103 @@ +import time +import requests import portfolio import simplejson as json from decimal import Decimal as D, ROUND_DOWN -from datetime import date, datetime +from datetime import date, datetime, timedelta +import inspect +from json import JSONDecodeError +from simplejson.errors import JSONDecodeError as SimpleJSONDecodeError -__all__ = ["BalanceStore", "ReportStore", "TradeStore"] +__all__ = ["Portfolio", "BalanceStore", "ReportStore", "TradeStore"] class ReportStore: - logs = [] - verbose_print = True + def __init__(self, market, verbose_print=True): + self.market = market + self.verbose_print = verbose_print - @classmethod - def print_log(cls, message): - message = str(message) - if cls.verbose_print: - print(message) + self.print_logs = [] + self.logs = [] - @classmethod - def add_log(cls, hash_): - hash_["date"] = datetime.now() - cls.logs.append(hash_) + def merge(self, other_report): + self.logs += other_report.logs + self.logs.sort(key=lambda x: x["date"]) - @classmethod - def to_json(cls): - def default_json_serial(obj): - if isinstance(obj, (datetime, date)): - return obj.isoformat() - raise TypeError ("Type %s not serializable" % type(obj)) - return json.dumps(cls.logs, default=default_json_serial) + self.print_logs += other_report.print_logs + self.print_logs.sort(key=lambda x: x[0]) - @classmethod - def set_verbose(cls, verbose_print): - cls.verbose_print = verbose_print + def print_log(self, message): + now = datetime.now() + message = "{:%Y-%m-%d %H:%M:%S}: {}".format(now, str(message)) + self.print_logs.append([now, message]) + if self.verbose_print: + print(message) - @classmethod - def log_stage(cls, stage): - cls.print_log("-" * (len(stage) + 8)) - cls.print_log("[Stage] {}".format(stage)) + def add_log(self, hash_): + hash_["date"] = datetime.now() + self.logs.append(hash_) + + @staticmethod + def default_json_serial(obj): + if isinstance(obj, (datetime, date)): + return obj.isoformat() + return str(obj) + + def to_json(self): + return json.dumps(self.logs, default=self.default_json_serial, indent=" ") + + def to_json_array(self): + for log in (x.copy() for x in self.logs): + yield ( + log.pop("date"), + log.pop("type"), + json.dumps(log, default=self.default_json_serial, indent=" ") + ) + + def set_verbose(self, verbose_print): + self.verbose_print = verbose_print + + def log_stage(self, stage, **kwargs): + def as_json(element): + if callable(element): + return inspect.getsource(element).strip() + elif hasattr(element, "as_json"): + return element.as_json() + else: + return element - cls.add_log({ + args = { k: as_json(v) for k, v in kwargs.items() } + args_str = ["{}={}".format(k, v) for k, v in args.items()] + self.print_log("-" * (len(stage) + 8)) + self.print_log("[Stage] {} {}".format(stage, ", ".join(args_str))) + + self.add_log({ "type": "stage", "stage": stage, + "args": args, }) - @classmethod - def log_balances(cls, market, tag=None): - cls.print_log("[Balance]") - for currency, balance in BalanceStore.all.items(): - cls.print_log("\t{}".format(balance)) + def log_balances(self, tag=None): + self.print_log("[Balance]") + for currency, balance in self.market.balances.all.items(): + self.print_log("\t{}".format(balance)) - cls.add_log({ + self.add_log({ "type": "balance", "tag": tag, - "balances": BalanceStore.as_json() + "balances": self.market.balances.as_json() }) - @classmethod - def log_tickers(cls, market, amounts, other_currency, + def log_tickers(self, amounts, other_currency, compute_value, type): values = {} rates = {} + if callable(compute_value): + compute_value = inspect.getsource(compute_value).strip() + for currency, amount in amounts.items(): values[currency] = amount.as_json()["value"] rates[currency] = amount.rate - cls.add_log({ + self.add_log({ "type": "tickers", "compute_value": compute_value, "balance_type": type, @@ -72,9 +107,8 @@ class ReportStore: "total": sum(amounts.values()).as_json()["value"] }) - @classmethod - def log_dispatch(cls, amount, amounts, liquidity, repartition): - cls.add_log({ + def log_dispatch(self, amount, amounts, liquidity, repartition): + self.add_log({ "type": "dispatch", "liquidity": liquidity, "repartition_ratio": repartition, @@ -82,26 +116,26 @@ class ReportStore: "repartition": { k: v.as_json()["value"] for k, v in amounts.items() } }) - @classmethod - def log_trades(cls, matching_and_trades, only, debug): + def log_trades(self, matching_and_trades, only): trades = [] for matching, trade in matching_and_trades: trade_json = trade.as_json() trade_json["skipped"] = not matching trades.append(trade_json) - cls.add_log({ + self.add_log({ "type": "trades", "only": only, - "debug": debug, + "debug": self.market.debug, "trades": trades }) - @classmethod - def log_orders(cls, orders, tick=None, only=None, compute_value=None): - cls.print_log("[Orders]") - TradeStore.print_all_with_order(ind="\t") - cls.add_log({ + def log_orders(self, orders, tick=None, only=None, compute_value=None): + if callable(compute_value): + compute_value = inspect.getsource(compute_value).strip() + self.print_log("[Orders]") + self.market.trades.print_all_with_order(ind="\t") + self.add_log({ "type": "orders", "only": only, "compute_value": compute_value, @@ -109,21 +143,22 @@ class ReportStore: "orders": [order.as_json() for order in orders if order is not None] }) - @classmethod - def log_order(cls, order, tick, finished=False, update=None, + def log_order(self, order, tick, finished=False, update=None, new_order=None, compute_value=None): + if callable(compute_value): + compute_value = inspect.getsource(compute_value).strip() if finished: - cls.print_log("[Order] Finished {}".format(order)) + self.print_log("[Order] Finished {}".format(order)) elif update == "waiting": - cls.print_log("[Order] {}, tick {}, waiting".format(order, tick)) + self.print_log("[Order] {}, tick {}, waiting".format(order, tick)) elif update == "adjusting": - cls.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order)) + self.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order)) elif update == "market_fallback": - cls.print_log("[Order] {}, tick {}, fallbacking to market value".format(order, tick)) + self.print_log("[Order] {}, tick {}, fallbacking to market value".format(order, tick)) elif update == "market_adjust": - cls.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order, tick, new_order)) + self.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order, tick, new_order)) - cls.add_log({ + self.add_log({ "type": "order", "tick": tick, "update": update, @@ -132,18 +167,16 @@ class ReportStore: "new_order": new_order.as_json() if new_order is not None else None }) - @classmethod - def log_move_balances(cls, needed, moving, debug): - cls.add_log({ + def log_move_balances(self, needed, moving): + self.add_log({ "type": "move_balances", - "debug": debug, + "debug": self.market.debug, "needed": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in needed.items() }, "moving": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in moving.items() }, }) - @classmethod - def log_http_request(cls, method, url, body, headers, response): - cls.add_log({ + def log_http_request(self, method, url, body, headers, response): + self.add_log({ "type": "http_request", "method": method, "url": url, @@ -153,15 +186,14 @@ class ReportStore: "response": response.text }) - @classmethod - def log_error(cls, action, message=None, exception=None): - cls.print_log("[Error] {}".format(action)) + def log_error(self, action, message=None, exception=None): + self.print_log("[Error] {}".format(action)) if exception is not None: - cls.print_log(str("\t{}: {}".format(exception.__class__.__name__, exception))) + self.print_log(str("\t{}: {}".format(exception.__class__.__name__, exception))) if message is not None: - cls.print_log("\t{}".format(message)) + self.print_log("\t{}".format(message)) - cls.add_log({ + self.add_log({ "type": "error", "action": action, "exception_class": exception.__class__.__name__ if exception is not None else None, @@ -169,132 +201,300 @@ class ReportStore: "message": message, }) - @classmethod - def log_debug_action(cls, action): - cls.print_log("[Debug] {}".format(action)) + def log_debug_action(self, action): + self.print_log("[Debug] {}".format(action)) - cls.add_log({ + self.add_log({ "type": "debug_action", "action": action, }) + def log_market(self, args, user_id, market_id, report_path, debug): + self.add_log({ + "type": "market", + "commit": "$Format:%H$", + "args": vars(args), + "user_id": user_id, + "market_id": market_id, + "report_path": report_path, + "debug": debug, + }) + class BalanceStore: - all = {} + def __init__(self, market): + self.market = market + self.all = {} - @classmethod - def currencies(cls): - return cls.all.keys() + def currencies(self): + return self.all.keys() - @classmethod - def in_currency(cls, other_currency, market, compute_value="average", type="total"): + def in_currency(self, other_currency, compute_value="average", type="total"): amounts = {} - for currency, balance in cls.all.items(): + for currency, balance in self.all.items(): other_currency_amount = getattr(balance, type)\ - .in_currency(other_currency, market, compute_value=compute_value) + .in_currency(other_currency, self.market, compute_value=compute_value) amounts[currency] = other_currency_amount - ReportStore.log_tickers(market, amounts, other_currency, + self.market.report.log_tickers(amounts, other_currency, compute_value, type) return amounts - @classmethod - def fetch_balances(cls, market, tag=None): - all_balances = market.fetch_all_balances() + def fetch_balances(self, tag=None): + 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 cls.all: - cls.all[currency] = portfolio.Balance(currency, balance) - ReportStore.log_balances(market, tag=tag) + currency in self.all: + self.all[currency] = portfolio.Balance(currency, balance) + self.market.report.log_balances(tag=tag) - @classmethod - def dispatch_assets(cls, amount, liquidity="medium", repartition=None): + def dispatch_assets(self, amount, liquidity="medium", repartition=None): if repartition is None: - repartition = portfolio.Portfolio.repartition(liquidity=liquidity) + repartition = Portfolio.repartition(liquidity=liquidity) sum_ratio = sum([v[0] for k, v in repartition.items()]) amounts = {} for currency, (ptt, trade_type) in repartition.items(): amounts[currency] = ptt * amount / sum_ratio if trade_type == "short": amounts[currency] = - amounts[currency] - if currency not in BalanceStore.all: - cls.all[currency] = portfolio.Balance(currency, {}) - ReportStore.log_dispatch(amount, amounts, liquidity, repartition) + self.all.setdefault(currency, portfolio.Balance(currency, {})) + self.market.report.log_dispatch(amount, amounts, liquidity, repartition) return amounts - @classmethod - def as_json(cls): - return { k: v.as_json() for k, v in cls.all.items() } + def as_json(self): + return { k: v.as_json() for k, v in self.all.items() } class TradeStore: - all = [] - debug = False + def __init__(self, market): + self.market = market + self.all = [] - @classmethod - def compute_trades(cls, values_in_base, new_repartition, only=None, market=None, debug=False): + @property + def pending(self): + return list(filter(lambda t: t.pending, self.all)) + + def compute_trades(self, values_in_base, new_repartition, only=None): computed_trades = [] - cls.debug = cls.debug or debug base_currency = sum(values_in_base.values()).currency - for currency in BalanceStore.currencies(): + for currency in self.market.balances.currencies(): if currency == base_currency: continue value_from = values_in_base.get(currency, portfolio.Amount(base_currency, 0)) value_to = new_repartition.get(currency, portfolio.Amount(base_currency, 0)) if value_from.value * value_to.value < 0: - computed_trades.append(cls.trade_if_matching( + computed_trades.append(self.trade_if_matching( value_from, portfolio.Amount(base_currency, 0), - currency, only=only, market=market)) - computed_trades.append(cls.trade_if_matching( + currency, only=only)) + computed_trades.append(self.trade_if_matching( portfolio.Amount(base_currency, 0), value_to, - currency, only=only, market=market)) + currency, only=only)) else: - computed_trades.append(cls.trade_if_matching( + computed_trades.append(self.trade_if_matching( value_from, value_to, - currency, only=only, market=market)) + currency, only=only)) for matching, trade in computed_trades: if matching: - cls.all.append(trade) - ReportStore.log_trades(computed_trades, only, cls.debug) + self.all.append(trade) + self.market.report.log_trades(computed_trades, only) - @classmethod - def trade_if_matching(cls, value_from, value_to, currency, - only=None, market=None): + def trade_if_matching(self, value_from, value_to, currency, + only=None): trade = portfolio.Trade(value_from, value_to, currency, - market=market) + self.market) matching = only is None or trade.action == only return [matching, trade] - @classmethod - def prepare_orders(cls, only=None, compute_value="default"): + def prepare_orders(self, only=None, compute_value="default"): orders = [] - for trade in cls.all: + for trade in self.pending: if only is None or trade.action == only: orders.append(trade.prepare_order(compute_value=compute_value)) - ReportStore.log_orders(orders, only, compute_value) + self.market.report.log_orders(orders, only, compute_value) - @classmethod - def print_all_with_order(cls, ind=""): - for trade in cls.all: + def close_trades(self): + for trade in self.all: + trade.close() + + def print_all_with_order(self, ind=""): + for trade in self.all: trade.print_with_order(ind=ind) - @classmethod - def run_orders(cls): - orders = cls.all_orders(state="pending") + def run_orders(self): + orders = self.all_orders(state="pending") for order in orders: order.run() - ReportStore.log_stage("run_orders") - ReportStore.log_orders(orders) + self.market.report.log_stage("run_orders") + self.market.report.log_orders(orders) - @classmethod - def all_orders(cls, state=None): - all_orders = sum(map(lambda v: v.orders, cls.all), []) + def all_orders(self, state=None): + all_orders = sum(map(lambda v: v.orders, self.all), []) if state is None: return all_orders else: return list(filter(lambda o: o.status == state, all_orders)) - @classmethod - def update_all_orders_status(cls): - for order in cls.all_orders(state="open"): + def update_all_orders_status(self): + for order in self.all_orders(state="open"): order.get_status() +class NoopLock: + def __enter__(self, *args): + pass + def __exit__(self, *args): + pass + +class LockedVar: + def __init__(self, value): + self.lock = NoopLock() + self.val = value + + def start_lock(self): + import threading + self.lock = threading.Lock() + + def set(self, value): + with self.lock: + self.val = value + + def get(self, key=None): + with self.lock: + if key is not None and isinstance(self.val, dict): + return self.val.get(key) + else: + return self.val + + def __getattr__(self, key): + with self.lock: + return getattr(self.val, key) + +class Portfolio: + URL = "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json" + data = LockedVar(None) + liquidities = LockedVar({}) + last_date = LockedVar(None) + report = LockedVar(ReportStore(None)) + worker = None + worker_started = False + worker_notify = None + callback = None + + @classmethod + def start_worker(cls, poll=30): + import threading + + cls.worker = threading.Thread(name="portfolio", daemon=True, + target=cls.wait_for_notification, kwargs={"poll": poll}) + cls.worker_notify = threading.Event() + cls.callback = threading.Event() + + cls.last_date.start_lock() + cls.liquidities.start_lock() + cls.report.start_lock() + + cls.worker_started = True + cls.worker.start() + + @classmethod + def is_worker_thread(cls): + if cls.worker is None: + return False + else: + import threading + return cls.worker == threading.current_thread() + + @classmethod + def wait_for_notification(cls, poll=30): + if not cls.is_worker_thread(): + raise RuntimeError("This method needs to be ran with the worker") + while cls.worker_started: + cls.worker_notify.wait() + cls.worker_notify.clear() + cls.report.print_log("Fetching cryptoportfolio") + cls.get_cryptoportfolio(refetch=True) + cls.callback.set() + time.sleep(poll) + + @classmethod + def notify_and_wait(cls): + cls.callback.clear() + cls.worker_notify.set() + cls.callback.wait() + + @classmethod + def wait_for_recent(cls, delta=4, poll=30): + cls.get_cryptoportfolio() + while cls.last_date.get() is None or datetime.now() - cls.last_date.get() > timedelta(delta): + if cls.worker is None: + time.sleep(poll) + cls.report.print_log("Attempt to fetch up-to-date cryptoportfolio") + cls.get_cryptoportfolio(refetch=True) + + @classmethod + def repartition(cls, liquidity="medium"): + cls.get_cryptoportfolio() + liquidities = cls.liquidities.get(liquidity) + return liquidities[cls.last_date.get()] + + @classmethod + def get_cryptoportfolio(cls, refetch=False): + if cls.data.get() is not None and not refetch: + return + if cls.worker is not None and not cls.is_worker_thread(): + cls.notify_and_wait() + return + try: + r = requests.get(cls.URL) + cls.report.log_http_request(r.request.method, + r.request.url, r.request.body, r.request.headers, r) + except Exception as e: + cls.report.log_error("get_cryptoportfolio", exception=e) + return + try: + cls.data.set(r.json(parse_int=D, parse_float=D)) + cls.parse_cryptoportfolio() + except (JSONDecodeError, SimpleJSONDecodeError): + cls.data.set(None) + cls.last_date.set(None) + cls.liquidities.set({}) + + @classmethod + def parse_cryptoportfolio(cls): + def filter_weights(weight_hash): + if weight_hash[1][0] == 0: + return False + if weight_hash[0] == "_row": + return False + return True + + def clean_weights(i): + def clean_weights_(h): + if h[0].endswith("s"): + return [h[0][0:-1], (h[1][i], "short")] + else: + return [h[0], (h[1][i], "long")] + return clean_weights_ + + def parse_weights(portfolio_hash): + if "weights" not in portfolio_hash: + return {} + weights_hash = portfolio_hash["weights"] + weights = {} + for i in range(len(weights_hash["_row"])): + date = datetime.strptime(weights_hash["_row"][i], "%Y-%m-%d") + weights[date] = dict(filter( + filter_weights, + map(clean_weights(i), weights_hash.items()))) + return weights + + high_liquidity = parse_weights(cls.data.get("portfolio_1")) + medium_liquidity = parse_weights(cls.data.get("portfolio_2")) + + cls.liquidities.set({ + "medium": medium_liquidity, + "high": high_liquidity, + }) + cls.last_date.set(max( + max(medium_liquidity.keys(), default=datetime(1, 1, 1)), + max(high_liquidity.keys(), default=datetime(1, 1, 1)) + )) +