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