5 def _cw_exchange_sum(self
, *args
):
6 return sum([arg
for arg
in args
if isinstance(arg
, (float, int, decimal
.Decimal
))])
7 Exchange
.sum = _cw_exchange_sum
9 class poloniexE(poloniex
):
12 return int(time
.time() * 1000000000)
14 def fetch_margin_balance(self
):
16 portfolio.market.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
17 See DASH/BTC positions
18 {'amount': '-0.10000000', -> DASH empruntés (à rendre)
19 'basePrice': '0.06818560', -> à ce prix là (0.06828800 demandé * (1-0.15%))
20 'lendingFees': '0.00000000', -> ce que je dois à mon créditeur en intérêts
21 'liquidationPrice': '0.15107132', -> prix auquel ça sera liquidé (dépend de ce que j’ai déjà sur mon compte margin)
22 'pl': '-0.00000371', -> plus-value latente si je rachète tout de suite (négatif = perdu)
23 'total': '0.00681856', -> valeur totale empruntée en BTC (au moment de l'échange)
24 = amount * basePrice à erreur d'arrondi près
27 positions
= self
.privatePostGetMarginPosition({"currencyPair": "all"}
)
29 for symbol
, position
in positions
.items():
30 if position
["type"] == "none":
32 base_currency
, currency
= symbol
.split("_")
34 "amount": decimal
.Decimal(position
["amount"]),
35 "borrowedPrice": decimal
.Decimal(position
["basePrice"]),
36 "lendingFees": decimal
.Decimal(position
["lendingFees"]),
37 "pl": decimal
.Decimal(position
["pl"]),
38 "liquidationPrice": decimal
.Decimal(position
["liquidationPrice"]),
39 "type": position
["type"],
40 "total": decimal
.Decimal(position
["total"]),
41 "baseCurrency": base_currency
,
45 def fetch_balance_per_type(self
):
46 balances
= self
.privatePostReturnAvailableAccountBalances()
47 result
= {'info': balances}
48 for key
, balance
in balances
.items():
50 for currency
, amount
in balance
.items():
51 result
.setdefault(currency
, {})
52 result
[currency
][key
] = decimal
.Decimal(amount
)
53 result
[key
][currency
] = decimal
.Decimal(amount
)
56 def fetch_all_balances(self
):
57 exchange_balances
= self
.fetch_balance()
58 margin_balances
= self
.fetch_margin_balance()
59 balances_per_type
= self
.fetch_balance_per_type()
65 for currency
, exchange_balance
in exchange_balances
.items():
66 if currency
in ["info", "free", "used", "total"]:
69 margin_balance
= margin_balances
.get(currency
, {})
70 balance_per_type
= balances_per_type
.get(currency
, {})
72 all_balances
[currency
] = {
73 "total": exchange_balance
["total"] + margin_balance
.get("amount", 0),
74 "exchange_used": exchange_balance
["used"],
75 "exchange_total": exchange_balance
["total"] - balance_per_type
.get("margin", 0),
76 "exchange_free": exchange_balance
["free"] - balance_per_type
.get("margin", 0),
77 # Disponible sur le compte margin
78 "margin_available": balance_per_type
.get("margin", 0),
80 "margin_in_position": 0,
82 "margin_borrowed": -margin_balance
.get("amount", 0),
84 "margin_total": balance_per_type
.get("margin", 0) + margin_balance
.get("amount", 0),
85 "margin_pending_gain": 0,
86 "margin_lending_fees": margin_balance
.get("lendingFees", 0),
87 "margin_pending_base_gain": margin_balance
.get("pl", 0),
88 "margin_position_type": margin_balance
.get("type", None),
89 "margin_liquidation_price": margin_balance
.get("liquidationPrice", 0),
90 "margin_borrowed_base_price": margin_balance
.get("total", 0),
91 "margin_borrowed_base_currency": margin_balance
.get("baseCurrency", None),
93 if len(margin_balance
) > 0:
94 in_positions
.setdefault(margin_balance
["baseCurrency"], 0)
95 in_positions
[margin_balance
["baseCurrency"]] += margin_balance
["total"]
97 pending_pl
.setdefault(margin_balance
["baseCurrency"], 0)
98 pending_pl
[margin_balance
["baseCurrency"]] += margin_balance
["pl"]
100 # J’emprunte 0.12062983 que je revends à 0.06003598 BTC/DASH, soit 0.00724213 BTC.
101 # Sur ces 0.00724213 BTC je récupère 0.00724213*(1-0.0015) = 0.00723127 BTC
103 # -> ordertrades ne tient pas compte des fees
104 # amount = montant vendu (un seul mouvement)
106 # total = total en BTC (pour ce mouvement)
108 # amount = ce que je dois rendre
109 # basePrice = prix de vente en tenant compte des fees
110 # (amount * basePrice = la quantité de BTC que j’ai effectivement
111 # reçue à erreur d’arrondi près, utiliser plutôt "total")
112 # total = la quantité de BTC que j’ai reçue
113 # pl = plus value actuelle si je rachetais tout de suite
114 # -> marginaccountsummary:
115 # currentMargin = La marge actuelle (= netValue/totalBorrowedValue)
116 # totalValue = BTC actuellement en margin (déposé)
117 # totalBorrowedValue = sum (amount * ticker[lowestAsk])
119 # netValue = BTC actuellement en margin (déposé) + pl
121 # In [38]: m.ccxt.private_post_returnordertrades({"orderNumber": "XXXXXXXXXXXX"})
123 # [{'amount': '0.11882982',
124 # 'currencyPair': 'BTC_DASH',
125 # 'date': '2018-02-26 22:48:35',
126 # 'fee': '0.00150000',
127 # 'globalTradeID': 348891380,
128 # 'rate': '0.06003598',
129 # 'total': '0.00713406',
130 # 'tradeID': 9634443,
132 # {'amount': '0.00180000',
133 # 'currencyPair': 'BTC_DASH',
134 # 'date': '2018-02-26 22:48:30',
135 # 'fee': '0.00150000',
136 # 'globalTradeID': 348891375,
137 # 'rate': '0.06003598',
138 # 'total': '0.00010806',
139 # 'tradeID': 9634442,
142 # In [51]: m.ccxt.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
144 # {'amount': '-0.12062982',
145 # 'basePrice': '0.05994587',
146 # 'lendingFees': '0.00000000',
147 # 'liquidationPrice': '0.15531479',
148 # 'pl': '0.00000122',
149 # 'total': '0.00723126',
151 # In [52]: m.ccxt.privatePostGetMarginPosition({"currencyPair": "BTC_BTS"})
153 # {'amount': '-332.97159188',
154 # 'basePrice': '0.00002171',
155 # 'lendingFees': '0.00000000',
156 # 'liquidationPrice': '0.00005543',
157 # 'pl': '0.00029548',
158 # 'total': '0.00723127',
161 # In [53]: m.ccxt.privatePostReturnMarginAccountSummary()
163 # {'currentMargin': '1.04341991',
164 # 'lendingFees': '0.00000000',
165 # 'netValue': '0.01478093',
166 # 'pl': '0.00029666',
167 # 'totalBorrowedValue': '0.01416585',
168 # 'totalValue': '0.01448427'}
170 for currency
, in_position
in in_positions
.items():
171 all_balances
[currency
]["total"] += in_position
172 all_balances
[currency
]["margin_in_position"] += in_position
173 all_balances
[currency
]["margin_total"] += in_position
175 for currency
, pl
in pending_pl
.items():
176 all_balances
[currency
]["margin_pending_gain"] += pl
180 def create_exchange_order(self
, symbol
, type, side
, amount
, price
=None, params
={}):
181 return super(poloniexE
, self
).create_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
183 def create_margin_order(self
, symbol
, type, side
, amount
, price
=None, lending_rate
=None, params
={}):
185 raise ExchangeError(self
.id + ' allows limit orders only')
187 method
= 'privatePostMargin' + self
.capitalize(side
)
188 market
= self
.market(symbol
)
190 amount
= float(amount
)
191 if lending_rate
is not None:
192 params
= self
.extend({"lendingRate": lending_rate}
, params
)
193 response
= getattr(self
, method
)(self
.extend({
194 'currencyPair': market
['id'],
195 'rate': self
.price_to_precision(symbol
, price
),
196 'amount': self
.amount_to_precision(symbol
, amount
),
198 timestamp
= self
.milliseconds()
199 order
= self
.parse_order(self
.extend({
200 'timestamp': timestamp
,
206 }, response
), market
)
208 self
.orders
[id] = order
209 return self
.extend({'info': response}
, order
)
211 def order_precision(self
, symbol
):
214 def transfer_balance(self
, currency
, amount
, from_account
, to_account
):
215 result
= self
.privatePostTransferBalance({
216 "currency": currency
,
218 "fromAccount": from_account
,
219 "toAccount": to_account
,
221 return result
["success"] == 1
223 def close_margin_position(self
, currency
, base_currency
):
225 closeMarginPosition({"currencyPair": "BTC_DASH"})
226 fermer la position au prix du marché
228 symbol
= "{}_{}".format(base_currency
, currency
)
229 self
.privatePostCloseMarginPosition({"currencyPair": symbol}
)
231 def tradable_balances(self
):
233 portfolio.market.privatePostReturnTradableBalances()
234 Returns tradable balances in margin
235 'BTC_DASH': {'BTC': '0.01266999', 'DASH': '0.08574839'},
236 Je peux emprunter jusqu’à 0.08574839 DASH ou 0.01266999 BTC (une position est déjà ouverte)
237 'BTC_CLAM': {'BTC': '0.00585143', 'CLAM': '7.79300395'},
238 Je peux emprunter 7.7 CLAM pour les vendre contre des BTC, ou emprunter 0.00585143 BTC pour acheter des CLAM
241 tradable_balances
= self
.privatePostReturnTradableBalances()
242 for symbol
, balances
in tradable_balances
.items():
243 for currency
, balance
in balances
.items():
244 balances
[currency
] = decimal
.Decimal(balance
)
245 return tradable_balances
247 def margin_summary(self
):
249 portfolio.market.privatePostReturnMarginAccountSummary()
250 Returns current informations for margin
251 {'currentMargin': '1.49680968', -> marge (ne doit pas descendre sous 20% / 0.2)
252 = netValue / totalBorrowedValue
253 'lendingFees': '0.00000000', -> fees totaux
254 'netValue': '0.01008254', -> balance + plus-value
255 'pl': '0.00008254', -> plus value latente (somme des positions)
256 'totalBorrowedValue': '0.00673602', -> valeur empruntée convertie en BTC.
257 (= sum(amount * ticker[lowerAsk]) pour amount dans marginposition)
258 'totalValue': '0.01000000'} -> balance (collateral déposé en margin)
260 summary
= self
.privatePostReturnMarginAccountSummary()
263 "current_margin": decimal
.Decimal(summary
["currentMargin"]),
264 "lending_fees": decimal
.Decimal(summary
["lendingFees"]),
265 "gains": decimal
.Decimal(summary
["pl"]),
266 "total_borrowed": decimal
.Decimal(summary
["totalBorrowedValue"]),
267 "total": decimal
.Decimal(summary
["totalValue"]),
272 Wrapped to allow nonce with other libraries
274 return self
.nanoseconds()
276 def fetch_balance(self
, params
={}):
278 Wrapped to get decimals
281 balances
= self
.privatePostReturnCompleteBalances(self
.extend({
284 result
= {'info': balances}
285 currencies
= list(balances
.keys())
286 for c
in range(0, len(currencies
)):
288 balance
= balances
[id]
289 currency
= self
.common_currency_code(id)
291 'free': decimal
.Decimal(balance
['available']),
292 'used': decimal
.Decimal(balance
['onOrders']),
293 'total': decimal
.Decimal(0.0),
295 account
['total'] = self
.sum(account
['free'], account
['used'])
296 result
[currency
] = account
297 return self
.parse_balance(result
)
299 def parse_ticker(self
, ticker
, market
=None):
301 Wrapped to get decimals
303 timestamp
= self
.milliseconds()
306 symbol
= market
['symbol']
309 'timestamp': timestamp
,
310 'datetime': self
.iso8601(timestamp
),
311 'high': decimal
.Decimal(ticker
['high24hr']),
312 'low': decimal
.Decimal(ticker
['low24hr']),
313 'bid': decimal
.Decimal(ticker
['highestBid']),
314 'ask': decimal
.Decimal(ticker
['lowestAsk']),
319 'last': decimal
.Decimal(ticker
['last']),
320 'change': decimal
.Decimal(ticker
['percentChange']),
323 'baseVolume': decimal
.Decimal(ticker
['quoteVolume']),
324 'quoteVolume': decimal
.Decimal(ticker
['baseVolume']),
328 def create_order(self
, symbol
, type, side
, amount
, price
=None, account
="exchange", lending_rate
=None, params
={}):
330 Wrapped to handle margin and exchange accounts
332 if account
== "exchange":
333 return self
.create_exchange_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
334 elif account
== "margin":
335 return self
.create_margin_order(symbol
, type, side
, amount
, price
=price
, lending_rate
=lending_rate
, params
=params
)
337 raise NotImplementedError