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