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