]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blame - ccxt_wrapper.py
Add make_order and get_user_market helpers
[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
41 {'amount': '-0.10000000', -> DASH empruntés
42 'basePrice': '0.06818560', -> à ce prix là (0.06828800 demandé * (1-0.15%))
43 'lendingFees': '0.00000000', -> ce que je dois à mon créditeur
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)
46 'total': '0.00681856', -> valeur totale empruntée en BTC
47 'type': 'short'}
48 """
49 positions = self.privatePostGetMarginPosition({"currencyPair": "all"})
50 parsed = {}
51 for symbol, position in positions.items():
52 if position["type"] == "none":
53 continue
54 base_currency, currency = symbol.split("_")
55 parsed[currency] = {
56 "amount": decimal.Decimal(position["amount"]),
57 "borrowedPrice": decimal.Decimal(position["basePrice"]),
58 "lendingFees": decimal.Decimal(position["lendingFees"]),
59 "pl": decimal.Decimal(position["pl"]),
60 "liquidationPrice": decimal.Decimal(position["liquidationPrice"]),
61 "type": position["type"],
62 "total": decimal.Decimal(position["total"]),
63 "baseCurrency": base_currency,
64 }
65 return parsed
66
67 def fetch_balance_per_type(self):
68 balances = self.privatePostReturnAvailableAccountBalances()
69 result = {'info': balances}
70 for key, balance in balances.items():
71 result[key] = {}
72 for currency, amount in balance.items():
73 if currency not in result:
74 result[currency] = {}
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 = {}
86
87 for currency, exchange_balance in exchange_balances.items():
88 if currency in ["info", "free", "used", "total"]:
89 continue
90
91 margin_balance = margin_balances.get(currency, {})
92 balance_per_type = balances_per_type.get(currency, {})
93
94 all_balances[currency] = {
95 "total": exchange_balance["total"] + margin_balance.get("amount", 0),
96 "exchange_used": exchange_balance["used"],
97 "exchange_total": exchange_balance["total"] - balance_per_type.get("margin", 0),
98 "exchange_free": exchange_balance["free"] - balance_per_type.get("margin", 0),
99 "margin_free": balance_per_type.get("margin", 0) + margin_balance.get("amount", 0),
100 "margin_borrowed": 0,
101 "margin_total": balance_per_type.get("margin", 0) + margin_balance.get("amount", 0),
102 "margin_lending_fees": margin_balance.get("lendingFees", 0),
103 "margin_pending_gain": margin_balance.get("pl", 0),
104 "margin_position_type": margin_balance.get("type", None),
105 "margin_liquidation_price": margin_balance.get("liquidationPrice", 0),
106 "margin_borrowed_base_price": margin_balance.get("total", 0),
107 "margin_borrowed_base_currency": margin_balance.get("baseCurrency", None),
774c099c 108 }
2308a1c4
IB
109 if len(margin_balance) > 0:
110 if margin_balance["baseCurrency"] not in in_positions:
111 in_positions[margin_balance["baseCurrency"]] = 0
112 in_positions[margin_balance["baseCurrency"]] += margin_balance["total"]
113
114 for currency, in_position in in_positions.items():
115 all_balances[currency]["total"] += in_position
116 all_balances[currency]["margin_total"] += in_position
117 all_balances[currency]["margin_borrowed"] += in_position
118
119 return all_balances
120
121 def parse_ticker(self, ticker, market=None):
122 timestamp = self.milliseconds()
123 symbol = None
124 if market:
125 symbol = market['symbol']
126 return {
127 'symbol': symbol,
128 'timestamp': timestamp,
129 'datetime': self.iso8601(timestamp),
130 'high': decimal.Decimal(ticker['high24hr']),
131 'low': decimal.Decimal(ticker['low24hr']),
132 'bid': decimal.Decimal(ticker['highestBid']),
133 'ask': decimal.Decimal(ticker['lowestAsk']),
134 'vwap': None,
135 'open': None,
136 'close': None,
137 'first': None,
138 'last': decimal.Decimal(ticker['last']),
139 'change': decimal.Decimal(ticker['percentChange']),
140 'percentage': None,
141 'average': None,
142 'baseVolume': decimal.Decimal(ticker['quoteVolume']),
143 'quoteVolume': decimal.Decimal(ticker['baseVolume']),
144 'info': ticker,
145 }
146
147 def create_margin_order(self, symbol, type, side, amount, price=None, lending_rate=None, params={}):
148 if type == 'market':
149 raise ExchangeError(self.id + ' allows limit orders only')
150 self.load_markets()
151 method = 'privatePostMargin' + self.capitalize(side)
152 market = self.market(symbol)
153 price = float(price)
154 amount = float(amount)
155 if lending_rate is not None:
156 params = self.extend({"lendingRate": lending_rate}, params)
157 response = getattr(self, method)(self.extend({
158 'currencyPair': market['id'],
159 'rate': self.price_to_precision(symbol, price),
160 'amount': self.amount_to_precision(symbol, amount),
161 }, params))
162 timestamp = self.milliseconds()
163 order = self.parse_order(self.extend({
164 'timestamp': timestamp,
165 'status': 'open',
166 'type': type,
167 'side': side,
168 'price': price,
169 'amount': amount,
170 }, response), market)
171 id = order['id']
172 self.orders[id] = order
173 return self.extend({'info': response}, order)
174
175 def create_exchange_order(self, symbol, type, side, amount, price=None, params={}):
176 return super(poloniexE, self).create_order(symbol, type, side, amount, price=price, params=params)
177
178 def create_order(self, symbol, type, side, amount, price=None, account="exchange", lending_rate=None, params={}):
179 if account == "exchange":
180 return self.create_exchange_order(symbol, type, side, amount, price=price, params=params)
181 elif account == "margin":
182 return self.create_margin_order(symbol, type, side, amount, price=price, lending_rate=lending_rate, params=params)
183 else:
184 raise NotImplementedError
185
186 def order_precision(self, symbol):
187 return 8
188
189 def transfer_balance(self, currency, amount, from_account, to_account):
190 result = self.privatePostTransferBalance({
191 "currency": currency,
192 "amount": amount,
193 "fromAccount": from_account,
194 "toAccount": to_account,
195 "confirmed": 1})
196 return result["success"] == 1
197
198 def close_margin_position(self, currency, base_currency):
199 """
200 closeMarginPosition({"currencyPair": "BTC_DASH"})
201 fermer la position au prix du marché
202 """
203 symbol = "{}_{}".format(base_currency, currency)
204 self.privatePostCloseMarginPosition({"currencyPair": symbol})
205
206 def tradable_balances(self):
207 """
208 portfolio.market.privatePostReturnTradableBalances()
209 Returns tradable balances in margin
210 'BTC_DASH': {'BTC': '0.01266999', 'DASH': '0.08574839'},
211 Je peux emprunter jusqu’à 0.08574839 DASH ou 0.01266999 BTC (une position est déjà ouverte)
212 'BTC_CLAM': {'BTC': '0.00585143', 'CLAM': '7.79300395'},
213 Je peux emprunter 7.7 CLAM pour les vendre contre des BTC, ou emprunter 0.00585143 BTC pour acheter des CLAM
214 """
215
216 tradable_balances = self.privatePostReturnTradableBalances()
217 for symbol, balances in tradable_balances.items():
218 for currency, balance in balances.items():
219 balances[currency] = decimal.Decimal(balance)
220 return tradable_balances
221
222 def margin_summary(self):
223 """
224 portfolio.market.privatePostReturnMarginAccountSummary()
225 Returns current informations for margin
226 {'currentMargin': '1.49680968', -> marge (ne doit pas descendre sous 20% / 0.2)
227 = netValue / totalBorrowedValue
228 'lendingFees': '0.00000000', -> fees totaux
229 'netValue': '0.01008254', -> balance + plus-value
230 'pl': '0.00008254', -> plus value latente (somme des positions)
231 'totalBorrowedValue': '0.00673602', -> valeur en BTC empruntée
232 'totalValue': '0.01000000'} -> valeur totale en compte
233 """
234 summary = self.privatePostReturnMarginAccountSummary()
235
236 return {
237 "current_margin": decimal.Decimal(summary["currentMargin"]),
238 "lending_fees": decimal.Decimal(summary["lendingFees"]),
239 "gains": decimal.Decimal(summary["pl"]),
240 "total_borrowed": decimal.Decimal(summary["totalBorrowedValue"]),
241 "total": decimal.Decimal(summary["totalValue"]),
774c099c 242 }
774c099c 243