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