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().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
, InvalidNonce
))
38 return origin_request(path
, **kwargs
)
40 def __init__(self
, *args
, **kwargs
):
41 super().__init
__(*args
, **kwargs
)
43 # For requests logging
44 self
.session
.origin_request
= self
.session
.request
45 self
.session
._parent
= self
47 def request_wrap(self
, *args
, **kwargs
):
48 r
= self
.origin_request(*args
, **kwargs
)
49 self
._parent
._market
.report
.log_http_request(args
[0],
50 args
[1], kwargs
["data"], kwargs
["headers"], r
)
52 self
.session
.request
= request_wrap
.__get
__(self
.session
,
53 self
.session
.__class
__)
57 return int(time
.time() * 1000000000)
59 def fetch_margin_balance(self
):
61 portfolio.market.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
62 See DASH/BTC positions
63 {'amount': '-0.10000000', -> DASH empruntés (à rendre)
64 'basePrice': '0.06818560', -> à ce prix là (0.06828800 demandé * (1-0.15%))
65 'lendingFees': '0.00000000', -> ce que je dois à mon créditeur en intérêts
66 'liquidationPrice': '0.15107132', -> prix auquel ça sera liquidé (dépend de ce que j’ai déjà sur mon compte margin)
67 'pl': '-0.00000371', -> plus-value latente si je rachète tout de suite (négatif = perdu)
68 'total': '0.00681856', -> valeur totale empruntée en BTC (au moment de l'échange)
69 = amount * basePrice à erreur d'arrondi près
72 positions
= self
.privatePostGetMarginPosition({"currencyPair": "all"}
)
74 for symbol
, position
in positions
.items():
75 if position
["type"] == "none":
77 base_currency
, currency
= symbol
.split("_")
79 "amount": decimal
.Decimal(position
["amount"]),
80 "borrowedPrice": decimal
.Decimal(position
["basePrice"]),
81 "lendingFees": decimal
.Decimal(position
["lendingFees"]),
82 "pl": decimal
.Decimal(position
["pl"]),
83 "liquidationPrice": decimal
.Decimal(position
["liquidationPrice"]),
84 "type": position
["type"],
85 "total": decimal
.Decimal(position
["total"]),
86 "baseCurrency": base_currency
,
90 def fetch_balance_per_type(self
):
91 balances
= self
.privatePostReturnAvailableAccountBalances()
92 result
= {'info': balances}
93 for key
, balance
in balances
.items():
95 for currency
, amount
in balance
.items():
96 result
.setdefault(currency
, {})
97 result
[currency
][key
] = decimal
.Decimal(amount
)
98 result
[key
][currency
] = decimal
.Decimal(amount
)
101 def fetch_all_balances(self
):
102 exchange_balances
= self
.fetch_balance()
103 margin_balances
= self
.fetch_margin_balance()
104 balances_per_type
= self
.fetch_balance_per_type()
110 for currency
, exchange_balance
in exchange_balances
.items():
111 if currency
in ["info", "free", "used", "total"]:
114 margin_balance
= margin_balances
.get(currency
, {})
115 balance_per_type
= balances_per_type
.get(currency
, {})
117 all_balances
[currency
] = {
118 "total": exchange_balance
["total"] + margin_balance
.get("amount", 0),
119 "exchange_used": exchange_balance
["used"],
120 "exchange_total": exchange_balance
["total"] - balance_per_type
.get("margin", 0),
121 "exchange_free": exchange_balance
["free"] - balance_per_type
.get("margin", 0),
122 # Disponible sur le compte margin
123 "margin_available": balance_per_type
.get("margin", 0),
125 "margin_in_position": 0,
127 "margin_borrowed": -margin_balance
.get("amount", 0),
129 "margin_total": balance_per_type
.get("margin", 0) + margin_balance
.get("amount", 0),
130 "margin_pending_gain": 0,
131 "margin_lending_fees": margin_balance
.get("lendingFees", 0),
132 "margin_pending_base_gain": margin_balance
.get("pl", 0),
133 "margin_position_type": margin_balance
.get("type", None),
134 "margin_liquidation_price": margin_balance
.get("liquidationPrice", 0),
135 "margin_borrowed_base_price": margin_balance
.get("total", 0),
136 "margin_borrowed_base_currency": margin_balance
.get("baseCurrency", None),
138 if len(margin_balance
) > 0:
139 in_positions
.setdefault(margin_balance
["baseCurrency"], 0)
140 in_positions
[margin_balance
["baseCurrency"]] += margin_balance
["total"]
142 pending_pl
.setdefault(margin_balance
["baseCurrency"], 0)
143 pending_pl
[margin_balance
["baseCurrency"]] += margin_balance
["pl"]
145 # J’emprunte 0.12062983 que je revends à 0.06003598 BTC/DASH, soit 0.00724213 BTC.
146 # Sur ces 0.00724213 BTC je récupère 0.00724213*(1-0.0015) = 0.00723127 BTC
148 # -> ordertrades ne tient pas compte des fees
149 # amount = montant vendu (un seul mouvement)
151 # total = total en BTC (pour ce mouvement)
153 # amount = ce que je dois rendre
154 # basePrice = prix de vente en tenant compte des fees
155 # (amount * basePrice = la quantité de BTC que j’ai effectivement
156 # reçue à erreur d’arrondi près, utiliser plutôt "total")
157 # total = la quantité de BTC que j’ai reçue
158 # pl = plus value actuelle si je rachetais tout de suite
159 # -> marginaccountsummary:
160 # currentMargin = La marge actuelle (= netValue/totalBorrowedValue)
161 # totalValue = BTC actuellement en margin (déposé)
162 # totalBorrowedValue = sum (amount * ticker[lowestAsk])
164 # netValue = BTC actuellement en margin (déposé) + pl
166 # In [38]: m.ccxt.private_post_returnordertrades({"orderNumber": "XXXXXXXXXXXX"})
168 # [{'amount': '0.11882982',
169 # 'currencyPair': 'BTC_DASH',
170 # 'date': '2018-02-26 22:48:35',
171 # 'fee': '0.00150000',
172 # 'globalTradeID': 348891380,
173 # 'rate': '0.06003598',
174 # 'total': '0.00713406',
175 # 'tradeID': 9634443,
177 # {'amount': '0.00180000',
178 # 'currencyPair': 'BTC_DASH',
179 # 'date': '2018-02-26 22:48:30',
180 # 'fee': '0.00150000',
181 # 'globalTradeID': 348891375,
182 # 'rate': '0.06003598',
183 # 'total': '0.00010806',
184 # 'tradeID': 9634442,
187 # In [51]: m.ccxt.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
189 # {'amount': '-0.12062982',
190 # 'basePrice': '0.05994587',
191 # 'lendingFees': '0.00000000',
192 # 'liquidationPrice': '0.15531479',
193 # 'pl': '0.00000122',
194 # 'total': '0.00723126',
196 # In [52]: m.ccxt.privatePostGetMarginPosition({"currencyPair": "BTC_BTS"})
198 # {'amount': '-332.97159188',
199 # 'basePrice': '0.00002171',
200 # 'lendingFees': '0.00000000',
201 # 'liquidationPrice': '0.00005543',
202 # 'pl': '0.00029548',
203 # 'total': '0.00723127',
206 # In [53]: m.ccxt.privatePostReturnMarginAccountSummary()
208 # {'currentMargin': '1.04341991',
209 # 'lendingFees': '0.00000000',
210 # 'netValue': '0.01478093',
211 # 'pl': '0.00029666',
212 # 'totalBorrowedValue': '0.01416585',
213 # 'totalValue': '0.01448427'}
215 for currency
, in_position
in in_positions
.items():
216 all_balances
[currency
]["total"] += in_position
217 all_balances
[currency
]["margin_in_position"] += in_position
218 all_balances
[currency
]["margin_total"] += in_position
220 for currency
, pl
in pending_pl
.items():
221 all_balances
[currency
]["margin_pending_gain"] += pl
225 def create_exchange_order(self
, symbol
, type, side
, amount
, price
=None, params
={}):
226 return super().create_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
228 def create_margin_order(self
, symbol
, type, side
, amount
, price
=None, lending_rate
=None, params
={}):
230 raise ExchangeError(self
.id + ' allows limit orders only')
232 method
= 'privatePostMargin' + self
.capitalize(side
)
233 market
= self
.market(symbol
)
235 amount
= float(amount
)
236 if lending_rate
is not None:
237 params
= self
.extend({"lendingRate": lending_rate}
, params
)
238 response
= getattr(self
, method
)(self
.extend({
239 'currencyPair': market
['id'],
240 'rate': self
.price_to_precision(symbol
, price
),
241 'amount': self
.amount_to_precision(symbol
, amount
),
243 timestamp
= self
.milliseconds()
244 order
= self
.parse_order(self
.extend({
245 'timestamp': timestamp
,
251 }, response
), market
)
253 self
.orders
[id] = order
254 return self
.extend({'info': response}
, order
)
256 def order_precision(self
, symbol
):
259 def transfer_balance(self
, currency
, amount
, from_account
, to_account
):
260 result
= self
.privatePostTransferBalance({
261 "currency": currency
,
263 "fromAccount": from_account
,
264 "toAccount": to_account
,
266 return result
["success"] == 1
268 def close_margin_position(self
, currency
, base_currency
):
270 closeMarginPosition({"currencyPair": "BTC_DASH"})
271 fermer la position au prix du marché
273 symbol
= "{}_{}".format(base_currency
, currency
)
274 self
.privatePostCloseMarginPosition({"currencyPair": symbol}
)
276 def tradable_balances(self
):
278 portfolio.market.privatePostReturnTradableBalances()
279 Returns tradable balances in margin
280 'BTC_DASH': {'BTC': '0.01266999', 'DASH': '0.08574839'},
281 Je peux emprunter jusqu’à 0.08574839 DASH ou 0.01266999 BTC (une position est déjà ouverte)
282 'BTC_CLAM': {'BTC': '0.00585143', 'CLAM': '7.79300395'},
283 Je peux emprunter 7.7 CLAM pour les vendre contre des BTC, ou emprunter 0.00585143 BTC pour acheter des CLAM
286 tradable_balances
= self
.privatePostReturnTradableBalances()
287 for symbol
, balances
in tradable_balances
.items():
288 for currency
, balance
in balances
.items():
289 balances
[currency
] = decimal
.Decimal(balance
)
290 return tradable_balances
292 def margin_summary(self
):
294 portfolio.market.privatePostReturnMarginAccountSummary()
295 Returns current informations for margin
296 {'currentMargin': '1.49680968', -> marge (ne doit pas descendre sous 20% / 0.2)
297 = netValue / totalBorrowedValue
298 'lendingFees': '0.00000000', -> fees totaux
299 'netValue': '0.01008254', -> balance + plus-value
300 'pl': '0.00008254', -> plus value latente (somme des positions)
301 'totalBorrowedValue': '0.00673602', -> valeur empruntée convertie en BTC.
302 (= sum(amount * ticker[lowerAsk]) pour amount dans marginposition)
303 'totalValue': '0.01000000'} -> balance (collateral déposé en margin)
305 summary
= self
.privatePostReturnMarginAccountSummary()
308 "current_margin": decimal
.Decimal(summary
["currentMargin"]),
309 "lending_fees": decimal
.Decimal(summary
["lendingFees"]),
310 "gains": decimal
.Decimal(summary
["pl"]),
311 "total_borrowed": decimal
.Decimal(summary
["totalBorrowedValue"]),
312 "total": decimal
.Decimal(summary
["totalValue"]),
317 Wrapped to allow nonce with other libraries
319 return self
.nanoseconds()
321 def fetch_balance(self
, params
={}):
323 Wrapped to get decimals
326 balances
= self
.privatePostReturnCompleteBalances(self
.extend({
329 result
= {'info': balances}
330 currencies
= list(balances
.keys())
331 for c
in range(0, len(currencies
)):
333 balance
= balances
[id]
334 currency
= self
.common_currency_code(id)
336 'free': decimal
.Decimal(balance
['available']),
337 'used': decimal
.Decimal(balance
['onOrders']),
338 'total': decimal
.Decimal(0.0),
340 account
['total'] = self
.sum(account
['free'], account
['used'])
341 result
[currency
] = account
342 return self
.parse_balance(result
)
344 def parse_ticker(self
, ticker
, market
=None):
346 Wrapped to get decimals
348 timestamp
= self
.milliseconds()
351 symbol
= market
['symbol']
354 'timestamp': timestamp
,
355 'datetime': self
.iso8601(timestamp
),
356 'high': decimal
.Decimal(ticker
['high24hr']),
357 'low': decimal
.Decimal(ticker
['low24hr']),
358 'bid': decimal
.Decimal(ticker
['highestBid']),
359 'ask': decimal
.Decimal(ticker
['lowestAsk']),
364 'last': decimal
.Decimal(ticker
['last']),
365 'change': decimal
.Decimal(ticker
['percentChange']),
368 'baseVolume': decimal
.Decimal(ticker
['quoteVolume']),
369 'quoteVolume': decimal
.Decimal(ticker
['baseVolume']),
373 def create_order(self
, symbol
, type, side
, amount
, price
=None, account
="exchange", lending_rate
=None, params
={}):
375 Wrapped to handle margin and exchange accounts
377 if account
== "exchange":
378 return self
.create_exchange_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
379 elif account
== "margin":
380 return self
.create_margin_order(symbol
, type, side
, amount
, price
=price
, lending_rate
=lending_rate
, params
=params
)
382 raise NotImplementedError