aboutsummaryrefslogtreecommitdiff
path: root/ccxt_wrapper.py
blob: 4ed2116a32e9a57a37027b471b1e6e38c5a65789 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
from ccxt import *
import decimal

def _cw_exchange_sum(self, *args):
    return sum([arg for arg in args if isinstance(arg, (float, int, decimal.Decimal))])
Exchange.sum = _cw_exchange_sum

class poloniexE(poloniex):
    def fetch_balance(self, params={}):
        self.load_markets()
        balances = self.privatePostReturnCompleteBalances(self.extend({
            'account': 'all',
            }, params))
        result = {'info': balances}
        currencies = list(balances.keys())
        for c in range(0, len(currencies)):
            id = currencies[c]
            balance = balances[id]
            currency = self.common_currency_code(id)
            account = {
                    'free': decimal.Decimal(balance['available']),
                    'used': decimal.Decimal(balance['onOrders']),
                    'total': decimal.Decimal(0.0),
                    }
            account['total'] = self.sum(account['free'], account['used'])
            result[currency] = account
        return self.parse_balance(result)

    def fetch_margin_balance(self):
        """
        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'}
        """
        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"]),
                    "baseCurrency": base_currency, 
                    }
        return parsed

    def fetch_balance_per_type(self):
        balances = self.privatePostReturnAvailableAccountBalances()
        result = {'info': balances}
        for key, balance in balances.items():
            result[key] = {}
            for currency, amount in balance.items():
                if currency not in result:
                    result[currency] = {}
                result[currency][key] = decimal.Decimal(amount)
                result[key][currency] = decimal.Decimal(amount)
        return result

    def fetch_all_balances(self):
        exchange_balances = self.fetch_balance()
        margin_balances = self.fetch_margin_balance()
        balances_per_type = self.fetch_balance_per_type()

        all_balances = {}
        in_positions = {}

        for currency, exchange_balance in exchange_balances.items():
            if currency in ["info", "free", "used", "total"]:
                continue

            margin_balance = margin_balances.get(currency, {})
            balance_per_type = balances_per_type.get(currency, {})

            all_balances[currency] = {
                "total": exchange_balance["total"] + margin_balance.get("amount", 0),
                "exchange_used": exchange_balance["used"],
                "exchange_total": exchange_balance["total"] - balance_per_type.get("margin", 0),
                "exchange_free": exchange_balance["free"] - balance_per_type.get("margin", 0),
                "margin_free": balance_per_type.get("margin", 0) + margin_balance.get("amount", 0),
                "margin_borrowed": 0,
                "margin_total": balance_per_type.get("margin", 0) + margin_balance.get("amount", 0),
                "margin_lending_fees": margin_balance.get("lendingFees", 0),
                "margin_pending_gain": margin_balance.get("pl", 0),
                "margin_position_type": margin_balance.get("type", None),
                "margin_liquidation_price": margin_balance.get("liquidationPrice", 0),
                "margin_borrowed_base_price": margin_balance.get("total", 0),
                "margin_borrowed_base_currency": margin_balance.get("baseCurrency", None),
                }
            if len(margin_balance) > 0:
                if margin_balance["baseCurrency"] not in in_positions:
                    in_positions[margin_balance["baseCurrency"]] = 0
                in_positions[margin_balance["baseCurrency"]] += margin_balance["total"]

        for currency, in_position in in_positions.items():
            all_balances[currency]["total"] += in_position
            all_balances[currency]["margin_total"] += in_position
            all_balances[currency]["margin_borrowed"] += in_position

        return all_balances

    def parse_ticker(self, ticker, market=None):
        timestamp = self.milliseconds()
        symbol = None
        if market:
            symbol = market['symbol']
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': decimal.Decimal(ticker['high24hr']),
            'low': decimal.Decimal(ticker['low24hr']),
            'bid': decimal.Decimal(ticker['highestBid']),
            'ask': decimal.Decimal(ticker['lowestAsk']),
            'vwap': None,
            'open': None,
            'close': None,
            'first': None,
            'last': decimal.Decimal(ticker['last']),
            'change': decimal.Decimal(ticker['percentChange']),
            'percentage': None,
            'average': None,
            'baseVolume': decimal.Decimal(ticker['quoteVolume']),
            'quoteVolume': decimal.Decimal(ticker['baseVolume']),
            'info': ticker,
        }

    def create_margin_order(self, symbol, type, side, amount, price=None, lending_rate=None, params={}):
        if type == 'market':
            raise ExchangeError(self.id + ' allows limit orders only')
        self.load_markets()
        method = 'privatePostMargin' + self.capitalize(side)
        market = self.market(symbol)
        price = float(price)
        amount = float(amount)
        if lending_rate is not None:
            params = self.extend({"lendingRate": lending_rate}, params)
        response = getattr(self, method)(self.extend({
            'currencyPair': market['id'],
            'rate': self.price_to_precision(symbol, price),
            'amount': self.amount_to_precision(symbol, amount),
        }, params))
        timestamp = self.milliseconds()
        order = self.parse_order(self.extend({
            'timestamp': timestamp,
            'status': 'open',
            'type': type,
            'side': side,
            'price': price,
            'amount': amount,
        }, response), market)
        id = order['id']
        self.orders[id] = order
        return self.extend({'info': response}, order)

    def create_exchange_order(self, symbol, type, side, amount, price=None, params={}):
        return super(poloniexE, self).create_order(symbol, type, side, amount, price=price, params=params)

    def create_order(self, symbol, type, side, amount, price=None, account="exchange", lending_rate=None, params={}):
        if account == "exchange":
            return self.create_exchange_order(symbol, type, side, amount, price=price, params=params)
        elif account == "margin":
            return self.create_margin_order(symbol, type, side, amount, price=price, lending_rate=lending_rate, params=params)
        else:
            raise NotImplementedError

    def order_precision(self, symbol):
        return 8

    def 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

    def close_margin_position(self, currency, base_currency):
        """
        closeMarginPosition({"currencyPair": "BTC_DASH"})
        fermer la position au prix du marché
        """
        symbol = "{}_{}".format(base_currency, currency)
        self.privatePostCloseMarginPosition({"currencyPair": symbol})

    def tradable_balances(self):
        """
        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
        """

        tradable_balances = self.privatePostReturnTradableBalances()
        for symbol, balances in tradable_balances.items():
            for currency, balance in balances.items():
                balances[currency] = decimal.Decimal(balance)
        return tradable_balances

    def margin_summary(self):
        """
        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
        """
        summary = self.privatePostReturnMarginAccountSummary()

        return {
                "current_margin": decimal.Decimal(summary["currentMargin"]),
                "lending_fees": decimal.Decimal(summary["lendingFees"]),
                "gains": decimal.Decimal(summary["pl"]),
                "total_borrowed": decimal.Decimal(summary["totalBorrowedValue"]),
                "total": decimal.Decimal(summary["totalValue"]),
                }