4 def exchange_sum(self
, *args
):
5 return sum([arg
for arg
in args
if isinstance(arg
, (float, int, decimal
.Decimal
))])
6 ccxt
.Exchange
.sum = exchange_sum
8 def poloniex_fetch_balance(self
, params
={}):
10 balances
= self
.privatePostReturnCompleteBalances(self
.extend({
13 result
= {'info': balances}
14 currencies
= list(balances
.keys())
15 for c
in range(0, len(currencies
)):
17 balance
= balances
[id]
18 currency
= self
.common_currency_code(id)
20 'free': decimal
.Decimal(balance
['available']),
21 'used': decimal
.Decimal(balance
['onOrders']),
22 'total': decimal
.Decimal(0.0),
24 account
['total'] = self
.sum(account
['free'], account
['used'])
25 result
[currency
] = account
26 return self
.parse_balance(result
)
27 ccxt
.poloniex
.fetch_balance
= poloniex_fetch_balance
29 def poloniex_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
,
58 ccxt
.poloniex
.fetch_margin_balance
= poloniex_fetch_margin_balance
60 def poloniex_fetch_balance_per_type(self
):
61 balances
= self
.privatePostReturnAvailableAccountBalances()
62 result
= {'info': balances}
63 for key
, balance
in balances
.items():
65 for currency
, amount
in balance
.items():
66 if currency
not in result
:
68 result
[currency
][key
] = decimal
.Decimal(amount
)
69 result
[key
][currency
] = decimal
.Decimal(amount
)
71 ccxt
.poloniex
.fetch_balance_per_type
= poloniex_fetch_balance_per_type
73 def poloniex_fetch_all_balances(self
):
74 exchange_balances
= self
.fetch_balance()
75 margin_balances
= self
.fetch_margin_balance()
76 balances_per_type
= self
.fetch_balance_per_type()
81 for currency
, exchange_balance
in exchange_balances
.items():
82 if currency
in ["info", "free", "used", "total"]:
85 margin_balance
= margin_balances
.get(currency
, {})
86 balance_per_type
= balances_per_type
.get(currency
, {})
88 all_balances
[currency
] = {
89 "total": exchange_balance
["total"] + margin_balance
.get("amount", 0),
90 "exchange_used": exchange_balance
["used"],
91 "exchange_total": exchange_balance
["total"] - balance_per_type
.get("margin", 0),
92 "exchange_free": exchange_balance
["free"] - balance_per_type
.get("margin", 0),
93 "margin_free": balance_per_type
.get("margin", 0) + margin_balance
.get("amount", 0),
95 "margin_total": balance_per_type
.get("margin", 0) + margin_balance
.get("amount", 0),
96 "margin_lending_fees": margin_balance
.get("lendingFees", 0),
97 "margin_pending_gain": margin_balance
.get("pl", 0),
98 "margin_position_type": margin_balance
.get("type", None),
99 "margin_liquidation_price": margin_balance
.get("liquidationPrice", 0),
100 "margin_borrowed_base_price": margin_balance
.get("total", 0),
101 "margin_borrowed_base_currency": margin_balance
.get("baseCurrency", None),
103 if len(margin_balance
) > 0:
104 if margin_balance
["baseCurrency"] not in in_positions
:
105 in_positions
[margin_balance
["baseCurrency"]] = 0
106 in_positions
[margin_balance
["baseCurrency"]] += margin_balance
["total"]
108 for currency
, in_position
in in_positions
.items():
109 all_balances
[currency
]["total"] += in_position
110 all_balances
[currency
]["margin_total"] += in_position
111 all_balances
[currency
]["margin_borrowed"] += in_position
114 ccxt
.poloniex
.fetch_all_balances
= poloniex_fetch_all_balances
116 def poloniex_parse_ticker(self
, ticker
, market
=None):
117 timestamp
= self
.milliseconds()
120 symbol
= market
['symbol']
123 'timestamp': timestamp
,
124 'datetime': self
.iso8601(timestamp
),
125 'high': decimal
.Decimal(ticker
['high24hr']),
126 'low': decimal
.Decimal(ticker
['low24hr']),
127 'bid': decimal
.Decimal(ticker
['highestBid']),
128 'ask': decimal
.Decimal(ticker
['lowestAsk']),
133 'last': decimal
.Decimal(ticker
['last']),
134 'change': decimal
.Decimal(ticker
['percentChange']),
137 'baseVolume': decimal
.Decimal(ticker
['quoteVolume']),
138 'quoteVolume': decimal
.Decimal(ticker
['baseVolume']),
141 ccxt
.poloniex
.parse_ticker
= poloniex_parse_ticker
143 def poloniex_create_margin_order(self
, symbol
, type, side
, amount
, price
=None, lending_rate
=None, params
={}):
145 raise ccxt
.ExchangeError(self
.id + ' allows limit orders only')
147 method
= 'privatePostMargin' + self
.capitalize(side
)
148 market
= self
.market(symbol
)
150 amount
= float(amount
)
151 if lending_rate
is not None:
152 params
= self
.extend({"lendingRate": lending_rate}
, params
)
153 response
= getattr(self
, method
)(self
.extend({
154 'currencyPair': market
['id'],
155 'rate': self
.price_to_precision(symbol
, price
),
156 'amount': self
.amount_to_precision(symbol
, amount
),
158 timestamp
= self
.milliseconds()
159 order
= self
.parse_order(self
.extend({
160 'timestamp': timestamp
,
166 }, response
), market
)
168 self
.orders
[id] = order
169 return self
.extend({'info': response}
, order
)
170 ccxt
.poloniex
.create_margin_order
= poloniex_create_margin_order
172 def poloniex_create_order(self
, symbol
, type, side
, amount
, price
=None, account
="exchange", lending_rate
=None, params
={}):
173 if account
== "exchange":
174 return self
.create_exchange_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
175 elif account
== "margin":
176 return self
.create_margin_order(symbol
, type, side
, amount
, price
=price
, lending_rate
=lending_rate
, params
=params
)
178 raise NotImplementedError
180 def poloniex_order_precision(self
, symbol
):
183 ccxt
.poloniex
.create_exchange_order
= ccxt
.poloniex
.create_order
184 ccxt
.poloniex
.create_order
= poloniex_create_order
185 ccxt
.poloniex
.order_precision
= poloniex_order_precision
187 def poloniex_transfer_balance(self
, currency
, amount
, from_account
, to_account
):
188 result
= self
.privatePostTransferBalance({
189 "currency": currency
,
191 "fromAccount": from_account
,
192 "toAccount": to_account
,
194 return result
["success"] == 1
195 ccxt
.poloniex
.transfer_balance
= poloniex_transfer_balance
197 def poloniex_close_margin_position(self
, currency
, base_currency
):
199 closeMarginPosition({"currencyPair": "BTC_DASH"})
200 fermer la position au prix du marché
202 symbol
= "{}_{}".format(base_currency
, currency
)
203 self
.privatePostCloseMarginPosition({"currencyPair": symbol}
)
204 ccxt
.poloniex
.close_margin_position
= poloniex_close_margin_position
206 def poloniex_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
221 ccxt
.poloniex
.fetch_tradable_balances
= poloniex_tradable_balances
223 def poloniex_margin_summary(self
):
225 portfolio.market.privatePostReturnMarginAccountSummary()
226 Returns current informations for margin
227 {'currentMargin': '1.49680968', -> marge (ne doit pas descendre sous 20% / 0.2)
228 = netValue / totalBorrowedValue
229 'lendingFees': '0.00000000', -> fees totaux
230 'netValue': '0.01008254', -> balance + plus-value
231 'pl': '0.00008254', -> plus value latente (somme des positions)
232 'totalBorrowedValue': '0.00673602', -> valeur en BTC empruntée
233 'totalValue': '0.01000000'} -> valeur totale en compte
235 summary
= self
.privatePostReturnMarginAccountSummary()
238 "current_margin": decimal
.Decimal(summary
["currentMargin"]),
239 "lending_fees": decimal
.Decimal(summary
["lendingFees"]),
240 "gains": decimal
.Decimal(summary
["pl"]),
241 "total_borrowed": decimal
.Decimal(summary
["totalBorrowedValue"]),
242 "total": decimal
.Decimal(summary
["totalValue"]),
244 ccxt
.poloniex
.margin_summary
= poloniex_margin_summary
245 market
= ccxt
.poloniex({
246 "apiKey": "XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX",
247 "secret": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",