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)
15 return self
.nanoseconds()
17 def fetch_balance(self
, params
={}):
19 balances
= self
.privatePostReturnCompleteBalances(self
.extend({
22 result
= {'info': balances}
23 currencies
= list(balances
.keys())
24 for c
in range(0, len(currencies
)):
26 balance
= balances
[id]
27 currency
= self
.common_currency_code(id)
29 'free': decimal
.Decimal(balance
['available']),
30 'used': decimal
.Decimal(balance
['onOrders']),
31 'total': decimal
.Decimal(0.0),
33 account
['total'] = self
.sum(account
['free'], account
['used'])
34 result
[currency
] = account
35 return self
.parse_balance(result
)
37 def fetch_margin_balance(self
):
39 portfolio.market.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
40 See DASH/BTC positions
41 {'amount': '-0.10000000', -> DASH empruntés (à rendre)
42 'basePrice': '0.06818560', -> à ce prix là (0.06828800 demandé * (1-0.15%))
43 'lendingFees': '0.00000000', -> ce que je dois à mon créditeur en intérêts
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 (au moment de l'échange)
47 = amount * basePrice à erreur d'arrondi près
50 positions
= self
.privatePostGetMarginPosition({"currencyPair": "all"}
)
52 for symbol
, position
in positions
.items():
53 if position
["type"] == "none":
55 base_currency
, currency
= symbol
.split("_")
57 "amount": decimal
.Decimal(position
["amount"]),
58 "borrowedPrice": decimal
.Decimal(position
["basePrice"]),
59 "lendingFees": decimal
.Decimal(position
["lendingFees"]),
60 "pl": decimal
.Decimal(position
["pl"]),
61 "liquidationPrice": decimal
.Decimal(position
["liquidationPrice"]),
62 "type": position
["type"],
63 "total": decimal
.Decimal(position
["total"]),
64 "baseCurrency": base_currency
,
68 def fetch_balance_per_type(self
):
69 balances
= self
.privatePostReturnAvailableAccountBalances()
70 result
= {'info': balances}
71 for key
, balance
in balances
.items():
73 for currency
, amount
in balance
.items():
74 result
.setdefault(currency
, {})
75 result
[currency
][key
] = decimal
.Decimal(amount
)
76 result
[key
][currency
] = decimal
.Decimal(amount
)
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()
88 for currency
, exchange_balance
in exchange_balances
.items():
89 if currency
in ["info", "free", "used", "total"]:
92 margin_balance
= margin_balances
.get(currency
, {})
93 balance_per_type
= balances_per_type
.get(currency
, {})
95 all_balances
[currency
] = {
96 "total": exchange_balance
["total"] + margin_balance
.get("amount", 0),
97 "exchange_used": exchange_balance
["used"],
98 "exchange_total": exchange_balance
["total"] - balance_per_type
.get("margin", 0),
99 "exchange_free": exchange_balance
["free"] - balance_per_type
.get("margin", 0),
100 # Disponible sur le compte margin
101 "margin_available": balance_per_type
.get("margin", 0),
103 "margin_in_position": 0,
105 "margin_borrowed": -margin_balance
.get("amount", 0),
107 "margin_total": balance_per_type
.get("margin", 0) + margin_balance
.get("amount", 0),
108 "margin_pending_gain": 0,
109 "margin_lending_fees": margin_balance
.get("lendingFees", 0),
110 "margin_pending_base_gain": margin_balance
.get("pl", 0),
111 "margin_position_type": margin_balance
.get("type", None),
112 "margin_liquidation_price": margin_balance
.get("liquidationPrice", 0),
113 "margin_borrowed_base_price": margin_balance
.get("total", 0),
114 "margin_borrowed_base_currency": margin_balance
.get("baseCurrency", None),
116 if len(margin_balance
) > 0:
117 in_positions
.setdefault(margin_balance
["baseCurrency"], 0)
118 in_positions
[margin_balance
["baseCurrency"]] += margin_balance
["total"]
120 pending_pl
.setdefault(margin_balance
["baseCurrency"], 0)
121 pending_pl
[margin_balance
["baseCurrency"]] += margin_balance
["pl"]
123 # J’emprunte 0.12062983 que je revends à 0.06003598 BTC/DASH, soit 0.00724213 BTC.
124 # Sur ces 0.00724213 BTC je récupère 0.00724213*(1-0.0015) = 0.00723127 BTC
126 # -> ordertrades ne tient pas compte des fees
127 # amount = montant vendu (un seul mouvement)
129 # total = total en BTC (pour ce mouvement)
131 # amount = ce que je dois rendre
132 # basePrice = prix de vente en tenant compte des fees
133 # (amount * basePrice = la quantité de BTC que j’ai effectivement
134 # reçue à erreur d’arrondi près, utiliser plutôt "total")
135 # total = la quantité de BTC que j’ai reçue
136 # pl = plus value actuelle si je rachetais tout de suite
137 # -> marginaccountsummary:
138 # currentMargin = La marge actuelle (= netValue/totalBorrowedValue)
139 # totalValue = BTC actuellement en margin (déposé)
140 # totalBorrowedValue = sum (amount * ticker[lowestAsk])
142 # netValue = BTC actuellement en margin (déposé) + pl
144 # In [38]: m.ccxt.private_post_returnordertrades({"orderNumber": "XXXXXXXXXXXX"})
146 # [{'amount': '0.11882982',
147 # 'currencyPair': 'BTC_DASH',
148 # 'date': '2018-02-26 22:48:35',
149 # 'fee': '0.00150000',
150 # 'globalTradeID': 348891380,
151 # 'rate': '0.06003598',
152 # 'total': '0.00713406',
153 # 'tradeID': 9634443,
155 # {'amount': '0.00180000',
156 # 'currencyPair': 'BTC_DASH',
157 # 'date': '2018-02-26 22:48:30',
158 # 'fee': '0.00150000',
159 # 'globalTradeID': 348891375,
160 # 'rate': '0.06003598',
161 # 'total': '0.00010806',
162 # 'tradeID': 9634442,
165 # In [51]: m.ccxt.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
167 # {'amount': '-0.12062982',
168 # 'basePrice': '0.05994587',
169 # 'lendingFees': '0.00000000',
170 # 'liquidationPrice': '0.15531479',
171 # 'pl': '0.00000122',
172 # 'total': '0.00723126',
174 # In [52]: m.ccxt.privatePostGetMarginPosition({"currencyPair": "BTC_BTS"})
176 # {'amount': '-332.97159188',
177 # 'basePrice': '0.00002171',
178 # 'lendingFees': '0.00000000',
179 # 'liquidationPrice': '0.00005543',
180 # 'pl': '0.00029548',
181 # 'total': '0.00723127',
184 # In [53]: m.ccxt.privatePostReturnMarginAccountSummary()
186 # {'currentMargin': '1.04341991',
187 # 'lendingFees': '0.00000000',
188 # 'netValue': '0.01478093',
189 # 'pl': '0.00029666',
190 # 'totalBorrowedValue': '0.01416585',
191 # 'totalValue': '0.01448427'}
193 for currency
, in_position
in in_positions
.items():
194 all_balances
[currency
]["total"] += in_position
195 all_balances
[currency
]["margin_in_position"] += in_position
196 all_balances
[currency
]["margin_total"] += in_position
198 for currency
, pl
in pending_pl
.items():
199 all_balances
[currency
]["margin_pending_gain"] += pl
203 def parse_ticker(self
, ticker
, market
=None):
204 timestamp
= self
.milliseconds()
207 symbol
= market
['symbol']
210 'timestamp': timestamp
,
211 'datetime': self
.iso8601(timestamp
),
212 'high': decimal
.Decimal(ticker
['high24hr']),
213 'low': decimal
.Decimal(ticker
['low24hr']),
214 'bid': decimal
.Decimal(ticker
['highestBid']),
215 'ask': decimal
.Decimal(ticker
['lowestAsk']),
220 'last': decimal
.Decimal(ticker
['last']),
221 'change': decimal
.Decimal(ticker
['percentChange']),
224 'baseVolume': decimal
.Decimal(ticker
['quoteVolume']),
225 'quoteVolume': decimal
.Decimal(ticker
['baseVolume']),
229 def create_margin_order(self
, symbol
, type, side
, amount
, price
=None, lending_rate
=None, params
={}):
231 raise ExchangeError(self
.id + ' allows limit orders only')
233 method
= 'privatePostMargin' + self
.capitalize(side
)
234 market
= self
.market(symbol
)
236 amount
= float(amount
)
237 if lending_rate
is not None:
238 params
= self
.extend({"lendingRate": lending_rate}
, params
)
239 response
= getattr(self
, method
)(self
.extend({
240 'currencyPair': market
['id'],
241 'rate': self
.price_to_precision(symbol
, price
),
242 'amount': self
.amount_to_precision(symbol
, amount
),
244 timestamp
= self
.milliseconds()
245 order
= self
.parse_order(self
.extend({
246 'timestamp': timestamp
,
252 }, response
), market
)
254 self
.orders
[id] = order
255 return self
.extend({'info': response}
, order
)
257 def create_exchange_order(self
, symbol
, type, side
, amount
, price
=None, params
={}):
258 return super(poloniexE
, self
).create_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
260 def create_order(self
, symbol
, type, side
, amount
, price
=None, account
="exchange", lending_rate
=None, params
={}):
261 if account
== "exchange":
262 return self
.create_exchange_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
263 elif account
== "margin":
264 return self
.create_margin_order(symbol
, type, side
, amount
, price
=price
, lending_rate
=lending_rate
, params
=params
)
266 raise NotImplementedError
268 def order_precision(self
, symbol
):
271 def transfer_balance(self
, currency
, amount
, from_account
, to_account
):
272 result
= self
.privatePostTransferBalance({
273 "currency": currency
,
275 "fromAccount": from_account
,
276 "toAccount": to_account
,
278 return result
["success"] == 1
280 def close_margin_position(self
, currency
, base_currency
):
282 closeMarginPosition({"currencyPair": "BTC_DASH"})
283 fermer la position au prix du marché
285 symbol
= "{}_{}".format(base_currency
, currency
)
286 self
.privatePostCloseMarginPosition({"currencyPair": symbol}
)
288 def tradable_balances(self
):
290 portfolio.market.privatePostReturnTradableBalances()
291 Returns tradable balances in margin
292 'BTC_DASH': {'BTC': '0.01266999', 'DASH': '0.08574839'},
293 Je peux emprunter jusqu’à 0.08574839 DASH ou 0.01266999 BTC (une position est déjà ouverte)
294 'BTC_CLAM': {'BTC': '0.00585143', 'CLAM': '7.79300395'},
295 Je peux emprunter 7.7 CLAM pour les vendre contre des BTC, ou emprunter 0.00585143 BTC pour acheter des CLAM
298 tradable_balances
= self
.privatePostReturnTradableBalances()
299 for symbol
, balances
in tradable_balances
.items():
300 for currency
, balance
in balances
.items():
301 balances
[currency
] = decimal
.Decimal(balance
)
302 return tradable_balances
304 def margin_summary(self
):
306 portfolio.market.privatePostReturnMarginAccountSummary()
307 Returns current informations for margin
308 {'currentMargin': '1.49680968', -> marge (ne doit pas descendre sous 20% / 0.2)
309 = netValue / totalBorrowedValue
310 'lendingFees': '0.00000000', -> fees totaux
311 'netValue': '0.01008254', -> balance + plus-value
312 'pl': '0.00008254', -> plus value latente (somme des positions)
313 'totalBorrowedValue': '0.00673602', -> valeur empruntée convertie en BTC.
314 (= sum(amount * ticker[lowerAsk]) pour amount dans marginposition)
315 'totalValue': '0.01000000'} -> balance (collateral déposé en margin)
317 summary
= self
.privatePostReturnMarginAccountSummary()
320 "current_margin": decimal
.Decimal(summary
["currentMargin"]),
321 "lending_fees": decimal
.Decimal(summary
["lendingFees"]),
322 "gains": decimal
.Decimal(summary
["pl"]),
323 "total_borrowed": decimal
.Decimal(summary
["totalBorrowedValue"]),
324 "total": decimal
.Decimal(summary
["totalValue"]),