]>
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 print_log(self, message): | |
21 | message = str(message) | |
22 | if self.verbose_print: | |
23 | print(message) | |
24 | ||
25 | def add_log(self, hash_): | |
26 | hash_["date"] = datetime.now() | |
27 | self.logs.append(hash_) | |
28 | ||
29 | def to_json(self): | |
30 | def default_json_serial(obj): | |
31 | if isinstance(obj, (datetime, date)): | |
32 | return obj.isoformat() | |
33 | return str(obj) | |
34 | return json.dumps(self.logs, default=default_json_serial, indent=" ") | |
35 | ||
36 | def set_verbose(self, verbose_print): | |
37 | self.verbose_print = verbose_print | |
38 | ||
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()] | |
50 | self.print_log("-" * (len(stage) + 8)) | |
51 | self.print_log("[Stage] {} {}".format(stage, ", ".join(args_str))) | |
52 | ||
53 | self.add_log({ | |
54 | "type": "stage", | |
55 | "stage": stage, | |
56 | "args": args, | |
57 | }) | |
58 | ||
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)) | |
63 | ||
64 | self.add_log({ | |
65 | "type": "balance", | |
66 | "tag": tag, | |
67 | "balances": self.market.balances.as_json() | |
68 | }) | |
69 | ||
70 | def log_tickers(self, amounts, other_currency, | |
71 | compute_value, type): | |
72 | values = {} | |
73 | rates = {} | |
74 | if callable(compute_value): | |
75 | compute_value = inspect.getsource(compute_value).strip() | |
76 | ||
77 | for currency, amount in amounts.items(): | |
78 | values[currency] = amount.as_json()["value"] | |
79 | rates[currency] = amount.rate | |
80 | self.add_log({ | |
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 | ||
90 | def log_dispatch(self, amount, amounts, liquidity, repartition): | |
91 | self.add_log({ | |
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 | ||
99 | def log_trades(self, matching_and_trades, only): | |
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 | ||
106 | self.add_log({ | |
107 | "type": "trades", | |
108 | "only": only, | |
109 | "debug": self.market.debug, | |
110 | "trades": trades | |
111 | }) | |
112 | ||
113 | def log_orders(self, orders, tick=None, only=None, compute_value=None): | |
114 | if callable(compute_value): | |
115 | compute_value = inspect.getsource(compute_value).strip() | |
116 | self.print_log("[Orders]") | |
117 | self.market.trades.print_all_with_order(ind="\t") | |
118 | self.add_log({ | |
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 | ||
126 | def log_order(self, order, tick, finished=False, update=None, | |
127 | new_order=None, compute_value=None): | |
128 | if callable(compute_value): | |
129 | compute_value = inspect.getsource(compute_value).strip() | |
130 | if finished: | |
131 | self.print_log("[Order] Finished {}".format(order)) | |
132 | elif update == "waiting": | |
133 | self.print_log("[Order] {}, tick {}, waiting".format(order, tick)) | |
134 | elif update == "adjusting": | |
135 | self.print_log("[Order] {}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order)) | |
136 | elif update == "market_fallback": | |
137 | self.print_log("[Order] {}, tick {}, fallbacking to market value".format(order, tick)) | |
138 | elif update == "market_adjust": | |
139 | self.print_log("[Order] {}, tick {}, market value, cancelling and adjusting to {}".format(order, tick, new_order)) | |
140 | ||
141 | self.add_log({ | |
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 | ||
150 | def log_move_balances(self, needed, moving): | |
151 | self.add_log({ | |
152 | "type": "move_balances", | |
153 | "debug": self.market.debug, | |
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 | ||
158 | def log_http_request(self, method, url, body, headers, response): | |
159 | self.add_log({ | |
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 | ||
169 | def log_error(self, action, message=None, exception=None): | |
170 | self.print_log("[Error] {}".format(action)) | |
171 | if exception is not None: | |
172 | self.print_log(str("\t{}: {}".format(exception.__class__.__name__, exception))) | |
173 | if message is not None: | |
174 | self.print_log("\t{}".format(message)) | |
175 | ||
176 | self.add_log({ | |
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 | ||
184 | def log_debug_action(self, action): | |
185 | self.print_log("[Debug] {}".format(action)) | |
186 | ||
187 | self.add_log({ | |
188 | "type": "debug_action", | |
189 | "action": action, | |
190 | }) | |
191 | ||
192 | class BalanceStore: | |
193 | def __init__(self, market): | |
194 | self.market = market | |
195 | self.all = {} | |
196 | ||
197 | def currencies(self): | |
198 | return self.all.keys() | |
199 | ||
200 | def in_currency(self, other_currency, compute_value="average", type="total"): | |
201 | amounts = {} | |
202 | for currency, balance in self.all.items(): | |
203 | other_currency_amount = getattr(balance, type)\ | |
204 | .in_currency(other_currency, self.market, compute_value=compute_value) | |
205 | amounts[currency] = other_currency_amount | |
206 | self.market.report.log_tickers(amounts, other_currency, | |
207 | compute_value, type) | |
208 | return amounts | |
209 | ||
210 | def fetch_balances(self, tag=None): | |
211 | all_balances = self.market.ccxt.fetch_all_balances() | |
212 | for currency, balance in all_balances.items(): | |
213 | if balance["exchange_total"] != 0 or balance["margin_total"] != 0 or \ | |
214 | currency in self.all: | |
215 | self.all[currency] = portfolio.Balance(currency, balance) | |
216 | self.market.report.log_balances(tag=tag) | |
217 | ||
218 | def dispatch_assets(self, amount, liquidity="medium", repartition=None): | |
219 | if repartition is None: | |
220 | repartition = Portfolio.repartition(liquidity=liquidity) | |
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] | |
227 | self.all.setdefault(currency, portfolio.Balance(currency, {})) | |
228 | self.market.report.log_dispatch(amount, amounts, liquidity, repartition) | |
229 | return amounts | |
230 | ||
231 | def as_json(self): | |
232 | return { k: v.as_json() for k, v in self.all.items() } | |
233 | ||
234 | class TradeStore: | |
235 | def __init__(self, market): | |
236 | self.market = market | |
237 | self.all = [] | |
238 | ||
239 | @property | |
240 | def pending(self): | |
241 | return list(filter(lambda t: t.pending, self.all)) | |
242 | ||
243 | def compute_trades(self, values_in_base, new_repartition, only=None): | |
244 | computed_trades = [] | |
245 | base_currency = sum(values_in_base.values()).currency | |
246 | for currency in self.market.balances.currencies(): | |
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)) | |
251 | ||
252 | if value_from.value * value_to.value < 0: | |
253 | computed_trades.append(self.trade_if_matching( | |
254 | value_from, portfolio.Amount(base_currency, 0), | |
255 | currency, only=only)) | |
256 | computed_trades.append(self.trade_if_matching( | |
257 | portfolio.Amount(base_currency, 0), value_to, | |
258 | currency, only=only)) | |
259 | else: | |
260 | computed_trades.append(self.trade_if_matching( | |
261 | value_from, value_to, | |
262 | currency, only=only)) | |
263 | for matching, trade in computed_trades: | |
264 | if matching: | |
265 | self.all.append(trade) | |
266 | self.market.report.log_trades(computed_trades, only) | |
267 | ||
268 | def trade_if_matching(self, value_from, value_to, currency, | |
269 | only=None): | |
270 | trade = portfolio.Trade(value_from, value_to, currency, | |
271 | self.market) | |
272 | matching = only is None or trade.action == only | |
273 | return [matching, trade] | |
274 | ||
275 | def prepare_orders(self, only=None, compute_value="default"): | |
276 | orders = [] | |
277 | for trade in self.pending: | |
278 | if only is None or trade.action == only: | |
279 | orders.append(trade.prepare_order(compute_value=compute_value)) | |
280 | self.market.report.log_orders(orders, only, compute_value) | |
281 | ||
282 | def close_trades(self): | |
283 | for trade in self.all: | |
284 | trade.close() | |
285 | ||
286 | def print_all_with_order(self, ind=""): | |
287 | for trade in self.all: | |
288 | trade.print_with_order(ind=ind) | |
289 | ||
290 | def run_orders(self): | |
291 | orders = self.all_orders(state="pending") | |
292 | for order in orders: | |
293 | order.run() | |
294 | self.market.report.log_stage("run_orders") | |
295 | self.market.report.log_orders(orders) | |
296 | ||
297 | def all_orders(self, state=None): | |
298 | all_orders = sum(map(lambda v: v.orders, self.all), []) | |
299 | if state is None: | |
300 | return all_orders | |
301 | else: | |
302 | return list(filter(lambda o: o.status == state, all_orders)) | |
303 | ||
304 | def update_all_orders_status(self): | |
305 | for order in self.all_orders(state="open"): | |
306 | order.get_status() | |
307 | ||
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 | ||
383 |