Ejemplo n.º 1
0
    def __call__(self, command, args={}):
        """ Main Api Function
        - encodes and sends <command> with optional [args] to Poloniex api
        - raises 'poloniex.PoloniexError' if an api key or secret is missing
            (and the command is 'private'), if the <command> is not valid, or
            if an error is returned from poloniex.com
        - returns decoded json api message """
        # get command type
        cmdType = self.checkCmd(command)

        # pass the command
        args['command'] = command
        payload = {}
        # add timeout
        payload['timeout'] = self.timeout

        # private?
        if cmdType == 'Private':
            payload['url'] = 'https://poloniex.com/tradingApi'

            # wait for coach
            if self.coach:
                self.coach.wait()

            # set nonce
            args['nonce'] = self.nonce

            # add args to payload
            payload['data'] = args

            # sign data with our Secret
            sign = _new(
                self.secret.encode('utf-8'),
                _urlencode(args).encode('utf-8'),
                _sha512)

            # add headers to payload
            payload['headers'] = {'Sign': sign.hexdigest(),
                                  'Key': self.key}

            # send the call
            ret = _post(**payload)

            # return data
            return self.handleReturned(ret.text)

        # public?
        if cmdType == 'Public':
            # encode url
            payload['url'] = 'https://poloniex.com/public?' + _urlencode(args)

            # wait for coach
            if self.coach:
                self.coach.wait()

            # send the call
            ret = _get(**payload)

            # return data
            return self.handleReturned(ret.text)
Ejemplo n.º 2
0
def private_order(command, args={}):
    global API_key, Secret

    err = True
    while err:
        try:
            args['command'] = command
            args['nonce'] = nonce()
            postData = _urlencode(args)

            sign = _new(Secret.encode('utf-8'), postData.encode('utf-8'),
                        _sha512)

            ret = _post('https://poloniex.com/tradingApi',
                        data=args,
                        headers={
                            'Sign': sign.hexdigest(),
                            'Key': API_key
                        })

            return _loads(ret.text, parse_float=str)
        except KeyboardInterrupt:
            exit()
        except Exception:
            print(ret)
            print("### ERROR INESPERADO TIPO:", sys.exc_info()[1])
            print('### ERROR AL EJECUTAR PRIVATE ORDER ' + command + ' ###')
            print('### ESPERANDO 30 SEGUNDOS ###')
            time.sleep(30)
Ejemplo n.º 3
0
    def unsubscribe(self, chan):
        """ Sends the 'unsubscribe' command for <chan> """
        if isinstance(chan, int):
            chan = self._getChannelName(str(chan))
        # account chan?
        if chan == 'account':
            # sending commands to 'account' requires a key, secret and nonce
            if not self.key or not self.secret:
                raise PoloniexError(
                    "self.key and self.secret needed for 'account' channel")
            self.channels[chan]['sub'] = False
            payload = {'nonce': self.nonce}
            payload_encoded = _urlencode(payload)
            sign = _new(self.secret.encode('utf-8'),
                        payload_encoded.encode('utf-8'), _sha512)

            self.socket.send(
                _dumps({
                    'command': 'unsubscribe',
                    'channel': self.channels[chan]['id'],
                    'sign': sign.hexdigest(),
                    'key': self.key,
                    'payload': payload_encoded
                }))
        else:
            self.channels[chan]['sub'] = False
            self.socket.send(
                _dumps({
                    'command': 'unsubscribe',
                    'channel': self.channels[chan]['id']
                }))
Ejemplo n.º 4
0
    def unsubscribe(self, chan):
        """ Sends the 'unsubscribe' command for <chan> """
        # account chan?
        if chan in ['1000', 1000]:
            # sending commands to 'account' requires a key, secret and nonce
            if not self.key or not self.secret:
                raise PoloniexError(
                    "self.key and self.secret needed for 'account' channel")
            payload = {'nonce': self.nonce}
            payload_encoded = _urlencode(payload)
            sign = _new(self.secret.encode('utf-8'),
                        payload_encoded.encode('utf-8'), _sha512)

            self.socket.send(
                _dumps({
                    'command': 'unsubscribe',
                    'channel': chan,
                    'sign': sign.hexdigest(),
                    'key': self.key,
                    'payload': payload_encoded
                }))
        else:
            self.socket.send(
                _dumps({
                    'command': 'unsubscribe',
                    'channel': chan
                }))
