]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blame - ccxt_wrapper.py
Add print_balances helper
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git] / ccxt_wrapper.py
CommitLineData
774c099c
IB
1from ccxt import *
2import decimal
3
4def _cw_exchange_sum(self, *args):
5 return sum([arg for arg in args if isinstance(arg, (float, int, decimal.Decimal))])
6Exchange.sum = _cw_exchange_sum
7
2308a1c4
IB
8class poloniexE(poloniex):
9 def fetch_balance(self, params={}):
10 self.load_markets()
11 balances = self.privatePostReturnCompleteBalances(self.extend({
12 'account': 'all',
13 }, params))
14 result = {'info': balances}
15 currencies = list(balances.keys())
16 for c in range(0, len(currencies)):
17 id = currencies[c]
18 balance = balances[id]
19 currency = self.common_currency_code(id)
20 account = {
21 'free': decimal.Decimal(balance['available']),
22 'used': decimal.Decimal(balance['onOrders']),
23 'total': decimal.Decimal(0.0),
24 }
25 account['total'] = self.sum(account['free'], account['used'])
26 result[currency] = account
27 return self.parse_balance(result)
28
29 def fetch_margin_balance(self):
30 """
31 portfolio.market.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
32 See DASH/BTC positions
33 {'amount': '-0.10000000', -> DASH empruntés
34 'basePrice': '0.06818560', -> à ce prix là (0.06828800 demandé * (1-0.15%))
35 'lendingFees': '0.00000000', -> ce que je dois à mon créditeur
36 'liquidationPrice': '0.15107132', -> prix auquel ça sera liquidé (dépend de ce que j’ai déjà sur mon compte margin)
37 'pl': '-0.00000371', -> plus-value latente si je rachète tout de suite (négatif = perdu)
38 'total': '0.00681856', -> valeur totale empruntée en BTC
39 'type': 'short'}
40 """
41 positions = self.privatePostGetMarginPosition({"currencyPair": "all"})
42 parsed = {}
43 for symbol, position in positions.items():
44 if position["type"] == "none":
45 continue
46 base_currency, currency = symbol.split("_")
47 parsed[currency] = {
48 "amount": decimal.Decimal(position["amount"]),
49 "borrowedPrice": decimal.Decimal(position["basePrice"]),
50 "lendingFees": decimal.Decimal(position["lendingFees"]),
51 "pl": decimal.Decimal(position["pl"]),
52 "liquidationPrice": decimal.Decimal(position["liquidationPrice"]),
53 "type": position["type"],
54 "total": decimal.Decimal(position["total"]),
55 "baseCurrency": base_currency,
56 }
57 return parsed
58
59 def fetch_balance_per_type(self):
60 balances = self.privatePostReturnAvailableAccountBalances()
61 result = {'info': balances}
62 for key, balance in balances.items():
63 result[key] = {}
64 for currency, amount in balance.items():
65 if currency not in result:
66 result[currency] = {}
67 result[currency][key] = decimal.Decimal(amount)
68 result[key][currency] = decimal.Decimal(amount)
69 return result
70
71 def fetch_all_balances(self):
72 exchange_balances = self.fetch_balance()
73 margin_balances = self.fetch_margin_balance()
74 balances_per_type = self.fetch_balance_per_type()
75
76 all_balances = {}
77 in_positions = {}
78
79 for currency, exchange_balance in exchange_balances.items():
80 if currency in ["info", "free", "used", "total"]:
81 continue
82
83 margin_balance = margin_balances.get(currency, {})
84 balance_per_type = balances_per_type.get(currency, {})
85
86 all_balances[currency] = {
87 "total": exchange_balance["total"] + margin_balance.get("amount", 0),
88 "exchange_used": exchange_balance["used"],
89 "exchange_total": exchange_balance["total"] - balance_per_type.get("margin", 0),
90 "exchange_free": exchange_balance["free"] - balance_per_type.get("margin", 0),
91 "margin_free": balance_per_type.get("margin", 0) + margin_balance.get("amount", 0),
92 "margin_borrowed": 0,
93 "margin_total": balance_per_type.get("margin", 0) + margin_balance.get("amount", 0),
94 "margin_lending_fees": margin_balance.get("lendingFees", 0),
95 "margin_pending_gain": margin_balance.get("pl", 0),
96 "margin_position_type": margin_balance.get("type", None),
97 "margin_liquidation_price": margin_balance.get("liquidationPrice", 0),
98 "margin_borrowed_base_price": margin_balance.get("total", 0),
99 "margin_borrowed_base_currency": margin_balance.get("baseCurrency", None),
774c099c 100 }
2308a1c4
IB
101 if len(margin_balance) > 0:
102 if margin_balance["baseCurrency"] not in in_positions:
103 in_positions[margin_balance["baseCurrency"]] = 0
104 in_positions[margin_balance["baseCurrency"]] += margin_balance["total"]
105
106 for currency, in_position in in_positions.items():
107 all_balances[currency]["total"] += in_position
108 all_balances[currency]["margin_total"] += in_position
109 all_balances[currency]["margin_borrowed"] += in_position
110
111 return all_balances
112
113 def parse_ticker(self, ticker, market=None):
114 timestamp = self.milliseconds()
115 symbol = None
116 if market:
117 symbol = market['symbol']
118 return {
119 'symbol': symbol,
120 'timestamp': timestamp,
121 'datetime': self.iso8601(timestamp),
122 'high': decimal.Decimal(ticker['high24hr']),
123 'low': decimal.Decimal(ticker['low24hr']),
124 'bid': decimal.Decimal(ticker['highestBid']),
125 'ask': decimal.Decimal(ticker['lowestAsk']),
126 'vwap': None,
127 'open': None,
128 'close': None,
129 'first': None,
130 'last': decimal.Decimal(ticker['last']),
131 'change': decimal.Decimal(ticker['percentChange']),
132 'percentage': None,
133 'average': None,
134 'baseVolume': decimal.Decimal(ticker['quoteVolume']),
135 'quoteVolume': decimal.Decimal(ticker['baseVolume']),
136 'info': ticker,
137 }
138
139 def create_margin_order(self, symbol, type, side, amount, price=None, lending_rate=None, params={}):
140 if type == 'market':
141 raise ExchangeError(self.id + ' allows limit orders only')
142 self.load_markets()
143 method = 'privatePostMargin' + self.capitalize(side)
144 market = self.market(symbol)
145 price = float(price)
146 amount = float(amount)
147 if lending_rate is not None:
148 params = self.extend({"lendingRate": lending_rate}, params)
149 response = getattr(self, method)(self.extend({
150 'currencyPair': market['id'],
151 'rate': self.price_to_precision(symbol, price),
152 'amount': self.amount_to_precision(symbol, amount),
153 }, params))
154 timestamp = self.milliseconds()
155 order = self.parse_order(self.extend({
156 'timestamp': timestamp,
157 'status': 'open',
158 'type': type,
159 'side': side,
160 'price': price,
161 'amount': amount,
162 }, response), market)
163 id = order['id']
164 self.orders[id] = order
165 return self.extend({'info': response}, order)
166
167 def create_exchange_order(self, symbol, type, side, amount, price=None, params={}):
168 return super(poloniexE, self).create_order(symbol, type, side, amount, price=price, params=params)
169
170 def create_order(self, symbol, type, side, amount, price=None, account="exchange", lending_rate=None, params={}):
171 if account == "exchange":
172 return self.create_exchange_order(symbol, type, side, amount, price=price, params=params)
173 elif account == "margin":
174 return self.create_margin_order(symbol, type, side, amount, price=price, lending_rate=lending_rate, params=params)
175 else:
176 raise NotImplementedError
177
178 def order_precision(self, symbol):
179 return 8
180
181 def transfer_balance(self, currency, amount, from_account, to_account):
182 result = self.privatePostTransferBalance({
183 "currency": currency,
184 "amount": amount,
185 "fromAccount": from_account,
186 "toAccount": to_account,
187 "confirmed": 1})
188 return result["success"] == 1
189
190 def close_margin_position(self, currency, base_currency):
191 """
192 closeMarginPosition({"currencyPair": "BTC_DASH"})
193 fermer la position au prix du marché
194 """
195 symbol = "{}_{}".format(base_currency, currency)
196 self.privatePostCloseMarginPosition({"currencyPair": symbol})
197
198 def tradable_balances(self):
199 """
200 portfolio.market.privatePostReturnTradableBalances()
201 Returns tradable balances in margin
202 'BTC_DASH': {'BTC': '0.01266999', 'DASH': '0.08574839'},
203 Je peux emprunter jusqu’à 0.08574839 DASH ou 0.01266999 BTC (une position est déjà ouverte)
204 'BTC_CLAM': {'BTC': '0.00585143', 'CLAM': '7.79300395'},
205 Je peux emprunter 7.7 CLAM pour les vendre contre des BTC, ou emprunter 0.00585143 BTC pour acheter des CLAM
206 """
207
208 tradable_balances = self.privatePostReturnTradableBalances()
209 for symbol, balances in tradable_balances.items():
210 for currency, balance in balances.items():
211 balances[currency] = decimal.Decimal(balance)
212 return tradable_balances
213
214 def margin_summary(self):
215 """
216 portfolio.market.privatePostReturnMarginAccountSummary()
217 Returns current informations for margin
218 {'currentMargin': '1.49680968', -> marge (ne doit pas descendre sous 20% / 0.2)
219 = netValue / totalBorrowedValue
220 'lendingFees': '0.00000000', -> fees totaux
221 'netValue': '0.01008254', -> balance + plus-value
222 'pl': '0.00008254', -> plus value latente (somme des positions)
223 'totalBorrowedValue': '0.00673602', -> valeur en BTC empruntée
224 'totalValue': '0.01000000'} -> valeur totale en compte
225 """
226 summary = self.privatePostReturnMarginAccountSummary()
227
228 return {
229 "current_margin": decimal.Decimal(summary["currentMargin"]),
230 "lending_fees": decimal.Decimal(summary["lendingFees"]),
231 "gains": decimal.Decimal(summary["pl"]),
232 "total_borrowed": decimal.Decimal(summary["totalBorrowedValue"]),
233 "total": decimal.Decimal(summary["totalValue"]),
774c099c 234 }
774c099c 235