3 from decimal
import Decimal
as D
4 # Put your poloniex api key in market.py
5 from market
import market
7 # FIXME: Améliorer le bid/ask
8 # FIXME: J'essayais d'utiliser plus de bitcoins que j'en avais à disposition
9 # FIXME: better compute moves to avoid rounding errors
12 URL
= "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json"
17 def repartition_pertenthousand(cls
, liquidity
="medium"):
18 cls
.parse_cryptoportfolio()
19 liquidities
= cls
.liquidities
[liquidity
]
20 last_date
= sorted(liquidities
.keys())[-1]
21 return liquidities
[last_date
]
24 def get_cryptoportfolio(cls
):
27 urllib3
.disable_warnings()
28 http
= urllib3
.PoolManager()
31 r
= http
.request("GET", cls
.URL
)
35 cls
.data
= json
.loads(r
.data
,
38 except json
.JSONDecodeError
:
42 def parse_cryptoportfolio(cls
):
44 cls
.get_cryptoportfolio()
46 def filter_weights(weight_hash
):
47 if weight_hash
[1] == 0:
49 if weight_hash
[0] == "_row":
54 def clean_weights_(h
):
55 if type(h
[1][i
]) == str:
56 return [h
[0], h
[1][i
]]
58 return [h
[0], int(h
[1][i
] * 10000)]
61 def parse_weights(portfolio_hash
):
62 # FIXME: we'll need shorts at some point
63 assert all(map(lambda x
: x
== "long", portfolio_hash
["holding"]["direction"]))
64 weights_hash
= portfolio_hash
["weights"]
66 for i
in range(len(weights_hash
["_row"])):
67 weights
[weights_hash
["_row"][i
]] = dict(filter(
69 map(clean_weights(i
), weights_hash
.items())))
72 high_liquidity
= parse_weights(cls
.data
["portfolio_1"])
73 medium_liquidity
= parse_weights(cls
.data
["portfolio_2"])
76 "medium": medium_liquidity
,
77 "high": high_liquidity
,
83 def __init__(self
, currency
, value
, linked_to
=None, ticker
=None):
84 self
.currency
= currency
86 self
.linked_to
= linked_to
89 self
.ticker_cache
= {}
90 self
.ticker_cache_timestamp
= time
.time()
92 def in_currency(self
, other_currency
, market
, action
=None, compute_value
="average"):
93 if other_currency
== self
.currency
:
95 asset_ticker
= Trade
.get_ticker(self
.currency
, other_currency
, market
)
96 if asset_ticker
is not None:
99 self
.value
* Trade
.compute_value(asset_ticker
, action
, compute_value
=compute_value
),
103 raise Exception("This asset is not available in the chosen market")
106 return Amount(self
.currency
, abs(self
.value
))
108 def __add__(self
, other
):
109 if other
.currency
!= self
.currency
and other
.value
* self
.value
!= 0:
110 raise Exception("Summing amounts must be done with same currencies")
111 return Amount(self
.currency
, self
.value
+ other
.value
)
113 def __radd__(self
, other
):
117 return self
.__add
__(other
)
119 def __sub__(self
, other
):
120 if other
.currency
!= self
.currency
and other
.value
* self
.value
!= 0:
121 raise Exception("Summing amounts must be done with same currencies")
122 return Amount(self
.currency
, self
.value
- other
.value
)
124 def __mul__(self
, value
):
125 if type(value
) != int and type(value
) != float and type(value
) != D
:
126 raise TypeError("Amount may only be multiplied by numbers")
127 return Amount(self
.currency
, self
.value
* value
)
129 def __rmul__(self
, value
):
130 return self
.__mul
__(value
)
132 def __floordiv__(self
, value
):
133 if type(value
) != int and type(value
) != float and type(value
) != D
:
134 raise TypeError("Amount may only be multiplied by integers")
135 return Amount(self
.currency
, self
.value
/ value
)
137 def __truediv__(self
, value
):
138 return self
.__floordiv
__(value
)
140 def __lt__(self
, other
):
141 if self
.currency
!= other
.currency
:
142 raise Exception("Comparing amounts must be done with same currencies")
143 return self
.value
< other
.value
145 def __eq__(self
, other
):
147 return self
.value
== 0
148 if self
.currency
!= other
.currency
:
149 raise Exception("Comparing amounts must be done with same currencies")
150 return self
.value
== other
.value
153 if self
.linked_to
is None:
154 return "{:.8f} {}".format(self
.value
, self
.currency
)
156 return "{:.8f} {} [{}]".format(self
.value
, self
.currency
, self
.linked_to
)
159 if self
.linked_to
is None:
160 return "Amount({:.8f} {})".format(self
.value
, self
.currency
)
162 return "Amount({:.8f} {} -> {})".format(self
.value
, self
.currency
, repr(self
.linked_to
))
167 def __init__(self
, currency
, total_value
, free_value
, used_value
):
168 self
.currency
= currency
169 self
.total
= Amount(currency
, total_value
)
170 self
.free
= Amount(currency
, free_value
)
171 self
.used
= Amount(currency
, used_value
)
174 def from_hash(cls
, currency
, hash_
):
175 return cls(currency
, hash_
["total"], hash_
["free"], hash_
["used"])
178 def in_currency(cls
, other_currency
, market
, compute_value
="average", type="total"):
180 for currency
in cls
.known_balances
:
181 balance
= cls
.known_balances
[currency
]
182 other_currency_amount
= getattr(balance
, type)\
183 .in_currency(other_currency
, market
, compute_value
=compute_value
)
184 amounts
[currency
] = other_currency_amount
189 return cls
.known_balances
.keys()
192 def _fill_balances(cls
, hash_
):
194 if key
in ["info", "free", "used", "total"]:
196 if hash_
[key
]["total"] > 0:
197 cls
.known_balances
[key
] = cls
.from_hash(key
, hash_
[key
])
200 def fetch_balances(cls
, market
):
201 cls
._fill
_balances
(market
.fetch_balance())
202 return cls
.known_balances
205 def dispatch_assets(cls
, amount
):
206 repartition_pertenthousand
= Portfolio
.repartition_pertenthousand()
207 sum_pertenthousand
= sum([v
for k
, v
in repartition_pertenthousand
.items()])
209 for currency
, ptt
in repartition_pertenthousand
.items():
210 amounts
[currency
] = ptt
* amount
/ sum_pertenthousand
211 if currency
not in cls
.known_balances
:
212 cls
.known_balances
[currency
] = cls(currency
, 0, 0, 0)
216 def prepare_trades(cls
, market
, base_currency
="BTC", compute_value
=None):
217 cls
.fetch_balances(market
)
218 values_in_base
= cls
.in_currency(base_currency
, market
)
219 total_base_value
= sum(values_in_base
.values())
220 new_repartition
= cls
.dispatch_assets(total_base_value
)
221 # Recompute it in case we have new currencies
222 values_in_base
= cls
.in_currency(base_currency
, market
)
223 Trade
.compute_trades(values_in_base
, new_repartition
, market
=market
, compute_value
=compute_value
)
226 return "Balance({} [{}/{}/{}])".format(self
.currency
, str(self
.free
), str(self
.used
), str(self
.total
))
229 def average_inverse(ticker
, action
):
230 if ticker
["inverted"]:
231 return 1/ticker
["original"]["average"]
233 return ticker
["average"]
236 "default": lambda x
, y
: x
[y
],
237 "average_inverse": average_inverse
,
238 "average": lambda x
, y
: x
["average"],
239 "bid": lambda x
, y
: x
["bid"],
240 "ask": lambda x
, y
: x
["ask"],
247 def __init__(self
, value_from
, value_to
, currency
, market
=None):
248 # We have value_from of currency, and want to finish with value_to of
249 # that currency. value_* may not be in currency's terms
250 self
.currency
= currency
251 self
.value_from
= value_from
252 self
.value_to
= value_to
255 assert self
.value_from
.currency
== self
.value_to
.currency
256 assert self
.value_from
.linked_to
is not None and self
.value_from
.linked_to
.currency
== self
.currency
257 self
.base_currency
= self
.value_from
.currency
261 def fetch_fees(cls
, market
):
262 if market
.__class
__ not in cls
.fees_cache
:
263 cls
.fees_cache
[market
.__class
__] = market
.fetch_fees()
264 return cls
.fees_cache
[market
.__class
__]
267 ticker_cache_timestamp
= time
.time()
269 def get_ticker(cls
, c1
, c2
, market
, refresh
=False):
273 "average": (1/ticker
["bid"] + 1/ticker
["ask"]) / 2,
276 def augment_ticker(ticker
):
279 "average": (ticker
["bid"] + ticker
["ask"] ) / 2,
282 if time
.time() - cls
.ticker_cache_timestamp
> 5:
283 cls
.ticker_cache
= {}
284 cls
.ticker_cache_timestamp
= time
.time()
286 if (c1
, c2
, market
.__class
__) in cls
.ticker_cache
:
287 return cls
.ticker_cache
[(c1
, c2
, market
.__class
__)]
288 if (c2
, c1
, market
.__class
__) in cls
.ticker_cache
:
289 return invert(cls
.ticker_cache
[(c2
, c1
, market
.__class
__)])
292 cls
.ticker_cache
[(c1
, c2
, market
.__class
__)] = market
.fetch_ticker("{}/{}".format(c1
, c2
))
293 augment_ticker(cls
.ticker_cache
[(c1
, c2
, market
.__class
__)])
294 except ccxt
.ExchangeError
:
296 cls
.ticker_cache
[(c2
, c1
, market
.__class
__)] = market
.fetch_ticker("{}/{}".format(c2
, c1
))
297 augment_ticker(cls
.ticker_cache
[(c2
, c1
, market
.__class
__)])
298 except ccxt
.ExchangeError
:
299 cls
.ticker_cache
[(c1
, c2
, market
.__class
__)] = None
300 return cls
.get_ticker(c1
, c2
, market
)
303 def compute_trades(cls
, values_in_base
, new_repartition
, market
=None, compute_value
=None):
304 base_currency
= sum(values_in_base
.values()).currency
305 for currency
in Balance
.currencies():
306 if currency
== base_currency
:
308 cls
.trades
[currency
] = cls(
309 values_in_base
.get(currency
, Amount(base_currency
, 0)),
310 new_repartition
.get(currency
, Amount(base_currency
, 0)),
314 if compute_value
is not None:
315 cls
.trades
[currency
].prepare_order(compute_value
=compute_value
)
320 if self
.value_from
== self
.value_to
:
322 if self
.base_currency
== self
.currency
:
325 if self
.value_from
< self
.value_to
:
330 def order_action(self
, inverted
):
331 if self
.value_from
< self
.value_to
:
332 return "ask" if not inverted
else "bid"
334 return "bid" if not inverted
else "ask"
336 def prepare_order(self
, compute_value
="default"):
337 if self
.action
is None:
339 ticker
= self
.value_from
.ticker
340 inverted
= ticker
["inverted"]
343 value_from
= self
.value_from
.linked_to
344 # The ticker will most probably be inverted, but we want the average
345 # of the initial value
346 value_to
= self
.value_to
.in_currency(self
.currency
, self
.market
, compute_value
="average_inverse")
347 delta
= abs(value_to
- value_from
)
348 currency
= self
.base_currency
350 ticker
= ticker
["original"]
351 delta
= abs(self
.value_to
- self
.value_from
)
352 currency
= self
.currency
354 rate
= Trade
.compute_value(ticker
, self
.order_action(inverted
), compute_value
=compute_value
)
356 self
.orders
.append(Order(self
.order_action(inverted
), delta
, rate
, currency
))
359 def compute_value(cls
, ticker
, action
, compute_value
="default"):
360 if type(compute_value
) == str:
361 compute_value
= Computation
.computations
[compute_value
]
362 return compute_value(ticker
, action
)
366 return sum(map(lambda v
: v
.orders
, cls
.trades
.values()), [])
369 def follow_orders(cls
, market
):
370 orders
= cls
.all_orders()
372 while len(orders
) != len(finished_orders
):
375 if order
in finished_orders
:
377 if order
.get_status(market
) != "open":
378 finished_orders
.append(order
)
379 print("finished {}".format(order
))
380 print("All orders finished")
383 return "Trade({} -> {} in {}, {})".format(
392 def __init__(self
, action
, amount
, rate
, base_currency
):
396 self
.base_currency
= base_currency
398 self
.status
= "not run"
401 return "Order({} {} at {} {} [{}])".format(
409 def run(self
, market
):
410 symbol
= "{}/{}".format(self
.amount
.currency
, self
.base_currency
)
411 amount
= self
.amount
.value
414 print("market.create_order('{}', 'limit', '{}', {}, price={})".format(
415 symbol
, self
.action
, amount
, self
.rate
))
418 self
.result
= market
.create_order(symbol
, 'limit', self
.action
, amount
, price
=self
.rate
)
423 def get_status(self
, market
):
424 # other states are "closed" and "canceled"
425 if self
.status
== "open":
426 result
= market
.fetch_order(self
.result
['id'])
427 self
.status
= result
["status"]
430 def print_orders(market
, base_currency
="BTC"):
431 Balance
.prepare_trades(market
, base_currency
=base_currency
, compute_value
="average")
432 for currency
, balance
in Balance
.known_balances
.items():
434 for currency
, trade
in Trade
.trades
.items():
436 for order
in trade
.orders
:
437 print("\t", order
, sep
="")
439 def make_orders(market
, base_currency
="BTC"):
440 Balance
.prepare_trades(market
, base_currency
=base_currency
)
441 for currency
, trade
in Trade
.trades
.items():
443 for order
in trade
.orders
:
444 print("\t", order
, sep
="")
447 if __name__
== '__main__':