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