Ejemplo n.º 5
0
    def api(self, command, args={}):
        """
        returns 'False' if invalid command or if no APIKey or Secret is specified (if command is "private")
        returns {"error":"<error message>"} if API error
        """
        if command in PUBLIC_COMMANDS:
            url = 'https://poloniex.com/public?'
            args['command'] = command
            ret = urlopen(Request(url + urlencode(args)))
            return json.loads(ret.read().decode(encoding='UTF-8'))
        elif command in TRADING_COMMANDS:
            ####TODO: test if this works
            payload = {}
            payload['url'] = 'https://poloniex.com/tradingApi'
            args['command'] = command
            args['nonce'] = self.nonce
            # add args to payload
            payload['data'] = args

            # sign data with our Secret
            sign = _new(self.secret.encode('utf-8'),
                        urlencode(args).encode('utf-8'), sha512)

            # add headers to payload
            payload['headers'] = {'Sign': sign.hexdigest(), 'Key': self.key}
            print(payload)
            # send the call
            ret = post(**payload)
            print(ret)
            return json.loads(ret.read().decode(encoding='UTF-8'))
        else:
            return False
Ejemplo n.º 6
0
    def __call__(self, command, args={}):
        """ Main Api Function
        - encodes and sends <command> with optional [args] to Poloniex api
        - raises 'poloniex.PoloniexError' if an api key or secret is missing
            (and the command is 'private'), if the <command> is not valid, or
            if an error is returned from poloniex.com
        - returns decoded json api message """
        global PUBLIC_COMMANDS, PRIVATE_COMMANDS

        # check in with the coach
        if self.coach:
            self.coach.wait()

        # pass the command
        args['command'] = command

        # private?
        if command in PRIVATE_COMMANDS:
            # check for keys
            if not self.key or not self.secret:
                raise PoloniexError("An Api Key and Secret needed!")
            # set nonce
            args['nonce'] = self.nonce
            # encode arguments for url
            postData = _urlencode(args)
            # sign postData with our Secret
            sign = _new(self.secret.encode('utf-8'), postData.encode('utf-8'),
                        _sha512)
            # post request
            ret = _post('https://poloniex.com/tradingApi',
                        data=args,
                        headers={
                            'Sign': sign.hexdigest(),
                            'Key': self.key
                        },
                        timeout=self.timeout)
            # decode json
            return self.parseJson(ret.text)

        # public?
        elif command in PUBLIC_COMMANDS:
            ret = _get('https://poloniex.com/public?' + _urlencode(args),
                       timeout=self.timeout)
            # decode json
            return self.parseJson(ret.text)
        else:
            raise PoloniexError("Invalid Command!: %s" % command)
Ejemplo n.º 7
0
    def private_command(self, args, timeout=30):
        date = None
        for _ in range(timeout):
            args['nonce'] = int(time.time() * 10)
            sign = _new(self.api_secret.encode('utf-8'),
                        _urlencode(args).encode('utf-8'), _sha512)
            headers = {'Key': self.api_key, 'Sign': sign.hexdigest()}
            payload = {
                'url': 'https://poloniex.com/tradingApi',
                'headers': headers,
                'data': args
            }

            data = self.post_with_retry(payload)
            if 'error' in data:
                print(data)
                data = None
                time.sleep(1)
                continue
            else:
                break
        return data
