Esempio n. 1
0
    def cancel(self, pairs, orderId):
        URL = "/v1/order/cancel"
        # self.log.debug("{url}", url=self.__url)
        url = self.__url + URL
        # self.log.debug("{url}", url=url)
        symbol = self.getSymbol(pairs)
        params = {}
        params['order_id'] = orderId
        headers = getPostHeaders(url, URL, payload_params=params)
        d = post(reactor, url, headers=headers)

        def handleBody(body):
            # self.log.debug("{body}", body=body)
            data = json.loads(body)
            # self.log.debug("{data}", data=data)

            assert 'is_cancelled' in data, str(data)
            is_cancelled = data['is_cancelled']
            # except KeyError:
            #     is_cancelled = False
            #     if 'error' in data:
            #         err = data['error']
            #         self.log.debug("{err}", err=err)
            #         if err == 'ERR_RATE_LIMIT':
            #             time.sleep(1)
            #     return (False, data)
            if is_cancelled:
                return True
            else:
                return False

        d.addCallback(handleBody)
        d.addErrback(self.defaultErrhandler)

        return d
Esempio n. 2
0
    def getAddress(self, coin):
        URL = "/api2/1/private/depositAddress/"

        url = self.__url['balance'] + URL
        # self.log.debug("{url}", url=url)

        prams = {'currency': coin.upper()}

        body = self.getPostBodyStr(prams)
        header = self.getPostHeader(body)
        # self.log.debug("{header}", header=header)
        # self.log.debug("{prams}", prams=prams)

        d = post(reactor, url, headers=header, body=body)

        def handleBody(body):
            data = json.loads(body)
            # self.log.debug("{data}", data=data)

            flag = data['result']
            if isinstance(flag, str):
                flag = flag.upper() == 'TRUE'
            assert flag, f"{data.get('message', 'unknown error')}, ErrorCode: {data.get('code', 'unknown')}"

            addr = data['addr']
            return addr

        d.addCallback(handleBody)
        d.addErrback(self.defaultErrhandler)

        return d
Esempio n. 3
0
    def sell(self, coinPair, price, amount):
        URL = "/api2/1/private/sell/"

        url = self.__url['balance'] + URL
        # self.log.debug("{url}", url=url)

        prams = {
            'currencyPair': self.getSymbol(coinPair),
            'rate': price,
            'amount': amount
        }
        body = self.getPostBodyStr(prams)
        header = self.getPostHeader(body)
        # self.log.debug("{header}", header=header)
        # self.log.debug("{prams}", prams=prams)

        d = post(reactor, url, headers=header, body=body)

        def handleBody(body):
            # self.log.debug("{body}", body=body)
            data = json.loads(body)
            # self.log.debug("{data}", data=data)

            flag = data['result']
            if isinstance(flag, str):
                flag = flag.upper() == 'TRUE'
            assert flag, f"{data.get('message', 'unknown error')}, ErrorCode: {data.get('code', 'unknown')}"

            orederId = int(data['orderNumber'])
            return orederId

        d.addCallback(handleBody)
        d.addErrback(self.defaultErrhandler)

        return d
Esempio n. 4
0
    def getOrderHistory(self, pairs, givenTime=float(time.time()) - 259200):
        #View your latest inactive orders. Limited to last 3 days and 1 request per minute.
        #All times are UTC timestamps expressed as seconds (eg 1477409622)
        #default givenTime:3 days ago
        URL = "/v1/orders/hist"
        # self.log.debug("{url}", url=self.__url)
        url = self.__url + URL
        # self.log.debug("{url}", url=url)
        symbol = self.getSymbol(pairs)
        headers = getPostHeaders(url, URL)
        d = post(reactor, url, headers=headers)

        def handleBody(body):
            # self.log.debug("{body}", body=body)
            data = json.loads(body)
            # self.log.debug("{data}", data=data)
            orderList = []

            assert isinstance(data, list), str(data)
            for order in data:
                assert 'price' in order, str(order)
                timestamp = order['timestamp']
                symbolGet = order['symbol'].upper()
                # self.log.debug("{symbolGet}{symbol}", symbolGet=symbolGet, symbol=symbol)
                if float(timestamp) >= givenTime and symbol == symbolGet:
                    status = 'open'
                    if order['is_cancelled']:
                        status = 'cancelled'
                    elif not order['is_live']:  #若没有被取消,并且不能继续被填充(not live),
                        status = 'done'  #则表示交易已完成(done)
                    orderList.append({
                        'orderId':
                        order['id'],
                        'timestamp':
                        timestamp,  #返回的字典中添加了时间戳信息
                        'type':
                        order['side'],
                        'iniPrice':
                        float(order['price']),
                        'initAmount':
                        float(order['original_amount']),
                        'coinPair':
                        order['symbol'],
                        'status':
                        status
                    })
                # except KeyError:
                #     if 'error' in data:
                #         err = data['error']
                #         self.log.debug("{err}", err=err)
                #         if err == 'ERR_RATE_LIMIT':
                #             time.sleep(1)

            return orderList

        d.addCallback(handleBody)
        d.addErrback(self.ratelimitErrhandler)

        return d
