3 # Put your poloniex api key in market.py
4 from market
import market
6 # FIXME: Améliorer le bid/ask
7 # FIXME: J'essayais d'utiliser plus de bitcoins que j'en avais à disposition
8 # FIXME: better compute moves to avoid rounding errors
10 def static_var(varname
, value
):
12 setattr(func
, varname
, value
)
17 URL
= "https://cryptoportfolio.io/wp-content/uploads/portfolio/json/cryptoportfolio.json"
22 def repartition_pertenthousand(cls
, liquidity
="medium"):
23 cls
.parse_cryptoportfolio()
24 liquidities
= cls
.liquidities
[liquidity
]
25 last_date
= sorted(liquidities
.keys())[-1]
26 return liquidities
[last_date
]
29 def get_cryptoportfolio(cls
):
32 urllib3
.disable_warnings()
33 http
= urllib3
.PoolManager()
36 r
= http
.request("GET", cls
.URL
)
40 cls
.data
= json
.loads(r
.data
)
41 except json
.JSONDecodeError
:
45 def parse_cryptoportfolio(cls
):
47 cls
.get_cryptoportfolio()
49 def filter_weights(weight_hash
):
50 if weight_hash
[1] == 0:
52 if weight_hash
[0] == "_row":
57 def clean_weights_(h
):
58 if type(h
[1][i
]) == str:
59 return [h
[0], h
[1][i
]]
61 return [h
[0], int(h
[1][i
] * 10000)]
64 def parse_weights(portfolio_hash
):
65 # FIXME: we'll need shorts at some point
66 assert all(map(lambda x
: x
== "long", portfolio_hash
["holding"]["direction"]))
67 weights_hash
= portfolio_hash
["weights"]
69 for i
in range(len(weights_hash
["_row"])):
70 weights
[weights_hash
["_row"][i
]] = dict(filter(
72 map(clean_weights(i
), weights_hash
.items())))
75 high_liquidity
= parse_weights(cls
.data
["portfolio_1"])
76 medium_liquidity
= parse_weights(cls
.data
["portfolio_2"])
79 "medium": medium_liquidity
,
80 "high": high_liquidity
,
86 def __init__(self
, currency
, value
, int_val
=None, linked_to
=None, ticker
=None):
87 self
.currency
= currency
89 self
._value
= int(value
* 10**self
.MAX_DIGITS
)
92 self
.linked_to
= linked_to
95 self
.ticker_cache
= {}
96 self
.ticker_cache_timestamp
= time
.time()
100 return self
._value
/ 10 ** self
.MAX_DIGITS
102 def in_currency(self
, other_currency
, market
, action
="average"):
103 if other_currency
== self
.currency
:
105 asset_ticker
= Trade
.get_ticker(self
.currency
, other_currency
, market
)
106 if asset_ticker
is not None:
110 int_val
=int(self
._value
* asset_ticker
[action
]),
114 raise Exception("This asset is not available in the chosen market")
117 return Amount(self
.currency
, 0, int_val
=abs(self
._value
))
119 def __add__(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
, 0, int_val
=self
._value
+ other
._value
)
124 def __radd__(self
, other
):
128 return self
.__add
__(other
)
130 def __sub__(self
, other
):
131 if other
.currency
!= self
.currency
and other
._value
* self
._value
!= 0:
132 raise Exception("Summing amounts must be done with same currencies")
133 return Amount(self
.currency
, 0, int_val
=self
._value
- other
._value
)
138 def __mul__(self
, value
):
139 if type(value
) != int and type(value
) != float:
140 raise TypeError("Amount may only be multiplied by numbers")
141 return Amount(self
.currency
, 0, int_val
=(self
._value
* value
))
143 def __rmul__(self
, value
):
144 return self
.__mul
__(value
)
146 def __floordiv__(self
, value
):
147 if type(value
) != int:
148 raise TypeError("Amount may only be multiplied by integers")
149 return Amount(self
.currency
, 0, int_val
=(self
._value
// value
))
151 def __truediv__(self
, value
):
152 return self
.__floordiv
__(value
)
154 def __lt__(self
, other
):
155 if self
.currency
!= other
.currency
:
156 raise Exception("Comparing amounts must be done with same currencies")
157 return self
._value
< other
._value
159 def __eq__(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
167 if self
.linked_to
is None:
168 return "{:.8f} {}".format(self
.value
, self
.currency
)
170 return "{:.8f} {} [{}]".format(self
.value
, self
.currency
, self
.linked_to
)
173 if self
.linked_to
is None:
174 return "Amount({:.8f} {})".format(self
.value
, self
.currency
)
176 return "Amount({:.8f} {} -> {})".format(self
.value
, self
.currency
, repr(self
.linked_to
))
181 def __init__(self
, currency
, total_value
, free_value
, used_value
):
182 self
.currency
= currency
183 self
.total
= Amount(currency
, total_value
)
184 self
.free
= Amount(currency
, free_value
)
185 self
.used
= Amount(currency
, used_value
)
188 def from_hash(cls
, currency
, hash_
):
189 return cls(currency
, hash_
["total"], hash_
["free"], hash_
["used"])
192 def in_currency(cls
, other_currency
, market
, action
="average", type="total"):
194 for currency
in cls
.known_balances
:
195 balance
= cls
.known_balances
[currency
]
196 other_currency_amount
= getattr(balance
, type)\
197 .in_currency(other_currency
, market
, action
=action
)
198 amounts
[currency
] = other_currency_amount
203 return cls
.known_balances
.keys()
206 def _fill_balances(cls
, hash_
):
208 if key
in ["info", "free", "used", "total"]:
210 if hash_
[key
]["total"] > 0:
211 cls
.known_balances
[key
] = cls
.from_hash(key
, hash_
[key
])
214 def fetch_balances(cls
, market
):
215 cls
._fill
_balances
(market
.fetch_balance())
216 return cls
.known_balances
219 def dispatch_assets(cls
, amount
):
220 repartition_pertenthousand
= Portfolio
.repartition_pertenthousand()
221 sum_pertenthousand
= sum([v
for k
, v
in repartition_pertenthousand
.items()])
223 for currency
, ptt
in repartition_pertenthousand
.items():
224 amounts
[currency
] = ptt
* amount
/ sum_pertenthousand
225 if currency
not in cls
.known_balances
:
226 cls
.known_balances
[currency
] = cls(currency
, 0, 0, 0)
230 def prepare_trades(cls
, market
, base_currency
="BTC"):
231 cls
.fetch_balances(market
)
232 values_in_base
= cls
.in_currency(base_currency
, market
)
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
, market
=market
)
238 return "Balance({} [{}/{}/{}])".format(self
.currency
, str(self
.free
), str(self
.used
), str(self
.total
))
243 def __init__(self
, value_from
, value_to
, currency
, market
=None):
244 # We have value_from of currency, and want to finish with value_to of
245 # that currency. value_* may not be in currency's terms
246 self
.currency
= currency
247 self
.value_from
= value_from
248 self
.value_to
= value_to
251 assert self
.value_from
.currency
== self
.value_to
.currency
252 assert self
.value_from
.linked_to
is not None and self
.value_from
.linked_to
.currency
== self
.currency
253 self
.base_currency
= self
.value_from
.currency
257 def fetch_fees(cls
, market
):
258 if market
.__class
__ not in cls
.fees_cache
:
259 cls
.fees_cache
[market
.__class
__] = market
.fetch_fees()
260 return cls
.fees_cache
[market
.__class
__]
263 ticker_cache_timestamp
= time
.time()
265 def get_ticker(cls
, c1
, c2
, market
, refresh
=False):
269 "average": (float(1/ticker
["bid"]) + float(1/ticker
["ask"]) ) / 2,
272 def augment_ticker(ticker
):
275 "average": (ticker
["bid"] + ticker
["ask"] ) / 2,
278 if time
.time() - cls
.ticker_cache_timestamp
> 5:
279 cls
.ticker_cache
= {}
280 cls
.ticker_cache_timestamp
= time
.time()
282 if (c1
, c2
, market
.__class
__) in cls
.ticker_cache
:
283 return cls
.ticker_cache
[(c1
, c2
, market
.__class
__)]
284 if (c2
, c1
, market
.__class
__) in cls
.ticker_cache
:
285 return invert(cls
.ticker_cache
[(c2
, c1
, market
.__class
__)])
288 cls
.ticker_cache
[(c1
, c2
, market
.__class
__)] = market
.fetch_ticker("{}/{}".format(c1
, c2
))
289 augment_ticker(cls
.ticker_cache
[(c1
, c2
, market
.__class
__)])
290 except ccxt
.ExchangeError
:
292 cls
.ticker_cache
[(c2
, c1
, market
.__class
__)] = market
.fetch_ticker("{}/{}".format(c2
, c1
))
293 augment_ticker(cls
.ticker_cache
[(c2
, c1
, market
.__class
__)])
294 except ccxt
.ExchangeError
:
295 cls
.ticker_cache
[(c1
, c2
, market
.__class
__)] = None
296 return cls
.get_ticker(c1
, c2
, market
)
299 def compute_trades(cls
, values_in_base
, new_repartition
, market
=None):
300 base_currency
= sum(values_in_base
.values()).currency
301 for currency
in Balance
.currencies():
302 if currency
== base_currency
:
304 cls
.trades
[currency
] = cls(
305 values_in_base
.get(currency
, Amount(base_currency
, 0)),
306 new_repartition
.get(currency
, Amount(base_currency
, 0)),
310 cls
.trades
[currency
].prepare_order()
315 if self
.value_from
== self
.value_to
:
317 if self
.base_currency
== self
.currency
:
320 if self
.value_from
< self
.value_to
:
325 def order_action(self
, inverted
):
326 if self
.value_from
< self
.value_to
:
327 return "ask" if not inverted
else "bid"
329 return "bid" if not inverted
else "ask"
331 def prepare_order(self
):
332 if self
.action
is None:
334 ticker
= self
.value_from
.ticker
335 inverted
= ticker
["inverted"]
338 value_from
= self
.value_from
.linked_to
339 value_to
= self
.value_to
.in_currency(self
.currency
, self
.market
)
340 delta
= abs(value_to
- value_from
)
341 currency
= self
.base_currency
343 ticker
= ticker
["original"]
344 delta
= abs(self
.value_to
- self
.value_from
)
345 currency
= self
.currency
347 rate
= ticker
[self
.order_action(inverted
)]
349 self
.orders
.append(Order(self
.order_action(inverted
), delta
, rate
, currency
))
353 return sum(map(lambda v
: v
.orders
, cls
.trades
.values()), [])
356 def follow_orders(cls
, market
):
357 orders
= cls
.all_orders()
359 while len(orders
) != len(finished_orders
):
362 if order
in finished_orders
:
364 if order
.get_status(market
) != "open":
365 finished_orders
.append(order
)
366 print("finished {}".format(order
))
367 print("All orders finished")
370 return "Trade({} -> {} in {}, {})".format(
379 def __init__(self
, action
, amount
, rate
, base_currency
):
383 self
.base_currency
= base_currency
385 self
.status
= "not run"
388 return "Order({} {} at {} {} [{}])".format(
396 def run(self
, market
):
397 symbol
= "{}/{}".format(self
.amount
.currency
, self
.base_currency
)
398 amount
= self
.amount
.value
401 print("market.create_order('{}', 'limit', '{}', {}, price={})".format(
402 symbol
, self
.action
, amount
, self
.rate
))
405 self
.result
= market
.create_order(symbol
, 'limit', self
.action
, amount
, price
=self
.rate
)
410 def get_status(self
, market
):
411 # other states are "closed" and "canceled"
412 if self
.status
== "open":
413 result
= market
.fetch_order(self
.result
['id'])
414 self
.status
= result
["status"]
417 def print_orders(market
, base_currency
="BTC"):
418 Balance
.prepare_trades(market
, base_currency
=base_currency
)
419 for currency
, trade
in Trade
.trades
.items():
421 for order
in trade
.orders
:
422 print("\t", order
, sep
="")
424 def make_orders(market
, base_currency
="BTC"):
425 Balance
.prepare_trades(market
, base_currency
=base_currency
)
426 for currency
, trade
in Trade
.trades
.items():
428 for order
in trade
.orders
:
429 print("\t", order
, sep
="")
432 if __name__
== '__main__':