2 from datetime
import datetime
3 from decimal
import Decimal
as D
, ROUND_DOWN
4 # Put your poloniex api key in market.py
5 from json
import JSONDecodeError
10 # FIXME: correctly handle web call timeouts
13 URL
= "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json"
18 def repartition(cls
, liquidity
="medium"):
19 cls
.parse_cryptoportfolio()
20 liquidities
= cls
.liquidities
[liquidity
]
21 cls
.last_date
= sorted(liquidities
.keys())[-1]
22 return liquidities
[cls
.last_date
]
25 def get_cryptoportfolio(cls
):
27 r
= requests
.get(cls
.URL
)
31 cls
.data
= r
.json(parse_int
=D
, parse_float
=D
)
32 except JSONDecodeError
:
36 def parse_cryptoportfolio(cls
):
38 cls
.get_cryptoportfolio()
40 def filter_weights(weight_hash
):
41 if weight_hash
[1][0] == 0:
43 if weight_hash
[0] == "_row":
48 def clean_weights_(h
):
49 if h
[0].endswith("s"):
50 return [h
[0][0:-1], (h
[1][i
], "short")]
52 return [h
[0], (h
[1][i
], "long")]
55 def parse_weights(portfolio_hash
):
56 weights_hash
= portfolio_hash
["weights"]
58 for i
in range(len(weights_hash
["_row"])):
59 weights
[weights_hash
["_row"][i
]] = dict(filter(
61 map(clean_weights(i
), weights_hash
.items())))
64 high_liquidity
= parse_weights(cls
.data
["portfolio_1"])
65 medium_liquidity
= parse_weights(cls
.data
["portfolio_2"])
68 "medium": medium_liquidity
,
69 "high": high_liquidity
,
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"],
81 def compute_value(cls
, ticker
, action
, compute_value
="default"):
86 if isinstance(compute_value
, str):
87 compute_value
= cls
.computations
[compute_value
]
88 return compute_value(ticker
, action
)
91 def __init__(self
, currency
, value
, linked_to
=None, ticker
=None, rate
=None):
92 self
.currency
= currency
94 self
.linked_to
= linked_to
98 def in_currency(self
, other_currency
, market
, rate
=None, action
=None, compute_value
="average"):
99 if other_currency
== self
.currency
:
107 asset_ticker
= h
.get_ticker(self
.currency
, other_currency
, market
)
108 if asset_ticker
is not None:
109 rate
= Computation
.compute_value(asset_ticker
, action
, compute_value
=compute_value
)
117 raise Exception("This asset is not available in the chosen market")
119 def __round__(self
, n
=8):
120 return Amount(self
.currency
, self
.value
.quantize(D(1)/D(10**n
), rounding
=ROUND_DOWN
))
123 return Amount(self
.currency
, abs(self
.value
))
125 def __add__(self
, other
):
126 if other
.currency
!= self
.currency
and other
.value
* self
.value
!= 0:
127 raise Exception("Summing amounts must be done with same currencies")
128 return Amount(self
.currency
, self
.value
+ other
.value
)
130 def __radd__(self
, other
):
134 return self
.__add
__(other
)
136 def __sub__(self
, other
):
139 if other
.currency
!= self
.currency
and other
.value
* self
.value
!= 0:
140 raise Exception("Summing amounts must be done with same currencies")
141 return Amount(self
.currency
, self
.value
- other
.value
)
143 def __mul__(self
, value
):
144 if not isinstance(value
, (int, float, D
)):
145 raise TypeError("Amount may only be multiplied by numbers")
146 return Amount(self
.currency
, self
.value
* value
)
148 def __rmul__(self
, value
):
149 return self
.__mul
__(value
)
151 def __floordiv__(self
, value
):
152 if not isinstance(value
, (int, float, D
)):
153 raise TypeError("Amount may only be divided by numbers")
154 return Amount(self
.currency
, self
.value
/ value
)
156 def __truediv__(self
, value
):
157 return self
.__floordiv
__(value
)
159 def __lt__(self
, other
):
161 return self
.value
< 0
162 if self
.currency
!= other
.currency
:
163 raise Exception("Comparing amounts must be done with same currencies")
164 return self
.value
< other
.value
166 def __le__(self
, other
):
167 return self
== other
or self
< other
169 def __gt__(self
, other
):
170 return not self
<= other
172 def __ge__(self
, other
):
173 return not self
< other
175 def __eq__(self
, other
):
177 return self
.value
== 0
178 if self
.currency
!= other
.currency
:
179 raise Exception("Comparing amounts must be done with same currencies")
180 return self
.value
== other
.value
182 def __ne__(self
, other
):
183 return not self
== other
186 return Amount(self
.currency
, - self
.value
)
189 if self
.linked_to
is None:
190 return "{:.8f} {}".format(self
.value
, self
.currency
)
192 return "{:.8f} {} [{}]".format(self
.value
, self
.currency
, self
.linked_to
)
195 if self
.linked_to
is None:
196 return "Amount({:.8f} {})".format(self
.value
, self
.currency
)
198 return "Amount({:.8f} {} -> {})".format(self
.value
, self
.currency
, repr(self
.linked_to
))
202 def __init__(self
, currency
, hash_
):
203 self
.currency
= currency
205 "exchange_total", "exchange_used", "exchange_free",
206 "margin_total", "margin_borrowed", "margin_free"]:
207 setattr(self
, key
, Amount(currency
, hash_
.get(key
, 0)))
209 self
.margin_position_type
= hash_
.get("margin_position_type")
211 if hash_
.get("margin_borrowed_base_currency") is not None:
212 base_currency
= hash_
["margin_borrowed_base_currency"]
214 "margin_liquidation_price",
215 "margin_pending_gain",
216 "margin_lending_fees",
217 "margin_borrowed_base_price"
219 setattr(self
, key
, Amount(base_currency
, hash_
.get(key
, 0)))
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
))
228 exchange
= " Exch: [❌{}]".format(str(self
.exchange_used
))
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
))
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
))
246 if self
.margin_total
!= 0 and self
.exchange_total
!= 0:
247 total
= " Total: [{}]".format(str(self
.total
))
251 return "Balance({}".format(self
.currency
) + "".join([exchange
, margin
, total
]) + ")"
254 def __init__(self
, value_from
, value_to
, currency
, market
=None):
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
262 assert self
.value_from
.currency
== self
.value_to
.currency
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)
267 self
.base_currency
= self
.value_from
.currency
271 if self
.value_from
== self
.value_to
:
273 if self
.base_currency
== self
.currency
:
276 if abs(self
.value_from
) < abs(self
.value_to
):
281 def order_action(self
, inverted
):
282 if (self
.value_from
< self
.value_to
) != inverted
:
288 def trade_type(self
):
289 if self
.value_from
+ self
.value_to
< 0:
294 def filled_amount(self
, in_base_currency
=False):
296 for order
in self
.orders
:
297 filled_amount
+= order
.filled_amount(in_base_currency
=in_base_currency
)
300 def update_order(self
, order
, tick
):
302 if tick
in [0, 1, 3, 4, 6]:
303 print("{}, tick {}, waiting".format(order
, tick
))
305 new_order
= self
.prepare_order(compute_value
=lambda x
, y
: (x
[y
] + x
["average"]) / 2)
306 print("{}, tick {}, cancelling and adjusting to {}".format(order
, tick
, new_order
))
308 new_order
= self
.prepare_order(compute_value
=lambda x
, y
: (x
[y
]*2 + x
["average"]) / 3)
309 print("{}, tick {}, cancelling and adjusting to {}".format(order
, tick
, new_order
))
312 print("{}, tick {}, fallbacking to market value".format(order
, tick
))
313 if (tick
- 7) % 3 == 0:
314 new_order
= self
.prepare_order(compute_value
="default")
315 print("{}, tick {}, market value, cancelling and adjusting to {}".format(order
, tick
, new_order
))
317 if new_order
is not None:
321 def prepare_order(self
, compute_value
="default"):
322 if self
.action
is None:
324 ticker
= h
.get_ticker(self
.currency
, self
.base_currency
, self
.market
)
325 inverted
= ticker
["inverted"]
327 ticker
= ticker
["original"]
328 rate
= Computation
.compute_value(ticker
, self
.order_action(inverted
), compute_value
=compute_value
)
330 delta_in_base
= abs(self
.value_from
- self
.value_to
)
331 # 9 BTC's worth of move (10 - 1 or 1 - 10 depending on case)
334 base_currency
= self
.base_currency
336 if self
.action
== "dispose":
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".
343 delta
= delta
- filled
344 # I already sold 60 FOO, 30 left
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
350 # -> I "buy" "9 / rate" FOO at proposed rate "rate"
352 # I already bought 3 / rate FOO, 6 / rate left
354 base_currency
= self
.currency
356 if self
.action
== "dispose":
357 filled
= self
.filled_amount(in_base_currency
=True)
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
369 # I already bought 300/125 BTC, only 600/125 left
371 filled
= self
.filled_amount(in_base_currency
=False)
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
381 delta
= delta
- filled
382 # I already sold 4 BTC, only 5 left
384 close_if_possible
= (self
.value_to
== 0)
387 print("Less to do than already filled: {}".format(delta
))
390 order
= Order(self
.order_action(inverted
),
391 delta
, rate
, base_currency
, self
.trade_type
,
392 self
.market
, self
, close_if_possible
=close_if_possible
)
393 self
.orders
.append(order
)
397 return "Trade({} -> {} in {}, {})".format(
403 def print_with_order(self
):
405 for order
in self
.orders
:
406 print("\t", order
, sep
="")
409 def __init__(self
, action
, amount
, rate
, base_currency
, trade_type
, market
,
410 trade
, close_if_possible
=False):
414 self
.base_currency
= base_currency
416 self
.trade_type
= trade_type
419 self
.status
= "pending"
421 self
.close_if_possible
= close_if_possible
423 self
.fetch_cache_timestamp
= None
426 return "Order({} {} {} at {} {} [{}]{})".format(
433 " ✂" if self
.close_if_possible
else "",
438 if self
.trade_type
== "long":
445 return self
.status
== "open"
449 return self
.status
== "pending"
453 return self
.status
== "closed" or self
.status
== "canceled" or self
.status
== "error"
456 symbol
= "{}/{}".format(self
.amount
.currency
, self
.base_currency
)
457 amount
= round(self
.amount
, self
.market
.order_precision(symbol
)).value
460 print("market.create_order('{}', 'limit', '{}', {}, price={}, account={})".format(
461 symbol
, self
.action
, amount
, self
.rate
, self
.account
))
462 self
.results
.append({"debug": True, "id": -1}
)
465 self
.results
.append(self
.market
.create_order(symbol
, 'limit', self
.action
, amount
, price
=self
.rate
, account
=self
.account
))
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
)
473 self
.id = self
.results
[0]["id"]
476 def get_status(self
):
479 # other states are "closed" and "canceled"
480 if not self
.finished
:
483 self
.mark_finished_order()
486 def mark_finished_order(self
):
489 if self
.status
== "closed":
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
)
493 def fetch(self
, force
=False):
494 if TradeStore
.debug
or (not force
and self
.fetch_cache_timestamp
is not None
495 and time
.time() - self
.fetch_cache_timestamp
< 10):
497 self
.fetch_cache_timestamp
= time
.time()
499 result
= self
.market
.fetch_order(self
.id)
500 self
.results
.append(result
)
502 self
.status
= result
["status"]
503 # Time at which the order started
504 self
.timestamp
= result
["datetime"]
505 self
.fetch_mouvements()
507 # FIXME: consider open order with dust remaining as closed
509 def dust_amount_remaining(self
):
510 return self
.remaining_amount() < Amount(self
.amount
.currency
, D("0.001"))
512 def remaining_amount(self
):
513 if self
.status
== "open":
515 return self
.amount
- self
.filled_amount()
517 def filled_amount(self
, in_base_currency
=False):
518 if self
.status
== "open":
521 for mouvement
in self
.mouvements
:
523 filled_amount
+= mouvement
.total_in_base
525 filled_amount
+= mouvement
.total
528 def fetch_mouvements(self
):
529 mouvements
= self
.market
.privatePostReturnOrderTrades({"orderNumber": self.id}
)
532 for mouvement_hash
in mouvements
:
533 self
.mouvements
.append(Mouvement(self
.amount
.currency
,
534 self
.base_currency
, mouvement_hash
))
538 self
.status
= "canceled"
540 self
.market
.cancel_order(self
.id)
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"])
556 if __name__
== '__main__': # pragma: no cover
557 from market
import market
558 h
.print_orders(market
)