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_balances(self
):
30 positions
= self
.privatePostGetMarginPosition({"currencyPair": "all"}
)
32 for symbol
, position
in positions
.items():
33 if position
["type"] == "none":
35 base_currency
, currency
= symbol
.split("_")
37 "amount": decimal
.Decimal(position
["amount"]),
38 "borrowedPrice": decimal
.Decimal(position
["basePrice"]),
39 "lendingFees": decimal
.Decimal(position
["lendingFees"]),
40 "pl": decimal
.Decimal(position
["pl"]),
41 "liquidationPrice": decimal
.Decimal(position
["liquidationPrice"]),
42 "type": position
["type"],
43 "total": decimal
.Decimal(position
["total"]),
44 "base_currency": base_currency
,
47 ccxt
.poloniex
.fetch_margin_balances
= poloniex_fetch_margin_balances
49 def poloniex_fetch_balance_with_margin(self
, params
={}):
50 exchange_balance
= self
.fetch_balance(params
=params
)
51 margin_balances
= self
.fetch_margin_balances()
53 for currency
, balance
in margin_balances
.items():
54 assert exchange_balance
[currency
]["total"] == 0
55 assert balance
["type"] == "short"
56 exchange_balance
[currency
]["total"] = balance
["amount"]
57 exchange_balance
[currency
]["marginPosition"] = balance
58 return exchange_balance
59 ccxt
.poloniex
.fetch_balance_with_margin
= poloniex_fetch_balance_with_margin
62 def poloniex_fetch_balance_per_type(self
):
63 balances
= self
.privatePostReturnAvailableAccountBalances()
64 result
= {'info': balances}
65 for key
, balance
in balances
.items():
67 for currency
, amount
in balance
.items():
68 if currency
not in result
:
70 result
[currency
][key
] = decimal
.Decimal(amount
)
71 result
[key
][currency
] = decimal
.Decimal(amount
)
73 ccxt
.poloniex
.fetch_balance_per_type
= poloniex_fetch_balance_per_type
75 def poloniex_parse_ticker(self
, ticker
, market
=None):
76 timestamp
= self
.milliseconds()
79 symbol
= market
['symbol']
82 'timestamp': timestamp
,
83 'datetime': self
.iso8601(timestamp
),
84 'high': decimal
.Decimal(ticker
['high24hr']),
85 'low': decimal
.Decimal(ticker
['low24hr']),
86 'bid': decimal
.Decimal(ticker
['highestBid']),
87 'ask': decimal
.Decimal(ticker
['lowestAsk']),
92 'last': decimal
.Decimal(ticker
['last']),
93 'change': decimal
.Decimal(ticker
['percentChange']),
96 'baseVolume': decimal
.Decimal(ticker
['quoteVolume']),
97 'quoteVolume': decimal
.Decimal(ticker
['baseVolume']),
100 ccxt
.poloniex
.parse_ticker
= poloniex_parse_ticker
102 def poloniex_create_margin_order(self
, symbol
, type, side
, amount
, price
=None, lending_rate
=None, params
={}):
104 raise ccxt
.ExchangeError(self
.id + ' allows limit orders only')
106 method
= 'privatePostMargin' + self
.capitalize(side
)
107 market
= self
.market(symbol
)
109 amount
= float(amount
)
110 if lending_rate
is not None:
111 params
= self
.extend({"lendingRate": lending_rate}
, params
)
112 response
= getattr(self
, method
)(self
.extend({
113 'currencyPair': market
['id'],
114 'rate': self
.price_to_precision(symbol
, price
),
115 'amount': self
.amount_to_precision(symbol
, amount
),
117 timestamp
= self
.milliseconds()
118 order
= self
.parse_order(self
.extend({
119 'timestamp': timestamp
,
125 }, response
), market
)
127 self
.orders
[id] = order
128 return self
.extend({'info': response}
, order
)
129 ccxt
.poloniex
.create_margin_order
= poloniex_create_margin_order
131 def poloniex_create_order(self
, symbol
, type, side
, amount
, price
=None, account
="exchange", lending_rate
=None, params
={}):
132 if account
== "exchange":
133 return self
.create_exchange_order(symbol
, type, side
, amount
, price
=price
, params
=params
)
134 elif account
== "margin":
135 return self
.create_margin_order(symbol
, type, side
, amount
, price
=price
, lending_rate
=lending_rate
, params
=params
)
137 raise NotImplementedError
139 def poloniex_order_precision(self
, symbol
):
142 ccxt
.poloniex
.create_exchange_order
= ccxt
.poloniex
.create_order
143 ccxt
.poloniex
.create_order
= poloniex_create_order
144 ccxt
.poloniex
.order_precision
= poloniex_order_precision
146 def poloniex_transfer_balance(self
, currency
, amount
, from_account
, to_account
):
147 result
= self
.privatePostTransferBalance({
148 "currency": currency
,
150 "fromAccount": from_account
,
151 "toAccount": to_account
,
153 return result
["success"] == 1
154 ccxt
.poloniex
.transfer_balance
= poloniex_transfer_balance
156 # portfolio.market.create_order("DASH/BTC", "limit", "sell", 0.1, price=0.06828800, account="margin")
158 # portfolio.market.privatePostReturnTradableBalances()
159 # Returns tradable balances in margin
160 # 'BTC_DASH': {'BTC': '0.01266999', 'DASH': '0.08574839'},
161 # Je peux emprunter jusqu’à 0.08574839 DASH ou 0.01266999 BTC (une position est
163 # 'BTC_CLAM': {'BTC': '0.00585143', 'CLAM': '7.79300395'},
164 # Je peux emprunter 7.7 CLAM pour les vendre contre des BTC, ou emprunter
165 # 0.00585143 BTC pour acheter des CLAM
167 # portfolio.market.privatePostReturnMarginAccountSummary()
168 # Returns current informations for margin
169 # {'currentMargin': '1.49680968', -> marge (ne doit pas descendre sous 20% / 0.2)
170 # = netValue / totalBorrowedValue
171 # 'lendingFees': '0.00000000', -> fees totaux
172 # 'netValue': '0.01008254', -> balance + plus-value
173 # 'pl': '0.00008254', -> plus value latente (somme des positions)
174 # 'totalBorrowedValue': '0.00673602', -> valeur en BTC empruntée
175 # 'totalValue': '0.01000000'} -> valeur totale en compte
178 # portfolio.market.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
179 # See DASH/BTC positions
180 # {'amount': '-0.10000000', -> DASH empruntés
181 # 'basePrice': '0.06818560', -> à ce prix là (0.06828800 demandé * (1-0.15%))
182 # 'lendingFees': '0.00000000', -> ce que je dois à mon créditeur
183 # 'liquidationPrice': '0.15107132', -> prix auquel ça sera liquidé (dépend de ce que j’ai déjà sur mon compte margin)
184 # 'pl': '-0.00000371', -> plus-value latente si je rachète tout de suite (négatif = perdu)
185 # 'total': '0.00681856', -> valeur totale empruntée en BTC
189 # closeMarginPosition({"currencyPair": "BTC_DASH"}) : fermer la position au prix
191 # Nécessaire à la fin
192 # portfolio.market.create_order("DASH/BTC", "limit", "buy", 0.1, price=0.06726487, account="margin")
194 # portfolio.market.fetch_balance_per_type()
195 # Ne suffit pas pour calculer les positions: ne contient que les 0.01 envoyés
196 # TODO: vérifier si fetch_balance marque ces 0.01 comme disponibles -> oui
198 market
= ccxt
.poloniex({
199 "apiKey": "XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX",
200 "secret": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",