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