]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blame - store.py
Use generic parser for market processing
[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
e7d7c0e5 6import datetime
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:
e7d7c0e5 14 def __init__(self, market, verbose_print=True, no_http_dup=False):
f86ee140
IB
15 self.market = market
16 self.verbose_print = verbose_print
3d0247f9 17
718e3e91 18 self.print_logs = []
f86ee140
IB
19 self.logs = []
20
e7d7c0e5
IB
21 self.no_http_dup = no_http_dup
22 self.last_http = None
23
9bde69bf
IB
24 def merge(self, other_report):
25 self.logs += other_report.logs
26 self.logs.sort(key=lambda x: x["date"])
27
718e3e91
IB
28 self.print_logs += other_report.print_logs
29 self.print_logs.sort(key=lambda x: x[0])
30
f86ee140 31 def print_log(self, message):
e7d7c0e5 32 now = datetime.datetime.now()
718e3e91
IB
33 message = "{:%Y-%m-%d %H:%M:%S}: {}".format(now, str(message))
34 self.print_logs.append([now, message])
f86ee140 35 if self.verbose_print:
3d0247f9
IB
36 print(message)
37
f86ee140 38 def add_log(self, hash_):
e7d7c0e5
IB
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
f86ee140 46 self.logs.append(hash_)
e7d7c0e5 47 return hash_
3d0247f9 48
b4e0ba0b
IB
49 @staticmethod
50 def default_json_serial(obj):
e7d7c0e5 51 if isinstance(obj, (datetime.datetime, datetime.date)):
b4e0ba0b
IB
52 return obj.isoformat()
53 return str(obj)
54
f86ee140 55 def to_json(self):
b4e0ba0b
IB
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 )
3d0247f9 65
f86ee140
IB
66 def set_verbose(self, verbose_print):
67 self.verbose_print = verbose_print
3d0247f9 68
7bd830a8
IB
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()]
f86ee140 80 self.print_log("-" * (len(stage) + 8))
7bd830a8 81 self.print_log("[Stage] {} {}".format(stage, ", ".join(args_str)))
3d0247f9 82
f86ee140 83 self.add_log({
3d0247f9
IB
84 "type": "stage",
85 "stage": stage,
7bd830a8 86 "args": args,
3d0247f9
IB
87 })
88
f86ee140
IB
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))
3d0247f9 93
f86ee140 94 self.add_log({
3d0247f9 95 "type": "balance",
18167a3c 96 "tag": tag,
f86ee140 97 "balances": self.market.balances.as_json()
3d0247f9
IB
98 })
99
f86ee140 100 def log_tickers(self, amounts, other_currency,
3d0247f9
IB
101 compute_value, type):
102 values = {}
103 rates = {}
aca4d437
IB
104 if callable(compute_value):
105 compute_value = inspect.getsource(compute_value).strip()
106
3d0247f9
IB
107 for currency, amount in amounts.items():
108 values[currency] = amount.as_json()["value"]
109 rates[currency] = amount.rate
f86ee140 110 self.add_log({
3d0247f9
IB
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
f86ee140
IB
120 def log_dispatch(self, amount, amounts, liquidity, repartition):
121 self.add_log({
3d0247f9
IB
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
f86ee140 129 def log_trades(self, matching_and_trades, only):
3d0247f9
IB
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
f86ee140 136 self.add_log({
3d0247f9
IB
137 "type": "trades",
138 "only": only,
f86ee140 139 "debug": self.market.debug,
3d0247f9
IB
140 "trades": trades
141 })
142
f86ee140 143 def log_orders(self, orders, tick=None, only=None, compute_value=None):
aca4d437
IB
144 if callable(compute_value):
145 compute_value = inspect.getsource(compute_value).strip()
f86ee140
IB
146 self.print_log("[Orders]")
147 self.market.trades.print_all_with_order(ind="\t")
148 self.add_log({
3d0247f9
IB
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
f86ee140 156 def log_order(self, order, tick, finished=False, update=None,
3d0247f9 157 new_order=None, compute_value=None):
aca4d437
IB
158 if callable(compute_value):
159 compute_value = inspect.getsource(compute_value).strip()
3d0247f9 160 if finished:
f86ee140 161 self.print_log("[Order] Finished {}".format(order))
3d0247f9 162 elif update == "waiting":
f86ee140 163 self.print_log("[Order] {}, tick {}, waiting".format(order, tick))
3d0247f9 164 elif update == "adjusting":
f86ee140 165 self.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order))
3d0247f9 166 elif update == "market_fallback":
f86ee140 167 self.print_log("[Order] {}, tick {}, fallbacking to market value".format(order, tick))
3d0247f9 168 elif update == "market_adjust":
f86ee140 169 self.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order, tick, new_order))
3d0247f9 170
f86ee140 171 self.add_log({
3d0247f9
IB
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
f86ee140
IB
180 def log_move_balances(self, needed, moving):
181 self.add_log({
3d0247f9 182 "type": "move_balances",
f86ee140 183 "debug": self.market.debug,
3d0247f9
IB
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
f86ee140 188 def log_http_request(self, method, url, body, headers, response):
d8e233ac
IB
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 })
e7d7c0e5
IB
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:
d8e233ac
IB
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,
9fe90554 214 "duration": response.elapsed.total_seconds(),
e7d7c0e5
IB
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,
9fe90554 226 "duration": response.elapsed.total_seconds(),
e7d7c0e5
IB
227 "response": response.text,
228 "response_same_as": None,
d8e233ac 229 })
3d0247f9 230
f86ee140
IB
231 def log_error(self, action, message=None, exception=None):
232 self.print_log("[Error] {}".format(action))
3d0247f9 233 if exception is not None:
f86ee140 234 self.print_log(str("\t{}: {}".format(exception.__class__.__name__, exception)))
3d0247f9 235 if message is not None:
f86ee140 236 self.print_log("\t{}".format(message))
3d0247f9 237
f86ee140 238 self.add_log({
3d0247f9
IB
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
f86ee140
IB
246 def log_debug_action(self, action):
247 self.print_log("[Debug] {}".format(action))
3d0247f9 248
f86ee140 249 self.add_log({
3d0247f9
IB
250 "type": "debug_action",
251 "action": action,
252 })
6ca5a1ec 253
e7d7c0e5 254 def log_market(self, args):
90d7423e
IB
255 self.add_log({
256 "type": "market",
257 "commit": "$Format:%H$",
258 "args": vars(args),
90d7423e
IB
259 })
260
6ca5a1ec 261class BalanceStore:
f86ee140
IB
262 def __init__(self, market):
263 self.market = market
264 self.all = {}
6ca5a1ec 265
f86ee140
IB
266 def currencies(self):
267 return self.all.keys()
6ca5a1ec 268
f86ee140 269 def in_currency(self, other_currency, compute_value="average", type="total"):
6ca5a1ec 270 amounts = {}
f86ee140 271 for currency, balance in self.all.items():
6ca5a1ec 272 other_currency_amount = getattr(balance, type)\
f86ee140 273 .in_currency(other_currency, self.market, compute_value=compute_value)
6ca5a1ec 274 amounts[currency] = other_currency_amount
f86ee140 275 self.market.report.log_tickers(amounts, other_currency,
3d0247f9 276 compute_value, type)
6ca5a1ec
IB
277 return amounts
278
f86ee140
IB
279 def fetch_balances(self, tag=None):
280 all_balances = self.market.ccxt.fetch_all_balances()
6ca5a1ec
IB
281 for currency, balance in all_balances.items():
282 if balance["exchange_total"] != 0 or balance["margin_total"] != 0 or \
f86ee140
IB
283 currency in self.all:
284 self.all[currency] = portfolio.Balance(currency, balance)
285 self.market.report.log_balances(tag=tag)
6ca5a1ec 286
f86ee140 287 def dispatch_assets(self, amount, liquidity="medium", repartition=None):
6ca5a1ec 288 if repartition is None:
ada1b5f1 289 repartition = Portfolio.repartition(liquidity=liquidity)
6ca5a1ec
IB
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]
aca4d437 296 self.all.setdefault(currency, portfolio.Balance(currency, {}))
f86ee140 297 self.market.report.log_dispatch(amount, amounts, liquidity, repartition)
6ca5a1ec
IB
298 return amounts
299
f86ee140
IB
300 def as_json(self):
301 return { k: v.as_json() for k, v in self.all.items() }
3d0247f9 302
6ca5a1ec 303class TradeStore:
f86ee140
IB
304 def __init__(self, market):
305 self.market = market
306 self.all = []
6ca5a1ec 307
aca4d437
IB
308 @property
309 def pending(self):
17598517 310 return list(filter(lambda t: t.pending, self.all))
aca4d437 311
f86ee140 312 def compute_trades(self, values_in_base, new_repartition, only=None):
3d0247f9 313 computed_trades = []
6ca5a1ec 314 base_currency = sum(values_in_base.values()).currency
f86ee140 315 for currency in self.market.balances.currencies():
6ca5a1ec
IB
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))
1aa7d4fa 320
6ca5a1ec 321 if value_from.value * value_to.value < 0:
f86ee140 322 computed_trades.append(self.trade_if_matching(
1aa7d4fa 323 value_from, portfolio.Amount(base_currency, 0),
f86ee140
IB
324 currency, only=only))
325 computed_trades.append(self.trade_if_matching(
1aa7d4fa 326 portfolio.Amount(base_currency, 0), value_to,
f86ee140 327 currency, only=only))
6ca5a1ec 328 else:
f86ee140 329 computed_trades.append(self.trade_if_matching(
3d0247f9 330 value_from, value_to,
f86ee140 331 currency, only=only))
3d0247f9
IB
332 for matching, trade in computed_trades:
333 if matching:
f86ee140
IB
334 self.all.append(trade)
335 self.market.report.log_trades(computed_trades, only)
1aa7d4fa 336
f86ee140
IB
337 def trade_if_matching(self, value_from, value_to, currency,
338 only=None):
1aa7d4fa 339 trade = portfolio.Trade(value_from, value_to, currency,
f86ee140 340 self.market)
3d0247f9
IB
341 matching = only is None or trade.action == only
342 return [matching, trade]
6ca5a1ec 343
f86ee140 344 def prepare_orders(self, only=None, compute_value="default"):
3d0247f9 345 orders = []
aca4d437 346 for trade in self.pending:
6ca5a1ec 347 if only is None or trade.action == only:
3d0247f9 348 orders.append(trade.prepare_order(compute_value=compute_value))
f86ee140 349 self.market.report.log_orders(orders, only, compute_value)
6ca5a1ec 350
17598517
IB
351 def close_trades(self):
352 for trade in self.all:
353 trade.close()
354
f86ee140
IB
355 def print_all_with_order(self, ind=""):
356 for trade in self.all:
3d0247f9 357 trade.print_with_order(ind=ind)
6ca5a1ec 358
f86ee140
IB
359 def run_orders(self):
360 orders = self.all_orders(state="pending")
3d0247f9 361 for order in orders:
6ca5a1ec 362 order.run()
f86ee140
IB
363 self.market.report.log_stage("run_orders")
364 self.market.report.log_orders(orders)
6ca5a1ec 365
f86ee140
IB
366 def all_orders(self, state=None):
367 all_orders = sum(map(lambda v: v.orders, self.all), [])
6ca5a1ec
IB
368 if state is None:
369 return all_orders
370 else:
371 return list(filter(lambda o: o.status == state, all_orders))
372
f86ee140
IB
373 def update_all_orders_status(self):
374 for order in self.all_orders(state="open"):
6ca5a1ec
IB
375 order.get_status()
376
dc1ca9a3
IB
377class NoopLock:
378 def __enter__(self, *args):
379 pass
380 def __exit__(self, *args):
381 pass
382
383class 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
ada1b5f1
IB
407class Portfolio:
408 URL = "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json"
dc1ca9a3
IB
409 data = LockedVar(None)
410 liquidities = LockedVar({})
411 last_date = LockedVar(None)
e7d7c0e5 412 report = LockedVar(ReportStore(None, no_http_dup=True))
dc1ca9a3 413 worker = None
a0dcf4e0 414 worker_tag = ""
dc1ca9a3
IB
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
a0dcf4e0 432 cls.worker_tag = "[Worker] "
dc1ca9a3
IB
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()
e7d7c0e5
IB
450 if cls.worker_started:
451 cls.worker_notify.clear()
a0dcf4e0 452 cls.report.print_log("[Worker] Fetching cryptoportfolio")
e7d7c0e5
IB
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()
ada1b5f1
IB
461
462 @classmethod
dc1ca9a3
IB
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):
ada1b5f1 470 cls.get_cryptoportfolio()
e7d7c0e5 471 while cls.last_date.get() is None or datetime.datetime.now() - cls.last_date.get() > datetime.timedelta(delta):
dc1ca9a3
IB
472 if cls.worker is None:
473 time.sleep(poll)
474 cls.report.print_log("Attempt to fetch up-to-date cryptoportfolio")
ada1b5f1
IB
475 cls.get_cryptoportfolio(refetch=True)
476
477 @classmethod
478 def repartition(cls, liquidity="medium"):
479 cls.get_cryptoportfolio()
dc1ca9a3
IB
480 liquidities = cls.liquidities.get(liquidity)
481 return liquidities[cls.last_date.get()]
ada1b5f1
IB
482
483 @classmethod
484 def get_cryptoportfolio(cls, refetch=False):
dc1ca9a3
IB
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()
ada1b5f1
IB
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:
a0dcf4e0 495 cls.report.log_error("{}get_cryptoportfolio".format(cls.worker_tag), exception=e)
ada1b5f1
IB
496 return
497 try:
dc1ca9a3 498 cls.data.set(r.json(parse_int=D, parse_float=D))
ada1b5f1
IB
499 cls.parse_cryptoportfolio()
500 except (JSONDecodeError, SimpleJSONDecodeError):
dc1ca9a3
IB
501 cls.data.set(None)
502 cls.last_date.set(None)
503 cls.liquidities.set({})
ada1b5f1
IB
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):
dc1ca9a3
IB
523 if "weights" not in portfolio_hash:
524 return {}
ada1b5f1
IB
525 weights_hash = portfolio_hash["weights"]
526 weights = {}
527 for i in range(len(weights_hash["_row"])):
e7d7c0e5 528 date = datetime.datetime.strptime(weights_hash["_row"][i], "%Y-%m-%d")
ada1b5f1
IB
529 weights[date] = dict(filter(
530 filter_weights,
531 map(clean_weights(i), weights_hash.items())))
532 return weights
533
dc1ca9a3
IB
534 high_liquidity = parse_weights(cls.data.get("portfolio_1"))
535 medium_liquidity = parse_weights(cls.data.get("portfolio_2"))
ada1b5f1 536
dc1ca9a3
IB
537 cls.liquidities.set({
538 "medium": medium_liquidity,
539 "high": high_liquidity,
540 })
541 cls.last_date.set(max(
e7d7c0e5
IB
542 max(medium_liquidity.keys(), default=datetime.datetime(1, 1, 1)),
543 max(high_liquidity.keys(), default=datetime.datetime(1, 1, 1))
dc1ca9a3 544 ))
ada1b5f1 545