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