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