aboutsummaryrefslogtreecommitdiff
path: root/market.py
diff options
context:
space:
mode:
Diffstat (limited to 'market.py')
-rw-r--r--market.py244
1 files changed, 1 insertions, 243 deletions
diff --git a/market.py b/market.py
index 979fbbf..deaab88 100644
--- a/market.py
+++ b/market.py
@@ -1,247 +1,5 @@
1import ccxt 1import ccxt_wrapper as ccxt
2import decimal
3 2
4def exchange_sum(self, *args):
5 return sum([arg for arg in args if isinstance(arg, (float, int, decimal.Decimal))])
6ccxt.Exchange.sum = exchange_sum
7
8def poloniex_fetch_balance(self, params={}):
9 self.load_markets()
10 balances = self.privatePostReturnCompleteBalances(self.extend({
11 'account': 'all',
12 }, params))
13 result = {'info': balances}
14 currencies = list(balances.keys())
15 for c in range(0, len(currencies)):
16 id = currencies[c]
17 balance = balances[id]
18 currency = self.common_currency_code(id)
19 account = {
20 'free': decimal.Decimal(balance['available']),
21 'used': decimal.Decimal(balance['onOrders']),
22 'total': decimal.Decimal(0.0),
23 }
24 account['total'] = self.sum(account['free'], account['used'])
25 result[currency] = account
26 return self.parse_balance(result)
27ccxt.poloniex.fetch_balance = poloniex_fetch_balance
28
29def poloniex_fetch_margin_balance(self):
30 """
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
39 'type': 'short'}
40 """
41 positions = self.privatePostGetMarginPosition({"currencyPair": "all"})
42 parsed = {}
43 for symbol, position in positions.items():
44 if position["type"] == "none":
45 continue
46 base_currency, currency = symbol.split("_")
47 parsed[currency] = {
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,
56 }
57 return parsed
58ccxt.poloniex.fetch_margin_balance = poloniex_fetch_margin_balance
59
60def poloniex_fetch_balance_per_type(self):
61 balances = self.privatePostReturnAvailableAccountBalances()
62 result = {'info': balances}
63 for key, balance in balances.items():
64 result[key] = {}
65 for currency, amount in balance.items():
66 if currency not in result:
67 result[currency] = {}
68 result[currency][key] = decimal.Decimal(amount)
69 result[key][currency] = decimal.Decimal(amount)
70 return result
71ccxt.poloniex.fetch_balance_per_type = poloniex_fetch_balance_per_type
72
73def 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()
77
78 all_balances = {}
79 in_positions = {}
80
81 for currency, exchange_balance in exchange_balances.items():
82 if currency in ["info", "free", "used", "total"]:
83 continue
84
85 margin_balance = margin_balances.get(currency, {})
86 balance_per_type = balances_per_type.get(currency, {})
87
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),
94 "margin_borrowed": 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),
102 }
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"]
107
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
112
113 return all_balances
114ccxt.poloniex.fetch_all_balances = poloniex_fetch_all_balances
115
116def poloniex_parse_ticker(self, ticker, market=None):
117 timestamp = self.milliseconds()
118 symbol = None
119 if market:
120 symbol = market['symbol']
121 return {
122 'symbol': 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']),
129 'vwap': None,
130 'open': None,
131 'close': None,
132 'first': None,
133 'last': decimal.Decimal(ticker['last']),
134 'change': decimal.Decimal(ticker['percentChange']),
135 'percentage': None,
136 'average': None,
137 'baseVolume': decimal.Decimal(ticker['quoteVolume']),
138 'quoteVolume': decimal.Decimal(ticker['baseVolume']),
139 'info': ticker,
140 }
141ccxt.poloniex.parse_ticker = poloniex_parse_ticker
142
143def poloniex_create_margin_order(self, symbol, type, side, amount, price=None, lending_rate=None, params={}):
144 if type == 'market':
145 raise ccxt.ExchangeError(self.id + ' allows limit orders only')
146 self.load_markets()
147 method = 'privatePostMargin' + self.capitalize(side)
148 market = self.market(symbol)
149 price = float(price)
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),
157 }, params))
158 timestamp = self.milliseconds()
159 order = self.parse_order(self.extend({
160 'timestamp': timestamp,
161 'status': 'open',
162 'type': type,
163 'side': side,
164 'price': price,
165 'amount': amount,
166 }, response), market)
167 id = order['id']
168 self.orders[id] = order
169 return self.extend({'info': response}, order)
170ccxt.poloniex.create_margin_order = poloniex_create_margin_order
171
172def 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)
177 else:
178 raise NotImplementedError
179
180def poloniex_order_precision(self, symbol):
181 return 8
182
183ccxt.poloniex.create_exchange_order = ccxt.poloniex.create_order
184ccxt.poloniex.create_order = poloniex_create_order
185ccxt.poloniex.order_precision = poloniex_order_precision
186
187def poloniex_transfer_balance(self, currency, amount, from_account, to_account):
188 result = self.privatePostTransferBalance({
189 "currency": currency,
190 "amount": amount,
191 "fromAccount": from_account,
192 "toAccount": to_account,
193 "confirmed": 1})
194 return result["success"] == 1
195ccxt.poloniex.transfer_balance = poloniex_transfer_balance
196
197def poloniex_close_margin_position(self, currency, base_currency):
198 """
199 closeMarginPosition({"currencyPair": "BTC_DASH"})
200 fermer la position au prix du marché
201 """
202 symbol = "{}_{}".format(base_currency, currency)
203 self.privatePostCloseMarginPosition({"currencyPair": symbol})
204ccxt.poloniex.close_margin_position = poloniex_close_margin_position
205
206def poloniex_tradable_balances(self):
207 """
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
214 """
215
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
221ccxt.poloniex.fetch_tradable_balances = poloniex_tradable_balances
222
223def poloniex_margin_summary(self):
224 """
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
234 """
235 summary = self.privatePostReturnMarginAccountSummary()
236
237 return {
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"]),
243 }
244ccxt.poloniex.margin_summary = poloniex_margin_summary
245market = ccxt.poloniex({ 3market = ccxt.poloniex({
246 "apiKey": "XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX", 4 "apiKey": "XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX",
247 "secret": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", 5 "secret": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",