Exemplo 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)
Exemplo n.º 2
0
def _request_ocsp(cert, issuer, uri):
    # https://cryptography.io/en/latest/x509/ocsp/#creating-requests
    builder = _OCSPRequestBuilder()
    # add_certificate returns a new instance
    builder = builder.add_certificate(cert, issuer, _SHA1())
    ocsp_request = builder.build()
    try:
        response = _post(uri,
                         data=ocsp_request.public_bytes(_Encoding.DER),
                         headers={'Content-Type': 'application/ocsp-request'},
                         timeout=5)
    except _RequestException:
        _LOGGER.debug("HTTP request failed")
        return None
    if response.status_code != 200:
        _LOGGER.debug("HTTP request returned %d", response.status_code)
        return None
    ocsp_response = _load_der_ocsp_response(response.content)
    _LOGGER.debug("OCSP response status: %r", ocsp_response.response_status)
    if ocsp_response.response_status != _OCSPResponseStatus.SUCCESSFUL:
        return None
    # RFC6960, Section 3.2, Number 1. Only relevant if we need to
    # talk to the responder directly.
    # Accessing response.serial_number raises if response status is not
    # SUCCESSFUL.
    if ocsp_response.serial_number != ocsp_request.serial_number:
        _LOGGER.debug("Response serial number does not match request")
        return None
    return ocsp_response
Exemplo n.º 3
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)
Exemplo n.º 4
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)
Exemplo n.º 5
0
    def action(self, command=None, body=None, year=None):
        if not self.user or not self.passwd:
            raise FikenError("Username and Password needed!")
        if command in RELS:
            url = self.base_rel + self.company_Slug + '/' + command

            if year:
                url = url + '/' + year

            if self.debug_endpoint:
                print("Current url is: {}".format(url))
                print("Current body is:")
                print(body)

            if body:
                header = {
                    "Content-Type": "application/json",
                    "Accept": "application/hal+json"
                }

                ret = _post(url=url,
                            data=body,
                            headers=header,
                            auth=HTTPBasicAuth(self.user, self.passwd),
                            timeout=self.timeout)
            else:
                ret = _get(url,
                           auth=HTTPBasicAuth(self.user, self.passwd),
                           timeout=self.timeout)

            if ret.status_code != 201:
                print(ret.content)
                raise FikenError(ret.status_code)

            if body:
                headers = ret.headers
                return headers
            else:
                self.json_out = _loads(ret.text,
                                       parse_float=self.parse_float,
                                       parse_int=self.parse_int)
                return self.json_out
        else:
            raise FikenError("Invalid command")
def _get_ocsp_response(cert, issuer, uri, ocsp_response_cache):
    ocsp_request = _build_ocsp_request(cert, issuer)
    try:
        ocsp_response = ocsp_response_cache[ocsp_request]
        _LOGGER.debug("Using cached OCSP response.")
    except KeyError:
        try:
            response = _post(
                uri,
                data=ocsp_request.public_bytes(_Encoding.DER),
                headers={"Content-Type": "application/ocsp-request"},
                timeout=5,
            )
        except _RequestException as exc:
            _LOGGER.debug("HTTP request failed: %s", exc)
            return None
        if response.status_code != 200:
            _LOGGER.debug("HTTP request returned %d", response.status_code)
            return None
        ocsp_response = _load_der_ocsp_response(response.content)
        _LOGGER.debug("OCSP response status: %r",
                      ocsp_response.response_status)
        if ocsp_response.response_status != _OCSPResponseStatus.SUCCESSFUL:
            return None
        # RFC6960, Section 3.2, Number 1. Only relevant if we need to
        # talk to the responder directly.
        # Accessing response.serial_number raises if response status is not
        # SUCCESSFUL.
        if ocsp_response.serial_number != ocsp_request.serial_number:
            _LOGGER.debug("Response serial number does not match request")
            return None
        if not _verify_response(issuer, ocsp_response):
            # The response failed verification.
            return None
        _LOGGER.debug("Caching OCSP response.")
        ocsp_response_cache[ocsp_request] = ocsp_response

    return ocsp_response
 def marketTradeHist(self, pair, start=False, end=time()):
     """
     Returns public trade history for <pair>
     starting at <start> and ending at [end=time()]
     """
     if self._coaching:
         self.apicoach.wait()
     if not start:
         start = time()-self.HOUR
     try:
         ret = _post(
                 'https://poloniex.com/public?'+_urlencode({
                     'command': 'returnTradeHistory',
                     'currencyPair': str(pair).upper(),
                     'start': str(start),
                     'end': str(end)
                     }),
                 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)
    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!")
Exemplo 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!")
Exemplo n.º 10
0
def send_message(message):
    """Send a message to the #calls channel in the ML discord."""
    _post(_DISCORD_WEBHOOK_URL, json={"content": message})
Exemplo n.º 11
0
 def post(url, slug=None, related_objects=None, **kwargs):
     return _post(url, **kwargs)
Exemplo n.º 12
0
def post(url, **kwargs):
    return _post(url, **_add_request_id(kwargs))
Exemplo n.º 13
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!")
 def post(url, slug=None, related_objects=None, **kwargs):
     return _post(url, **kwargs)
Exemplo n.º 15
0
def notify(message):
    """Notify people via Discord about the given message."""
    _post(_DISCORD_WEBHOOK_URL, json={"content": message})
def post(url, payload, *a, **kw):
    return _post(url,
                 *a,
                 json=payload,
                 auth=HTTPDigestAuth(USERNAME, PASSWORD),
                 **kw)