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