Esempio n. 5
0
    def getOrder(self, pairs, orderId):
        URL = "/v1/order/status"
        # self.log.debug("{url}", url=self.__url)
        url = self.__url + URL
        # self.log.debug("{url}", url=url)
        symbol = self.getSymbol(pairs)
        params = {}
        params['order_id'] = orderId
        headers = getPostHeaders(url, URL, payload_params=params)
        d = post(reactor, url, headers=headers)

        def handleBody(body):
            # self.log.debug("{body}", body=body)
            data = json.loads(body)
            # self.log.debug("{data}", data=data)

            assert 'side' in data, str(data)
            side = data['side']
            price = float(data['price'])
            amount = float(data['original_amount'])
            is_cancelled = data['is_cancelled']
            is_live = data['is_live']
            timestamp = data['timestamp']
            # except KeyError:
            #     side = ''
            #     price = '0'
            #     amount = '0'
            #     is_cancelled = False
            #     is_live = False
            #     if 'error' in data:
            #         err = data['error']
            #         self.log.debug("{err}", err=err)
            #         if err == 'ERR_RATE_LIMIT':
            #             time.sleep(1)

            status = 'open'
            if 'error' in data:  #若有错误,status置为'error'
                status = 'error'
            elif is_cancelled:
                status = 'cancelled'
            elif not is_live:  #若没有被取消,并且不能继续被填充(not live),
                status = 'done'  #则表示交易已完成(done)
            order_data = dict()
            order_data = {
                'orderId': orderId,
                'timestamp': timestamp,  #返回的字典中添加了时间戳信息
                'type': side,
                'iniPrice': price,
                'initAmount': amount,
                'coinPair': symbol,
                'status': status
            }
            return order_data

        d.addCallback(handleBody)
        d.addErrback(self.defaultErrhandler)

        return d
Esempio n. 6
0
    def getOrder(self, orderId, coinPair):
        URL = "/api2/1/private/getOrder/"

        url = self.__url['balance'] + URL
        # self.log.debug("{url}", url=url)

        prams = {
            'orderNumber': orderId,
            'currencyPair': self.getSymbol(coinPair),
        }

        body = self.getPostBodyStr(prams)
        header = self.getPostHeader(body)
        # self.log.debug("{header}", header=header)
        # self.log.debug("{prams}", prams=prams)

        d = post(reactor, url, headers=header, body=body)

        def handleBody(body):
            # self.log.debug("{body}", body=body)
            data = json.loads(body)

            # self.log.debug("{data}", data=data)

            flag = data['result']
            if isinstance(flag, str):
                flag = flag.upper() == 'TRUE'
            assert flag, f"{data.get('message', 'unknown error')}, ErrorCode: {data.get('code', 'unknown')}"

            status = data['order']['status']
            if status == 'closed':
                status = 'done'

            order = {
                'orderId': orderId,
                'type': data['order']['type'],
                'initPrice': float(data['order']['initialRate']),
                'initAmount': float(data['order']['initialAmount']),
                'coinPair': coinPair,
                'status': status
            }
            # self.log.debug("{order!s}", order=order)

            return order

        d.addCallback(handleBody)
        d.addErrback(self.defaultErrhandler)

        return d
