]>
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 | ||
20 | def print_log(self, message): | |
3d0247f9 | 21 | message = str(message) |
f86ee140 | 22 | if self.verbose_print: |
3d0247f9 IB |
23 | print(message) |
24 | ||
f86ee140 | 25 | def add_log(self, hash_): |
3d0247f9 | 26 | hash_["date"] = datetime.now() |
f86ee140 | 27 | self.logs.append(hash_) |
3d0247f9 | 28 | |
f86ee140 | 29 | def to_json(self): |
3d0247f9 IB |
30 | def default_json_serial(obj): |
31 | if isinstance(obj, (datetime, date)): | |
32 | return obj.isoformat() | |
be54a201 | 33 | return str(obj) |
f861492d | 34 | return json.dumps(self.logs, default=default_json_serial, indent=" ") |
3d0247f9 | 35 | |
f86ee140 IB |
36 | def set_verbose(self, verbose_print): |
37 | self.verbose_print = verbose_print | |
3d0247f9 | 38 | |
7bd830a8 IB |
39 | def log_stage(self, stage, **kwargs): |
40 | def as_json(element): | |
41 | if callable(element): | |
42 | return inspect.getsource(element).strip() | |
43 | elif hasattr(element, "as_json"): | |
44 | return element.as_json() | |
45 | else: | |
46 | return element | |
47 | ||
48 | args = { k: as_json(v) for k, v in kwargs.items() } | |
49 | args_str = ["{}={}".format(k, v) for k, v in args.items()] | |
f86ee140 | 50 | self.print_log("-" * (len(stage) + 8)) |
7bd830a8 | 51 | self.print_log("[Stage] {} {}".format(stage, ", ".join(args_str))) |
3d0247f9 | 52 | |
f86ee140 | 53 | self.add_log({ |
3d0247f9 IB |
54 | "type": "stage", |
55 | "stage": stage, | |
7bd830a8 | 56 | "args": args, |
3d0247f9 IB |
57 | }) |
58 | ||
f86ee140 IB |
59 | def log_balances(self, tag=None): |
60 | self.print_log("[Balance]") | |
61 | for currency, balance in self.market.balances.all.items(): | |
62 | self.print_log("\t{}".format(balance)) | |
3d0247f9 | 63 | |
f86ee140 | 64 | self.add_log({ |
3d0247f9 | 65 | "type": "balance", |
18167a3c | 66 | "tag": tag, |
f86ee140 | 67 | "balances": self.market.balances.as_json() |
3d0247f9 IB |
68 | }) |
69 | ||
f86ee140 | 70 | def log_tickers(self, amounts, other_currency, |
3d0247f9 IB |
71 | compute_value, type): |
72 | values = {} | |
73 | rates = {} | |
aca4d437 IB |
74 | if callable(compute_value): |
75 | compute_value = inspect.getsource(compute_value).strip() | |
76 | ||
3d0247f9 IB |
77 | for currency, amount in amounts.items(): |
78 | values[currency] = amount.as_json()["value"] | |
79 | rates[currency] = amount.rate | |
f86ee140 | 80 | self.add_log({ |
3d0247f9 IB |
81 | "type": "tickers", |
82 | "compute_value": compute_value, | |
83 | "balance_type": type, | |
84 | "currency": other_currency, | |
85 | "balances": values, | |
86 | "rates": rates, | |
87 | "total": sum(amounts.values()).as_json()["value"] | |
88 | }) | |
89 | ||
f86ee140 IB |
90 | def log_dispatch(self, amount, amounts, liquidity, repartition): |
91 | self.add_log({ | |
3d0247f9 IB |
92 | "type": "dispatch", |
93 | "liquidity": liquidity, | |
94 | "repartition_ratio": repartition, | |
95 | "total_amount": amount.as_json(), | |
96 | "repartition": { k: v.as_json()["value"] for k, v in amounts.items() } | |
97 | }) | |
98 | ||
f86ee140 | 99 | def log_trades(self, matching_and_trades, only): |
3d0247f9 IB |
100 | trades = [] |
101 | for matching, trade in matching_and_trades: | |
102 | trade_json = trade.as_json() | |
103 | trade_json["skipped"] = not matching | |
104 | trades.append(trade_json) | |
105 | ||
f86ee140 | 106 | self.add_log({ |
3d0247f9 IB |
107 | "type": "trades", |
108 | "only": only, | |
f86ee140 | 109 | "debug": self.market.debug, |
3d0247f9 IB |
110 | "trades": trades |
111 | }) | |
112 | ||
f86ee140 | 113 | def log_orders(self, orders, tick=None, only=None, compute_value=None): |
aca4d437 IB |
114 | if callable(compute_value): |
115 | compute_value = inspect.getsource(compute_value).strip() | |
f86ee140 IB |
116 | self.print_log("[Orders]") |
117 | self.market.trades.print_all_with_order(ind="\t") | |
118 | self.add_log({ | |
3d0247f9 IB |
119 | "type": "orders", |
120 | "only": only, | |
121 | "compute_value": compute_value, | |
122 | "tick": tick, | |
123 | "orders": [order.as_json() for order in orders if order is not None] | |
124 | }) | |
125 | ||
f86ee140 | 126 | def log_order(self, order, tick, finished=False, update=None, |
3d0247f9 | 127 | new_order=None, compute_value=None): |
aca4d437 IB |
128 | if callable(compute_value): |
129 | compute_value = inspect.getsource(compute_value).strip() | |
3d0247f9 | 130 | if finished: |
f86ee140 | 131 | self.print_log("[Order] Finished {}".format(order)) |
3d0247f9 | 132 | elif update == "waiting": |
f86ee140 | 133 | self.print_log("[Order] {}, tick {}, waiting".format(order, tick)) |
3d0247f9 | 134 | elif update == "adjusting": |
f86ee140 | 135 | self.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order)) |
3d0247f9 | 136 | elif update == "market_fallback": |
f86ee140 | 137 | self.print_log("[Order] {}, tick {}, fallbacking to market value".format(order, tick)) |
3d0247f9 | 138 | elif update == "market_adjust": |
f86ee140 | 139 | self.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order, tick, new_order)) |
3d0247f9 | 140 | |
f86ee140 | 141 | self.add_log({ |
3d0247f9 IB |
142 | "type": "order", |
143 | "tick": tick, | |
144 | "update": update, | |
145 | "order": order.as_json(), | |
146 | "compute_value": compute_value, | |
147 | "new_order": new_order.as_json() if new_order is not None else None | |
148 | }) | |
149 | ||
f86ee140 IB |
150 | def log_move_balances(self, needed, moving): |
151 | self.add_log({ | |
3d0247f9 | 152 | "type": "move_balances", |
f86ee140 | 153 | "debug": self.market.debug, |
3d0247f9 IB |
154 | "needed": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in needed.items() }, |
155 | "moving": { k: v.as_json()["value"] if isinstance(v, portfolio.Amount) else v for k, v in moving.items() }, | |
156 | }) | |
157 | ||
f86ee140 IB |
158 | def log_http_request(self, method, url, body, headers, response): |
159 | self.add_log({ | |
3d0247f9 IB |
160 | "type": "http_request", |
161 | "method": method, | |
162 | "url": url, | |
163 | "body": body, | |
164 | "headers": headers, | |
165 | "status": response.status_code, | |
166 | "response": response.text | |
167 | }) | |
168 | ||
f86ee140 IB |
169 | def log_error(self, action, message=None, exception=None): |
170 | self.print_log("[Error] {}".format(action)) | |
3d0247f9 | 171 | if exception is not None: |
f86ee140 | 172 | self.print_log(str("\t{}: {}".format(exception.__class__.__name__, exception))) |
3d0247f9 | 173 | if message is not None: |
f86ee140 | 174 | self.print_log("\t{}".format(message)) |
3d0247f9 | 175 | |
f86ee140 | 176 | self.add_log({ |
3d0247f9 IB |
177 | "type": "error", |
178 | "action": action, | |
179 | "exception_class": exception.__class__.__name__ if exception is not None else None, | |
180 | "exception_message": str(exception) if exception is not None else None, | |
181 | "message": message, | |
182 | }) | |
183 | ||
f86ee140 IB |
184 | def log_debug_action(self, action): |
185 | self.print_log("[Debug] {}".format(action)) | |
3d0247f9 | 186 | |
f86ee140 | 187 | self.add_log({ |
3d0247f9 IB |
188 | "type": "debug_action", |
189 | "action": action, | |
190 | }) | |
6ca5a1ec IB |
191 | |
192 | class BalanceStore: | |
f86ee140 IB |
193 | def __init__(self, market): |
194 | self.market = market | |
195 | self.all = {} | |
6ca5a1ec | 196 | |
f86ee140 IB |
197 | def currencies(self): |
198 | return self.all.keys() | |
6ca5a1ec | 199 | |
f86ee140 | 200 | def in_currency(self, other_currency, compute_value="average", type="total"): |
6ca5a1ec | 201 | amounts = {} |
f86ee140 | 202 | for currency, balance in self.all.items(): |
6ca5a1ec | 203 | other_currency_amount = getattr(balance, type)\ |
f86ee140 | 204 | .in_currency(other_currency, self.market, compute_value=compute_value) |
6ca5a1ec | 205 | amounts[currency] = other_currency_amount |
f86ee140 | 206 | self.market.report.log_tickers(amounts, other_currency, |
3d0247f9 | 207 | compute_value, type) |
6ca5a1ec IB |
208 | return amounts |
209 | ||
f86ee140 IB |
210 | def fetch_balances(self, tag=None): |
211 | all_balances = self.market.ccxt.fetch_all_balances() | |
6ca5a1ec IB |
212 | for currency, balance in all_balances.items(): |
213 | if balance["exchange_total"] != 0 or balance["margin_total"] != 0 or \ | |
f86ee140 IB |
214 | currency in self.all: |
215 | self.all[currency] = portfolio.Balance(currency, balance) | |
216 | self.market.report.log_balances(tag=tag) | |
6ca5a1ec | 217 | |
f86ee140 | 218 | def dispatch_assets(self, amount, liquidity="medium", repartition=None): |
6ca5a1ec | 219 | if repartition is None: |
ada1b5f1 | 220 | repartition = Portfolio.repartition(liquidity=liquidity) |
6ca5a1ec IB |
221 | sum_ratio = sum([v[0] for k, v in repartition.items()]) |
222 | amounts = {} | |
223 | for currency, (ptt, trade_type) in repartition.items(): | |
224 | amounts[currency] = ptt * amount / sum_ratio | |
225 | if trade_type == "short": | |
226 | amounts[currency] = - amounts[currency] | |
aca4d437 | 227 | self.all.setdefault(currency, portfolio.Balance(currency, {})) |
f86ee140 | 228 | self.market.report.log_dispatch(amount, amounts, liquidity, repartition) |
6ca5a1ec IB |
229 | return amounts |
230 | ||
f86ee140 IB |
231 | def as_json(self): |
232 | return { k: v.as_json() for k, v in self.all.items() } | |
3d0247f9 | 233 | |
6ca5a1ec | 234 | class TradeStore: |
f86ee140 IB |
235 | def __init__(self, market): |
236 | self.market = market | |
237 | self.all = [] | |
6ca5a1ec | 238 | |
aca4d437 IB |
239 | @property |
240 | def pending(self): | |
17598517 | 241 | return list(filter(lambda t: t.pending, self.all)) |
aca4d437 | 242 | |
f86ee140 | 243 | def compute_trades(self, values_in_base, new_repartition, only=None): |
3d0247f9 | 244 | computed_trades = [] |
6ca5a1ec | 245 | base_currency = sum(values_in_base.values()).currency |
f86ee140 | 246 | for currency in self.market.balances.currencies(): |
6ca5a1ec IB |
247 | if currency == base_currency: |
248 | continue | |
249 | value_from = values_in_base.get(currency, portfolio.Amount(base_currency, 0)) | |
250 | value_to = new_repartition.get(currency, portfolio.Amount(base_currency, 0)) | |
1aa7d4fa | 251 | |
6ca5a1ec | 252 | if value_from.value * value_to.value < 0: |
f86ee140 | 253 | computed_trades.append(self.trade_if_matching( |
1aa7d4fa | 254 | value_from, portfolio.Amount(base_currency, 0), |
f86ee140 IB |
255 | currency, only=only)) |
256 | computed_trades.append(self.trade_if_matching( | |
1aa7d4fa | 257 | portfolio.Amount(base_currency, 0), value_to, |
f86ee140 | 258 | currency, only=only)) |
6ca5a1ec | 259 | else: |
f86ee140 | 260 | computed_trades.append(self.trade_if_matching( |
3d0247f9 | 261 | value_from, value_to, |
f86ee140 | 262 | currency, only=only)) |
3d0247f9 IB |
263 | for matching, trade in computed_trades: |
264 | if matching: | |
f86ee140 IB |
265 | self.all.append(trade) |
266 | self.market.report.log_trades(computed_trades, only) | |
1aa7d4fa | 267 | |
f86ee140 IB |
268 | def trade_if_matching(self, value_from, value_to, currency, |
269 | only=None): | |
1aa7d4fa | 270 | trade = portfolio.Trade(value_from, value_to, currency, |
f86ee140 | 271 | self.market) |
3d0247f9 IB |
272 | matching = only is None or trade.action == only |
273 | return [matching, trade] | |
6ca5a1ec | 274 | |
f86ee140 | 275 | def prepare_orders(self, only=None, compute_value="default"): |
3d0247f9 | 276 | orders = [] |
aca4d437 | 277 | for trade in self.pending: |
6ca5a1ec | 278 | if only is None or trade.action == only: |
3d0247f9 | 279 | orders.append(trade.prepare_order(compute_value=compute_value)) |
f86ee140 | 280 | self.market.report.log_orders(orders, only, compute_value) |
6ca5a1ec | 281 | |
17598517 IB |
282 | def close_trades(self): |
283 | for trade in self.all: | |
284 | trade.close() | |
285 | ||
f86ee140 IB |
286 | def print_all_with_order(self, ind=""): |
287 | for trade in self.all: | |
3d0247f9 | 288 | trade.print_with_order(ind=ind) |
6ca5a1ec | 289 | |
f86ee140 IB |
290 | def run_orders(self): |
291 | orders = self.all_orders(state="pending") | |
3d0247f9 | 292 | for order in orders: |
6ca5a1ec | 293 | order.run() |
f86ee140 IB |
294 | self.market.report.log_stage("run_orders") |
295 | self.market.report.log_orders(orders) | |
6ca5a1ec | 296 | |
f86ee140 IB |
297 | def all_orders(self, state=None): |
298 | all_orders = sum(map(lambda v: v.orders, self.all), []) | |
6ca5a1ec IB |
299 | if state is None: |
300 | return all_orders | |
301 | else: | |
302 | return list(filter(lambda o: o.status == state, all_orders)) | |
303 | ||
f86ee140 IB |
304 | def update_all_orders_status(self): |
305 | for order in self.all_orders(state="open"): | |
6ca5a1ec IB |
306 | order.get_status() |
307 | ||
ada1b5f1 IB |
308 | class Portfolio: |
309 | URL = "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json" | |
310 | liquidities = {} | |
311 | data = None | |
312 | last_date = None | |
313 | report = ReportStore(None) | |
314 | ||
315 | @classmethod | |
316 | def wait_for_recent(cls, delta=4): | |
317 | cls.get_cryptoportfolio() | |
318 | while cls.last_date is None or datetime.now() - cls.last_date > timedelta(delta): | |
319 | time.sleep(30) | |
320 | cls.report.print_log("Attempt to fetch up-to-date cryptoportfolio") | |
321 | cls.get_cryptoportfolio(refetch=True) | |
322 | ||
323 | @classmethod | |
324 | def repartition(cls, liquidity="medium"): | |
325 | cls.get_cryptoportfolio() | |
326 | liquidities = cls.liquidities[liquidity] | |
327 | return liquidities[cls.last_date] | |
328 | ||
329 | @classmethod | |
330 | def get_cryptoportfolio(cls, refetch=False): | |
331 | if cls.data is not None and not refetch: | |
332 | return | |
333 | try: | |
334 | r = requests.get(cls.URL) | |
335 | cls.report.log_http_request(r.request.method, | |
336 | r.request.url, r.request.body, r.request.headers, r) | |
337 | except Exception as e: | |
338 | cls.report.log_error("get_cryptoportfolio", exception=e) | |
339 | return | |
340 | try: | |
341 | cls.data = r.json(parse_int=D, parse_float=D) | |
342 | cls.parse_cryptoportfolio() | |
343 | except (JSONDecodeError, SimpleJSONDecodeError): | |
344 | cls.data = None | |
345 | cls.liquidities = {} | |
346 | ||
347 | @classmethod | |
348 | def parse_cryptoportfolio(cls): | |
349 | def filter_weights(weight_hash): | |
350 | if weight_hash[1][0] == 0: | |
351 | return False | |
352 | if weight_hash[0] == "_row": | |
353 | return False | |
354 | return True | |
355 | ||
356 | def clean_weights(i): | |
357 | def clean_weights_(h): | |
358 | if h[0].endswith("s"): | |
359 | return [h[0][0:-1], (h[1][i], "short")] | |
360 | else: | |
361 | return [h[0], (h[1][i], "long")] | |
362 | return clean_weights_ | |
363 | ||
364 | def parse_weights(portfolio_hash): | |
365 | weights_hash = portfolio_hash["weights"] | |
366 | weights = {} | |
367 | for i in range(len(weights_hash["_row"])): | |
368 | date = datetime.strptime(weights_hash["_row"][i], "%Y-%m-%d") | |
369 | weights[date] = dict(filter( | |
370 | filter_weights, | |
371 | map(clean_weights(i), weights_hash.items()))) | |
372 | return weights | |
373 | ||
374 | high_liquidity = parse_weights(cls.data["portfolio_1"]) | |
375 | medium_liquidity = parse_weights(cls.data["portfolio_2"]) | |
376 | ||
377 | cls.liquidities = { | |
378 | "medium": medium_liquidity, | |
379 | "high": high_liquidity, | |
380 | } | |
381 | cls.last_date = max(max(medium_liquidity.keys()), max(high_liquidity.keys())) | |
382 | ||
6ca5a1ec | 383 |