]>
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 | |
ada1b5f1 | 6 | from datetime import date, datetime, timedelta |
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: | |
f86ee140 IB |
14 | def __init__(self, market, verbose_print=True): |
15 | self.market = market | |
16 | self.verbose_print = verbose_print | |
3d0247f9 | 17 | |
718e3e91 | 18 | self.print_logs = [] |
f86ee140 IB |
19 | self.logs = [] |
20 | ||
9bde69bf IB |
21 | def merge(self, other_report): |
22 | self.logs += other_report.logs | |
23 | self.logs.sort(key=lambda x: x["date"]) | |
24 | ||
718e3e91 IB |
25 | self.print_logs += other_report.print_logs |
26 | self.print_logs.sort(key=lambda x: x[0]) | |
27 | ||
f86ee140 | 28 | def print_log(self, message): |
718e3e91 IB |
29 | now = datetime.now() |
30 | message = "{:%Y-%m-%d %H:%M:%S}: {}".format(now, str(message)) | |
31 | self.print_logs.append([now, message]) | |
f86ee140 | 32 | if self.verbose_print: |
3d0247f9 IB |
33 | print(message) |
34 | ||
f86ee140 | 35 | def add_log(self, hash_): |
3d0247f9 | 36 | hash_["date"] = datetime.now() |
f86ee140 | 37 | self.logs.append(hash_) |
3d0247f9 | 38 | |
f86ee140 | 39 | def to_json(self): |
3d0247f9 IB |
40 | def default_json_serial(obj): |
41 | if isinstance(obj, (datetime, date)): | |
42 | return obj.isoformat() | |
be54a201 | 43 | return str(obj) |
f861492d | 44 | return json.dumps(self.logs, default=default_json_serial, indent=" ") |
3d0247f9 | 45 | |
f86ee140 IB |
46 | def set_verbose(self, verbose_print): |
47 | self.verbose_print = verbose_print | |
3d0247f9 | 48 | |
7bd830a8 IB |
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()] | |
f86ee140 | 60 | self.print_log("-" * (len(stage) + 8)) |
7bd830a8 | 61 | self.print_log("[Stage] {} {}".format(stage, ", ".join(args_str))) |
3d0247f9 | 62 | |
f86ee140 | 63 | self.add_log({ |
3d0247f9 IB |
64 | "type": "stage", |
65 | "stage": stage, | |
7bd830a8 | 66 | "args": args, |
3d0247f9 IB |
67 | }) |
68 | ||
f86ee140 IB |
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)) | |
3d0247f9 | 73 | |
f86ee140 | 74 | self.add_log({ |
3d0247f9 | 75 | "type": "balance", |
18167a3c | 76 | "tag": tag, |
f86ee140 | 77 | "balances": self.market.balances.as_json() |
3d0247f9 IB |
78 | }) |
79 | ||
f86ee140 | 80 | def log_tickers(self, amounts, other_currency, |
3d0247f9 IB |
81 | compute_value, type): |
82 | values = {} | |
83 | rates = {} | |
aca4d437 IB |
84 | if callable(compute_value): |
85 | compute_value = inspect.getsource(compute_value).strip() | |
86 | ||
3d0247f9 IB |
87 | for currency, amount in amounts.items(): |
88 | values[currency] = amount.as_json()["value"] | |
89 | rates[currency] = amount.rate | |
f86ee140 | 90 | self.add_log({ |
3d0247f9 IB |
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 | ||
f86ee140 IB |
100 | def log_dispatch(self, amount, amounts, liquidity, repartition): |
101 | self.add_log({ | |
3d0247f9 IB |
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 | ||
f86ee140 | 109 | def log_trades(self, matching_and_trades, only): |
3d0247f9 IB |
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 | ||
f86ee140 | 116 | self.add_log({ |
3d0247f9 IB |
117 | "type": "trades", |
118 | "only": only, | |
f86ee140 | 119 | "debug": self.market.debug, |
3d0247f9 IB |
120 | "trades": trades |
121 | }) | |
122 | ||
f86ee140 | 123 | def log_orders(self, orders, tick=None, only=None, compute_value=None): |
aca4d437 IB |
124 | if callable(compute_value): |
125 | compute_value = inspect.getsource(compute_value).strip() | |
f86ee140 IB |
126 | self.print_log("[Orders]") |
127 | self.market.trades.print_all_with_order(ind="\t") | |
128 | self.add_log({ | |
3d0247f9 IB |
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 | ||
f86ee140 | 136 | def log_order(self, order, tick, finished=False, update=None, |
3d0247f9 | 137 | new_order=None, compute_value=None): |
aca4d437 IB |
138 | if callable(compute_value): |
139 | compute_value = inspect.getsource(compute_value).strip() | |
3d0247f9 | 140 | if finished: |
f86ee140 | 141 | self.print_log("[Order] Finished {}".format(order)) |
3d0247f9 | 142 | elif update == "waiting": |
f86ee140 | 143 | self.print_log("[Order] {}, tick {}, waiting".format(order, tick)) |
3d0247f9 | 144 | elif update == "adjusting": |
f86ee140 | 145 | self.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order)) |
3d0247f9 | 146 | elif update == "market_fallback": |
f86ee140 | 147 | self.print_log("[Order] {}, tick {}, fallbacking to market value".format(order, tick)) |
3d0247f9 | 148 | elif update == "market_adjust": |
f86ee140 | 149 | self.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order, tick, new_order)) |
3d0247f9 | 150 | |
f86ee140 | 151 | self.add_log({ |
3d0247f9 IB |
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 | ||
f86ee140 IB |
160 | def log_move_balances(self, needed, moving): |
161 | self.add_log({ | |
3d0247f9 | 162 | "type": "move_balances", |
f86ee140 | 163 | "debug": self.market.debug, |
3d0247f9 IB |
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 | ||
f86ee140 IB |
168 | def log_http_request(self, method, url, body, headers, response): |
169 | self.add_log({ | |
3d0247f9 IB |
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 | ||
f86ee140 IB |
179 | def log_error(self, action, message=None, exception=None): |
180 | self.print_log("[Error] {}".format(action)) | |
3d0247f9 | 181 | if exception is not None: |
f86ee140 | 182 | self.print_log(str("\t{}: {}".format(exception.__class__.__name__, exception))) |
3d0247f9 | 183 | if message is not None: |
f86ee140 | 184 | self.print_log("\t{}".format(message)) |
3d0247f9 | 185 | |
f86ee140 | 186 | self.add_log({ |
3d0247f9 IB |
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 | ||
f86ee140 IB |
194 | def log_debug_action(self, action): |
195 | self.print_log("[Debug] {}".format(action)) | |
3d0247f9 | 196 | |
f86ee140 | 197 | self.add_log({ |
3d0247f9 IB |
198 | "type": "debug_action", |
199 | "action": action, | |
200 | }) | |
6ca5a1ec IB |
201 | |
202 | class BalanceStore: | |
f86ee140 IB |
203 | def __init__(self, market): |
204 | self.market = market | |
205 | self.all = {} | |
6ca5a1ec | 206 | |
f86ee140 IB |
207 | def currencies(self): |
208 | return self.all.keys() | |
6ca5a1ec | 209 | |
f86ee140 | 210 | def in_currency(self, other_currency, compute_value="average", type="total"): |
6ca5a1ec | 211 | amounts = {} |
f86ee140 | 212 | for currency, balance in self.all.items(): |
6ca5a1ec | 213 | other_currency_amount = getattr(balance, type)\ |
f86ee140 | 214 | .in_currency(other_currency, self.market, compute_value=compute_value) |
6ca5a1ec | 215 | amounts[currency] = other_currency_amount |
f86ee140 | 216 | self.market.report.log_tickers(amounts, other_currency, |
3d0247f9 | 217 | compute_value, type) |
6ca5a1ec IB |
218 | return amounts |
219 | ||
f86ee140 IB |
220 | def fetch_balances(self, tag=None): |
221 | all_balances = self.market.ccxt.fetch_all_balances() | |
6ca5a1ec IB |
222 | for currency, balance in all_balances.items(): |
223 | if balance["exchange_total"] != 0 or balance["margin_total"] != 0 or \ | |
f86ee140 IB |
224 | currency in self.all: |
225 | self.all[currency] = portfolio.Balance(currency, balance) | |
226 | self.market.report.log_balances(tag=tag) | |
6ca5a1ec | 227 | |
f86ee140 | 228 | def dispatch_assets(self, amount, liquidity="medium", repartition=None): |
6ca5a1ec | 229 | if repartition is None: |
ada1b5f1 | 230 | repartition = Portfolio.repartition(liquidity=liquidity) |
6ca5a1ec IB |
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] | |
aca4d437 | 237 | self.all.setdefault(currency, portfolio.Balance(currency, {})) |
f86ee140 | 238 | self.market.report.log_dispatch(amount, amounts, liquidity, repartition) |
6ca5a1ec IB |
239 | return amounts |
240 | ||
f86ee140 IB |
241 | def as_json(self): |
242 | return { k: v.as_json() for k, v in self.all.items() } | |
3d0247f9 | 243 | |
6ca5a1ec | 244 | class TradeStore: |
f86ee140 IB |
245 | def __init__(self, market): |
246 | self.market = market | |
247 | self.all = [] | |
6ca5a1ec | 248 | |
aca4d437 IB |
249 | @property |
250 | def pending(self): | |
17598517 | 251 | return list(filter(lambda t: t.pending, self.all)) |
aca4d437 | 252 | |
f86ee140 | 253 | def compute_trades(self, values_in_base, new_repartition, only=None): |
3d0247f9 | 254 | computed_trades = [] |
6ca5a1ec | 255 | base_currency = sum(values_in_base.values()).currency |
f86ee140 | 256 | for currency in self.market.balances.currencies(): |
6ca5a1ec IB |
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)) | |
1aa7d4fa | 261 | |
6ca5a1ec | 262 | if value_from.value * value_to.value < 0: |
f86ee140 | 263 | computed_trades.append(self.trade_if_matching( |
1aa7d4fa | 264 | value_from, portfolio.Amount(base_currency, 0), |
f86ee140 IB |
265 | currency, only=only)) |
266 | computed_trades.append(self.trade_if_matching( | |
1aa7d4fa | 267 | portfolio.Amount(base_currency, 0), value_to, |
f86ee140 | 268 | currency, only=only)) |
6ca5a1ec | 269 | else: |
f86ee140 | 270 | computed_trades.append(self.trade_if_matching( |
3d0247f9 | 271 | value_from, value_to, |
f86ee140 | 272 | currency, only=only)) |
3d0247f9 IB |
273 | for matching, trade in computed_trades: |
274 | if matching: | |
f86ee140 IB |
275 | self.all.append(trade) |
276 | self.market.report.log_trades(computed_trades, only) | |
1aa7d4fa | 277 | |
f86ee140 IB |
278 | def trade_if_matching(self, value_from, value_to, currency, |
279 | only=None): | |
1aa7d4fa | 280 | trade = portfolio.Trade(value_from, value_to, currency, |
f86ee140 | 281 | self.market) |
3d0247f9 IB |
282 | matching = only is None or trade.action == only |
283 | return [matching, trade] | |
6ca5a1ec | 284 | |
f86ee140 | 285 | def prepare_orders(self, only=None, compute_value="default"): |
3d0247f9 | 286 | orders = [] |
aca4d437 | 287 | for trade in self.pending: |
6ca5a1ec | 288 | if only is None or trade.action == only: |
3d0247f9 | 289 | orders.append(trade.prepare_order(compute_value=compute_value)) |
f86ee140 | 290 | self.market.report.log_orders(orders, only, compute_value) |
6ca5a1ec | 291 | |
17598517 IB |
292 | def close_trades(self): |
293 | for trade in self.all: | |
294 | trade.close() | |
295 | ||
f86ee140 IB |
296 | def print_all_with_order(self, ind=""): |
297 | for trade in self.all: | |
3d0247f9 | 298 | trade.print_with_order(ind=ind) |
6ca5a1ec | 299 | |
f86ee140 IB |
300 | def run_orders(self): |
301 | orders = self.all_orders(state="pending") | |
3d0247f9 | 302 | for order in orders: |
6ca5a1ec | 303 | order.run() |
f86ee140 IB |
304 | self.market.report.log_stage("run_orders") |
305 | self.market.report.log_orders(orders) | |
6ca5a1ec | 306 | |
f86ee140 IB |
307 | def all_orders(self, state=None): |
308 | all_orders = sum(map(lambda v: v.orders, self.all), []) | |
6ca5a1ec IB |
309 | if state is None: |
310 | return all_orders | |
311 | else: | |
312 | return list(filter(lambda o: o.status == state, all_orders)) | |
313 | ||
f86ee140 IB |
314 | def update_all_orders_status(self): |
315 | for order in self.all_orders(state="open"): | |
6ca5a1ec IB |
316 | order.get_status() |
317 | ||
dc1ca9a3 IB |
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 | ||
ada1b5f1 IB |
348 | class Portfolio: |
349 | URL = "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json" | |
dc1ca9a3 IB |
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) | |
ada1b5f1 IB |
394 | |
395 | @classmethod | |
dc1ca9a3 IB |
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): | |
ada1b5f1 | 403 | cls.get_cryptoportfolio() |
dc1ca9a3 IB |
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") | |
ada1b5f1 IB |
408 | cls.get_cryptoportfolio(refetch=True) |
409 | ||
410 | @classmethod | |
411 | def repartition(cls, liquidity="medium"): | |
412 | cls.get_cryptoportfolio() | |
dc1ca9a3 IB |
413 | liquidities = cls.liquidities.get(liquidity) |
414 | return liquidities[cls.last_date.get()] | |
ada1b5f1 IB |
415 | |
416 | @classmethod | |
417 | def get_cryptoportfolio(cls, refetch=False): | |
dc1ca9a3 IB |
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() | |
ada1b5f1 IB |
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: | |
dc1ca9a3 | 431 | cls.data.set(r.json(parse_int=D, parse_float=D)) |
ada1b5f1 IB |
432 | cls.parse_cryptoportfolio() |
433 | except (JSONDecodeError, SimpleJSONDecodeError): | |
dc1ca9a3 IB |
434 | cls.data.set(None) |
435 | cls.last_date.set(None) | |
436 | cls.liquidities.set({}) | |
ada1b5f1 IB |
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): | |
dc1ca9a3 IB |
456 | if "weights" not in portfolio_hash: |
457 | return {} | |
ada1b5f1 IB |
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 | ||
dc1ca9a3 IB |
467 | high_liquidity = parse_weights(cls.data.get("portfolio_1")) |
468 | medium_liquidity = parse_weights(cls.data.get("portfolio_2")) | |
ada1b5f1 | 469 | |
dc1ca9a3 IB |
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 | )) | |
ada1b5f1 | 478 | |
6ca5a1ec | 479 |