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