예제 #1
0
    def authenticate(self, key=None, secret=None, key_file=None):
        """Authenticate a user.
        :param key:        User's public key.
        :param secret:     User's private key.
        :param key_file:   A ke file with public and private keys.
        :return True if authentication was successful
        If key file is provided, it will override values provided via key and secret
        """
        self._key = key
        self._secret = secret
        self._keyFile = key_file

        self.logger.info('Authenticating ...')
        rest_client = BinanceRESTClient(key=key,
                                        secret=secret,
                                        key_file=key_file)
        ret = rest_client.create_listen_key()
        try:
            self._listenKey = ret['listenKey']
            self.logger.info('Authentication successful')
        except:
            self.logger.info('Authentication failed')
            return False

        # get a snapshot of open orders
        open_orders = rest_client.open_orders()
        if open_orders is not None:
            for order in open_orders:
                order_id = int(order['orderId'])
                timestamp = int(order['timestamp'])
                symbol = order['symbol']
                order_type = order['type']
                side = order['side']
                price = float(order['price'])
                amount = float(order['amount'])
                filled = float(order['filled'])
                total = price * amount
                percent_filled = '{:.2f}'.format(100 * filled / amount)

                self._orders.append([
                    order_id, timestamp, symbol, order_type, side, price,
                    amount, percent_filled, total
                ])

        # get a snapshot of balances
        self._balances = rest_client.balance()
        if self._balances is None:
            self._balances = {}

        self._subscribe(self._listenKey)

        self.authenticated = True
        return True
def demo_binance_authenticated_api(file_path):
    """Runs a demo of Binance authenticated endpoints.
    :param file_path    the full path to the key file
    For a set of Binance authenticated endpoints, signs and sends a request using the REST client
    and the provided key_file and prints the formatted result in the console
    NOTE: the key file must be provided in the exchanges/api_keys folder with the name binance.key

    Endpoints tested:
        server_time
        balance
        user_trades
        place_limit_order
        order
        open_orders
        open_orders_for
        all_orders
        all_orders_since
        cancel_order
    """
    # 1. Make sure to update the key file before running this demo
    # 2. Set the prices so that they do not get filled (i.e. buy price bellow current price)
    try:
        binance = BinanceRESTClient(key_file=file_path)
        assert binance.authenticated

        print('=' * 100)
        print('   TESTING Binance authenticated endpoints')
        print('=' * 100)
        print()

        print()
        print('SERVER TIME\n' + '-' * 30)
        print(binance.server_time())
        print()
        print('BALANCES\n' + '-' * 30)
        print(binance.balance()['BTC'])
        print()
        print('MY TRADES\n' + '-' * 30)
        print(binance.user_trades('BNBBTC', limit=10))

        print()
        print('PLACE LIMIT ORDER\n' + '-' * 30)
        order1 = binance.place_limit_order('buy', 'bnbbtc', 1, 0.0010655)
        print(order1)
        print()
        print('PLACE LIMIT ORDER\n' + '-' * 30)
        order2 = binance.place_limit_order('buy', 'trxbtc', 1000, 0.00000085)
        print(order2)
        print()
        print('PLACE LIMIT ORDER\n' + '-' * 30)
        order3 = binance.place_limit_order('buy', 'bnbbtc', 1, 0.00113)
        print(order3)

        print()
        print('GET A SINGLE ORDER STATUS\n' + '-' * 30)
        res = binance.order(order1['orderId'], 'BNBBTC')
        for r in res.items():
            print(r)
        print()
        print('GET ALL OPEN ORDERS\n' + '-' * 30)
        res = binance.open_orders()
        for r in res:
            print(r)
        print()
        print('GET ALL OPEN ORDERS FOR A SYMBOL\n' + '-' * 30)
        res = binance.open_orders_for(order1['symbol'])
        for r in res:
            print(r)
        print()
        print('GET ALL ORDERS FOR A SYMBOL\n' + '-' * 30)
        res = binance.all_orders(order1['symbol'], limit=10)
        for r in res:
            print(r)
        print()
        print('GET ALL ORDERS STARTING FROM THE FIRST ORDER\n' + '-' * 30)
        res = binance.all_orders_since(order1['symbol'], order1['orderId'])
        for r in res:
            print(r)

        print()
        print('CANCEL ORDER\n' + '-' * 30)
        print(binance.cancel_order(order1['orderId'], order1['symbol']))
        print()
        print('CANCEL ORDER\n' + '-' * 30)
        print(binance.cancel_order(order2['orderId'], order2['symbol']))
        print()
        print('CANCEL ORDER\n' + '-' * 30)
        print(binance.cancel_order(order3['orderId'], order3['symbol']))
    except ExchangeException as e:
        print(e)
        print(''.join(traceback.format_exc()))