]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git/blobdiff - market.py
Work in progress to use shorts
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Trader.git] / market.py
index 1601e2dce82ec6d3e2b63624bd355755bd565b8e..1e1e083447bd4b319a7edb35b749592be0408cf3 100644 (file)
--- a/market.py
+++ b/market.py
@@ -4,6 +4,7 @@ import decimal
 def exchange_sum(self, *args):
     return sum([arg for arg in args if isinstance(arg, (float, int, decimal.Decimal))])
 ccxt.Exchange.sum = exchange_sum
+
 def poloniex_fetch_balance(self, params={}):
     self.load_markets()
     balances = self.privatePostReturnCompleteBalances(self.extend({
@@ -25,6 +26,39 @@ def poloniex_fetch_balance(self, params={}):
     return self.parse_balance(result)
 ccxt.poloniex.fetch_balance = poloniex_fetch_balance
 
+def poloniex_fetch_margin_balances(self):
+    positions = self.privatePostGetMarginPosition({"currencyPair": "all"})
+    parsed = {}
+    for symbol, position in positions.items():
+        if position["type"] == "none":
+            continue
+        base_currency, currency = symbol.split("_")
+        parsed[currency] = {
+                "amount": decimal.Decimal(position["amount"]),
+                "borrowedPrice": decimal.Decimal(position["basePrice"]),
+                "lendingFees": decimal.Decimal(position["lendingFees"]),
+                "pl": decimal.Decimal(position["pl"]),
+                "liquidationPrice": decimal.Decimal(position["liquidationPrice"]),
+                "type": position["type"],
+                "total": decimal.Decimal(position["total"]),
+                "base_currency": base_currency, 
+                }
+    return parsed
+ccxt.poloniex.fetch_margin_balances = poloniex_fetch_margin_balances
+
+def poloniex_fetch_balance_with_margin(self, params={}):
+    exchange_balance = self.fetch_balance(params=params)
+    margin_balances = self.fetch_margin_balances()
+
+    for currency, balance in margin_balances.items():
+        assert exchange_balance[currency]["total"] == 0
+        assert balance["type"] == "short"
+        exchange_balance[currency]["total"] = balance["amount"]
+        exchange_balance[currency]["marginPosition"] = balance
+    return exchange_balance
+ccxt.poloniex.fetch_balance_with_margin = poloniex_fetch_balance_with_margin
+
+
 def poloniex_fetch_balance_per_type(self):
     balances = self.privatePostReturnAvailableAccountBalances()
     result = {'info': balances}
@@ -92,6 +126,7 @@ def poloniex_create_margin_order(self, symbol, type, side, amount, price=None, l
     id = order['id']
     self.orders[id] = order
     return self.extend({'info': response}, order)
+ccxt.poloniex.create_margin_order = poloniex_create_margin_order
 
 def poloniex_create_order(self, symbol, type, side, amount, price=None, account="exchange", lending_rate=None, params={}):
     if account == "exchange":
@@ -100,8 +135,65 @@ def poloniex_create_order(self, symbol, type, side, amount, price=None, account=
         return self.create_margin_order(symbol, type, side, amount, price=price, lending_rate=lending_rate, params=params)
     else:
         raise NotImplementedError
+
+def poloniex_order_precision(self, symbol):
+    return 8
+
 ccxt.poloniex.create_exchange_order = ccxt.poloniex.create_order
 ccxt.poloniex.create_order = poloniex_create_order
+ccxt.poloniex.order_precision = poloniex_order_precision
+
+def poloniex_transfer_balance(self, currency, amount, from_account, to_account):
+    result = self.privatePostTransferBalance({
+        "currency": currency,
+        "amount": amount,
+        "fromAccount": from_account,
+        "toAccount": to_account,
+        "confirmed": 1})
+    return result["success"] == 1
+ccxt.poloniex.transfer_balance = poloniex_transfer_balance
+
+# portfolio.market.create_order("DASH/BTC", "limit", "sell", 0.1, price=0.06828800, account="margin")
+
+# portfolio.market.privatePostReturnTradableBalances()
+# Returns tradable balances in margin
+# 'BTC_DASH': {'BTC': '0.01266999', 'DASH': '0.08574839'},
+# Je peux emprunter jusqu’à 0.08574839 DASH ou 0.01266999 BTC (une position est
+# déjà ouverte)
+# 'BTC_CLAM': {'BTC': '0.00585143', 'CLAM': '7.79300395'},
+# Je peux emprunter 7.7 CLAM pour les vendre contre des BTC, ou emprunter
+# 0.00585143 BTC pour acheter des CLAM
+
+# portfolio.market.privatePostReturnMarginAccountSummary()
+# Returns current informations for margin
+# {'currentMargin': '1.49680968',      -> marge (ne doit pas descendre sous 20% / 0.2)
+#                                         = netValue / totalBorrowedValue
+#  'lendingFees': '0.00000000',        -> fees totaux
+#  'netValue': '0.01008254',           -> balance + plus-value
+#  'pl': '0.00008254',                 -> plus value latente (somme des positions)
+#  'totalBorrowedValue': '0.00673602', -> valeur en BTC empruntée
+#  'totalValue': '0.01000000'}         -> valeur totale en compte
+
+
+# portfolio.market.privatePostGetMarginPosition({"currencyPair": "BTC_DASH"})
+# See DASH/BTC positions
+# {'amount': '-0.10000000',          -> DASH empruntés
+#  'basePrice': '0.06818560',        -> à ce prix là (0.06828800 demandé * (1-0.15%))
+#  'lendingFees': '0.00000000',      -> ce que je dois à mon créditeur
+#  'liquidationPrice': '0.15107132', -> prix auquel ça sera liquidé (dépend de ce que j’ai déjà sur mon compte margin)
+#  'pl': '-0.00000371',              -> plus-value latente si je rachète tout de suite (négatif = perdu)
+#  'total': '0.00681856',            -> valeur totale empruntée en BTC
+#  'type': 'short'}
+
+
+# closeMarginPosition({"currencyPair": "BTC_DASH"}) : fermer la position au prix
+# du marché
+# Nécessaire à la fin
+# portfolio.market.create_order("DASH/BTC", "limit", "buy", 0.1, price=0.06726487, account="margin")
+
+# portfolio.market.fetch_balance_per_type()
+# Ne suffit pas pour calculer les positions: ne contient que les 0.01 envoyés
+# TODO: vérifier si fetch_balance marque ces 0.01 comme disponibles -> oui
 
 market = ccxt.poloniex({
     "apiKey": "XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX",