Skip to content Skip to sidebar Skip to footer

Issues Placing A Trade With Binance Api Using Python

I am trying to place a trade on the US version of Binance API without the use of external libraries. I can successfully get prices and display my account balance using GET requests

Solution 1:

The problem was with the following lines:

# Encode params into url
url = 'https://api.binance.us/api/v3/order/test?' + urllib.parse.urlencode(params)

# Add signature to url
url += f'&signature={signature}'

Apparently, when using urllib GET request payloads have to be encoded into the url itself, however POST requests require you to pass them into into the data parameter:

data = urllib.parse.urlencode(params).encode('ascii')
req = urllib.request.Request(url, data=data, headers=headers)

In my question, I was passing my payload through the url AND the data parameter. Removing the url payload fixes the issue. Side note for anyone stumbling upon this, putting a question mark ? after the url is optional for POST requests but not GET requests when using urllib

Working code to post a trade without external libraries:

import json
import time
import hmac
import hashlib
import settings
import urllib.parse
import urllib.request

params = {
        'symbol': 'BTCUSD',
        'side': 'BUY',
        'type': 'MARKET',
        'quantity': 1,
        'timestamp': int(time.time() * 1000)
}

secret = bytes(settings.SECRET_KEY.encode('utf-8'))
signature = hmac.new(secret, urllib.parse.urlencode(params).encode('utf-8'), hashlib.sha256).hexdigest()

params['signature'] = signature

url = 'https://api.binance.us/api/v3/order/test'
headers = {'X-MBX-APIKEY': settings.API_KEY}

data = urllib.parse.urlencode(params).encode('ascii')
req = urllib.request.Request(url, data=data, headers=headers)

response = urllib.request.urlopen(req)
response_str = response.read().decode('utf-8')
response_json = json.loads(response_str)

print(response_json)

Post a Comment for "Issues Placing A Trade With Binance Api Using Python"