]>
Commit | Line | Data |
---|---|---|
1 | import time | |
2 | from decimal import Decimal as D, ROUND_DOWN | |
3 | # Put your poloniex api key in market.py | |
4 | from json import JSONDecodeError | |
5 | import requests | |
6 | import helper as h | |
7 | from store import * | |
8 | ||
9 | # FIXME: correctly handle web call timeouts | |
10 | ||
11 | class Portfolio: | |
12 | URL = "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json" | |
13 | liquidities = {} | |
14 | data = None | |
15 | ||
16 | @classmethod | |
17 | def repartition(cls, liquidity="medium"): | |
18 | cls.parse_cryptoportfolio() | |
19 | liquidities = cls.liquidities[liquidity] | |
20 | cls.last_date = sorted(liquidities.keys())[-1] | |
21 | return liquidities[cls.last_date] | |
22 | ||
23 | @classmethod | |
24 | def get_cryptoportfolio(cls): | |
25 | try: | |
26 | r = requests.get(cls.URL) | |
27 | except Exception: | |
28 | return | |
29 | try: | |
30 | cls.data = r.json(parse_int=D, parse_float=D) | |
31 | except JSONDecodeError: | |
32 | cls.data = None | |
33 | ||
34 | @classmethod | |
35 | def parse_cryptoportfolio(cls): | |
36 | if cls.data is None: | |
37 | cls.get_cryptoportfolio() | |
38 | ||
39 | def filter_weights(weight_hash): | |
40 | if weight_hash[1][0] == 0: | |
41 | return False | |
42 | if weight_hash[0] == "_row": | |
43 | return False | |
44 | return True | |
45 | ||
46 | def clean_weights(i): | |
47 | def clean_weights_(h): | |
48 | if h[0].endswith("s"): | |
49 | return [h[0][0:-1], (h[1][i], "short")] | |
50 | else: | |
51 | return [h[0], (h[1][i], "long")] | |
52 | return clean_weights_ | |
53 | ||
54 | def parse_weights(portfolio_hash): | |
55 | weights_hash = portfolio_hash["weights"] | |
56 | weights = {} | |
57 | for i in range(len(weights_hash["_row"])): | |
58 | weights[weights_hash["_row"][i]] = dict(filter( | |
59 | filter_weights, | |
60 | map(clean_weights(i), weights_hash.items()))) | |
61 | return weights | |
62 | ||
63 | high_liquidity = parse_weights(cls.data["portfolio_1"]) | |
64 | medium_liquidity = parse_weights(cls.data["portfolio_2"]) | |
65 | ||
66 | cls.liquidities = { | |
67 | "medium": medium_liquidity, | |
68 | "high": high_liquidity, | |
69 | } | |
70 | ||
71 | class Computation: | |
72 | computations = { | |
73 | "default": lambda x, y: x[y], | |
74 | "average": lambda x, y: x["average"], | |
75 | "bid": lambda x, y: x["bid"], | |
76 | "ask": lambda x, y: x["ask"], | |
77 | } | |
78 | ||
79 | @classmethod | |
80 | def compute_value(cls, ticker, action, compute_value="default"): | |
81 | if action == "buy": | |
82 | action = "ask" | |
83 | if action == "sell": | |
84 | action = "bid" | |
85 | if isinstance(compute_value, str): | |
86 | compute_value = cls.computations[compute_value] | |
87 | return compute_value(ticker, action) | |
88 | ||
89 | class Amount: | |
90 | def __init__(self, currency, value, linked_to=None, ticker=None, rate=None): | |
91 | self.currency = currency | |
92 | self.value = D(value) | |
93 | self.linked_to = linked_to | |
94 | self.ticker = ticker | |
95 | self.rate = rate | |
96 | ||
97 | def in_currency(self, other_currency, market, rate=None, action=None, compute_value="average"): | |
98 | if other_currency == self.currency: | |
99 | return self | |
100 | if rate is not None: | |
101 | return Amount( | |
102 | other_currency, | |
103 | self.value * rate, | |
104 | linked_to=self, | |
105 | rate=rate) | |
106 | asset_ticker = h.get_ticker(self.currency, other_currency, market) | |
107 | if asset_ticker is not None: | |
108 | rate = Computation.compute_value(asset_ticker, action, compute_value=compute_value) | |
109 | return Amount( | |
110 | other_currency, | |
111 | self.value * rate, | |
112 | linked_to=self, | |
113 | ticker=asset_ticker, | |
114 | rate=rate) | |
115 | else: | |
116 | raise Exception("This asset is not available in the chosen market") | |
117 | ||
118 | def __round__(self, n=8): | |
119 | return Amount(self.currency, self.value.quantize(D(1)/D(10**n), rounding=ROUND_DOWN)) | |
120 | ||
121 | def __abs__(self): | |
122 | return Amount(self.currency, abs(self.value)) | |
123 | ||
124 | def __add__(self, other): | |
125 | if other.currency != self.currency and other.value * self.value != 0: | |
126 | raise Exception("Summing amounts must be done with same currencies") | |
127 | return Amount(self.currency, self.value + other.value) | |
128 | ||
129 | def __radd__(self, other): | |
130 | if other == 0: | |
131 | return self | |
132 | else: | |
133 | return self.__add__(other) | |
134 | ||
135 | def __sub__(self, other): | |
136 | if other == 0: | |
137 | return self | |
138 | if other.currency != self.currency and other.value * self.value != 0: | |
139 | raise Exception("Summing amounts must be done with same currencies") | |
140 | return Amount(self.currency, self.value - other.value) | |
141 | ||
142 | def __mul__(self, value): | |
143 | if not isinstance(value, (int, float, D)): | |
144 | raise TypeError("Amount may only be multiplied by numbers") | |
145 | return Amount(self.currency, self.value * value) | |
146 | ||
147 | def __rmul__(self, value): | |
148 | return self.__mul__(value) | |
149 | ||
150 | def __floordiv__(self, value): | |
151 | if not isinstance(value, (int, float, D)): | |
152 | raise TypeError("Amount may only be divided by numbers") | |
153 | return Amount(self.currency, self.value / value) | |
154 | ||
155 | def __truediv__(self, value): | |
156 | return self.__floordiv__(value) | |
157 | ||
158 | def __lt__(self, other): | |
159 | if other == 0: | |
160 | return self.value < 0 | |
161 | if self.currency != other.currency: | |
162 | raise Exception("Comparing amounts must be done with same currencies") | |
163 | return self.value < other.value | |
164 | ||
165 | def __le__(self, other): | |
166 | return self == other or self < other | |
167 | ||
168 | def __gt__(self, other): | |
169 | return not self <= other | |
170 | ||
171 | def __ge__(self, other): | |
172 | return not self < other | |
173 | ||
174 | def __eq__(self, other): | |
175 | if other == 0: | |
176 | return self.value == 0 | |
177 | if self.currency != other.currency: | |
178 | raise Exception("Comparing amounts must be done with same currencies") | |
179 | return self.value == other.value | |
180 | ||
181 | def __ne__(self, other): | |
182 | return not self == other | |
183 | ||
184 | def __neg__(self): | |
185 | return Amount(self.currency, - self.value) | |
186 | ||
187 | def __str__(self): | |
188 | if self.linked_to is None: | |
189 | return "{:.8f} {}".format(self.value, self.currency) | |
190 | else: | |
191 | return "{:.8f} {} [{}]".format(self.value, self.currency, self.linked_to) | |
192 | ||
193 | def __repr__(self): | |
194 | if self.linked_to is None: | |
195 | return "Amount({:.8f} {})".format(self.value, self.currency) | |
196 | else: | |
197 | return "Amount({:.8f} {} -> {})".format(self.value, self.currency, repr(self.linked_to)) | |
198 | ||
199 | class Balance: | |
200 | ||
201 | def __init__(self, currency, hash_): | |
202 | self.currency = currency | |
203 | for key in ["total", | |
204 | "exchange_total", "exchange_used", "exchange_free", | |
205 | "margin_total", "margin_borrowed", "margin_free"]: | |
206 | setattr(self, key, Amount(currency, hash_.get(key, 0))) | |
207 | ||
208 | self.margin_position_type = hash_.get("margin_position_type") | |
209 | ||
210 | if hash_.get("margin_borrowed_base_currency") is not None: | |
211 | base_currency = hash_["margin_borrowed_base_currency"] | |
212 | for key in [ | |
213 | "margin_liquidation_price", | |
214 | "margin_pending_gain", | |
215 | "margin_lending_fees", | |
216 | "margin_borrowed_base_price" | |
217 | ]: | |
218 | setattr(self, key, Amount(base_currency, hash_.get(key, 0))) | |
219 | ||
220 | def __repr__(self): | |
221 | if self.exchange_total > 0: | |
222 | if self.exchange_free > 0 and self.exchange_used > 0: | |
223 | exchange = " Exch: [✔{} + ❌{} = {}]".format(str(self.exchange_free), str(self.exchange_used), str(self.exchange_total)) | |
224 | elif self.exchange_free > 0: | |
225 | exchange = " Exch: [✔{}]".format(str(self.exchange_free)) | |
226 | else: | |
227 | exchange = " Exch: [❌{}]".format(str(self.exchange_used)) | |
228 | else: | |
229 | exchange = "" | |
230 | ||
231 | if self.margin_total > 0: | |
232 | if self.margin_free != 0 and self.margin_borrowed != 0: | |
233 | margin = " Margin: [✔{} + borrowed {} = {}]".format(str(self.margin_free), str(self.margin_borrowed), str(self.margin_total)) | |
234 | elif self.margin_free != 0: | |
235 | margin = " Margin: [✔{}]".format(str(self.margin_free)) | |
236 | else: | |
237 | margin = " Margin: [borrowed {}]".format(str(self.margin_borrowed)) | |
238 | elif self.margin_total < 0: | |
239 | margin = " Margin: [{} @@ {}/{}]".format(str(self.margin_total), | |
240 | str(self.margin_borrowed_base_price), | |
241 | str(self.margin_lending_fees)) | |
242 | else: | |
243 | margin = "" | |
244 | ||
245 | if self.margin_total != 0 and self.exchange_total != 0: | |
246 | total = " Total: [{}]".format(str(self.total)) | |
247 | else: | |
248 | total = "" | |
249 | ||
250 | return "Balance({}".format(self.currency) + "".join([exchange, margin, total]) + ")" | |
251 | ||
252 | class Trade: | |
253 | def __init__(self, value_from, value_to, currency, market=None): | |
254 | # We have value_from of currency, and want to finish with value_to of | |
255 | # that currency. value_* may not be in currency's terms | |
256 | self.currency = currency | |
257 | self.value_from = value_from | |
258 | self.value_to = value_to | |
259 | self.orders = [] | |
260 | self.market = market | |
261 | assert self.value_from.currency == self.value_to.currency | |
262 | if self.value_from != 0: | |
263 | assert self.value_from.linked_to is not None and self.value_from.linked_to.currency == self.currency | |
264 | elif self.value_from.linked_to is None: | |
265 | self.value_from.linked_to = Amount(self.currency, 0) | |
266 | self.base_currency = self.value_from.currency | |
267 | ||
268 | @property | |
269 | def action(self): | |
270 | if self.value_from == self.value_to: | |
271 | return None | |
272 | if self.base_currency == self.currency: | |
273 | return None | |
274 | ||
275 | if self.value_from < self.value_to: | |
276 | return "acquire" | |
277 | else: | |
278 | return "dispose" | |
279 | ||
280 | def order_action(self, inverted): | |
281 | if (self.value_from < self.value_to) != inverted: | |
282 | return "buy" | |
283 | else: | |
284 | return "sell" | |
285 | ||
286 | @property | |
287 | def trade_type(self): | |
288 | if self.value_from + self.value_to < 0: | |
289 | return "short" | |
290 | else: | |
291 | return "long" | |
292 | ||
293 | def filled_amount(self, in_base_currency=False): | |
294 | filled_amount = 0 | |
295 | for order in self.orders: | |
296 | filled_amount += order.filled_amount(in_base_currency=in_base_currency) | |
297 | return filled_amount | |
298 | ||
299 | def update_order(self, order, tick): | |
300 | new_order = None | |
301 | if tick in [0, 1, 3, 4, 6]: | |
302 | print("{}, tick {}, waiting".format(order, tick)) | |
303 | elif tick == 2: | |
304 | self.prepare_order(compute_value=lambda x, y: (x[y] + x["average"]) / 2) | |
305 | new_order = self.orders[-1] | |
306 | print("{}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order)) | |
307 | elif tick ==5: | |
308 | self.prepare_order(compute_value=lambda x, y: (x[y]*2 + x["average"]) / 3) | |
309 | new_order = self.orders[-1] | |
310 | print("{}, tick {}, cancelling and adjusting to {}".format(order, tick, new_order)) | |
311 | elif tick >= 7: | |
312 | if tick == 7: | |
313 | print("{}, tick {}, fallbacking to market value".format(order, tick)) | |
314 | if (tick - 7) % 3 == 0: | |
315 | self.prepare_order(compute_value="default") | |
316 | new_order = self.orders[-1] | |
317 | print("{}, tick {}, market value, cancelling and adjusting to {}".format(order, tick, new_order)) | |
318 | ||
319 | if new_order is not None: | |
320 | order.cancel() | |
321 | new_order.run() | |
322 | ||
323 | def prepare_order(self, compute_value="default"): | |
324 | if self.action is None: | |
325 | return | |
326 | ticker = h.get_ticker(self.currency, self.base_currency, self.market) | |
327 | inverted = ticker["inverted"] | |
328 | if inverted: | |
329 | ticker = ticker["original"] | |
330 | rate = Computation.compute_value(ticker, self.order_action(inverted), compute_value=compute_value) | |
331 | ||
332 | delta_in_base = abs(self.value_from - self.value_to) | |
333 | # 9 BTC's worth of move (10 - 1 or 1 - 10 depending on case) | |
334 | ||
335 | if not inverted: | |
336 | base_currency = self.base_currency | |
337 | # BTC | |
338 | if self.action == "dispose": | |
339 | filled = self.filled_amount(in_base_currency=False) | |
340 | delta = delta_in_base.in_currency(self.currency, self.market, rate=1/self.value_from.rate) | |
341 | # I have 10 BTC worth of FOO, and I want to sell 9 BTC | |
342 | # worth of it, computed first with rate 10 FOO = 1 BTC. | |
343 | # -> I "sell" "90" FOO at proposed rate "rate". | |
344 | ||
345 | delta = delta - filled | |
346 | # I already sold 60 FOO, 30 left | |
347 | else: | |
348 | filled = self.filled_amount(in_base_currency=True) | |
349 | delta = (delta_in_base - filled).in_currency(self.currency, self.market, rate=1/rate) | |
350 | # I want to buy 9 BTC worth of FOO, computed with rate | |
351 | # 10 FOO = 1 BTC | |
352 | # -> I "buy" "9 / rate" FOO at proposed rate "rate" | |
353 | ||
354 | # I already bought 3 / rate FOO, 6 / rate left | |
355 | else: | |
356 | base_currency = self.currency | |
357 | # FOO | |
358 | if self.action == "dispose": | |
359 | filled = self.filled_amount(in_base_currency=True) | |
360 | # Base is FOO | |
361 | ||
362 | delta = (delta_in_base.in_currency(self.currency, self.market, rate=1/self.value_from.rate) | |
363 | - filled).in_currency(self.base_currency, self.market, rate=1/rate) | |
364 | # I have 10 BTC worth of FOO, and I want to sell 9 BTC worth of it | |
365 | # computed at rate 1 Foo = 0.01 BTC | |
366 | # Computation says I should sell it at 125 FOO / BTC | |
367 | # -> delta_in_base = 9 BTC | |
368 | # -> delta = (9 * 1/0.01 FOO) * 1/125 = 7.2 BTC | |
369 | # Action: "buy" "7.2 BTC" at rate "125" "FOO" on market | |
370 | ||
371 | # I already bought 300/125 BTC, only 600/125 left | |
372 | else: | |
373 | filled = self.filled_amount(in_base_currency=False) | |
374 | # Base is FOO | |
375 | ||
376 | delta = delta_in_base | |
377 | # I have 1 BTC worth of FOO, and I want to buy 9 BTC worth of it | |
378 | # At rate 100 Foo / BTC | |
379 | # Computation says I should buy it at 125 FOO / BTC | |
380 | # -> delta_in_base = 9 BTC | |
381 | # Action: "sell" "9 BTC" at rate "125" "FOO" on market | |
382 | ||
383 | delta = delta - filled | |
384 | # I already sold 4 BTC, only 5 left | |
385 | ||
386 | close_if_possible = (self.value_to == 0) | |
387 | ||
388 | if delta <= 0: | |
389 | print("Less to do than already filled: {}".format(delta)) | |
390 | return | |
391 | ||
392 | self.orders.append(Order(self.order_action(inverted), | |
393 | delta, rate, base_currency, self.trade_type, | |
394 | self.market, self, close_if_possible=close_if_possible)) | |
395 | ||
396 | def __repr__(self): | |
397 | return "Trade({} -> {} in {}, {})".format( | |
398 | self.value_from, | |
399 | self.value_to, | |
400 | self.currency, | |
401 | self.action) | |
402 | ||
403 | def print_with_order(self): | |
404 | print(self) | |
405 | for order in self.orders: | |
406 | print("\t", order, sep="") | |
407 | ||
408 | class Order: | |
409 | def __init__(self, action, amount, rate, base_currency, trade_type, market, | |
410 | trade, close_if_possible=False): | |
411 | self.action = action | |
412 | self.amount = amount | |
413 | self.rate = rate | |
414 | self.base_currency = base_currency | |
415 | self.market = market | |
416 | self.trade_type = trade_type | |
417 | self.results = [] | |
418 | self.mouvements = [] | |
419 | self.status = "pending" | |
420 | self.trade = trade | |
421 | self.close_if_possible = close_if_possible | |
422 | ||
423 | def __repr__(self): | |
424 | return "Order({} {} {} at {} {} [{}]{})".format( | |
425 | self.action, | |
426 | self.trade_type, | |
427 | self.amount, | |
428 | self.rate, | |
429 | self.base_currency, | |
430 | self.status, | |
431 | " ✂" if self.close_if_possible else "", | |
432 | ) | |
433 | ||
434 | @property | |
435 | def account(self): | |
436 | if self.trade_type == "long": | |
437 | return "exchange" | |
438 | else: | |
439 | return "margin" | |
440 | ||
441 | @property | |
442 | def pending(self): | |
443 | return self.status == "pending" | |
444 | ||
445 | @property | |
446 | def finished(self): | |
447 | return self.status == "closed" or self.status == "canceled" or self.status == "error" | |
448 | ||
449 | @property | |
450 | def id(self): | |
451 | return self.results[0]["id"] | |
452 | ||
453 | def run(self): | |
454 | symbol = "{}/{}".format(self.amount.currency, self.base_currency) | |
455 | amount = round(self.amount, self.market.order_precision(symbol)).value | |
456 | ||
457 | if TradeStore.debug: | |
458 | print("market.create_order('{}', 'limit', '{}', {}, price={}, account={})".format( | |
459 | symbol, self.action, amount, self.rate, self.account)) | |
460 | self.status = "open" | |
461 | self.results.append({"debug": True, "id": -1}) | |
462 | else: | |
463 | try: | |
464 | self.results.append(self.market.create_order(symbol, 'limit', self.action, amount, price=self.rate, account=self.account)) | |
465 | self.status = "open" | |
466 | except Exception as e: | |
467 | self.status = "error" | |
468 | print("error when running market.create_order('{}', 'limit', '{}', {}, price={}, account={})".format( | |
469 | symbol, self.action, amount, self.rate, self.account)) | |
470 | self.error_message = str("{}: {}".format(e.__class__.__name__, e)) | |
471 | print(self.error_message) | |
472 | ||
473 | def get_status(self): | |
474 | if TradeStore.debug: | |
475 | return self.status | |
476 | # other states are "closed" and "canceled" | |
477 | if self.status == "open": | |
478 | self.fetch() | |
479 | if self.status != "open": | |
480 | self.mark_finished_order() | |
481 | return self.status | |
482 | ||
483 | def mark_finished_order(self): | |
484 | if TradeStore.debug: | |
485 | return | |
486 | if self.status == "closed": | |
487 | if self.trade_type == "short" and self.action == "buy" and self.close_if_possible: | |
488 | self.market.close_margin_position(self.amount.currency, self.base_currency) | |
489 | ||
490 | fetch_cache_timestamp = None | |
491 | def fetch(self, force=False): | |
492 | if TradeStore.debug or (not force and self.fetch_cache_timestamp is not None | |
493 | and time.time() - self.fetch_cache_timestamp < 10): | |
494 | return | |
495 | self.fetch_cache_timestamp = time.time() | |
496 | ||
497 | self.results.append(self.market.fetch_order(self.id)) | |
498 | result = self.results[-1] | |
499 | self.status = result["status"] | |
500 | # Time at which the order started | |
501 | self.timestamp = result["datetime"] | |
502 | self.fetch_mouvements() | |
503 | ||
504 | # FIXME: consider open order with dust remaining as closed | |
505 | ||
506 | @property | |
507 | def dust_amount_remaining(self): | |
508 | return self.remaining_amount < 0.001 | |
509 | ||
510 | @property | |
511 | def remaining_amount(self): | |
512 | if self.status == "open": | |
513 | self.fetch() | |
514 | return self.amount - self.filled_amount() | |
515 | ||
516 | def filled_amount(self, in_base_currency=False): | |
517 | if self.status == "open": | |
518 | self.fetch() | |
519 | filled_amount = 0 | |
520 | for mouvement in self.mouvements: | |
521 | if in_base_currency: | |
522 | filled_amount += mouvement.total_in_base | |
523 | else: | |
524 | filled_amount += mouvement.total | |
525 | return filled_amount | |
526 | ||
527 | def fetch_mouvements(self): | |
528 | mouvements = self.market.privatePostReturnOrderTrades({"orderNumber": self.id}) | |
529 | self.mouvements = [] | |
530 | ||
531 | for mouvement_hash in mouvements: | |
532 | self.mouvements.append(Mouvement(self.amount.currency, | |
533 | self.base_currency, mouvement_hash)) | |
534 | ||
535 | def cancel(self): | |
536 | if TradeStore.debug: | |
537 | self.status = "canceled" | |
538 | return | |
539 | self.market.cancel_order(self.result['id']) | |
540 | self.fetch() | |
541 | ||
542 | class Mouvement: | |
543 | def __init__(self, currency, base_currency, hash_): | |
544 | self.currency = currency | |
545 | self.base_currency = base_currency | |
546 | self.id = hash_["id"] | |
547 | self.action = hash_["type"] | |
548 | self.fee_rate = D(hash_["fee"]) | |
549 | self.date = datetime.strptime(hash_["date"], '%Y-%m-%d %H:%M:%S') | |
550 | self.rate = D(hash_["rate"]) | |
551 | self.total = Amount(currency, hash_["amount"]) | |
552 | # rate * total = total_in_base | |
553 | self.total_in_base = Amount(base_currency, hash_["total"]) | |
554 | ||
555 | if __name__ == '__main__': | |
556 | from market import market | |
557 | h.print_orders(market) |