Esempio n. 7
0
    def getBalances(self, coins):
        #ratelimit: 20 req/min
        URL = "/v1/balances"
        # self.log.debug("{url}", url=self.__url)
        url = self.__url + URL
        # self.log.debug("{url}", url=url)
        headers = getPostHeaders(url, URL)
        d = post(reactor, url, headers=headers)
        for i in range(len(coins)):
            if coins[i] == 'usdt':
                coins[i] = 'usd'

        def handleBody(body):
            # self.log.debug("{body}", body=body)
            data = json.loads(body)
            # self.log.debug("{data}", data=data)
            balances = dict()
            assert isinstance(data, list), str(data)

            for b in data:
                b_type = b['type']
                b_currency = b['currency']
                b_available = b['available']
                # except Exception as e:
                #     b_type = ''
                #     b_currency = ''
                #     b_available = 0.0
                #     if 'error' in data:
                #         err = data['error']
                #         self.log.debug('{err} from getBalances()', err=err)
                #         if err == 'ERR_RATE_LIMIT':
                #             time.sleep(1)
                if b_type == 'exchange':
                    # self.log.debug("{b}", b=b)
                    if b_currency in coins:
                        # self.log.debug("{currency}", currency=b['currency'])
                        balances[b_currency] = float(
                            b_available)  #balance that is available to trade

            if balances == {}:
                return None
            return balances

        d.addCallback(handleBody)
        d.addErrback(self.ratelimitErrhandler)

        return d
Esempio n. 8
0
def httpPost(url, resource, params, callback=None, errback=None):
    headers = {
        "Content-type": ["application/x-www-form-urlencoded"],
        'User-Agent': [
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'
        ],
    }
    postdata = urllib.parse.urlencode(params)
    # print(url + resource)
    # print(postdata)
    d = post(reactor, url=url + resource, headers=headers, body=postdata)
    if callback:
        d.addCallback(callback)
    if errback:
        d.addErrback(errback)

    return d
Esempio n. 9
0
    def sell(self, pairs, price, amount):
        URL = "/v1/order/new"
        # self.log.debug("{url}", url=self.__url)
        url = self.__url + URL
        # self.log.debug("{url}", url=url)
        symbol = self.getSymbol(pairs)
        params = {
            'symbol': symbol,
            'amount': format(amount, '0.8f'),
            'price': str(price),
            'side': 'sell',
            'type': 'exchange limit',
            'exchange': 'bitfinex'
        }
        headers = getPostHeaders(url, URL, payload_params=params)
        d = post(reactor, url, headers=headers)

        def handleBody(body):
            # self.log.debug("{body}", body=body)
            data = json.loads(body)
            # self.log.debug("{data}", data=data)

            assert 'order_id' in data, str(data)
            order_id = data['order_id']
            return int(order_id)
            # try:
            #     order_id = data['order_id']
            #     return (True, int(order_id))
            # except KeyError:
            #     self.log.debug("{data}", data=data)
            #     order_id = '0'
            #     if 'error' in data:
            #         err = data['error']
            #         self.log.debug("{err}", err=err)
            #         if err == 'ERR_RATE_LIMIT':
            #             time.sleep(1)
            #     return (False, data)

        d.addCallback(handleBody)
        d.addErrback(self.defaultErrhandler)

        return d
Esempio n. 10
0
    def cancelOrder(self, orderId, coinPair=None):
        params = {}
        url = "/v1/order/orders/{0}/submitcancel".format(orderId)
        url, params = self.api_key_post(params, url)
        headers = self.postHeaders()
        postdata = json.dumps(params)
        d = post(reactor, url, headers=headers, body=postdata)

        def handleBody(body):
            data = json.loads(body)
            assert 'status' in data
            if data['status'] == 'ok':
                return data
            elif data['status'] == 'error':
                return (data['err-code'], data['err-msg'])

        d.addCallback(handleBody)
        d.addErrback(handleBody)

        return d
Esempio n. 11
0
    def getBalances(self, coins=None):
        assert coins is None or isinstance(
            coins, (list, tuple)), "type of 'coins' must be 'list' or 'tuple'"
        URL = "/api2/1/private/balances/"
        url = self.__url['balance'] + URL
        # self.log.debug("{url}", url=url)

        prams = {}

        body = self.getPostBodyStr(prams)
        header = self.getPostHeader(body)
        # self.log.debug("{header}", header=header)
        # self.log.debug("{prams}", prams=prams)

        d = post(reactor, url, headers=header, body=body)

        def handleBody(body):
            data = json.loads(body)
            # self.log.debug("{data}", data=data)

            flag = data['result']
            if isinstance(flag, str):
                flag = flag.upper() == 'TRUE'
            assert flag, f"{data.get('message', 'unknown error')}, ErrorCode: {data.get('code', 'unknown')}"

            if not data['available']:
                return {}
            balances = {
                key: float(value)
                for key, value in data['available'].items()
            }

            if not coins:
                return balances
            else:
                return {coin: balances.get(coin.upper(), 0) for coin in coins}

        d.addCallback(handleBody)
        d.addErrback(self.defaultErrhandler)

        return d
