]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blame - store.py
Fix ccxt switching currency codes
[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,
e7d7c0e5
IB
214 "response": None,
215 "response_same_as": self.last_http["date"]
216 })
217 else:
218 self.last_http = self.add_log({
219 "type": "http_request",
220 "method": method,
221 "url": url,
222 "body": body,
223 "headers": headers,
224 "status": response.status_code,
225 "response": response.text,
226 "response_same_as": None,
d8e233ac 227 })
3d0247f9 228
f86ee140
IB
229 def log_error(self, action, message=None, exception=None):
230 self.print_log("[Error] {}".format(action))
3d0247f9 231 if exception is not None:
f86ee140 232 self.print_log(str("\t{}: {}".format(exception.__class__.__name__, exception)))
3d0247f9 233 if message is not None:
f86ee140 234 self.print_log("\t{}".format(message))
3d0247f9 235
f86ee140 236 self.add_log({
3d0247f9
IB
237 "type": "error",
238 "action": action,
239 "exception_class": exception.__class__.__name__ if exception is not None else None,
240 "exception_message": str(exception) if exception is not None else None,
241 "message": message,
242 })
243
f86ee140
IB
244 def log_debug_action(self, action):
245 self.print_log("[Debug] {}".format(action))
3d0247f9 246
f86ee140 247 self.add_log({
3d0247f9
IB
248 "type": "debug_action",
249 "action": action,
250 })
6ca5a1ec 251
e7d7c0e5 252 def log_market(self, args):
90d7423e
IB
253 self.add_log({
254 "type": "market",
255 "commit": "$Format:%H$",
256 "args": vars(args),
90d7423e
IB
257 })
258
6ca5a1ec 259class BalanceStore:
f86ee140
IB
260 def __init__(self, market):
261 self.market = market
262 self.all = {}
6ca5a1ec 263
f86ee140
IB
264 def currencies(self):
265 return self.all.keys()
6ca5a1ec 266
f86ee140 267 def in_currency(self, other_currency, compute_value="average", type="total"):
6ca5a1ec 268 amounts = {}
f86ee140 269 for currency, balance in self.all.items():
6ca5a1ec 270 other_currency_amount = getattr(balance, type)\
f86ee140 271 .in_currency(other_currency, self.market, compute_value=compute_value)
6ca5a1ec 272 amounts[currency] = other_currency_amount
f86ee140 273 self.market.report.log_tickers(amounts, other_currency,
3d0247f9 274 compute_value, type)
6ca5a1ec
IB
275 return amounts
276
f86ee140
IB
277 def fetch_balances(self, tag=None):
278 all_balances = self.market.ccxt.fetch_all_balances()
6ca5a1ec
IB
279 for currency, balance in all_balances.items():
280 if balance["exchange_total"] != 0 or balance["margin_total"] != 0 or \
f86ee140
IB
281 currency in self.all:
282 self.all[currency] = portfolio.Balance(currency, balance)
283 self.market.report.log_balances(tag=tag)
6ca5a1ec 284
f86ee140 285 def dispatch_assets(self, amount, liquidity="medium", repartition=None):
6ca5a1ec 286 if repartition is None:
ada1b5f1 287 repartition = Portfolio.repartition(liquidity=liquidity)
6ca5a1ec
IB
288 sum_ratio = sum([v[0] for k, v in repartition.items()])
289 amounts = {}
290 for currency, (ptt, trade_type) in repartition.items():
291 amounts[currency] = ptt * amount / sum_ratio
292 if trade_type == "short":
293 amounts[currency] = - amounts[currency]
aca4d437 294 self.all.setdefault(currency, portfolio.Balance(currency, {}))
f86ee140 295 self.market.report.log_dispatch(amount, amounts, liquidity, repartition)
6ca5a1ec
IB
296 return amounts
297
f86ee140
IB
298 def as_json(self):
299 return { k: v.as_json() for k, v in self.all.items() }
3d0247f9 300
6ca5a1ec 301class TradeStore:
f86ee140
IB
302 def __init__(self, market):
303 self.market = market
304 self.all = []
6ca5a1ec 305
aca4d437
IB
306 @property
307 def pending(self):
17598517 308 return list(filter(lambda t: t.pending, self.all))
aca4d437 309
f86ee140 310 def compute_trades(self, values_in_base, new_repartition, only=None):
3d0247f9 311 computed_trades = []
6ca5a1ec 312 base_currency = sum(values_in_base.values()).currency
f86ee140 313 for currency in self.market.balances.currencies():
6ca5a1ec
IB
314 if currency == base_currency:
315 continue
316 value_from = values_in_base.get(currency, portfolio.Amount(base_currency, 0))
317 value_to = new_repartition.get(currency, portfolio.Amount(base_currency, 0))
1aa7d4fa 318
6ca5a1ec 319 if value_from.value * value_to.value < 0:
f86ee140 320 computed_trades.append(self.trade_if_matching(
1aa7d4fa 321 value_from, portfolio.Amount(base_currency, 0),
f86ee140
IB
322 currency, only=only))
323 computed_trades.append(self.trade_if_matching(
1aa7d4fa 324 portfolio.Amount(base_currency, 0), value_to,
f86ee140 325 currency, only=only))
6ca5a1ec 326 else:
f86ee140 327 computed_trades.append(self.trade_if_matching(
3d0247f9 328 value_from, value_to,
f86ee140 329 currency, only=only))
3d0247f9
IB
330 for matching, trade in computed_trades:
331 if matching:
f86ee140
IB
332 self.all.append(trade)
333 self.market.report.log_trades(computed_trades, only)
1aa7d4fa 334
f86ee140
IB
335 def trade_if_matching(self, value_from, value_to, currency,
336 only=None):
1aa7d4fa 337 trade = portfolio.Trade(value_from, value_to, currency,
f86ee140 338 self.market)
3d0247f9
IB
339 matching = only is None or trade.action == only
340 return [matching, trade]
6ca5a1ec 341
f86ee140 342 def prepare_orders(self, only=None, compute_value="default"):
3d0247f9 343 orders = []
aca4d437 344 for trade in self.pending:
6ca5a1ec 345 if only is None or trade.action == only:
3d0247f9 346 orders.append(trade.prepare_order(compute_value=compute_value))
f86ee140 347 self.market.report.log_orders(orders, only, compute_value)
6ca5a1ec 348
17598517
IB
349 def close_trades(self):
350 for trade in self.all:
351 trade.close()
352
f86ee140
IB
353 def print_all_with_order(self, ind=""):
354 for trade in self.all:
3d0247f9 355 trade.print_with_order(ind=ind)
6ca5a1ec 356
f86ee140
IB
357 def run_orders(self):
358 orders = self.all_orders(state="pending")
3d0247f9 359 for order in orders:
6ca5a1ec 360 order.run()
f86ee140
IB
361 self.market.report.log_stage("run_orders")
362 self.market.report.log_orders(orders)
6ca5a1ec 363
f86ee140
IB
364 def all_orders(self, state=None):
365 all_orders = sum(map(lambda v: v.orders, self.all), [])
6ca5a1ec
IB
366 if state is None:
367 return all_orders
368 else:
369 return list(filter(lambda o: o.status == state, all_orders))
370
f86ee140
IB
371 def update_all_orders_status(self):
372 for order in self.all_orders(state="open"):
6ca5a1ec
IB
373 order.get_status()
374
dc1ca9a3
IB
375class NoopLock:
376 def __enter__(self, *args):
377 pass
378 def __exit__(self, *args):
379 pass
380
381class LockedVar:
382 def __init__(self, value):
383 self.lock = NoopLock()
384 self.val = value
385
386 def start_lock(self):
387 import threading
388 self.lock = threading.Lock()
389
390 def set(self, value):
391 with self.lock:
392 self.val = value
393
394 def get(self, key=None):
395 with self.lock:
396 if key is not None and isinstance(self.val, dict):
397 return self.val.get(key)
398 else:
399 return self.val
400
401 def __getattr__(self, key):
402 with self.lock:
403 return getattr(self.val, key)
404
ada1b5f1
IB
405class Portfolio:
406 URL = "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json"
dc1ca9a3
IB
407 data = LockedVar(None)
408 liquidities = LockedVar({})
409 last_date = LockedVar(None)
e7d7c0e5 410 report = LockedVar(ReportStore(None, no_http_dup=True))
dc1ca9a3 411 worker = None
a0dcf4e0 412 worker_tag = ""
dc1ca9a3
IB
413 worker_started = False
414 worker_notify = None
415 callback = None
416
417 @classmethod
418 def start_worker(cls, poll=30):
419 import threading
420
421 cls.worker = threading.Thread(name="portfolio", daemon=True,
422 target=cls.wait_for_notification, kwargs={"poll": poll})
423 cls.worker_notify = threading.Event()
424 cls.callback = threading.Event()
425
426 cls.last_date.start_lock()
427 cls.liquidities.start_lock()
428 cls.report.start_lock()
429
a0dcf4e0 430 cls.worker_tag = "[Worker] "
dc1ca9a3
IB
431 cls.worker_started = True
432 cls.worker.start()
433
434 @classmethod
435 def is_worker_thread(cls):
436 if cls.worker is None:
437 return False
438 else:
439 import threading
440 return cls.worker == threading.current_thread()
441
442 @classmethod
443 def wait_for_notification(cls, poll=30):
444 if not cls.is_worker_thread():
445 raise RuntimeError("This method needs to be ran with the worker")
446 while cls.worker_started:
447 cls.worker_notify.wait()
e7d7c0e5
IB
448 if cls.worker_started:
449 cls.worker_notify.clear()
a0dcf4e0 450 cls.report.print_log("[Worker] Fetching cryptoportfolio")
e7d7c0e5
IB
451 cls.get_cryptoportfolio(refetch=True)
452 cls.callback.set()
453 time.sleep(poll)
454
455 @classmethod
456 def stop_worker(cls):
457 cls.worker_started = False
458 cls.worker_notify.set()
ada1b5f1
IB
459
460 @classmethod
dc1ca9a3
IB
461 def notify_and_wait(cls):
462 cls.callback.clear()
463 cls.worker_notify.set()
464 cls.callback.wait()
465
466 @classmethod
467 def wait_for_recent(cls, delta=4, poll=30):
ada1b5f1 468 cls.get_cryptoportfolio()
e7d7c0e5 469 while cls.last_date.get() is None or datetime.datetime.now() - cls.last_date.get() > datetime.timedelta(delta):
dc1ca9a3
IB
470 if cls.worker is None:
471 time.sleep(poll)
472 cls.report.print_log("Attempt to fetch up-to-date cryptoportfolio")
ada1b5f1
IB
473 cls.get_cryptoportfolio(refetch=True)
474
475 @classmethod
476 def repartition(cls, liquidity="medium"):
477 cls.get_cryptoportfolio()
dc1ca9a3
IB
478 liquidities = cls.liquidities.get(liquidity)
479 return liquidities[cls.last_date.get()]
ada1b5f1
IB
480
481 @classmethod
482 def get_cryptoportfolio(cls, refetch=False):
dc1ca9a3
IB
483 if cls.data.get() is not None and not refetch:
484 return
485 if cls.worker is not None and not cls.is_worker_thread():
486 cls.notify_and_wait()
ada1b5f1
IB
487 return
488 try:
489 r = requests.get(cls.URL)
490 cls.report.log_http_request(r.request.method,
491 r.request.url, r.request.body, r.request.headers, r)
492 except Exception as e:
a0dcf4e0 493 cls.report.log_error("{}get_cryptoportfolio".format(cls.worker_tag), exception=e)
ada1b5f1
IB
494 return
495 try:
dc1ca9a3 496 cls.data.set(r.json(parse_int=D, parse_float=D))
ada1b5f1
IB
497 cls.parse_cryptoportfolio()
498 except (JSONDecodeError, SimpleJSONDecodeError):
dc1ca9a3
IB
499 cls.data.set(None)
500 cls.last_date.set(None)
501 cls.liquidities.set({})
ada1b5f1
IB
502
503 @classmethod
504 def parse_cryptoportfolio(cls):
505 def filter_weights(weight_hash):
506 if weight_hash[1][0] == 0:
507 return False
508 if weight_hash[0] == "_row":
509 return False
510 return True
511
512 def clean_weights(i):
513 def clean_weights_(h):
514 if h[0].endswith("s"):
515 return [h[0][0:-1], (h[1][i], "short")]
516 else:
517 return [h[0], (h[1][i], "long")]
518 return clean_weights_
519
520 def parse_weights(portfolio_hash):
dc1ca9a3
IB
521 if "weights" not in portfolio_hash:
522 return {}
ada1b5f1
IB
523 weights_hash = portfolio_hash["weights"]
524 weights = {}
525 for i in range(len(weights_hash["_row"])):
e7d7c0e5 526 date = datetime.datetime.strptime(weights_hash["_row"][i], "%Y-%m-%d")
ada1b5f1
IB
527 weights[date] = dict(filter(
528 filter_weights,
529 map(clean_weights(i), weights_hash.items())))
530 return weights
531
dc1ca9a3
IB
532 high_liquidity = parse_weights(cls.data.get("portfolio_1"))
533 medium_liquidity = parse_weights(cls.data.get("portfolio_2"))
ada1b5f1 534
dc1ca9a3
IB
535 cls.liquidities.set({
536 "medium": medium_liquidity,
537 "high": high_liquidity,
538 })
539 cls.last_date.set(max(
e7d7c0e5
IB
540 max(medium_liquidity.keys(), default=datetime.datetime(1, 1, 1)),
541 max(high_liquidity.keys(), default=datetime.datetime(1, 1, 1))
dc1ca9a3 542 ))
ada1b5f1 543