Untitled

 avatar
unknown
plain_text
2 years ago
1.9 kB
7
Indexable
import hmac
import time
import hashlib
import requests
from urllib.parse import urlencode


def dispatch_request(api_key, http_method):
    session = requests.Session()
    session.headers.update(
        {"Content-Type": "application/json;charset=utf-8", "X-MBX-APIKEY": api_key}
    )
    return {
        "GET": session.get,
        "DELETE": session.delete,
        "PUT": session.put,
        "POST": session.post,
    }.get(http_method, "GET")


def get_timestamp():
    return int(time.time() * 1000)


def hashing(api_secret, query_string):
    return hmac.new(
        api_secret.encode("utf-8"), query_string.encode("utf-8"), hashlib.  sha256
    ).hexdigest()


class requester:
    def __init__(self, api_key, api_secret):
        self.api_key = api_key
        self.api_secret = api_secret
        self.base_url = "https://api.binance.com"

    def send_signed_request(self, http_method, url_path, payload={}):
        query_string = urlencode(payload, True)
        if query_string:
            query_string = "{}&timestamp={}".format(query_string, get_timestamp())
        else:
            query_string = "timestamp={}".format(get_timestamp())

        url = (
                self.base_url + url_path + "?" + query_string + "&signature=" + hashing(self.api_secret,
                                                                                   query_string)
        )

        params = {"url": url, "params": {}}
        response = dispatch_request(self.api_key, http_method)(**params)
        return response.json()


    def send_public_request(self, url_path, payload={}):
        query_string = urlencode(payload, True)
        url = self.base_url + url_path
        if query_string:
            url = url + "?" + query_string
        #print("{}".format(url))
        response = dispatch_request(self.api_key, "GET")(url=url)
        return response.json()
Editor is loading...