+__all__ = ["Portfolio", "BalanceStore", "ReportStore", "TradeStore"]
+
+class ReportStore:
+ def __init__(self, market, verbose_print=True):
+ self.market = market
+ self.verbose_print = verbose_print
+
+ self.print_logs = []
+ self.logs = []
+
+ def merge(self, other_report):
+ self.logs += other_report.logs
+ self.logs.sort(key=lambda x: x["date"])
+
+ self.print_logs += other_report.print_logs
+ self.print_logs.sort(key=lambda x: x[0])
+
+ 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)
+
+ 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
+
+ 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,
+ })
+
+ 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))
+
+ self.add_log({
+ "type": "balance",
+ "tag": tag,
+ "balances": self.market.balances.as_json()
+ })
+
+ 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
+ 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"]
+ })
+
+ def log_dispatch(self, amount, amounts, liquidity, repartition):
+ self.add_log({
+ "type": "dispatch",
+ "liquidity": liquidity,
+ "repartition_ratio": repartition,
+ "total_amount": amount.as_json(),
+ "repartition": { k: v.as_json()["value"] for k, v in amounts.items() }
+ })
+
+ 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)
+
+ self.add_log({
+ "type": "trades",
+ "only": only,
+ "debug": self.market.debug,
+ "trades": trades
+ })
+
+ 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,
+ "tick": tick,
+ "orders": [order.as_json() for order in orders if order is not 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:
+ self.print_log("[Order] Finished {}".format(order))
+ elif update == "waiting":
+ self.print_log("[Order] {}, tick {}, waiting".format(order, tick))
+ elif update == "adjusting":
+ self.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order))
+ elif update == "market_fallback":
+ self.print_log("[Order] {}, tick {}, fallbacking to market value".format(order, tick))
+ elif update == "market_adjust":
+ self.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order, tick, new_order))
+
+ self.add_log({
+ "type": "order",
+ "tick": tick,
+ "update": update,
+ "order": order.as_json(),
+ "compute_value": compute_value,
+ "new_order": new_order.as_json() if new_order is not None else None
+ })
+
+ def log_move_balances(self, needed, moving):
+ self.add_log({
+ "type": "move_balances",
+ "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() },
+ })
+
+ def log_http_request(self, method, url, body, headers, response):
+ self.add_log({
+ "type": "http_request",
+ "method": method,
+ "url": url,
+ "body": body,
+ "headers": headers,
+ "status": response.status_code,
+ "response": response.text
+ })
+
+ def log_error(self, action, message=None, exception=None):
+ self.print_log("[Error] {}".format(action))
+ if exception is not None:
+ self.print_log(str("\t{}: {}".format(exception.__class__.__name__, exception)))
+ if message is not None:
+ self.print_log("\t{}".format(message))
+
+ self.add_log({
+ "type": "error",
+ "action": action,
+ "exception_class": exception.__class__.__name__ if exception is not None else None,
+ "exception_message": str(exception) if exception is not None else None,
+ "message": message,
+ })
+
+ def log_debug_action(self, action):
+ self.print_log("[Debug] {}".format(action))
+
+ self.add_log({
+ "type": "debug_action",
+ "action": action,
+ })