Ejemplo n.º 8
0
    def __call__(self, command, args={}):
        """
        Main Api Function
        - encodes and sends <command> with optional [args] to Poloniex api
        - raises 'ValueError' if an api key or secret is missing
            (and the command is 'private'), or if the <command> is not valid
        - returns decoded json api message
        """
        global PUBLIC_COMMANDS, PRIVATE_COMMANDS

        # check in with the coach
        if self._coaching:
            self.apicoach.wait()

        # pass the command
        args['command'] = command

        # private?
        if command in PRIVATE_COMMANDS:
            # check for keys
            if not self.Key or not self.Secret:
                raise ValueError("A Key and Secret needed!")
            # set nonce
            args['nonce'] = self.nonce

            try:
                # encode arguments for url
                postData = _urlencode(args)
                # sign postData with our Secret
                sign = _new(
                        self.Secret.encode('utf-8'),
                        postData.encode('utf-8'),
                        _sha512)
                # post request
                ret = _post(
                        'https://poloniex.com/tradingApi',
                        data=args,
                        headers={
                            'Sign': sign.hexdigest(),
                            'Key': self.Key
                            },
                        timeout=self.timeout)
            except Exception as e:
                raise e
            finally:
                # increment nonce(no matter what)
                self.nonce += 1
            # return decoded json
            try:
                return _loads(ret.text, parse_float=unicode)
            except NameError:
                return _loads(ret.text, parse_float=str)

        # public?
        elif command in PUBLIC_COMMANDS:
            try:
                ret = _post(
                        'https://poloniex.com/public?' + _urlencode(args),
                        timeout=self.timeout)
            except Exception as e:
                raise e
            try:
                return _loads(ret.text, parse_float=unicode)
            except NameError:
                return _loads(ret.text, parse_float=str)
        else:
            raise ValueError("Invalid Command!")
Ejemplo n.º 9
0
    def __call__(self, command, args={}):
        """
        Main Api Function
        - encodes and sends <command> with optional [args] to Poloniex api
        - raises 'ValueError' if an api key or secret is missing
            (and the command is 'private'), or if the <command> is not valid
        - returns decoded json api message
        """
        global PUBLIC_COMMANDS, PRIVATE_COMMANDS

        # check in with the coach
        if self._coaching:
            self.apicoach.wait()

        # pass the command
        args['command'] = command

        # private?
        if command in PRIVATE_COMMANDS:
            # check for keys
            if not self.Key or not self.Secret:
                raise ValueError("A Key and Secret needed!")
            # set nonce
            args['nonce'] = self.nonce

            try:
                # encode arguments for url
                postData = _urlencode(args)
                # sign postData with our Secret
                sign = _new(
                        self.Secret.encode('utf-8'),
                        postData.encode('utf-8'),
                        _sha512)
                # post request
                ret = _post(
                        'https://poloniex.com/tradingApi',
                        data=args,
                        headers={
                            'Sign': sign.hexdigest(),
                            'Key': self.Key
                            },
                        timeout=self.timeout)
            except Exception as e:
                raise e
            finally:
                # increment nonce(no matter what)
                self.nonce += 1
            # return decoded json
            try:
                return _loads(ret.text, parse_float=unicode)
            except NameError:
                return _loads(ret.text, parse_float=str)

        # public?
        elif command in PUBLIC_COMMANDS:
            try:
                ret = _get(
                        'https://poloniex.com/public?' + _urlencode(args),
                        timeout=self.timeout)
            except Exception as e:
                raise e
            try:
                return _loads(ret.text, parse_float=unicode)
            except NameError:
                return _loads(ret.text, parse_float=str)
        else:
            raise ValueError("Invalid Command!")