Esempio n. 12
0
    def cancel(self, orderId, coinPair):
        URL = "/api2/1/private/cancelOrder/"

        url = self.__url['balance'] + URL
        # self.log.debug("{url}", url=url)

        prams = {
            'orderNumber': orderId,
            'currencyPair': self.getSymbol(coinPair),
        }
        body = self.getPostBodyStr(prams)
        header = self.getPostHeader(body)
        # self.log.debug("{header}", header=header)
        # self.log.debug("{prams}", prams=prams)

        d = post(reactor, url, headers=header, body=body)

        def handleBody(body):
            # self.log.debug("{body}", body=body)
            data = json.loads(body)
            # self.log.debug("{data}", data=data)

            flag = data['result']
            if isinstance(flag, str):
                flag = flag.upper() == 'TRUE'
            assert flag, f"{data.get('message', 'unknown error')}, ErrorCode: {data.get('code', 'unknown')}"

            return True

        def errhandler(failure):
            self.log.error("{failure}", failure=failure)
            return False

        d.addCallback(handleBody)
        d.addErrback(errhandler)

        return d
Esempio n. 13
0
    def sell(self, coinPair, price, amount):

        params = {
            "account-id": self.getAcctId(),
            "amount": amount,
            "symbol": self.getSymbol(coinPair),
            "type": "sell-limit",
            "source": "web",
            "price": price
        }
        url = '/v1/order/orders/place'
        url, params = self.api_key_post(params, url)
        headers = self.postHeaders()
        postdata = json.dumps(params)
        d = post(reactor, url, headers=headers, body=postdata)

        def handleBody(body):
            data = json.loads(body)
            self.log.debug("{data}", data=data)
            assert 'data' in data
            order_id = data['data']
            return int(order_id)

        #    try:
        #        return (True,int(order_id))
        #    except KeyError:
        #        self.log.debug("{data}", data=data)
        #        order_id = '0'
        #        if 'err-msg' in data:
        #            err = data['err-msg']
        #            self.log.error("{err}", err=err)
        #            return (False, data['err-msg'])

        d.addCallback(handleBody)
        d.addErrback(handleBody)

        return d
Esempio n. 14
0
    def getOrders(self, coinPair):
        URLdone = "/api2/1/private/tradeHistory/"
        URLopen = "/api2/1/private/openOrders/"

        urlDone = self.__url['balance'] + URLdone
        urlOpen = self.__url['balance'] + URLopen
        # self.log.debug("{url}", url=url)

        if coinPair:
            currencyPair = self.getSymbol(coinPair)
        else:
            currencyPair = ''

        prams = {
            'currencyPair': currencyPair,
        }

        body = self.getPostBodyStr(prams)
        header = self.getPostHeader(body)
        # self.log.debug("{header}", header=header)
        # self.log.debug("{prams}", prams=prams)

        dDone = post(reactor, urlDone, headers=header, body=body)
        dOpen = post(reactor, urlOpen, headers=header, body=body)

        d = defer.DeferredList([dDone, dOpen], consumeErrors=True)

        def handleBody(res):
            # self.log.debug("{res}", res=res)
            for state, err in res:
                if not state:
                    raise err

            (_, dataDone), (_, dataOpen) = res
            dataDone, dataOpen = json.loads(dataDone), json.loads(dataOpen)
            # self.log.debug("{dataDone}{dataOpen}", dataDone=dataDone, dataOpen=dataOpen)

            for data in [dataDone, dataOpen]:
                flag = data['result']
                if isinstance(flag, str):
                    flag = flag.upper() == 'TRUE'
                assert flag, f"{data.get('message', 'unknown error')}, ErrorCode: {data.get('code', 'unknown')}"

            orders = []
            for orderData in dataOpen['orders']:
                order = {
                    'orderId': orderData['orderNumber'],
                    'type': orderData['type'],
                    'initPrice': float(orderData['initialRate']),
                    'initAmount': float(orderData['initialAmount']),
                    'coinPair': tuple(orderData['currencyPair'].split('_')),
                    'status': 'open'
                }
                # self.log.debug("{order!s}", order=order)
                orders.append(order)
            for orderData in dataDone['trades']:
                order = {
                    'orderId': orderData['orderNumber'],
                    'type': orderData['type'],
                    'initPrice': float(orderData['rate']),
                    'initAmount': float(orderData['amount']),
                    'coinPair': tuple(orderData['pair'].split('_')),
                    'status': 'done'
                }
                # self.log.debug("{order!s}", order=order)
                orders.append(order)
            return orders

        d.addCallback(handleBody)
        d.addErrback(self.defaultErrhandler)

        return d