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