]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blame - ccxt_wrapper.py
Fix price imprecision due to floats
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git] / ccxt_wrapper.py
CommitLineData
774c099c
IB
1from ccxt import *
2import decimal
9f1408a3 3import time
c7c1e0b2
IB
4from retry.api import retry_call
5import re
d8e233ac
IB
6from requests.exceptions import RequestException
7from ssl import SSLError
774c099c
IB
8
9def _cw_exchange_sum(self, *args):
10 return sum([arg for arg in args if isinstance(arg, (float, int, decimal.Decimal))])
11Exchange.sum = _cw_exchange_sum
12
2308a1c4 13class poloniexE(poloniex):
c7c1e0b2
IB
14 RETRIABLE_CALLS = [
15 re.compile(r"^return"),
16 re.compile(r"^cancel"),
17 re.compile(r"^closeMarginPosition$"),
18 re.compile(r"^getMarginPosition$"),
19 ]
20
21 def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
22 """
23 Wrapped to allow retry of non-posting requests"
24 """
25
b03f2a30 26 origin_request = super().request
c7c1e0b2
IB
27 kwargs = {
28 "api": api,
29 "method": method,
30 "params": params,
31 "headers": headers,
32 "body": body
33 }
34
35 retriable = any(re.match(call, path) for call in self.RETRIABLE_CALLS)
36 if api == "public" or method == "GET" or retriable:
37 return retry_call(origin_request, fargs=[path], fkwargs=kwargs,
b47d7b54 38 tries=10, delay=1, exceptions=(RequestTimeout, InvalidNonce))
c7c1e0b2
IB
39 else:
40 return origin_request(path, **kwargs)
41
445b4a77 42 def __init__(self, *args, **kwargs):
b03f2a30 43 super().__init__(*args, **kwargs)
445b4a77
IB
44
45 # For requests logging
46 self.session.origin_request = self.session.request
47 self.session._parent = self
48
49 def request_wrap(self, *args, **kwargs):
e7d7c0e5
IB
50 kwargs["headers"]["X-market-id"] = str(self._parent._market.market_id)
51 kwargs["headers"]["X-user-id"] = str(self._parent._market.user_id)
d8e233ac
IB
52 try:
53 r = self.origin_request(*args, **kwargs)
54 self._parent._market.report.log_http_request(args[0],
55 args[1], kwargs["data"], kwargs["headers"], r)
56 return r
57 except (SSLError, RequestException) as e:
58 self._parent._market.report.log_http_request(args[0],
59 args[1], kwargs["data"], kwargs["headers"], e)
60 raise e
61
445b4a77
IB
62 self.session.request = request_wrap.__get__(self.session,
63 self.session.__class__)
64
9f1408a3
IB
65 @staticmethod
66 def nanoseconds():
67 return int(time.time() * 1000000000)
68
2308a1c4
IB
69 def fetch_margin_balance(self):
70 """
71 portfolio.market.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
72 See DASH/BTC positions
aca4d437 73 {'amount': '-0.10000000', -> DASH empruntés (à rendre)
2308a1c4 74 'basePrice': '0.06818560', -> à ce prix là (0.06828800 demandé * (1-0.15%))
aca4d437 75 'lendingFees': '0.00000000', -> ce que je dois à mon créditeur en intérêts
2308a1c4
IB
76 'liquidationPrice': '0.15107132', -> prix auquel ça sera liquidé (dépend de ce que j’ai déjà sur mon compte margin)
77 'pl': '-0.00000371', -> plus-value latente si je rachète tout de suite (négatif = perdu)
aca4d437
IB
78 'total': '0.00681856', -> valeur totale empruntée en BTC (au moment de l'échange)
79 = amount * basePrice à erreur d'arrondi près
2308a1c4
IB
80 'type': 'short'}
81 """
82 positions = self.privatePostGetMarginPosition({"currencyPair": "all"})
83 parsed = {}
84 for symbol, position in positions.items():
85 if position["type"] == "none":
86 continue
87 base_currency, currency = symbol.split("_")
88 parsed[currency] = {
89 "amount": decimal.Decimal(position["amount"]),
90 "borrowedPrice": decimal.Decimal(position["basePrice"]),
91 "lendingFees": decimal.Decimal(position["lendingFees"]),
92 "pl": decimal.Decimal(position["pl"]),
93 "liquidationPrice": decimal.Decimal(position["liquidationPrice"]),
94 "type": position["type"],
95 "total": decimal.Decimal(position["total"]),
96 "baseCurrency": base_currency,
97 }
98 return parsed
99
100 def fetch_balance_per_type(self):
101 balances = self.privatePostReturnAvailableAccountBalances()
102 result = {'info': balances}
103 for key, balance in balances.items():
104 result[key] = {}
105 for currency, amount in balance.items():
aca4d437 106 result.setdefault(currency, {})
2308a1c4
IB
107 result[currency][key] = decimal.Decimal(amount)
108 result[key][currency] = decimal.Decimal(amount)
109 return result
110
111 def fetch_all_balances(self):
112 exchange_balances = self.fetch_balance()
113 margin_balances = self.fetch_margin_balance()
114 balances_per_type = self.fetch_balance_per_type()
115
116 all_balances = {}
117 in_positions = {}
aca4d437 118 pending_pl = {}
2308a1c4
IB
119
120 for currency, exchange_balance in exchange_balances.items():
121 if currency in ["info", "free", "used", "total"]:
122 continue
123
124 margin_balance = margin_balances.get(currency, {})
125 balance_per_type = balances_per_type.get(currency, {})
126
127 all_balances[currency] = {
128 "total": exchange_balance["total"] + margin_balance.get("amount", 0),
129 "exchange_used": exchange_balance["used"],
130 "exchange_total": exchange_balance["total"] - balance_per_type.get("margin", 0),
131 "exchange_free": exchange_balance["free"] - balance_per_type.get("margin", 0),
aca4d437
IB
132 # Disponible sur le compte margin
133 "margin_available": balance_per_type.get("margin", 0),
134 # Bloqué en position
135 "margin_in_position": 0,
136 # Emprunté
137 "margin_borrowed": -margin_balance.get("amount", 0),
138 # Total
2308a1c4 139 "margin_total": balance_per_type.get("margin", 0) + margin_balance.get("amount", 0),
aca4d437 140 "margin_pending_gain": 0,
2308a1c4 141 "margin_lending_fees": margin_balance.get("lendingFees", 0),
aca4d437 142 "margin_pending_base_gain": margin_balance.get("pl", 0),
2308a1c4
IB
143 "margin_position_type": margin_balance.get("type", None),
144 "margin_liquidation_price": margin_balance.get("liquidationPrice", 0),
145 "margin_borrowed_base_price": margin_balance.get("total", 0),
146 "margin_borrowed_base_currency": margin_balance.get("baseCurrency", None),
774c099c 147 }
2308a1c4 148 if len(margin_balance) > 0:
aca4d437 149 in_positions.setdefault(margin_balance["baseCurrency"], 0)
2308a1c4
IB
150 in_positions[margin_balance["baseCurrency"]] += margin_balance["total"]
151
aca4d437
IB
152 pending_pl.setdefault(margin_balance["baseCurrency"], 0)
153 pending_pl[margin_balance["baseCurrency"]] += margin_balance["pl"]
154
155 # J’emprunte 0.12062983 que je revends à 0.06003598 BTC/DASH, soit 0.00724213 BTC.
156 # Sur ces 0.00724213 BTC je récupère 0.00724213*(1-0.0015) = 0.00723127 BTC
157 #
158 # -> ordertrades ne tient pas compte des fees
159 # amount = montant vendu (un seul mouvement)
160 # rate = à ce taux
161 # total = total en BTC (pour ce mouvement)
162 # -> marginposition:
163 # amount = ce que je dois rendre
164 # basePrice = prix de vente en tenant compte des fees
165 # (amount * basePrice = la quantité de BTC que j’ai effectivement
166 # reçue à erreur d’arrondi près, utiliser plutôt "total")
167 # total = la quantité de BTC que j’ai reçue
168 # pl = plus value actuelle si je rachetais tout de suite
169 # -> marginaccountsummary:
170 # currentMargin = La marge actuelle (= netValue/totalBorrowedValue)
171 # totalValue = BTC actuellement en margin (déposé)
172 # totalBorrowedValue = sum (amount * ticker[lowestAsk])
173 # pl = sum(pl)
174 # netValue = BTC actuellement en margin (déposé) + pl
175 # Exemple:
176 # In [38]: m.ccxt.private_post_returnordertrades({"orderNumber": "XXXXXXXXXXXX"})
177 # Out[38]:
178 # [{'amount': '0.11882982',
179 # 'currencyPair': 'BTC_DASH',
180 # 'date': '2018-02-26 22:48:35',
181 # 'fee': '0.00150000',
182 # 'globalTradeID': 348891380,
183 # 'rate': '0.06003598',
184 # 'total': '0.00713406',
185 # 'tradeID': 9634443,
186 # 'type': 'sell'},
187 # {'amount': '0.00180000',
188 # 'currencyPair': 'BTC_DASH',
189 # 'date': '2018-02-26 22:48:30',
190 # 'fee': '0.00150000',
191 # 'globalTradeID': 348891375,
192 # 'rate': '0.06003598',
193 # 'total': '0.00010806',
194 # 'tradeID': 9634442,
195 # 'type': 'sell'}]
196 #
197 # In [51]: m.ccxt.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
198 # Out[51]:
199 # {'amount': '-0.12062982',
200 # 'basePrice': '0.05994587',
201 # 'lendingFees': '0.00000000',
202 # 'liquidationPrice': '0.15531479',
203 # 'pl': '0.00000122',
204 # 'total': '0.00723126',
205 # 'type': 'short'}
206 # In [52]: m.ccxt.privatePostGetMarginPosition({"currencyPair": "BTC_BTS"})
207 # Out[52]:
208 # {'amount': '-332.97159188',
209 # 'basePrice': '0.00002171',
210 # 'lendingFees': '0.00000000',
211 # 'liquidationPrice': '0.00005543',
212 # 'pl': '0.00029548',
213 # 'total': '0.00723127',
214 # 'type': 'short'}
215 #
216 # In [53]: m.ccxt.privatePostReturnMarginAccountSummary()
217 # Out[53]:
218 # {'currentMargin': '1.04341991',
219 # 'lendingFees': '0.00000000',
220 # 'netValue': '0.01478093',
221 # 'pl': '0.00029666',
222 # 'totalBorrowedValue': '0.01416585',
223 # 'totalValue': '0.01448427'}
224
2308a1c4
IB
225 for currency, in_position in in_positions.items():
226 all_balances[currency]["total"] += in_position
aca4d437 227 all_balances[currency]["margin_in_position"] += in_position
2308a1c4 228 all_balances[currency]["margin_total"] += in_position
aca4d437
IB
229
230 for currency, pl in pending_pl.items():
231 all_balances[currency]["margin_pending_gain"] += pl
2308a1c4
IB
232
233 return all_balances
234
2308a1c4 235 def order_precision(self, symbol):
52ea19aa
IB
236 self.load_markets()
237 return self.markets[symbol]['precision']['price']
2308a1c4
IB
238
239 def transfer_balance(self, currency, amount, from_account, to_account):
240 result = self.privatePostTransferBalance({
241 "currency": currency,
242 "amount": amount,
243 "fromAccount": from_account,
244 "toAccount": to_account,
245 "confirmed": 1})
246 return result["success"] == 1
247
248 def close_margin_position(self, currency, base_currency):
249 """
250 closeMarginPosition({"currencyPair": "BTC_DASH"})
251 fermer la position au prix du marché
252 """
253 symbol = "{}_{}".format(base_currency, currency)
254 self.privatePostCloseMarginPosition({"currencyPair": symbol})
255
256 def tradable_balances(self):
257 """
258 portfolio.market.privatePostReturnTradableBalances()
259 Returns tradable balances in margin
260 'BTC_DASH': {'BTC': '0.01266999', 'DASH': '0.08574839'},
261 Je peux emprunter jusqu’à 0.08574839 DASH ou 0.01266999 BTC (une position est déjà ouverte)
262 'BTC_CLAM': {'BTC': '0.00585143', 'CLAM': '7.79300395'},
263 Je peux emprunter 7.7 CLAM pour les vendre contre des BTC, ou emprunter 0.00585143 BTC pour acheter des CLAM
264 """
265
266 tradable_balances = self.privatePostReturnTradableBalances()
267 for symbol, balances in tradable_balances.items():
268 for currency, balance in balances.items():
269 balances[currency] = decimal.Decimal(balance)
270 return tradable_balances
271
272 def margin_summary(self):
273 """
274 portfolio.market.privatePostReturnMarginAccountSummary()
275 Returns current informations for margin
276 {'currentMargin': '1.49680968', -> marge (ne doit pas descendre sous 20% / 0.2)
277 = netValue / totalBorrowedValue
278 'lendingFees': '0.00000000', -> fees totaux
279 'netValue': '0.01008254', -> balance + plus-value
280 'pl': '0.00008254', -> plus value latente (somme des positions)
aca4d437
IB
281 'totalBorrowedValue': '0.00673602', -> valeur empruntée convertie en BTC.
282 (= sum(amount * ticker[lowerAsk]) pour amount dans marginposition)
283 'totalValue': '0.01000000'} -> balance (collateral déposé en margin)
2308a1c4
IB
284 """
285 summary = self.privatePostReturnMarginAccountSummary()
286
287 return {
288 "current_margin": decimal.Decimal(summary["currentMargin"]),
289 "lending_fees": decimal.Decimal(summary["lendingFees"]),
290 "gains": decimal.Decimal(summary["pl"]),
291 "total_borrowed": decimal.Decimal(summary["totalBorrowedValue"]),
292 "total": decimal.Decimal(summary["totalValue"]),
774c099c 293 }
774c099c 294
3f415207
IB
295 def nonce(self):
296 """
297 Wrapped to allow nonce with other libraries
298 """
299 return self.nanoseconds()
300
301 def fetch_balance(self, params={}):
302 """
303 Wrapped to get decimals
304 """
305 self.load_markets()
306 balances = self.privatePostReturnCompleteBalances(self.extend({
307 'account': 'all',
308 }, params))
309 result = {'info': balances}
310 currencies = list(balances.keys())
311 for c in range(0, len(currencies)):
312 id = currencies[c]
313 balance = balances[id]
314 currency = self.common_currency_code(id)
315 account = {
316 'free': decimal.Decimal(balance['available']),
317 'used': decimal.Decimal(balance['onOrders']),
318 'total': decimal.Decimal(0.0),
319 }
320 account['total'] = self.sum(account['free'], account['used'])
321 result[currency] = account
322 return self.parse_balance(result)
323
324 def parse_ticker(self, ticker, market=None):
325 """
326 Wrapped to get decimals
327 """
328 timestamp = self.milliseconds()
329 symbol = None
330 if market:
331 symbol = market['symbol']
332 return {
333 'symbol': symbol,
334 'timestamp': timestamp,
335 'datetime': self.iso8601(timestamp),
336 'high': decimal.Decimal(ticker['high24hr']),
337 'low': decimal.Decimal(ticker['low24hr']),
338 'bid': decimal.Decimal(ticker['highestBid']),
339 'ask': decimal.Decimal(ticker['lowestAsk']),
340 'vwap': None,
341 'open': None,
342 'close': None,
343 'first': None,
344 'last': decimal.Decimal(ticker['last']),
345 'change': decimal.Decimal(ticker['percentChange']),
346 'percentage': None,
347 'average': None,
348 'baseVolume': decimal.Decimal(ticker['quoteVolume']),
349 'quoteVolume': decimal.Decimal(ticker['baseVolume']),
350 'info': ticker,
351 }
352
353 def create_order(self, symbol, type, side, amount, price=None, account="exchange", lending_rate=None, params={}):
354 """
52ea19aa 355 Wrapped to handle margin and exchange accounts, and get decimals
3f415207 356 """
52ea19aa
IB
357 if type == 'market':
358 raise ExchangeError(self.id + ' allows limit orders only')
359 self.load_markets()
3f415207 360 if account == "exchange":
52ea19aa 361 method = 'privatePost' + self.capitalize(side)
3f415207 362 elif account == "margin":
52ea19aa
IB
363 method = 'privatePostMargin' + self.capitalize(side)
364 if lending_rate is not None:
365 params = self.extend({"lendingRate": lending_rate}, params)
3f415207
IB
366 else:
367 raise NotImplementedError
52ea19aa
IB
368 market = self.market(symbol)
369 response = getattr(self, method)(self.extend({
370 'currencyPair': market['id'],
371 'rate': self.price_to_precision(symbol, price),
372 'amount': self.amount_to_precision(symbol, amount),
373 }, params))
374 timestamp = self.milliseconds()
375 order = self.parse_order(self.extend({
376 'timestamp': timestamp,
377 'status': 'open',
378 'type': type,
379 'side': side,
380 'price': price,
381 'amount': amount,
382 }, response), market)
383 id = order['id']
384 self.orders[id] = order
385 return self.extend({'info': response}, order)
386
387 def price_to_precision(self, symbol, price):
388 """
389 Wrapped to avoid float
390 """
391 return ('{:.' + str(self.markets[symbol]['precision']['price']) + 'f}').format(price).rstrip("0").rstrip(".")
392
393 def amount_to_precision(self, symbol, amount):
394 """
395 Wrapped to avoid float
396 """
397 return ('{:.' + str(self.markets[symbol]['precision']['amount']) + 'f}').format(amount).rstrip("0").rstrip(".")
3f415207 398
18de421e
IB
399 def common_currency_code(self, currency):
400 """
401 Wrapped to avoid the currency translation
402 """
403 return currency
3f415207 404
18de421e
IB
405 def currency_id(self, currency):
406 """
407 Wrapped to avoid the currency translation
408 """
409 return currency