]>
git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blob - portfolio.py
1fe56b5992222f8eafddae8479ae0fdbb9f1b987
1 from ccxt
import ExchangeError
3 from decimal
import Decimal
as D
4 # Put your poloniex api key in market.py
5 from market
import market
8 URL
= "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json"
13 def repartition_pertenthousand(cls
, liquidity
="medium"):
14 cls
.parse_cryptoportfolio()
15 liquidities
= cls
.liquidities
[liquidity
]
16 cls
.last_date
= sorted(liquidities
.keys())[-1]
17 return liquidities
[cls
.last_date
]
20 def get_cryptoportfolio(cls
):
23 urllib3
.disable_warnings()
24 http
= urllib3
.PoolManager()
27 r
= http
.request("GET", cls
.URL
)
31 cls
.data
= json
.loads(r
.data
,
34 except json
.JSONDecodeError
:
38 def parse_cryptoportfolio(cls
):
40 cls
.get_cryptoportfolio()
42 def filter_weights(weight_hash
):
43 if weight_hash
[1] == 0:
45 if weight_hash
[0] == "_row":
50 def clean_weights_(h
):
51 if isinstance(h
[1][i
], str):
52 return [h
[0], h
[1][i
]]
54 return [h
[0], int(h
[1][i
] * 10000)]
57 def parse_weights(portfolio_hash
):
58 # FIXME: we'll need shorts at some point
59 assert all(map(lambda x
: x
== "long", portfolio_hash
["holding"]["direction"]))
60 weights_hash
= portfolio_hash
["weights"]
62 for i
in range(len(weights_hash
["_row"])):
63 weights
[weights_hash
["_row"][i
]] = dict(filter(
65 map(clean_weights(i
), weights_hash
.items())))
68 high_liquidity
= parse_weights(cls
.data
["portfolio_1"])
69 medium_liquidity
= parse_weights(cls
.data
["portfolio_2"])
72 "medium": medium_liquidity
,
73 "high": high_liquidity
,
77 def __init__(self
, currency
, value
, linked_to
=None, ticker
=None, rate
=None):
78 self
.currency
= currency
80 self
.linked_to
= linked_to
84 self
.ticker_cache
= {}
85 self
.ticker_cache_timestamp
= time
.time()
87 def in_currency(self
, other_currency
, market
, rate
=None, action
=None, compute_value
="average"):
88 if other_currency
== self
.currency
:
96 asset_ticker
= Trade
.get_ticker(self
.currency
, other_currency
, market
)
97 if asset_ticker
is not None:
98 rate
= Trade
.compute_value(asset_ticker
, action
, compute_value
=compute_value
)
106 raise Exception("This asset is not available in the chosen market")
109 return Amount(self
.currency
, abs(self
.value
))
111 def __add__(self
, other
):
112 if other
.currency
!= self
.currency
and other
.value
* self
.value
!= 0:
113 raise Exception("Summing amounts must be done with same currencies")
114 return Amount(self
.currency
, self
.value
+ other
.value
)
116 def __radd__(self
, other
):
120 return self
.__add
__(other
)
122 def __sub__(self
, other
):
123 if other
.currency
!= self
.currency
and other
.value
* self
.value
!= 0:
124 raise Exception("Summing amounts must be done with same currencies")
125 return Amount(self
.currency
, self
.value
- other
.value
)
127 def __mul__(self
, value
):
128 if not isinstance(value
, (int, float, D
)):
129 raise TypeError("Amount may only be multiplied by numbers")
130 return Amount(self
.currency
, self
.value
* value
)
132 def __rmul__(self
, value
):
133 return self
.__mul
__(value
)
135 def __floordiv__(self
, value
):
136 if not isinstance(value
, (int, float, D
)):
137 raise TypeError("Amount may only be multiplied by integers")
138 return Amount(self
.currency
, self
.value
/ value
)
140 def __truediv__(self
, value
):
141 return self
.__floordiv
__(value
)
143 def __lt__(self
, other
):
144 if self
.currency
!= other
.currency
:
145 raise Exception("Comparing amounts must be done with same currencies")
146 return self
.value
< other
.value
148 def __eq__(self
, other
):
150 return self
.value
== 0
151 if self
.currency
!= other
.currency
:
152 raise Exception("Comparing amounts must be done with same currencies")
153 return self
.value
== other
.value
156 if self
.linked_to
is None:
157 return "{:.8f} {}".format(self
.value
, self
.currency
)
159 return "{:.8f} {} [{}]".format(self
.value
, self
.currency
, self
.linked_to
)
162 if self
.linked_to
is None:
163 return "Amount({:.8f} {})".format(self
.value
, self
.currency
)
165 return "Amount({:.8f} {} -> {})".format(self
.value
, self
.currency
, repr(self
.linked_to
))
170 def __init__(self
, currency
, total_value
, free_value
, used_value
):
171 self
.currency
= currency
172 self
.total
= Amount(currency
, total_value
)
173 self
.free
= Amount(currency
, free_value
)
174 self
.used
= Amount(currency
, used_value
)
177 def from_hash(cls
, currency
, hash_
):
178 return cls(currency
, hash_
["total"], hash_
["free"], hash_
["used"])
181 def in_currency(cls
, other_currency
, market
, compute_value
="average", type="total"):
183 for currency
in cls
.known_balances
:
184 balance
= cls
.known_balances
[currency
]
185 other_currency_amount
= getattr(balance
, type)\
186 .in_currency(other_currency
, market
, compute_value
=compute_value
)
187 amounts
[currency
] = other_currency_amount
192 return cls
.known_balances
.keys()
195 def _fill_balances(cls
, hash_
):
197 if key
in ["info", "free", "used", "total"]:
199 if hash_
[key
]["total"] > 0 or key
in cls
.known_balances
:
200 cls
.known_balances
[key
] = cls
.from_hash(key
, hash_
[key
])
203 def fetch_balances(cls
, market
):
204 cls
._fill
_balances
(market
.fetch_balance())
205 return cls
.known_balances
208 def dispatch_assets(cls
, amount
, repartition
=None):
209 if repartition
is None:
210 repartition
= Portfolio
.repartition_pertenthousand()
211 sum_pertenthousand
= sum([v
for k
, v
in repartition
.items()])
213 for currency
, ptt
in repartition
.items():
214 amounts
[currency
] = ptt
* amount
/ sum_pertenthousand
215 if currency
not in cls
.known_balances
:
216 cls
.known_balances
[currency
] = cls(currency
, 0, 0, 0)
220 def prepare_trades(cls
, market
, base_currency
="BTC", compute_value
="average"):
221 cls
.fetch_balances(market
)
222 values_in_base
= cls
.in_currency(base_currency
, market
, compute_value
=compute_value
)
223 total_base_value
= sum(values_in_base
.values())
224 new_repartition
= cls
.dispatch_assets(total_base_value
)
225 # Recompute it in case we have new currencies
226 values_in_base
= cls
.in_currency(base_currency
, market
, compute_value
=compute_value
)
227 Trade
.compute_trades(values_in_base
, new_repartition
, market
=market
)
230 def update_trades(cls
, market
, base_currency
="BTC", compute_value
="average", only
=None):
231 cls
.fetch_balances(market
)
232 values_in_base
= cls
.in_currency(base_currency
, market
, compute_value
=compute_value
)
233 total_base_value
= sum(values_in_base
.values())
234 new_repartition
= cls
.dispatch_assets(total_base_value
)
235 Trade
.compute_trades(values_in_base
, new_repartition
, only
=only
, market
=market
)
238 def prepare_trades_to_sell_all(cls
, market
, base_currency
="BTC", compute_value
="average"):
239 cls
.fetch_balances(market
)
240 values_in_base
= cls
.in_currency(base_currency
, market
, compute_value
=compute_value
)
241 total_base_value
= sum(values_in_base
.values())
242 new_repartition
= cls
.dispatch_assets(total_base_value
, repartition
={ base_currency: 1 }
)
243 Trade
.compute_trades(values_in_base
, new_repartition
, market
=market
)
246 return "Balance({} [{}/{}/{}])".format(self
.currency
, str(self
.free
), str(self
.used
), str(self
.total
))
250 "default": lambda x
, y
: x
[y
],
251 "average": lambda x
, y
: x
["average"],
252 "bid": lambda x
, y
: x
["bid"],
253 "ask": lambda x
, y
: x
["ask"],
260 def __init__(self
, value_from
, value_to
, currency
, market
=None):
261 # We have value_from of currency, and want to finish with value_to of
262 # that currency. value_* may not be in currency's terms
263 self
.currency
= currency
264 self
.value_from
= value_from
265 self
.value_to
= value_to
268 assert self
.value_from
.currency
== self
.value_to
.currency
269 assert self
.value_from
.linked_to
is not None and self
.value_from
.linked_to
.currency
== self
.currency
270 self
.base_currency
= self
.value_from
.currency
274 def fetch_fees(cls
, market
):
275 if market
.__class
__ not in cls
.fees_cache
:
276 cls
.fees_cache
[market
.__class
__] = market
.fetch_fees()
277 return cls
.fees_cache
[market
.__class
__]
280 ticker_cache_timestamp
= time
.time()
282 def get_ticker(cls
, c1
, c2
, market
, refresh
=False):
286 "average": (1/ticker
["bid"] + 1/ticker
["ask"]) / 2,
289 def augment_ticker(ticker
):
292 "average": (ticker
["bid"] + ticker
["ask"] ) / 2,
295 if time
.time() - cls
.ticker_cache_timestamp
> 5:
296 cls
.ticker_cache
= {}
297 cls
.ticker_cache_timestamp
= time
.time()
299 if (c1
, c2
, market
.__class
__) in cls
.ticker_cache
:
300 return cls
.ticker_cache
[(c1
, c2
, market
.__class
__)]
301 if (c2
, c1
, market
.__class
__) in cls
.ticker_cache
:
302 return invert(cls
.ticker_cache
[(c2
, c1
, market
.__class
__)])
305 cls
.ticker_cache
[(c1
, c2
, market
.__class
__)] = market
.fetch_ticker("{}/{}".format(c1
, c2
))
306 augment_ticker(cls
.ticker_cache
[(c1
, c2
, market
.__class
__)])
307 except ExchangeError
:
309 cls
.ticker_cache
[(c2
, c1
, market
.__class
__)] = market
.fetch_ticker("{}/{}".format(c2
, c1
))
310 augment_ticker(cls
.ticker_cache
[(c2
, c1
, market
.__class
__)])
311 except ExchangeError
:
312 cls
.ticker_cache
[(c1
, c2
, market
.__class
__)] = None
313 return cls
.get_ticker(c1
, c2
, market
)
316 def compute_trades(cls
, values_in_base
, new_repartition
, only
=None, market
=None):
317 base_currency
= sum(values_in_base
.values()).currency
318 for currency
in Balance
.currencies():
319 if currency
== base_currency
:
322 values_in_base
.get(currency
, Amount(base_currency
, 0)),
323 new_repartition
.get(currency
, Amount(base_currency
, 0)),
327 if only
is None or trade
.action
== only
:
328 cls
.trades
[currency
] = trade
332 def prepare_orders(cls
, only
=None, compute_value
="default"):
333 for currency
, trade
in cls
.trades
.items():
334 if only
is None or trade
.action
== only
:
335 trade
.prepare_order(compute_value
=compute_value
)
339 if self
.value_from
== self
.value_to
:
341 if self
.base_currency
== self
.currency
:
344 if self
.value_from
< self
.value_to
:
349 def order_action(self
, inverted
):
350 if self
.value_from
< self
.value_to
:
351 return "buy" if not inverted
else "sell"
353 return "sell" if not inverted
else "buy"
355 def prepare_order(self
, compute_value
="default"):
356 if self
.action
is None:
358 ticker
= self
.value_from
.ticker
359 inverted
= ticker
["inverted"]
361 ticker
= ticker
["original"]
362 rate
= Trade
.compute_value(ticker
, self
.order_action(inverted
), compute_value
=compute_value
)
365 delta_in_base
= abs(self
.value_from
- self
.value_to
)
366 # 9 BTC's worth of move (10 - 1 or 1 - 10 depending on case)
369 if self
.action
== "sell":
370 # I have 10 BTC worth of FOO, and I want to sell 9 BTC worth of it
371 # At rate 1 Foo = 0.1 BTC
372 value_from
= self
.value_from
.linked_to
373 # value_from = 100 FOO
374 value_to
= self
.value_to
.in_currency(self
.currency
, self
.market
, rate
=1/self
.value_from
.rate
)
375 # value_to = 10 FOO (1 BTC * 1/0.1)
376 delta
= abs(value_to
- value_from
)
378 # Action: "sell" "90 FOO" at rate "0.1" "BTC" on "market"
380 # Note: no rounding error possible: if we have value_to == 0, then delta == value_from
382 delta
= delta_in_base
.in_currency(self
.currency
, self
.market
, rate
=1/rate
)
383 # I want to buy 9 / 0.1 FOO
384 # Action: "buy" "90 FOO" at rate "0.1" "BTC" on "market"
386 # FIXME: Need to round up to the correct amount of FOO in case
387 # we want to use all BTC
388 currency
= self
.base_currency
391 if self
.action
== "sell":
392 # I have 10 BTC worth of FOO, and I want to sell 9 BTC worth of it
393 # At rate 1 Foo = 0.1 BTC
394 delta
= delta_in_base
395 # Action: "buy" "9 BTC" at rate "1/0.1" "FOO" on market
397 # FIXME: Need to round up to the correct amount of FOO in case
398 # we want to sell all
400 delta
= delta_in_base
401 # I want to buy 9 / 0.1 FOO
402 # Action: "sell" "9 BTC" at rate "1/0.1" "FOO" on "market"
404 # FIXME: Need to round up to the correct amount of FOO in case
405 # we want to use all BTC
407 currency
= self
.currency
410 self
.orders
.append(Order(self
.order_action(inverted
), delta
, rate
, currency
, self
.market
))
413 def compute_value(cls
, ticker
, action
, compute_value
="default"):
414 if isinstance(compute_value
, str):
415 compute_value
= Computation
.computations
[compute_value
]
416 return compute_value(ticker
, action
)
419 def all_orders(cls
, state
=None):
420 all_orders
= sum(map(lambda v
: v
.orders
, cls
.trades
.values()), [])
424 return list(filter(lambda o
: o
.status
== state
, all_orders
))
428 for order
in cls
.all_orders(state
="pending"):
432 def follow_orders(cls
, verbose
=True, sleep
=30):
433 orders
= cls
.all_orders()
435 while len(orders
) != len(finished_orders
):
438 if order
in finished_orders
:
440 if order
.get_status() != "open":
441 finished_orders
.append(order
)
443 print("finished {}".format(order
))
445 print("All orders finished")
448 def update_all_orders_status(cls
):
449 for order
in cls
.all_orders(state
="open"):
453 return "Trade({} -> {} in {}, {})".format(
460 def print_all_with_order(cls
):
461 for trade
in cls
.trades
.values():
462 trade
.print_with_order()
464 def print_with_order(self
):
466 for order
in self
.orders
:
467 print("\t", order
, sep
="")
470 def __init__(self
, action
, amount
, rate
, base_currency
, market
):
474 self
.base_currency
= base_currency
477 self
.status
= "pending"
480 return "Order({} {} at {} {} [{}])".format(
490 return self
.status
== "pending"
494 return self
.status
== "closed" or self
.status
== "canceled" or self
.status
== "error"
496 def run(self
, debug
=False):
497 symbol
= "{}/{}".format(self
.amount
.currency
, self
.base_currency
)
498 amount
= self
.amount
.value
501 print("market.create_order('{}', 'limit', '{}', {}, price={})".format(
502 symbol
, self
.action
, amount
, self
.rate
))
505 self
.result
= self
.market
.create_order(symbol
, 'limit', self
.action
, amount
, price
=self
.rate
)
507 except Exception as e
:
508 self
.status
= "error"
509 print("error when running market.create_order('{}', 'limit', '{}', {}, price={})".format(
510 symbol
, self
.action
, amount
, self
.rate
))
511 self
.error_message
= str("{}: {}".format(e
.__class
__.__name
__, e
))
512 print(self
.error_message
)
514 def get_status(self
):
515 # other states are "closed" and "canceled"
516 if self
.status
== "open":
517 result
= self
.market
.fetch_order(self
.result
['id'])
518 self
.status
= result
["status"]
522 self
.market
.cancel_order(self
.result
['id'])
524 def print_orders(market
, base_currency
="BTC"):
525 Balance
.prepare_trades(market
, base_currency
=base_currency
, compute_value
="average")
526 Trade
.prepare_orders(compute_value
="average")
527 for currency
, balance
in Balance
.known_balances
.items():
529 portfolio
.Trade
.print_all_with_order()
531 def make_orders(market
, base_currency
="BTC"):
532 Balance
.prepare_trades(market
, base_currency
=base_currency
)
533 for currency
, trade
in Trade
.trades
.items():
535 for order
in trade
.orders
:
536 print("\t", order
, sep
="")
539 if __name__
== '__main__':