]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blame - store.py
Add logging at market instance creation
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git] / store.py
CommitLineData
ada1b5f1
IB
1import time
2import requests
6ca5a1ec 3import portfolio
3d0247f9
IB
4import simplejson as json
5from decimal import Decimal as D, ROUND_DOWN
ada1b5f1 6from datetime import date, datetime, timedelta
aca4d437 7import inspect
ada1b5f1
IB
8from json import JSONDecodeError
9from simplejson.errors import JSONDecodeError as SimpleJSONDecodeError
6ca5a1ec 10
ada1b5f1 11__all__ = ["Portfolio", "BalanceStore", "ReportStore", "TradeStore"]
3d0247f9
IB
12
13class ReportStore:
f86ee140
IB
14 def __init__(self, market, verbose_print=True):
15 self.market = market
16 self.verbose_print = verbose_print
3d0247f9 17
718e3e91 18 self.print_logs = []
f86ee140
IB
19 self.logs = []
20
9bde69bf
IB
21 def merge(self, other_report):
22 self.logs += other_report.logs
23 self.logs.sort(key=lambda x: x["date"])
24
718e3e91
IB
25 self.print_logs += other_report.print_logs
26 self.print_logs.sort(key=lambda x: x[0])
27
f86ee140 28 def print_log(self, message):
718e3e91
IB
29 now = datetime.now()
30 message = "{:%Y-%m-%d %H:%M:%S}: {}".format(now, str(message))
31 self.print_logs.append([now, message])
f86ee140 32 if self.verbose_print:
3d0247f9
IB
33 print(message)
34
f86ee140 35 def add_log(self, hash_):
3d0247f9 36 hash_["date"] = datetime.now()
f86ee140 37 self.logs.append(hash_)
3d0247f9 38
b4e0ba0b
IB
39 @staticmethod
40 def default_json_serial(obj):
41 if isinstance(obj, (datetime, date)):
42 return obj.isoformat()
43 return str(obj)
44
f86ee140 45 def to_json(self):
b4e0ba0b
IB
46 return json.dumps(self.logs, default=self.default_json_serial, indent=" ")
47
48 def to_json_array(self):
49 for log in (x.copy() for x in self.logs):
50 yield (
51 log.pop("date"),
52 log.pop("type"),
53 json.dumps(log, default=self.default_json_serial, indent=" ")
54 )
3d0247f9 55
f86ee140
IB
56 def set_verbose(self, verbose_print):
57 self.verbose_print = verbose_print
3d0247f9 58
7bd830a8
IB
59 def log_stage(self, stage, **kwargs):
60 def as_json(element):
61 if callable(element):
62 return inspect.getsource(element).strip()
63 elif hasattr(element, "as_json"):
64 return element.as_json()
65 else:
66 return element
67
68 args = { k: as_json(v) for k, v in kwargs.items() }
69 args_str = ["{}={}".format(k, v) for k, v in args.items()]
f86ee140 70 self.print_log("-" * (len(stage) + 8))
7bd830a8 71 self.print_log("[Stage] {} {}".format(stage, ", ".join(args_str)))
3d0247f9 72
f86ee140 73 self.add_log({
3d0247f9
IB
74 "type": "stage",
75 "stage": stage,
7bd830a8 76 "args": args,
3d0247f9
IB
77 })
78
f86ee140
IB
79 def log_balances(self, tag=None):
80 self.print_log("[Balance]")
81 for currency, balance in self.market.balances.all.items():
82 self.print_log("\t{}".format(balance))
3d0247f9 83
f86ee140 84 self.add_log({
3d0247f9 85 "type": "balance",
18167a3c 86 "tag": tag,
f86ee140 87 "balances": self.market.balances.as_json()
3d0247f9
IB
88 })
89
f86ee140 90 def log_tickers(self, amounts, other_currency,
3d0247f9
IB
91 compute_value, type):
92 values = {}
93 rates = {}
aca4d437
IB
94 if callable(compute_value):
95 compute_value = inspect.getsource(compute_value).strip()
96
3d0247f9
IB
97 for currency, amount in amounts.items():
98 values[currency] = amount.as_json()["value"]
99 rates[currency] = amount.rate
f86ee140 100 self.add_log({
3d0247f9
IB
101 "type": "tickers",
102 "compute_value": compute_value,
103 "balance_type": type,
104 "currency": other_currency,
105 "balances": values,
106 "rates": rates,
107 "total": sum(amounts.values()).as_json()["value"]
108 })
109
f86ee140
IB
110 def log_dispatch(self, amount, amounts, liquidity, repartition):
111 self.add_log({
3d0247f9
IB
112 "type": "dispatch",
113 "liquidity": liquidity,
114 "repartition_ratio": repartition,
115 "total_amount": amount.as_json(),
116 "repartition": { k: v.as_json()["value"] for k, v in amounts.items() }
117 })
118
f86ee140 119 def log_trades(self, matching_and_trades, only):
3d0247f9
IB
120 trades = []
121 for matching, trade in matching_and_trades:
122 trade_json = trade.as_json()
123 trade_json["skipped"] = not matching
124 trades.append(trade_json)
125
f86ee140 126 self.add_log({
3d0247f9
IB
127 "type": "trades",
128 "only": only,
f86ee140 129 "debug": self.market.debug,
3d0247f9
IB
130 "trades": trades
131 })
132
f86ee140 133 def log_orders(self, orders, tick=None, only=None, compute_value=None):
aca4d437
IB
134 if callable(compute_value):
135 compute_value = inspect.getsource(compute_value).strip()
f86ee140
IB
136 self.print_log("[Orders]")
137 self.market.trades.print_all_with_order(ind="\t")
138 self.add_log({
3d0247f9
IB
139 "type": "orders",
140 "only": only,
141 "compute_value": compute_value,
142 "tick": tick,
143 "orders": [order.as_json() for order in orders if order is not None]
144 })
145
f86ee140 146 def log_order(self, order, tick, finished=False, update=None,
3d0247f9 147 new_order=None, compute_value=None):
aca4d437
IB
148 if callable(compute_value):
149 compute_value = inspect.getsource(compute_value).strip()
3d0247f9 150 if finished:
f86ee140 151 self.print_log("[Order] Finished {}".format(order))
3d0247f9 152 elif update == "waiting":
f86ee140 153 self.print_log("[Order] {}, tick {}, waiting".format(order, tick))
3d0247f9 154 elif update == "adjusting":
f86ee140 155 self.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order))
3d0247f9 156 elif update == "market_fallback":
f86ee140 157 self.print_log("[Order] {}, tick {}, fallbacking to market value".format(order, tick))
3d0247f9 158 elif update == "market_adjust":
f86ee140 159 self.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order, tick, new_order))
3d0247f9 160
f86ee140 161 self.add_log({
3d0247f9
IB
162 "type": "order",
163 "tick": tick,
164 "update": update,
165 "order": order.as_json(),
166 "compute_value": compute_value,
167 "new_order": new_order.as_json() if new_order is not None else None
168 })
169
f86ee140
IB
170 def log_move_balances(self, needed, moving):
171 self.add_log({
3d0247f9 172 "type": "move_balances",
f86ee140 173 "debug": self.market.debug,
3d0247f9
IB
174 "needed": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in needed.items() },
175 "moving": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in moving.items() },
176 })
177
f86ee140
IB
178 def log_http_request(self, method, url, body, headers, response):
179 self.add_log({
3d0247f9
IB
180 "type": "http_request",
181 "method": method,
182 "url": url,
183 "body": body,
184 "headers": headers,
185 "status": response.status_code,
186 "response": response.text
187 })
188
f86ee140
IB
189 def log_error(self, action, message=None, exception=None):
190 self.print_log("[Error] {}".format(action))
3d0247f9 191 if exception is not None:
f86ee140 192 self.print_log(str("\t{}: {}".format(exception.__class__.__name__, exception)))
3d0247f9 193 if message is not None:
f86ee140 194 self.print_log("\t{}".format(message))
3d0247f9 195
f86ee140 196 self.add_log({
3d0247f9
IB
197 "type": "error",
198 "action": action,
199 "exception_class": exception.__class__.__name__ if exception is not None else None,
200 "exception_message": str(exception) if exception is not None else None,
201 "message": message,
202 })
203
f86ee140
IB
204 def log_debug_action(self, action):
205 self.print_log("[Debug] {}".format(action))
3d0247f9 206
f86ee140 207 self.add_log({
3d0247f9
IB
208 "type": "debug_action",
209 "action": action,
210 })
6ca5a1ec 211
90d7423e
IB
212 def log_market(self, args, user_id, market_id, report_path, debug):
213 self.add_log({
214 "type": "market",
215 "commit": "$Format:%H$",
216 "args": vars(args),
217 "user_id": user_id,
218 "market_id": market_id,
219 "report_path": report_path,
220 "debug": debug,
221 })
222
6ca5a1ec 223class BalanceStore:
f86ee140
IB
224 def __init__(self, market):
225 self.market = market
226 self.all = {}
6ca5a1ec 227
f86ee140
IB
228 def currencies(self):
229 return self.all.keys()
6ca5a1ec 230
f86ee140 231 def in_currency(self, other_currency, compute_value="average", type="total"):
6ca5a1ec 232 amounts = {}
f86ee140 233 for currency, balance in self.all.items():
6ca5a1ec 234 other_currency_amount = getattr(balance, type)\
f86ee140 235 .in_currency(other_currency, self.market, compute_value=compute_value)
6ca5a1ec 236 amounts[currency] = other_currency_amount
f86ee140 237 self.market.report.log_tickers(amounts, other_currency,
3d0247f9 238 compute_value, type)
6ca5a1ec
IB
239 return amounts
240
f86ee140
IB
241 def fetch_balances(self, tag=None):
242 all_balances = self.market.ccxt.fetch_all_balances()
6ca5a1ec
IB
243 for currency, balance in all_balances.items():
244 if balance["exchange_total"] != 0 or balance["margin_total"] != 0 or \
f86ee140
IB
245 currency in self.all:
246 self.all[currency] = portfolio.Balance(currency, balance)
247 self.market.report.log_balances(tag=tag)
6ca5a1ec 248
f86ee140 249 def dispatch_assets(self, amount, liquidity="medium", repartition=None):
6ca5a1ec 250 if repartition is None:
ada1b5f1 251 repartition = Portfolio.repartition(liquidity=liquidity)
6ca5a1ec
IB
252 sum_ratio = sum([v[0] for k, v in repartition.items()])
253 amounts = {}
254 for currency, (ptt, trade_type) in repartition.items():
255 amounts[currency] = ptt * amount / sum_ratio
256 if trade_type == "short":
257 amounts[currency] = - amounts[currency]
aca4d437 258 self.all.setdefault(currency, portfolio.Balance(currency, {}))
f86ee140 259 self.market.report.log_dispatch(amount, amounts, liquidity, repartition)
6ca5a1ec
IB
260 return amounts
261
f86ee140
IB
262 def as_json(self):
263 return { k: v.as_json() for k, v in self.all.items() }
3d0247f9 264
6ca5a1ec 265class TradeStore:
f86ee140
IB
266 def __init__(self, market):
267 self.market = market
268 self.all = []
6ca5a1ec 269
aca4d437
IB
270 @property
271 def pending(self):
17598517 272 return list(filter(lambda t: t.pending, self.all))
aca4d437 273
f86ee140 274 def compute_trades(self, values_in_base, new_repartition, only=None):
3d0247f9 275 computed_trades = []
6ca5a1ec 276 base_currency = sum(values_in_base.values()).currency
f86ee140 277 for currency in self.market.balances.currencies():
6ca5a1ec
IB
278 if currency == base_currency:
279 continue
280 value_from = values_in_base.get(currency, portfolio.Amount(base_currency, 0))
281 value_to = new_repartition.get(currency, portfolio.Amount(base_currency, 0))
1aa7d4fa 282
6ca5a1ec 283 if value_from.value * value_to.value < 0:
f86ee140 284 computed_trades.append(self.trade_if_matching(
1aa7d4fa 285 value_from, portfolio.Amount(base_currency, 0),
f86ee140
IB
286 currency, only=only))
287 computed_trades.append(self.trade_if_matching(
1aa7d4fa 288 portfolio.Amount(base_currency, 0), value_to,
f86ee140 289 currency, only=only))
6ca5a1ec 290 else:
f86ee140 291 computed_trades.append(self.trade_if_matching(
3d0247f9 292 value_from, value_to,
f86ee140 293 currency, only=only))
3d0247f9
IB
294 for matching, trade in computed_trades:
295 if matching:
f86ee140
IB
296 self.all.append(trade)
297 self.market.report.log_trades(computed_trades, only)
1aa7d4fa 298
f86ee140
IB
299 def trade_if_matching(self, value_from, value_to, currency,
300 only=None):
1aa7d4fa 301 trade = portfolio.Trade(value_from, value_to, currency,
f86ee140 302 self.market)
3d0247f9
IB
303 matching = only is None or trade.action == only
304 return [matching, trade]
6ca5a1ec 305
f86ee140 306 def prepare_orders(self, only=None, compute_value="default"):
3d0247f9 307 orders = []
aca4d437 308 for trade in self.pending:
6ca5a1ec 309 if only is None or trade.action == only:
3d0247f9 310 orders.append(trade.prepare_order(compute_value=compute_value))
f86ee140 311 self.market.report.log_orders(orders, only, compute_value)
6ca5a1ec 312
17598517
IB
313 def close_trades(self):
314 for trade in self.all:
315 trade.close()
316
f86ee140
IB
317 def print_all_with_order(self, ind=""):
318 for trade in self.all:
3d0247f9 319 trade.print_with_order(ind=ind)
6ca5a1ec 320
f86ee140
IB
321 def run_orders(self):
322 orders = self.all_orders(state="pending")
3d0247f9 323 for order in orders:
6ca5a1ec 324 order.run()
f86ee140
IB
325 self.market.report.log_stage("run_orders")
326 self.market.report.log_orders(orders)
6ca5a1ec 327
f86ee140
IB
328 def all_orders(self, state=None):
329 all_orders = sum(map(lambda v: v.orders, self.all), [])
6ca5a1ec
IB
330 if state is None:
331 return all_orders
332 else:
333 return list(filter(lambda o: o.status == state, all_orders))
334
f86ee140
IB
335 def update_all_orders_status(self):
336 for order in self.all_orders(state="open"):
6ca5a1ec
IB
337 order.get_status()
338
dc1ca9a3
IB
339class NoopLock:
340 def __enter__(self, *args):
341 pass
342 def __exit__(self, *args):
343 pass
344
345class LockedVar:
346 def __init__(self, value):
347 self.lock = NoopLock()
348 self.val = value
349
350 def start_lock(self):
351 import threading
352 self.lock = threading.Lock()
353
354 def set(self, value):
355 with self.lock:
356 self.val = value
357
358 def get(self, key=None):
359 with self.lock:
360 if key is not None and isinstance(self.val, dict):
361 return self.val.get(key)
362 else:
363 return self.val
364
365 def __getattr__(self, key):
366 with self.lock:
367 return getattr(self.val, key)
368
ada1b5f1
IB
369class Portfolio:
370 URL = "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json"
dc1ca9a3
IB
371 data = LockedVar(None)
372 liquidities = LockedVar({})
373 last_date = LockedVar(None)
374 report = LockedVar(ReportStore(None))
375 worker = None
376 worker_started = False
377 worker_notify = None
378 callback = None
379
380 @classmethod
381 def start_worker(cls, poll=30):
382 import threading
383
384 cls.worker = threading.Thread(name="portfolio", daemon=True,
385 target=cls.wait_for_notification, kwargs={"poll": poll})
386 cls.worker_notify = threading.Event()
387 cls.callback = threading.Event()
388
389 cls.last_date.start_lock()
390 cls.liquidities.start_lock()
391 cls.report.start_lock()
392
393 cls.worker_started = True
394 cls.worker.start()
395
396 @classmethod
397 def is_worker_thread(cls):
398 if cls.worker is None:
399 return False
400 else:
401 import threading
402 return cls.worker == threading.current_thread()
403
404 @classmethod
405 def wait_for_notification(cls, poll=30):
406 if not cls.is_worker_thread():
407 raise RuntimeError("This method needs to be ran with the worker")
408 while cls.worker_started:
409 cls.worker_notify.wait()
410 cls.worker_notify.clear()
411 cls.report.print_log("Fetching cryptoportfolio")
412 cls.get_cryptoportfolio(refetch=True)
413 cls.callback.set()
414 time.sleep(poll)
ada1b5f1
IB
415
416 @classmethod
dc1ca9a3
IB
417 def notify_and_wait(cls):
418 cls.callback.clear()
419 cls.worker_notify.set()
420 cls.callback.wait()
421
422 @classmethod
423 def wait_for_recent(cls, delta=4, poll=30):
ada1b5f1 424 cls.get_cryptoportfolio()
dc1ca9a3
IB
425 while cls.last_date.get() is None or datetime.now() - cls.last_date.get() > timedelta(delta):
426 if cls.worker is None:
427 time.sleep(poll)
428 cls.report.print_log("Attempt to fetch up-to-date cryptoportfolio")
ada1b5f1
IB
429 cls.get_cryptoportfolio(refetch=True)
430
431 @classmethod
432 def repartition(cls, liquidity="medium"):
433 cls.get_cryptoportfolio()
dc1ca9a3
IB
434 liquidities = cls.liquidities.get(liquidity)
435 return liquidities[cls.last_date.get()]
ada1b5f1
IB
436
437 @classmethod
438 def get_cryptoportfolio(cls, refetch=False):
dc1ca9a3
IB
439 if cls.data.get() is not None and not refetch:
440 return
441 if cls.worker is not None and not cls.is_worker_thread():
442 cls.notify_and_wait()
ada1b5f1
IB
443 return
444 try:
445 r = requests.get(cls.URL)
446 cls.report.log_http_request(r.request.method,
447 r.request.url, r.request.body, r.request.headers, r)
448 except Exception as e:
449 cls.report.log_error("get_cryptoportfolio", exception=e)
450 return
451 try:
dc1ca9a3 452 cls.data.set(r.json(parse_int=D, parse_float=D))
ada1b5f1
IB
453 cls.parse_cryptoportfolio()
454 except (JSONDecodeError, SimpleJSONDecodeError):
dc1ca9a3
IB
455 cls.data.set(None)
456 cls.last_date.set(None)
457 cls.liquidities.set({})
ada1b5f1
IB
458
459 @classmethod
460 def parse_cryptoportfolio(cls):
461 def filter_weights(weight_hash):
462 if weight_hash[1][0] == 0:
463 return False
464 if weight_hash[0] == "_row":
465 return False
466 return True
467
468 def clean_weights(i):
469 def clean_weights_(h):
470 if h[0].endswith("s"):
471 return [h[0][0:-1], (h[1][i], "short")]
472 else:
473 return [h[0], (h[1][i], "long")]
474 return clean_weights_
475
476 def parse_weights(portfolio_hash):
dc1ca9a3
IB
477 if "weights" not in portfolio_hash:
478 return {}
ada1b5f1
IB
479 weights_hash = portfolio_hash["weights"]
480 weights = {}
481 for i in range(len(weights_hash["_row"])):
482 date = datetime.strptime(weights_hash["_row"][i], "%Y-%m-%d")
483 weights[date] = dict(filter(
484 filter_weights,
485 map(clean_weights(i), weights_hash.items())))
486 return weights
487
dc1ca9a3
IB
488 high_liquidity = parse_weights(cls.data.get("portfolio_1"))
489 medium_liquidity = parse_weights(cls.data.get("portfolio_2"))
ada1b5f1 490
dc1ca9a3
IB
491 cls.liquidities.set({
492 "medium": medium_liquidity,
493 "high": high_liquidity,
494 })
495 cls.last_date.set(max(
496 max(medium_liquidity.keys(), default=datetime(1, 1, 1)),
497 max(high_liquidity.keys(), default=datetime(1, 1, 1))
498 ))
ada1b5f1 499
6ca5a1ec 500