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
42 'basePrice': '0.06818560', -> à ce prix là (0.06828800 demandé * (1-0.15%))
43 'lendingFees': '0.00000000', -> ce que je dois à mon créditeur
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
49 positions
= self
.privatePostGetMarginPosition({"currencyPair": "all"}
)
51 for symbol
, position
in positions
.items():
52 if position
["type"] == "none":
54 base_currency
, currency
= symbol
.split("_")
56 "amount": decimal
.Decimal(position
["amount"]),
57 "borrowedPrice": decimal
.Decimal(position
["basePrice"]),
58 "lendingFees": decimal
.Decimal(position
["lendingFees"]),
59 "pl": decimal
.Decimal(position
["pl"]),
60 "liquidationPrice": decimal
.Decimal(position
["liquidationPrice"]),
61 "type": position
["type"],
62 "total": decimal
.Decimal(position
["total"]),
63 "baseCurrency": base_currency
,
67 def fetch_balance_per_type(self
):
68 balances
= self
.privatePostReturnAvailableAccountBalances()
69 result
= {'info': balances}
70 for key
, balance
in balances
.items():
72 for currency
, amount
in balance
.items():
73 if currency
not in result
:
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()
87 for currency
, exchange_balance
in exchange_balances
.items():
88 if currency
in ["info", "free", "used", "total"]:
91 margin_balance
= margin_balances
.get(currency
, {})
92 balance_per_type
= balances_per_type
.get(currency
, {})
94 all_balances
[currency
] = {
95 "total": exchange_balance
["total"] + margin_balance
.get("amount", 0),
96 "exchange_used": exchange_balance
["used"],
97 "exchange_total": exchange_balance
["total"] - balance_per_type
.get("margin", 0),
98 "exchange_free": exchange_balance
["free"] - balance_per_type
.get("margin", 0),
99 "margin_free": balance_per_type
.get("margin", 0) + margin_balance
.get("amount", 0),
100 "margin_borrowed": 0,
101 "margin_total": balance_per_type
.get("margin", 0) + margin_balance
.get("amount", 0),
102 "margin_lending_fees": margin_balance
.get("lendingFees", 0),
103 "margin_pending_gain": margin_balance
.get("pl", 0),
104 "margin_position_type": margin_balance
.get("type", None),
105 "margin_liquidation_price": margin_balance
.get("liquidationPrice", 0),
106 "margin_borrowed_base_price": margin_balance
.get("total", 0),
107 "margin_borrowed_base_currency": margin_balance
.get("baseCurrency", None),
109 if len(margin_balance
) > 0:
110 if margin_balance
["baseCurrency"] not in in_positions
:
111 in_positions
[margin_balance
["baseCurrency"]] = 0
112 in_positions
[margin_balance
["baseCurrency"]] += margin_balance
["total"]
114 for currency
, in_position
in in_positions
.items():
115 all_balances
[currency
]["total"] += in_position
116 all_balances
[currency
]["margin_total"] += in_position
117 all_balances
[currency
]["margin_borrowed"] += in_position
121 def parse_ticker(self
, ticker
, market
=None):
122 timestamp
= self
.milliseconds()
125 symbol
= market
['symbol']
128 'timestamp': timestamp
,
129 'datetime': self
.iso8601(timestamp
),
130 'high': decimal
.Decimal(ticker
['high24hr']),
131 'low': decimal
.Decimal(ticker
['low24hr']),
132 'bid': decimal
.Decimal(ticker
['highestBid']),
133 'ask': decimal
.Decimal(ticker
['lowestAsk']),
138 'last': decimal
.Decimal(ticker
['last']),
139 'change': decimal
.Decimal(ticker
['percentChange']),
142 'baseVolume': decimal
.Decimal(ticker
['quoteVolume']),
143 'quoteVolume': decimal
.Decimal(ticker
['baseVolume']),
147 def create_margin_order(self
, symbol
, type, side
, amount
, price
=None, lending_rate
=None, params
={}):
149 raise ExchangeError(self
.id + ' allows limit orders only')
151 method
= 'privatePostMargin' + self
.capitalize(side
)
152 market
= self
.market(symbol
)
154 amount
= float(amount
)
155 if lending_rate
is not None:
156 params
= self
.extend({"lendingRate": lending_rate}
, params
)
157 response
= getattr(self
, method
)(self
.extend({
158 'currencyPair': market
['id'],
159 'rate': self
.price_to_precision(symbol
, price
),
160 'amount': self
.amount_to_precision(symbol
, amount
),
162 timestamp
= self
.milliseconds()
163 order
= self
.parse_order(self
.extend({
164 'timestamp': timestamp
,
170 }, response
), market
)
172 self
.orders
[id] = order
173 return self
.extend({'info': response}
, order
)
175 def create_exchange_order(self
, symbol
, type, side
, amount
, price
=None, params
={}):
176 return super(poloniexE
, self
).create_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
178 def create_order(self
, symbol
, type, side
, amount
, price
=None, account
="exchange", lending_rate
=None, params
={}):
179 if account
== "exchange":
180 return self
.create_exchange_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
181 elif account
== "margin":
182 return self
.create_margin_order(symbol
, type, side
, amount
, price
=price
, lending_rate
=lending_rate
, params
=params
)
184 raise NotImplementedError
186 def order_precision(self
, symbol
):
189 def transfer_balance(self
, currency
, amount
, from_account
, to_account
):
190 result
= self
.privatePostTransferBalance({
191 "currency": currency
,
193 "fromAccount": from_account
,
194 "toAccount": to_account
,
196 return result
["success"] == 1
198 def close_margin_position(self
, currency
, base_currency
):
200 closeMarginPosition({"currencyPair": "BTC_DASH"})
201 fermer la position au prix du marché
203 symbol
= "{}_{}".format(base_currency
, currency
)
204 self
.privatePostCloseMarginPosition({"currencyPair": symbol}
)
206 def tradable_balances(self
):
208 portfolio.market.privatePostReturnTradableBalances()
209 Returns tradable balances in margin
210 'BTC_DASH': {'BTC': '0.01266999', 'DASH': '0.08574839'},
211 Je peux emprunter jusqu’à 0.08574839 DASH ou 0.01266999 BTC (une position est déjà ouverte)
212 'BTC_CLAM': {'BTC': '0.00585143', 'CLAM': '7.79300395'},
213 Je peux emprunter 7.7 CLAM pour les vendre contre des BTC, ou emprunter 0.00585143 BTC pour acheter des CLAM
216 tradable_balances
= self
.privatePostReturnTradableBalances()
217 for symbol
, balances
in tradable_balances
.items():
218 for currency
, balance
in balances
.items():
219 balances
[currency
] = decimal
.Decimal(balance
)
220 return tradable_balances
222 def margin_summary(self
):
224 portfolio.market.privatePostReturnMarginAccountSummary()
225 Returns current informations for margin
226 {'currentMargin': '1.49680968', -> marge (ne doit pas descendre sous 20% / 0.2)
227 = netValue / totalBorrowedValue
228 'lendingFees': '0.00000000', -> fees totaux
229 'netValue': '0.01008254', -> balance + plus-value
230 'pl': '0.00008254', -> plus value latente (somme des positions)
231 'totalBorrowedValue': '0.00673602', -> valeur en BTC empruntée
232 'totalValue': '0.01000000'} -> valeur totale en compte
234 summary
= self
.privatePostReturnMarginAccountSummary()
237 "current_margin": decimal
.Decimal(summary
["currentMargin"]),
238 "lending_fees": decimal
.Decimal(summary
["lendingFees"]),
239 "gains": decimal
.Decimal(summary
["pl"]),
240 "total_borrowed": decimal
.Decimal(summary
["totalBorrowedValue"]),
241 "total": decimal
.Decimal(summary
["totalValue"]),