Ejemplo n.º 10
0
    def __call__(self, group, command, args={}):
        """
        Queries Bittrex with given method and args
        - encodes and sends <command> with optional [args] to Poloniex api
        - raises 'bittrex.BittrexError' if an api key or secret is missing
            (and the command is 'private') or if the <command> is not valid
        - returns decoded json api message
        
        :param group: Param for queries classification in API
        :type command: str

        :param command: Query method for getting info
        :type command: str

        :param args: Extra options for query
        :type args: dict

        :return: JSON response from Bittrex
        :rtype : dict
        """

        from requests.exceptions import ReadTimeout, ConnectionError
        base_url = 'https://bittrex.com/Api/v2.0/'

        if command in PRIVATE_COMMANDS:
            if not self.api_key or not self.api_secret:
                raise BittrexError("Key and Secret needed!")
            url = base_url + 'key/{}/{}?'.format(group, command)

            args['nonce'] = self.nonce
            args['apikey'] = self.api_key
            url += _urlencode(args)

            if self.debug_endpoint == True:
                print(url)

            sign = _new(self.api_secret.encode('utf-8'), url.encode('utf-8'),
                        _sha512).hexdigest()
            # post request
            ret = _get(url, headers={'apisign': sign}, timeout=self.timeout)

            if ret.status_code != 200:
                raise BittrexError("Status Code: %s" % ret.status_code)

            jsonout = _loads(ret.text,
                             parse_float=self.parse_float,
                             parse_int=self.parse_int)
            return jsonout

        elif command in PUBLIC_COMMANDS:
            base_url += 'pub/{}/'.format(group)

            url = base_url + command + '?' + _urlencode(args)

            if self.debug_endpoint == True:
                print(url)

            ret = _get(url, timeout=self.timeout)

            if ret.status_code != 200:
                raise BittrexError("Status Code: %s" % ret.status_code)

            jsonout = _loads(ret.text,
                             parse_float=self.parse_float,
                             parse_int=self.parse_int)
            return jsonout
        else:
            raise BittrexError("Invalid Command: %s" % command)
Ejemplo n.º 11
0
    def __call__(self, command, args={}):
        """
        Main Api Function
        - encodes and sends <command> with optional [args] to Poloniex api
        - raises 'ValueError' if an api key or secret is missing
            (and the command is 'private'), or if the <command> is not valid
        - returns decoded json api message
        """
        global PUBLIC_COMMANDS, PRIVATE_COMMANDS

        # check in with the coach
        self.apicoach.wait()

        # pass the command
        args['command'] = command

        # private?
        if command in PRIVATE_COMMANDS:
            # check for keys
            if not self.Key or not self.Secret:
                raise ValueError("A Key and Secret needed!")
            # set nonce
            args['nonce'] = self.nonce

            try:
                # encode arguments for url
                postData = _urlencode(args)
                # sign postData with our Secret
                sign = _new(self.Secret.encode('utf-8'),
                            postData.encode('utf-8'), _sha512)
                # post request
                ret = _post('https://poloniex.com/tradingApi',
                            data=args,
                            headers={
                                'Sign': sign.hexdigest(),
                                'Key': self.Key
                            },
                            timeout=self.timeout)

            except Exception as e:
                raise e
            finally:
                pass
            # return decoded json
            try:
                text = ret.text
                if command not in self.nolog:
                    self.logger.debug("""
<{0}>
 <args>{1}</args>
 <RESULT>{2}</RESULT>
</{0}>
""".format(command, args, text, command))

                struct = _loads(text, parse_float=unicode)
                struct = self.retval_wrapper(struct)

                return struct
            except NameError:
                return _loads(text, parse_float=str)
            except:
                self.logger.debug("Unexpected error:", sys.exc_info()[0])
                self.logger.debug("<error>%s</error>", text)
                raise

        # public?
        elif command in PUBLIC_COMMANDS:
            try:
                args['nonce'] = self.nonce
                ret = _get('https://poloniex.com/public?' + _urlencode(args),
                           timeout=self.timeout)

            except Exception as e:
                raise e
            try:
                text = ret.text
                if command not in self.nolog:
                    self.logger.debug("""
<{0}>
 <args>{1}</args>
 <result>{2}</result>
</{0}>
                        """.format(command, args, text, command))

                struct = _loads(text, parse_float=unicode)
                struct = self.retval_wrapper(struct)

                return struct
            except NameError:
                return _loads(text, parse_float=str)
            except:
                self.logger.debug("Unexpected error:", sys.exc_info()[0])
                self.logger.debug("<error>%s</error>", text)
                raise
        else:
            raise ValueError("Invalid Command!")