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
11 def static_var(varname
, value
):
13 setattr(func
, varname
, value
)
18 URL
= "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json"
23 def repartition_pertenthousand(cls
, liquidity
="medium"):
24 cls
.parse_cryptoportfolio()
25 liquidities
= cls
.liquidities
[liquidity
]
26 last_date
= sorted(liquidities
.keys())[-1]
27 return liquidities
[last_date
]
30 def get_cryptoportfolio(cls
):
33 urllib3
.disable_warnings()
34 http
= urllib3
.PoolManager()
37 r
= http
.request("GET", cls
.URL
)
41 cls
.data
= json
.loads(r
.data
,
44 except json
.JSONDecodeError
:
48 def parse_cryptoportfolio(cls
):
50 cls
.get_cryptoportfolio()
52 def filter_weights(weight_hash
):
53 if weight_hash
[1] == 0:
55 if weight_hash
[0] == "_row":
60 def clean_weights_(h
):
61 if type(h
[1][i
]) == str:
62 return [h
[0], h
[1][i
]]
64 return [h
[0], int(h
[1][i
] * 10000)]
67 def parse_weights(portfolio_hash
):
68 # FIXME: we'll need shorts at some point
69 assert all(map(lambda x
: x
== "long", portfolio_hash
["holding"]["direction"]))
70 weights_hash
= portfolio_hash
["weights"]
72 for i
in range(len(weights_hash
["_row"])):
73 weights
[weights_hash
["_row"][i
]] = dict(filter(
75 map(clean_weights(i
), weights_hash
.items())))
78 high_liquidity
= parse_weights(cls
.data
["portfolio_1"])
79 medium_liquidity
= parse_weights(cls
.data
["portfolio_2"])
82 "medium": medium_liquidity
,
83 "high": high_liquidity
,
89 def __init__(self
, currency
, value
, linked_to
=None, ticker
=None):
90 self
.currency
= currency
92 self
.linked_to
= linked_to
95 self
.ticker_cache
= {}
96 self
.ticker_cache_timestamp
= time
.time()
98 def in_currency(self
, other_currency
, market
, action
="average"):
99 if other_currency
== self
.currency
:
101 asset_ticker
= Trade
.get_ticker(self
.currency
, other_currency
, market
)
102 if asset_ticker
is not None:
105 self
.value
* asset_ticker
[action
],
109 raise Exception("This asset is not available in the chosen market")
112 return Amount(self
.currency
, abs(self
.value
))
114 def __add__(self
, other
):
115 if other
.currency
!= self
.currency
and other
.value
* self
.value
!= 0:
116 raise Exception("Summing amounts must be done with same currencies")
117 return Amount(self
.currency
, self
.value
+ other
.value
)
119 def __radd__(self
, other
):
123 return self
.__add
__(other
)
125 def __sub__(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 __mul__(self
, value
):
131 if type(value
) != int and type(value
) != float and type(value
) != D
:
132 raise TypeError("Amount may only be multiplied by numbers")
133 return Amount(self
.currency
, self
.value
* value
)
135 def __rmul__(self
, value
):
136 return self
.__mul
__(value
)
138 def __floordiv__(self
, value
):
139 if type(value
) != int and type(value
) != float and type(value
) != D
:
140 raise TypeError("Amount may only be multiplied by integers")
141 return Amount(self
.currency
, self
.value
/ value
)
143 def __truediv__(self
, value
):
144 return self
.__floordiv
__(value
)
146 def __lt__(self
, other
):
147 if self
.currency
!= other
.currency
:
148 raise Exception("Comparing amounts must be done with same currencies")
149 return self
.value
< other
.value
151 def __eq__(self
, other
):
153 return self
.value
== 0
154 if self
.currency
!= other
.currency
:
155 raise Exception("Comparing amounts must be done with same currencies")
156 return self
.value
== other
.value
159 if self
.linked_to
is None:
160 return "{:.8f} {}".format(self
.value
, self
.currency
)
162 return "{:.8f} {} [{}]".format(self
.value
, self
.currency
, self
.linked_to
)
165 if self
.linked_to
is None:
166 return "Amount({:.8f} {})".format(self
.value
, self
.currency
)
168 return "Amount({:.8f} {} -> {})".format(self
.value
, self
.currency
, repr(self
.linked_to
))
173 def __init__(self
, currency
, total_value
, free_value
, used_value
):
174 self
.currency
= currency
175 self
.total
= Amount(currency
, total_value
)
176 self
.free
= Amount(currency
, free_value
)
177 self
.used
= Amount(currency
, used_value
)
180 def from_hash(cls
, currency
, hash_
):
181 return cls(currency
, hash_
["total"], hash_
["free"], hash_
["used"])
184 def in_currency(cls
, other_currency
, market
, action
="average", type="total"):
186 for currency
in cls
.known_balances
:
187 balance
= cls
.known_balances
[currency
]
188 other_currency_amount
= getattr(balance
, type)\
189 .in_currency(other_currency
, market
, action
=action
)
190 amounts
[currency
] = other_currency_amount
195 return cls
.known_balances
.keys()
198 def _fill_balances(cls
, hash_
):
200 if key
in ["info", "free", "used", "total"]:
202 if hash_
[key
]["total"] > 0:
203 cls
.known_balances
[key
] = cls
.from_hash(key
, hash_
[key
])
206 def fetch_balances(cls
, market
):
207 cls
._fill
_balances
(market
.fetch_balance())
208 return cls
.known_balances
211 def dispatch_assets(cls
, amount
):
212 repartition_pertenthousand
= Portfolio
.repartition_pertenthousand()
213 sum_pertenthousand
= sum([v
for k
, v
in repartition_pertenthousand
.items()])
215 for currency
, ptt
in repartition_pertenthousand
.items():
216 amounts
[currency
] = ptt
* amount
/ sum_pertenthousand
217 if currency
not in cls
.known_balances
:
218 cls
.known_balances
[currency
] = cls(currency
, 0, 0, 0)
222 def prepare_trades(cls
, market
, base_currency
="BTC"):
223 cls
.fetch_balances(market
)
224 values_in_base
= cls
.in_currency(base_currency
, market
)
225 total_base_value
= sum(values_in_base
.values())
226 new_repartition
= cls
.dispatch_assets(total_base_value
)
227 Trade
.compute_trades(values_in_base
, new_repartition
, market
=market
)
230 return "Balance({} [{}/{}/{}])".format(self
.currency
, str(self
.free
), str(self
.used
), str(self
.total
))
235 def __init__(self
, value_from
, value_to
, currency
, market
=None):
236 # We have value_from of currency, and want to finish with value_to of
237 # that currency. value_* may not be in currency's terms
238 self
.currency
= currency
239 self
.value_from
= value_from
240 self
.value_to
= value_to
243 assert self
.value_from
.currency
== self
.value_to
.currency
244 assert self
.value_from
.linked_to
is not None and self
.value_from
.linked_to
.currency
== self
.currency
245 self
.base_currency
= self
.value_from
.currency
249 def fetch_fees(cls
, market
):
250 if market
.__class
__ not in cls
.fees_cache
:
251 cls
.fees_cache
[market
.__class
__] = market
.fetch_fees()
252 return cls
.fees_cache
[market
.__class
__]
255 ticker_cache_timestamp
= time
.time()
257 def get_ticker(cls
, c1
, c2
, market
, refresh
=False):
261 "average": (1/ticker
["bid"] + 1/ticker
["ask"]) / 2,
264 def augment_ticker(ticker
):
267 "average": (ticker
["bid"] + ticker
["ask"] ) / 2,
270 if time
.time() - cls
.ticker_cache_timestamp
> 5:
271 cls
.ticker_cache
= {}
272 cls
.ticker_cache_timestamp
= time
.time()
274 if (c1
, c2
, market
.__class
__) in cls
.ticker_cache
:
275 return cls
.ticker_cache
[(c1
, c2
, market
.__class
__)]
276 if (c2
, c1
, market
.__class
__) in cls
.ticker_cache
:
277 return invert(cls
.ticker_cache
[(c2
, c1
, market
.__class
__)])
280 cls
.ticker_cache
[(c1
, c2
, market
.__class
__)] = market
.fetch_ticker("{}/{}".format(c1
, c2
))
281 augment_ticker(cls
.ticker_cache
[(c1
, c2
, market
.__class
__)])
282 except ccxt
.ExchangeError
:
284 cls
.ticker_cache
[(c2
, c1
, market
.__class
__)] = market
.fetch_ticker("{}/{}".format(c2
, c1
))
285 augment_ticker(cls
.ticker_cache
[(c2
, c1
, market
.__class
__)])
286 except ccxt
.ExchangeError
:
287 cls
.ticker_cache
[(c1
, c2
, market
.__class
__)] = None
288 return cls
.get_ticker(c1
, c2
, market
)
291 def compute_trades(cls
, values_in_base
, new_repartition
, market
=None):
292 base_currency
= sum(values_in_base
.values()).currency
293 for currency
in Balance
.currencies():
294 if currency
== base_currency
:
296 cls
.trades
[currency
] = cls(
297 values_in_base
.get(currency
, Amount(base_currency
, 0)),
298 new_repartition
.get(currency
, Amount(base_currency
, 0)),
302 cls
.trades
[currency
].prepare_order()
307 if self
.value_from
== self
.value_to
:
309 if self
.base_currency
== self
.currency
:
312 if self
.value_from
< self
.value_to
:
317 def order_action(self
, inverted
):
318 if self
.value_from
< self
.value_to
:
319 return "ask" if not inverted
else "bid"
321 return "bid" if not inverted
else "ask"
323 def prepare_order(self
):
324 if self
.action
is None:
326 ticker
= self
.value_from
.ticker
327 inverted
= ticker
["inverted"]
330 value_from
= self
.value_from
.linked_to
331 value_to
= self
.value_to
.in_currency(self
.currency
, self
.market
)
332 delta
= abs(value_to
- value_from
)
333 currency
= self
.base_currency
335 ticker
= ticker
["original"]
336 delta
= abs(self
.value_to
- self
.value_from
)
337 currency
= self
.currency
339 rate
= ticker
[self
.order_action(inverted
)]
341 self
.orders
.append(Order(self
.order_action(inverted
), delta
, rate
, currency
))
345 return sum(map(lambda v
: v
.orders
, cls
.trades
.values()), [])
348 def follow_orders(cls
, market
):
349 orders
= cls
.all_orders()
351 while len(orders
) != len(finished_orders
):
354 if order
in finished_orders
:
356 if order
.get_status(market
) != "open":
357 finished_orders
.append(order
)
358 print("finished {}".format(order
))
359 print("All orders finished")
362 return "Trade({} -> {} in {}, {})".format(
371 def __init__(self
, action
, amount
, rate
, base_currency
):
375 self
.base_currency
= base_currency
377 self
.status
= "not run"
380 return "Order({} {} at {} {} [{}])".format(
388 def run(self
, market
):
389 symbol
= "{}/{}".format(self
.amount
.currency
, self
.base_currency
)
390 amount
= self
.amount
.value
393 print("market.create_order('{}', 'limit', '{}', {}, price={})".format(
394 symbol
, self
.action
, amount
, self
.rate
))
397 self
.result
= market
.create_order(symbol
, 'limit', self
.action
, amount
, price
=self
.rate
)
402 def get_status(self
, market
):
403 # other states are "closed" and "canceled"
404 if self
.status
== "open":
405 result
= market
.fetch_order(self
.result
['id'])
406 self
.status
= result
["status"]
409 def print_orders(market
, base_currency
="BTC"):
410 Balance
.prepare_trades(market
, base_currency
=base_currency
)
411 for currency
, balance
in Balance
.known_balances
.items():
413 for currency
, trade
in Trade
.trades
.items():
415 for order
in trade
.orders
:
416 print("\t", order
, sep
="")
418 def make_orders(market
, base_currency
="BTC"):
419 Balance
.prepare_trades(market
, base_currency
=base_currency
)
420 for currency
, trade
in Trade
.trades
.items():
422 for order
in trade
.orders
:
423 print("\t", order
, sep
="")
426 if __name__
== '__main__':