The Easiest and Simplest use of BinanceApi for trades without any external library in Python

Gökhan ÇETİNKAYA
4 min readJul 4, 2021

The Binance API is a useful platform for people who are trying to make applications with automatic trading. If you want to make a trading bot for a Binance account with your specific algorithm, the API paves the way for this.

Yes, Binance API lets us make a trade with our algorithms written in python, java, or other languages but Its documentation is too hard to understand by a programmer who has no API experience. So I am hearing too much about this on the internet and in real life, I will try to let you make a trade with API in python in the easiest and simplest way.

We have an api_key and secret key. You can get it easily from binance.com.

We need to import;

import time # to make timestamp to compare our local time with Binance server time.import urllib # to communicate with Binance APIimport hmac # these two are for the hash out signature with 256.import hashlib # *import json # to get the specific object we want from the server’s responseAPI_KEY = "your_api_key"
SECRET_KEY = "your_secret_key"

First, we will try to get the prices of coins from the server. For this one, we don’t need to sign in (You already know from browsers or mobile applications). We can see the prices and also the orders for specific coins.

Let’s get prices;

def coinPrices():
requestURL = "https://api.binance.com/api/v3/ticker/price"

res = urllib.request.Request(requestURL, method="GET")

content = urllib.request.urlopen(res).read().decode("utf-8")

#you can use json or whatever you want to extract spesific objects from content -> example def wallet
print(content)

return content

I will explain the subjects you need to know to understand them very easily. We will use api.binance.api/v3 pattern for every task. ticker/price is the specific pattern to get the coin’s prices.

We will use urllib.request.Request method to connect the API and we give the method=”GET” to specify our aim. We just want to get some information from the API.

With urllib.request.urlopen(res), we create a channel with the res(we already connect above) and then with the channel we try to read the things that API says to us. But in this type of communication, we got the information in bytes. To make it string, we use .decode(“utf-8”).

We will use this template also in orderBook. We don’t need sign in the platform to see what’s going on there :D

def wallet(coinName):
bodyWallet = "recvWindow=7000&timestamp="+str(int(time.time()*1000))
requestURL = "https://api.binance.com/api/v3/account?"

requestURL += bodyWallet+"&signature="+encode(SECRET_KEY, bodyWallet)

res = urllib.request.Request(requestURL, method="GET")

res.add_header("X-MBX-APIKEY", API_KEY)
res.add_header("Content-Type", "application/x-www-form-urlencoded")

content = urllib.request.urlopen(res).read().decode("utf-8")

json_Wallet = json.loads(content)

for i in range(len(json_Wallet['balances'])):
if json_Wallet['balances'][i]['asset'] == coinName:
content = print(json_Wallet['balances'][i]['free'])
break

return content

What about the seeing our wallet? Like above we also have a request URL and it has /account now. But we will also have the bodyWallet string that has 2 parameters. If you remember I said it also in import time line. You can check from above! :D

&signature is the parameter,our key, to enter the API platform and introduce ourselves. To explain us to the server, we need to send bodyWallet(our system time and how much delay you want, I want 7 seconds differences with my time and server) and our secret key. The problem is the server doesn’t want to hear it native, but sha256.

def encode(secretKey, data):
return hmac.new(secretKey.encode("utf-8"), data.encode("utf-8"), hashlib.sha256).hexdigest()

To combine bodyWallet and secret key with making sha256, we will use encode function for it. You don’t need to know what’s happening there, you don’t need to change it whatever you do in this project.

At last, our requestURL is created now. We can connect to the API server like other functions we already did in coinPrices. But here we will add 2 parameters, it is solid for our Project, so I won’t talk about it too much to stay away from a mess.

We will create a channel like coinPrices, get information and change it to string. Now, we can see our all coins. To get the coin value we want we will use JSON to extract specific objects.

We will convert info to json_Wallet. Then with for loop, we will check the specific coin name.

def orderMarket( side, coinName, quantity): 
quan = ""
if side == "SELL":
quan = "quantity"
else:
quan = "quoteOrderQty"

bodyWallet = "symbol="+coinName+"USDT&side="+side+"&type=MARKET&"+quan+"="+quantity+"&recvWindow=7000&timestamp="+str(int(time.time()*1000))
requestURL = "https://api.binance.com/api/v3/order?"

requestURL += bodyWallet+"&signature="+encode(SECRET_KEY, bodyWallet)

res = urllib.request.Request(requestURL, method="POST")

res.add_header("X-MBX-APIKEY", API_KEY)
res.add_header("Content-Type", "application/x-www-form-urlencoded")

content = urllib.request.urlopen(res).read().decode("utf-8")

print(content)

return content

What about the trades? Trades are almost same as the wallet function we did above. The differences are trades are their own parameters to do their job. If you are already using, you know the market trade and their parameters or limit and their parameters. Nothing is complicated, when you look at the code you will get that part easily. We don’t need to talk about what is market or limit.

Another difference is when we give an order we need to use “POST” instead of “GET” for the method parameter. We want the give some information and try to make the server make our work so we need to post it!

With this knowledge, you can also understand the other functions when you take a look at them.

Have a good day!

whole code: mdmedicus/The-Simplest-BinanceApi-App-: The Easiest and Simplest use of BinanceApi for trades without any external library in Python (github.com)

mdmedicus

--

--

Gökhan ÇETİNKAYA

Lazy Doctor, Proffesional Java Desktop and Mobile Application Developer, Freelancer