]>
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 | |
f86ee140 IB |
18 | self.logs = [] |
19 | ||
9bde69bf IB |
20 | def merge(self, other_report): |
21 | self.logs += other_report.logs | |
22 | self.logs.sort(key=lambda x: x["date"]) | |
23 | ||
f86ee140 | 24 | def print_log(self, message): |
3d0247f9 | 25 | message = str(message) |
f86ee140 | 26 | if self.verbose_print: |
3d0247f9 IB |
27 | print(message) |
28 | ||
f86ee140 | 29 | def add_log(self, hash_): |
3d0247f9 | 30 | hash_["date"] = datetime.now() |
f86ee140 | 31 | self.logs.append(hash_) |
3d0247f9 | 32 | |
f86ee140 | 33 | def to_json(self): |
3d0247f9 IB |
34 | def default_json_serial(obj): |
35 | if isinstance(obj, (datetime, date)): | |
36 | return obj.isoformat() | |
be54a201 | 37 | return str(obj) |
f861492d | 38 | return json.dumps(self.logs, default=default_json_serial, indent=" ") |
3d0247f9 | 39 | |
f86ee140 IB |
40 | def set_verbose(self, verbose_print): |
41 | self.verbose_print = verbose_print | |
3d0247f9 | 42 | |
7bd830a8 IB |
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()] | |
f86ee140 | 54 | self.print_log("-" * (len(stage) + 8)) |
7bd830a8 | 55 | self.print_log("[Stage] {} {}".format(stage, ", ".join(args_str))) |
3d0247f9 | 56 | |
f86ee140 | 57 | self.add_log({ |
3d0247f9 IB |
58 | "type": "stage", |
59 | "stage": stage, | |
7bd830a8 | 60 | "args": args, |
3d0247f9 IB |
61 | }) |
62 | ||
f86ee140 IB |
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)) | |
3d0247f9 | 67 | |
f86ee140 | 68 | self.add_log({ |
3d0247f9 | 69 | "type": "balance", |
18167a3c | 70 | "tag": tag, |
f86ee140 | 71 | "balances": self.market.balances.as_json() |
3d0247f9 IB |
72 | }) |
73 | ||
f86ee140 | 74 | def log_tickers(self, amounts, other_currency, |
3d0247f9 IB |
75 | compute_value, type): |
76 | values = {} | |
77 | rates = {} | |
aca4d437 IB |
78 | if callable(compute_value): |
79 | compute_value = inspect.getsource(compute_value).strip() | |
80 | ||
3d0247f9 IB |
81 | for currency, amount in amounts.items(): |
82 | values[currency] = amount.as_json()["value"] | |
83 | rates[currency] = amount.rate | |
f86ee140 | 84 | self.add_log({ |
3d0247f9 IB |
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 | ||
f86ee140 IB |
94 | def log_dispatch(self, amount, amounts, liquidity, repartition): |
95 | self.add_log({ | |
3d0247f9 IB |
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 | ||
f86ee140 | 103 | def log_trades(self, matching_and_trades, only): |
3d0247f9 IB |
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 | ||
f86ee140 | 110 | self.add_log({ |
3d0247f9 IB |
111 | "type": "trades", |
112 | "only": only, | |
f86ee140 | 113 | "debug": self.market.debug, |
3d0247f9 IB |
114 | "trades": trades |
115 | }) | |
116 | ||
f86ee140 | 117 | def log_orders(self, orders, tick=None, only=None, compute_value=None): |
aca4d437 IB |
118 | if callable(compute_value): |
119 | compute_value = inspect.getsource(compute_value).strip() | |
f86ee140 IB |
120 | self.print_log("[Orders]") |
121 | self.market.trades.print_all_with_order(ind="\t") | |
122 | self.add_log({ | |
3d0247f9 IB |
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 | ||
f86ee140 | 130 | def log_order(self, order, tick, finished=False, update=None, |
3d0247f9 | 131 | new_order=None, compute_value=None): |
aca4d437 IB |
132 | if callable(compute_value): |
133 | compute_value = inspect.getsource(compute_value).strip() | |
3d0247f9 | 134 | if finished: |
f86ee140 | 135 | self.print_log("[Order] Finished {}".format(order)) |
3d0247f9 | 136 | elif update == "waiting": |
f86ee140 | 137 | self.print_log("[Order] {}, tick {}, waiting".format(order, tick)) |
3d0247f9 | 138 | elif update == "adjusting": |
f86ee140 | 139 | self.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order)) |
3d0247f9 | 140 | elif update == "market_fallback": |
f86ee140 | 141 | self.print_log("[Order] {}, tick {}, fallbacking to market value".format(order, tick)) |
3d0247f9 | 142 | elif update == "market_adjust": |
f86ee140 | 143 | self.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order, tick, new_order)) |
3d0247f9 | 144 | |
f86ee140 | 145 | self.add_log({ |
3d0247f9 IB |
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 | ||
f86ee140 IB |
154 | def log_move_balances(self, needed, moving): |
155 | self.add_log({ | |
3d0247f9 | 156 | "type": "move_balances", |
f86ee140 | 157 | "debug": self.market.debug, |
3d0247f9 IB |
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 | ||
f86ee140 IB |
162 | def log_http_request(self, method, url, body, headers, response): |
163 | self.add_log({ | |
3d0247f9 IB |
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 | ||
f86ee140 IB |
173 | def log_error(self, action, message=None, exception=None): |
174 | self.print_log("[Error] {}".format(action)) | |
3d0247f9 | 175 | if exception is not None: |
f86ee140 | 176 | self.print_log(str("\t{}: {}".format(exception.__class__.__name__, exception))) |
3d0247f9 | 177 | if message is not None: |
f86ee140 | 178 | self.print_log("\t{}".format(message)) |
3d0247f9 | 179 | |
f86ee140 | 180 | self.add_log({ |
3d0247f9 IB |
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 | ||
f86ee140 IB |
188 | def log_debug_action(self, action): |
189 | self.print_log("[Debug] {}".format(action)) | |
3d0247f9 | 190 | |
f86ee140 | 191 | self.add_log({ |
3d0247f9 IB |
192 | "type": "debug_action", |
193 | "action": action, | |
194 | }) | |
6ca5a1ec IB |
195 | |
196 | class BalanceStore: | |
f86ee140 IB |
197 | def __init__(self, market): |
198 | self.market = market | |
199 | self.all = {} | |
6ca5a1ec | 200 | |
f86ee140 IB |
201 | def currencies(self): |
202 | return self.all.keys() | |
6ca5a1ec | 203 | |
f86ee140 | 204 | def in_currency(self, other_currency, compute_value="average", type="total"): |
6ca5a1ec | 205 | amounts = {} |
f86ee140 | 206 | for currency, balance in self.all.items(): |
6ca5a1ec | 207 | other_currency_amount = getattr(balance, type)\ |
f86ee140 | 208 | .in_currency(other_currency, self.market, compute_value=compute_value) |
6ca5a1ec | 209 | amounts[currency] = other_currency_amount |
f86ee140 | 210 | self.market.report.log_tickers(amounts, other_currency, |
3d0247f9 | 211 | compute_value, type) |
6ca5a1ec IB |
212 | return amounts |
213 | ||
f86ee140 IB |
214 | def fetch_balances(self, tag=None): |
215 | all_balances = self.market.ccxt.fetch_all_balances() | |
6ca5a1ec IB |
216 | for currency, balance in all_balances.items(): |
217 | if balance["exchange_total"] != 0 or balance["margin_total"] != 0 or \ | |
f86ee140 IB |
218 | currency in self.all: |
219 | self.all[currency] = portfolio.Balance(currency, balance) | |
220 | self.market.report.log_balances(tag=tag) | |
6ca5a1ec | 221 | |
f86ee140 | 222 | def dispatch_assets(self, amount, liquidity="medium", repartition=None): |
6ca5a1ec | 223 | if repartition is None: |
ada1b5f1 | 224 | repartition = Portfolio.repartition(liquidity=liquidity) |
6ca5a1ec IB |
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] | |
aca4d437 | 231 | self.all.setdefault(currency, portfolio.Balance(currency, {})) |
f86ee140 | 232 | self.market.report.log_dispatch(amount, amounts, liquidity, repartition) |
6ca5a1ec IB |
233 | return amounts |
234 | ||
f86ee140 IB |
235 | def as_json(self): |
236 | return { k: v.as_json() for k, v in self.all.items() } | |
3d0247f9 | 237 | |
6ca5a1ec | 238 | class TradeStore: |
f86ee140 IB |
239 | def __init__(self, market): |
240 | self.market = market | |
241 | self.all = [] | |
6ca5a1ec | 242 | |
aca4d437 IB |
243 | @property |
244 | def pending(self): | |
17598517 | 245 | return list(filter(lambda t: t.pending, self.all)) |
aca4d437 | 246 | |
f86ee140 | 247 | def compute_trades(self, values_in_base, new_repartition, only=None): |
3d0247f9 | 248 | computed_trades = [] |
6ca5a1ec | 249 | base_currency = sum(values_in_base.values()).currency |
f86ee140 | 250 | for currency in self.market.balances.currencies(): |
6ca5a1ec IB |
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)) | |
1aa7d4fa | 255 | |
6ca5a1ec | 256 | if value_from.value * value_to.value < 0: |
f86ee140 | 257 | computed_trades.append(self.trade_if_matching( |
1aa7d4fa | 258 | value_from, portfolio.Amount(base_currency, 0), |
f86ee140 IB |
259 | currency, only=only)) |
260 | computed_trades.append(self.trade_if_matching( | |
1aa7d4fa | 261 | portfolio.Amount(base_currency, 0), value_to, |
f86ee140 | 262 | currency, only=only)) |
6ca5a1ec | 263 | else: |
f86ee140 | 264 | computed_trades.append(self.trade_if_matching( |
3d0247f9 | 265 | value_from, value_to, |
f86ee140 | 266 | currency, only=only)) |
3d0247f9 IB |
267 | for matching, trade in computed_trades: |
268 | if matching: | |
f86ee140 IB |
269 | self.all.append(trade) |
270 | self.market.report.log_trades(computed_trades, only) | |
1aa7d4fa | 271 | |
f86ee140 IB |
272 | def trade_if_matching(self, value_from, value_to, currency, |
273 | only=None): | |
1aa7d4fa | 274 | trade = portfolio.Trade(value_from, value_to, currency, |
f86ee140 | 275 | self.market) |
3d0247f9 IB |
276 | matching = only is None or trade.action == only |
277 | return [matching, trade] | |
6ca5a1ec | 278 | |
f86ee140 | 279 | def prepare_orders(self, only=None, compute_value="default"): |
3d0247f9 | 280 | orders = [] |
aca4d437 | 281 | for trade in self.pending: |
6ca5a1ec | 282 | if only is None or trade.action == only: |
3d0247f9 | 283 | orders.append(trade.prepare_order(compute_value=compute_value)) |
f86ee140 | 284 | self.market.report.log_orders(orders, only, compute_value) |
6ca5a1ec | 285 | |
17598517 IB |
286 | def close_trades(self): |
287 | for trade in self.all: | |
288 | trade.close() | |
289 | ||
f86ee140 IB |
290 | def print_all_with_order(self, ind=""): |
291 | for trade in self.all: | |
3d0247f9 | 292 | trade.print_with_order(ind=ind) |
6ca5a1ec | 293 | |
f86ee140 IB |
294 | def run_orders(self): |
295 | orders = self.all_orders(state="pending") | |
3d0247f9 | 296 | for order in orders: |
6ca5a1ec | 297 | order.run() |
f86ee140 IB |
298 | self.market.report.log_stage("run_orders") |
299 | self.market.report.log_orders(orders) | |
6ca5a1ec | 300 | |
f86ee140 IB |
301 | def all_orders(self, state=None): |
302 | all_orders = sum(map(lambda v: v.orders, self.all), []) | |
6ca5a1ec IB |
303 | if state is None: |
304 | return all_orders | |
305 | else: | |
306 | return list(filter(lambda o: o.status == state, all_orders)) | |
307 | ||
f86ee140 IB |
308 | def update_all_orders_status(self): |
309 | for order in self.all_orders(state="open"): | |
6ca5a1ec IB |
310 | order.get_status() |
311 | ||
dc1ca9a3 IB |
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 | ||
ada1b5f1 IB |
342 | class Portfolio: |
343 | URL = "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json" | |
dc1ca9a3 IB |
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) | |
ada1b5f1 IB |
388 | |
389 | @classmethod | |
dc1ca9a3 IB |
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): | |
ada1b5f1 | 397 | cls.get_cryptoportfolio() |
dc1ca9a3 IB |
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") | |
ada1b5f1 IB |
402 | cls.get_cryptoportfolio(refetch=True) |
403 | ||
404 | @classmethod | |
405 | def repartition(cls, liquidity="medium"): | |
406 | cls.get_cryptoportfolio() | |
dc1ca9a3 IB |
407 | liquidities = cls.liquidities.get(liquidity) |
408 | return liquidities[cls.last_date.get()] | |
ada1b5f1 IB |
409 | |
410 | @classmethod | |
411 | def get_cryptoportfolio(cls, refetch=False): | |
dc1ca9a3 IB |
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() | |
ada1b5f1 IB |
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: | |
dc1ca9a3 | 425 | cls.data.set(r.json(parse_int=D, parse_float=D)) |
ada1b5f1 IB |
426 | cls.parse_cryptoportfolio() |
427 | except (JSONDecodeError, SimpleJSONDecodeError): | |
dc1ca9a3 IB |
428 | cls.data.set(None) |
429 | cls.last_date.set(None) | |
430 | cls.liquidities.set({}) | |
ada1b5f1 IB |
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): | |
dc1ca9a3 IB |
450 | if "weights" not in portfolio_hash: |
451 | return {} | |
ada1b5f1 IB |
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 | ||
dc1ca9a3 IB |
461 | high_liquidity = parse_weights(cls.data.get("portfolio_1")) |
462 | medium_liquidity = parse_weights(cls.data.get("portfolio_2")) | |
ada1b5f1 | 463 | |
dc1ca9a3 IB |
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 | )) | |
ada1b5f1 | 472 | |
6ca5a1ec | 473 |