4 def _cw_exchange_sum(self
, *args
):
5 return sum([arg
for arg
in args
if isinstance(arg
, (float, int, decimal
.Decimal
))])
6 Exchange
.sum = _cw_exchange_sum
8 class poloniexE(poloniex
):
9 def fetch_balance(self
, params
={}):
11 balances
= self
.privatePostReturnCompleteBalances(self
.extend({
14 result
= {'info': balances}
15 currencies
= list(balances
.keys())
16 for c
in range(0, len(currencies
)):
18 balance
= balances
[id]
19 currency
= self
.common_currency_code(id)
21 'free': decimal
.Decimal(balance
['available']),
22 'used': decimal
.Decimal(balance
['onOrders']),
23 'total': decimal
.Decimal(0.0),
25 account
['total'] = self
.sum(account
['free'], account
['used'])
26 result
[currency
] = account
27 return self
.parse_balance(result
)
29 def fetch_margin_balance(self
):
31 portfolio.market.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
32 See DASH/BTC positions
33 {'amount': '-0.10000000', -> DASH empruntés
34 'basePrice': '0.06818560', -> à ce prix là (0.06828800 demandé * (1-0.15%))
35 'lendingFees': '0.00000000', -> ce que je dois à mon créditeur
36 'liquidationPrice': '0.15107132', -> prix auquel ça sera liquidé (dépend de ce que j’ai déjà sur mon compte margin)
37 'pl': '-0.00000371', -> plus-value latente si je rachète tout de suite (négatif = perdu)
38 'total': '0.00681856', -> valeur totale empruntée en BTC
41 positions
= self
.privatePostGetMarginPosition({"currencyPair": "all"}
)
43 for symbol
, position
in positions
.items():
44 if position
["type"] == "none":
46 base_currency
, currency
= symbol
.split("_")
48 "amount": decimal
.Decimal(position
["amount"]),
49 "borrowedPrice": decimal
.Decimal(position
["basePrice"]),
50 "lendingFees": decimal
.Decimal(position
["lendingFees"]),
51 "pl": decimal
.Decimal(position
["pl"]),
52 "liquidationPrice": decimal
.Decimal(position
["liquidationPrice"]),
53 "type": position
["type"],
54 "total": decimal
.Decimal(position
["total"]),
55 "baseCurrency": base_currency
,
59 def fetch_balance_per_type(self
):
60 balances
= self
.privatePostReturnAvailableAccountBalances()
61 result
= {'info': balances}
62 for key
, balance
in balances
.items():
64 for currency
, amount
in balance
.items():
65 if currency
not in result
:
67 result
[currency
][key
] = decimal
.Decimal(amount
)
68 result
[key
][currency
] = decimal
.Decimal(amount
)
71 def fetch_all_balances(self
):
72 exchange_balances
= self
.fetch_balance()
73 margin_balances
= self
.fetch_margin_balance()
74 balances_per_type
= self
.fetch_balance_per_type()
79 for currency
, exchange_balance
in exchange_balances
.items():
80 if currency
in ["info", "free", "used", "total"]:
83 margin_balance
= margin_balances
.get(currency
, {})
84 balance_per_type
= balances_per_type
.get(currency
, {})
86 all_balances
[currency
] = {
87 "total": exchange_balance
["total"] + margin_balance
.get("amount", 0),
88 "exchange_used": exchange_balance
["used"],
89 "exchange_total": exchange_balance
["total"] - balance_per_type
.get("margin", 0),
90 "exchange_free": exchange_balance
["free"] - balance_per_type
.get("margin", 0),
91 "margin_free": balance_per_type
.get("margin", 0) + margin_balance
.get("amount", 0),
93 "margin_total": balance_per_type
.get("margin", 0) + margin_balance
.get("amount", 0),
94 "margin_lending_fees": margin_balance
.get("lendingFees", 0),
95 "margin_pending_gain": margin_balance
.get("pl", 0),
96 "margin_position_type": margin_balance
.get("type", None),
97 "margin_liquidation_price": margin_balance
.get("liquidationPrice", 0),
98 "margin_borrowed_base_price": margin_balance
.get("total", 0),
99 "margin_borrowed_base_currency": margin_balance
.get("baseCurrency", None),
101 if len(margin_balance
) > 0:
102 if margin_balance
["baseCurrency"] not in in_positions
:
103 in_positions
[margin_balance
["baseCurrency"]] = 0
104 in_positions
[margin_balance
["baseCurrency"]] += margin_balance
["total"]
106 for currency
, in_position
in in_positions
.items():
107 all_balances
[currency
]["total"] += in_position
108 all_balances
[currency
]["margin_total"] += in_position
109 all_balances
[currency
]["margin_borrowed"] += in_position
113 def parse_ticker(self
, ticker
, market
=None):
114 timestamp
= self
.milliseconds()
117 symbol
= market
['symbol']
120 'timestamp': timestamp
,
121 'datetime': self
.iso8601(timestamp
),
122 'high': decimal
.Decimal(ticker
['high24hr']),
123 'low': decimal
.Decimal(ticker
['low24hr']),
124 'bid': decimal
.Decimal(ticker
['highestBid']),
125 'ask': decimal
.Decimal(ticker
['lowestAsk']),
130 'last': decimal
.Decimal(ticker
['last']),
131 'change': decimal
.Decimal(ticker
['percentChange']),
134 'baseVolume': decimal
.Decimal(ticker
['quoteVolume']),
135 'quoteVolume': decimal
.Decimal(ticker
['baseVolume']),
139 def create_margin_order(self
, symbol
, type, side
, amount
, price
=None, lending_rate
=None, params
={}):
141 raise ExchangeError(self
.id + ' allows limit orders only')
143 method
= 'privatePostMargin' + self
.capitalize(side
)
144 market
= self
.market(symbol
)
146 amount
= float(amount
)
147 if lending_rate
is not None:
148 params
= self
.extend({"lendingRate": lending_rate}
, params
)
149 response
= getattr(self
, method
)(self
.extend({
150 'currencyPair': market
['id'],
151 'rate': self
.price_to_precision(symbol
, price
),
152 'amount': self
.amount_to_precision(symbol
, amount
),
154 timestamp
= self
.milliseconds()
155 order
= self
.parse_order(self
.extend({
156 'timestamp': timestamp
,
162 }, response
), market
)
164 self
.orders
[id] = order
165 return self
.extend({'info': response}
, order
)
167 def create_exchange_order(self
, symbol
, type, side
, amount
, price
=None, params
={}):
168 return super(poloniexE
, self
).create_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
170 def create_order(self
, symbol
, type, side
, amount
, price
=None, account
="exchange", lending_rate
=None, params
={}):
171 if account
== "exchange":
172 return self
.create_exchange_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
173 elif account
== "margin":
174 return self
.create_margin_order(symbol
, type, side
, amount
, price
=price
, lending_rate
=lending_rate
, params
=params
)
176 raise NotImplementedError
178 def order_precision(self
, symbol
):
181 def transfer_balance(self
, currency
, amount
, from_account
, to_account
):
182 result
= self
.privatePostTransferBalance({
183 "currency": currency
,
185 "fromAccount": from_account
,
186 "toAccount": to_account
,
188 return result
["success"] == 1
190 def close_margin_position(self
, currency
, base_currency
):
192 closeMarginPosition({"currencyPair": "BTC_DASH"})
193 fermer la position au prix du marché
195 symbol
= "{}_{}".format(base_currency
, currency
)
196 self
.privatePostCloseMarginPosition({"currencyPair": symbol}
)
198 def tradable_balances(self
):
200 portfolio.market.privatePostReturnTradableBalances()
201 Returns tradable balances in margin
202 'BTC_DASH': {'BTC': '0.01266999', 'DASH': '0.08574839'},
203 Je peux emprunter jusqu’à 0.08574839 DASH ou 0.01266999 BTC (une position est déjà ouverte)
204 'BTC_CLAM': {'BTC': '0.00585143', 'CLAM': '7.79300395'},
205 Je peux emprunter 7.7 CLAM pour les vendre contre des BTC, ou emprunter 0.00585143 BTC pour acheter des CLAM
208 tradable_balances
= self
.privatePostReturnTradableBalances()
209 for symbol
, balances
in tradable_balances
.items():
210 for currency
, balance
in balances
.items():
211 balances
[currency
] = decimal
.Decimal(balance
)
212 return tradable_balances
214 def margin_summary(self
):
216 portfolio.market.privatePostReturnMarginAccountSummary()
217 Returns current informations for margin
218 {'currentMargin': '1.49680968', -> marge (ne doit pas descendre sous 20% / 0.2)
219 = netValue / totalBorrowedValue
220 'lendingFees': '0.00000000', -> fees totaux
221 'netValue': '0.01008254', -> balance + plus-value
222 'pl': '0.00008254', -> plus value latente (somme des positions)
223 'totalBorrowedValue': '0.00673602', -> valeur en BTC empruntée
224 'totalValue': '0.01000000'} -> valeur totale en compte
226 summary
= self
.privatePostReturnMarginAccountSummary()
229 "current_margin": decimal
.Decimal(summary
["currentMargin"]),
230 "lending_fees": decimal
.Decimal(summary
["lendingFees"]),
231 "gains": decimal
.Decimal(summary
["pl"]),
232 "total_borrowed": decimal
.Decimal(summary
["totalBorrowedValue"]),
233 "total": decimal
.Decimal(summary
["totalValue"]),