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