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