Post an order on Binance using Python

Posted on Sat 19 December 2020 in tech

Tutorial: Post an order on Binance using Python

Binance Power Toys

First store your apikey in a file, json format, with key and secret.

Next, from Python, load the key file:

   with open(apikey.json') as keyfile:
        apikey = json.load(keyfile)

Format the order struct for the currency and characteristics you desire.

   order = {
         'symbol': 'BTCUSDT',
         'side': 'BUY',
         'type': 'LIMIT',
         'timeInForce': 'GTC',
         'price': 9000, # 😛
         'quantity': 0.01,
         'recvWindow': 5000
         }

Build the exchange request.

   def send(order, apikey, apiurl='https://testnet.binance.vision/api/v3/order'):


        timestamp = int(time.time()*1000)

        binance_request = {}

        binance_request.update(order)

        binance_request['timestamp'] = timestamp

Make a method to sign the hashed request.

    def sign(apikey, hash_block):
        secret = apikey['secret']

        decoded_secret = secret.encode('utf-8') # base64.b64decode(secret)

        return hmac.new(decoded_secret, hash_block, hashlib.sha256).hexdigest()

Its an interesting choice that binance uses the 'encoded' secret as the secret rather than the data it represents.

Build and sign the hash block

        post_param = urllib.parse.urlencode(binance_request)

        hash_block = post_param.encode('utf-8')

        api_signature = sign(apikey, hash_block)

Send the resource to binance.

        resource = apiurl

        post_data = post_param + '&' + ('signature=%s' % api_signature)

        apikey = self.apikey['key']

        api_request = urllib.request.Request(resource, data=post_data.encode('utf-8'))
        api_request.add_header('X-MBX-APIKEY', apikey)

        with urllib.request.urlopen(api_request, context=ssl.create_default_context(cafile=certifi.where())) as request_stream:
            return request_stream.read()

        raise RuntimeError("Request failed!")

Working example code is available Binance Power Toys