4 from retry
.api
import retry_call
7 def _cw_exchange_sum(self
, *args
):
8 return sum([arg
for arg
in args
if isinstance(arg
, (float, int, decimal
.Decimal
))])
9 Exchange
.sum = _cw_exchange_sum
11 class poloniexE(poloniex
):
13 re
.compile(r
"^return"),
14 re
.compile(r
"^cancel"),
15 re
.compile(r
"^closeMarginPosition$"),
16 re
.compile(r
"^getMarginPosition$"),
19 def request(self
, path
, api
='public', method
='GET', params
={}, headers
=None, body
=None):
21 Wrapped to allow retry of non-posting requests"
24 origin_request
= super(poloniexE
, self
).request
33 retriable
= any(re
.match(call
, path
) for call
in self
.RETRIABLE_CALLS
)
34 if api
== "public" or method
== "GET" or retriable
:
35 return retry_call(origin_request
, fargs
=[path
], fkwargs
=kwargs
,
36 tries
=10, delay
=1, exceptions
=(RequestTimeout
,))
38 return origin_request(path
, **kwargs
)
42 return int(time
.time() * 1000000000)
44 def fetch_margin_balance(self
):
46 portfolio.market.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
47 See DASH/BTC positions
48 {'amount': '-0.10000000', -> DASH empruntés (à rendre)
49 'basePrice': '0.06818560', -> à ce prix là (0.06828800 demandé * (1-0.15%))
50 'lendingFees': '0.00000000', -> ce que je dois à mon créditeur en intérêts
51 'liquidationPrice': '0.15107132', -> prix auquel ça sera liquidé (dépend de ce que j’ai déjà sur mon compte margin)
52 'pl': '-0.00000371', -> plus-value latente si je rachète tout de suite (négatif = perdu)
53 'total': '0.00681856', -> valeur totale empruntée en BTC (au moment de l'échange)
54 = amount * basePrice à erreur d'arrondi près
57 positions
= self
.privatePostGetMarginPosition({"currencyPair": "all"}
)
59 for symbol
, position
in positions
.items():
60 if position
["type"] == "none":
62 base_currency
, currency
= symbol
.split("_")
64 "amount": decimal
.Decimal(position
["amount"]),
65 "borrowedPrice": decimal
.Decimal(position
["basePrice"]),
66 "lendingFees": decimal
.Decimal(position
["lendingFees"]),
67 "pl": decimal
.Decimal(position
["pl"]),
68 "liquidationPrice": decimal
.Decimal(position
["liquidationPrice"]),
69 "type": position
["type"],
70 "total": decimal
.Decimal(position
["total"]),
71 "baseCurrency": base_currency
,
75 def fetch_balance_per_type(self
):
76 balances
= self
.privatePostReturnAvailableAccountBalances()
77 result
= {'info': balances}
78 for key
, balance
in balances
.items():
80 for currency
, amount
in balance
.items():
81 result
.setdefault(currency
, {})
82 result
[currency
][key
] = decimal
.Decimal(amount
)
83 result
[key
][currency
] = decimal
.Decimal(amount
)
86 def fetch_all_balances(self
):
87 exchange_balances
= self
.fetch_balance()
88 margin_balances
= self
.fetch_margin_balance()
89 balances_per_type
= self
.fetch_balance_per_type()
95 for currency
, exchange_balance
in exchange_balances
.items():
96 if currency
in ["info", "free", "used", "total"]:
99 margin_balance
= margin_balances
.get(currency
, {})
100 balance_per_type
= balances_per_type
.get(currency
, {})
102 all_balances
[currency
] = {
103 "total": exchange_balance
["total"] + margin_balance
.get("amount", 0),
104 "exchange_used": exchange_balance
["used"],
105 "exchange_total": exchange_balance
["total"] - balance_per_type
.get("margin", 0),
106 "exchange_free": exchange_balance
["free"] - balance_per_type
.get("margin", 0),
107 # Disponible sur le compte margin
108 "margin_available": balance_per_type
.get("margin", 0),
110 "margin_in_position": 0,
112 "margin_borrowed": -margin_balance
.get("amount", 0),
114 "margin_total": balance_per_type
.get("margin", 0) + margin_balance
.get("amount", 0),
115 "margin_pending_gain": 0,
116 "margin_lending_fees": margin_balance
.get("lendingFees", 0),
117 "margin_pending_base_gain": margin_balance
.get("pl", 0),
118 "margin_position_type": margin_balance
.get("type", None),
119 "margin_liquidation_price": margin_balance
.get("liquidationPrice", 0),
120 "margin_borrowed_base_price": margin_balance
.get("total", 0),
121 "margin_borrowed_base_currency": margin_balance
.get("baseCurrency", None),
123 if len(margin_balance
) > 0:
124 in_positions
.setdefault(margin_balance
["baseCurrency"], 0)
125 in_positions
[margin_balance
["baseCurrency"]] += margin_balance
["total"]
127 pending_pl
.setdefault(margin_balance
["baseCurrency"], 0)
128 pending_pl
[margin_balance
["baseCurrency"]] += margin_balance
["pl"]
130 # J’emprunte 0.12062983 que je revends à 0.06003598 BTC/DASH, soit 0.00724213 BTC.
131 # Sur ces 0.00724213 BTC je récupère 0.00724213*(1-0.0015) = 0.00723127 BTC
133 # -> ordertrades ne tient pas compte des fees
134 # amount = montant vendu (un seul mouvement)
136 # total = total en BTC (pour ce mouvement)
138 # amount = ce que je dois rendre
139 # basePrice = prix de vente en tenant compte des fees
140 # (amount * basePrice = la quantité de BTC que j’ai effectivement
141 # reçue à erreur d’arrondi près, utiliser plutôt "total")
142 # total = la quantité de BTC que j’ai reçue
143 # pl = plus value actuelle si je rachetais tout de suite
144 # -> marginaccountsummary:
145 # currentMargin = La marge actuelle (= netValue/totalBorrowedValue)
146 # totalValue = BTC actuellement en margin (déposé)
147 # totalBorrowedValue = sum (amount * ticker[lowestAsk])
149 # netValue = BTC actuellement en margin (déposé) + pl
151 # In [38]: m.ccxt.private_post_returnordertrades({"orderNumber": "XXXXXXXXXXXX"})
153 # [{'amount': '0.11882982',
154 # 'currencyPair': 'BTC_DASH',
155 # 'date': '2018-02-26 22:48:35',
156 # 'fee': '0.00150000',
157 # 'globalTradeID': 348891380,
158 # 'rate': '0.06003598',
159 # 'total': '0.00713406',
160 # 'tradeID': 9634443,
162 # {'amount': '0.00180000',
163 # 'currencyPair': 'BTC_DASH',
164 # 'date': '2018-02-26 22:48:30',
165 # 'fee': '0.00150000',
166 # 'globalTradeID': 348891375,
167 # 'rate': '0.06003598',
168 # 'total': '0.00010806',
169 # 'tradeID': 9634442,
172 # In [51]: m.ccxt.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
174 # {'amount': '-0.12062982',
175 # 'basePrice': '0.05994587',
176 # 'lendingFees': '0.00000000',
177 # 'liquidationPrice': '0.15531479',
178 # 'pl': '0.00000122',
179 # 'total': '0.00723126',
181 # In [52]: m.ccxt.privatePostGetMarginPosition({"currencyPair": "BTC_BTS"})
183 # {'amount': '-332.97159188',
184 # 'basePrice': '0.00002171',
185 # 'lendingFees': '0.00000000',
186 # 'liquidationPrice': '0.00005543',
187 # 'pl': '0.00029548',
188 # 'total': '0.00723127',
191 # In [53]: m.ccxt.privatePostReturnMarginAccountSummary()
193 # {'currentMargin': '1.04341991',
194 # 'lendingFees': '0.00000000',
195 # 'netValue': '0.01478093',
196 # 'pl': '0.00029666',
197 # 'totalBorrowedValue': '0.01416585',
198 # 'totalValue': '0.01448427'}
200 for currency
, in_position
in in_positions
.items():
201 all_balances
[currency
]["total"] += in_position
202 all_balances
[currency
]["margin_in_position"] += in_position
203 all_balances
[currency
]["margin_total"] += in_position
205 for currency
, pl
in pending_pl
.items():
206 all_balances
[currency
]["margin_pending_gain"] += pl
210 def create_exchange_order(self
, symbol
, type, side
, amount
, price
=None, params
={}):
211 return super(poloniexE
, self
).create_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
213 def create_margin_order(self
, symbol
, type, side
, amount
, price
=None, lending_rate
=None, params
={}):
215 raise ExchangeError(self
.id + ' allows limit orders only')
217 method
= 'privatePostMargin' + self
.capitalize(side
)
218 market
= self
.market(symbol
)
220 amount
= float(amount
)
221 if lending_rate
is not None:
222 params
= self
.extend({"lendingRate": lending_rate}
, params
)
223 response
= getattr(self
, method
)(self
.extend({
224 'currencyPair': market
['id'],
225 'rate': self
.price_to_precision(symbol
, price
),
226 'amount': self
.amount_to_precision(symbol
, amount
),
228 timestamp
= self
.milliseconds()
229 order
= self
.parse_order(self
.extend({
230 'timestamp': timestamp
,
236 }, response
), market
)
238 self
.orders
[id] = order
239 return self
.extend({'info': response}
, order
)
241 def order_precision(self
, symbol
):
244 def transfer_balance(self
, currency
, amount
, from_account
, to_account
):
245 result
= self
.privatePostTransferBalance({
246 "currency": currency
,
248 "fromAccount": from_account
,
249 "toAccount": to_account
,
251 return result
["success"] == 1
253 def close_margin_position(self
, currency
, base_currency
):
255 closeMarginPosition({"currencyPair": "BTC_DASH"})
256 fermer la position au prix du marché
258 symbol
= "{}_{}".format(base_currency
, currency
)
259 self
.privatePostCloseMarginPosition({"currencyPair": symbol}
)
261 def tradable_balances(self
):
263 portfolio.market.privatePostReturnTradableBalances()
264 Returns tradable balances in margin
265 'BTC_DASH': {'BTC': '0.01266999', 'DASH': '0.08574839'},
266 Je peux emprunter jusqu’à 0.08574839 DASH ou 0.01266999 BTC (une position est déjà ouverte)
267 'BTC_CLAM': {'BTC': '0.00585143', 'CLAM': '7.79300395'},
268 Je peux emprunter 7.7 CLAM pour les vendre contre des BTC, ou emprunter 0.00585143 BTC pour acheter des CLAM
271 tradable_balances
= self
.privatePostReturnTradableBalances()
272 for symbol
, balances
in tradable_balances
.items():
273 for currency
, balance
in balances
.items():
274 balances
[currency
] = decimal
.Decimal(balance
)
275 return tradable_balances
277 def margin_summary(self
):
279 portfolio.market.privatePostReturnMarginAccountSummary()
280 Returns current informations for margin
281 {'currentMargin': '1.49680968', -> marge (ne doit pas descendre sous 20% / 0.2)
282 = netValue / totalBorrowedValue
283 'lendingFees': '0.00000000', -> fees totaux
284 'netValue': '0.01008254', -> balance + plus-value
285 'pl': '0.00008254', -> plus value latente (somme des positions)
286 'totalBorrowedValue': '0.00673602', -> valeur empruntée convertie en BTC.
287 (= sum(amount * ticker[lowerAsk]) pour amount dans marginposition)
288 'totalValue': '0.01000000'} -> balance (collateral déposé en margin)
290 summary
= self
.privatePostReturnMarginAccountSummary()
293 "current_margin": decimal
.Decimal(summary
["currentMargin"]),
294 "lending_fees": decimal
.Decimal(summary
["lendingFees"]),
295 "gains": decimal
.Decimal(summary
["pl"]),
296 "total_borrowed": decimal
.Decimal(summary
["totalBorrowedValue"]),
297 "total": decimal
.Decimal(summary
["totalValue"]),
302 Wrapped to allow nonce with other libraries
304 return self
.nanoseconds()
306 def fetch_balance(self
, params
={}):
308 Wrapped to get decimals
311 balances
= self
.privatePostReturnCompleteBalances(self
.extend({
314 result
= {'info': balances}
315 currencies
= list(balances
.keys())
316 for c
in range(0, len(currencies
)):
318 balance
= balances
[id]
319 currency
= self
.common_currency_code(id)
321 'free': decimal
.Decimal(balance
['available']),
322 'used': decimal
.Decimal(balance
['onOrders']),
323 'total': decimal
.Decimal(0.0),
325 account
['total'] = self
.sum(account
['free'], account
['used'])
326 result
[currency
] = account
327 return self
.parse_balance(result
)
329 def parse_ticker(self
, ticker
, market
=None):
331 Wrapped to get decimals
333 timestamp
= self
.milliseconds()
336 symbol
= market
['symbol']
339 'timestamp': timestamp
,
340 'datetime': self
.iso8601(timestamp
),
341 'high': decimal
.Decimal(ticker
['high24hr']),
342 'low': decimal
.Decimal(ticker
['low24hr']),
343 'bid': decimal
.Decimal(ticker
['highestBid']),
344 'ask': decimal
.Decimal(ticker
['lowestAsk']),
349 'last': decimal
.Decimal(ticker
['last']),
350 'change': decimal
.Decimal(ticker
['percentChange']),
353 'baseVolume': decimal
.Decimal(ticker
['quoteVolume']),
354 'quoteVolume': decimal
.Decimal(ticker
['baseVolume']),
358 def create_order(self
, symbol
, type, side
, amount
, price
=None, account
="exchange", lending_rate
=None, params
={}):
360 Wrapped to handle margin and exchange accounts
362 if account
== "exchange":
363 return self
.create_exchange_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
364 elif account
== "margin":
365 return self
.create_margin_order(symbol
, type, side
, amount
, price
=price
, lending_rate
=lending_rate
, params
=params
)
367 raise NotImplementedError