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