How to Connect to Binance with Python
Python Trading Bot
Binance is one of the world’s largest crypto exchanges. They cover pretty much everything you could wish for — staking, trading, savings and so much more.
In a huge win for crypto trading bot developers, they also have an excellent API. The API is robust and has reasonable query limits (especially given it’s free).
If you’re looking to integrate Binance trading into your algorithmic trading bot, you’ll first need to connect to Binance. To do this in a reasonably secure manner, implement the following functions.
Get API Key and Secret Key
Connecting to Binance requires (at a minimum) an api_key
and secret_key
. Here’s how to do this:
- Log on to Binance
- Navigate to the person icon at top right and select API Management
- Choose Create API
- Go through the options and store your API Key and Secret Key somewhere safe (especially the Secret Key!)
- Edit the restrictions to include
Enable Spot & Margin Trading
- (Highly Recommended) update your IP restrictions to ‘Restrict access to trusted IPs only’. This option will limit any access to your API such that only the IPs you specify are allowed.
Here’s my referral link if you’d like to sign up :)
Save API Key and Secret Key
Once you have your keys, create a file called settings.json
. In this file, drop your api_key
and secret_key
so that they look like this:
"binance": {
"BinanceKeys": {
"API_Key": "Your API Key",
"Secret_Key": "Your Secret Key"
}
Create a Function to Retrieve API Keys
Next, create a function to retrieve the keys based on a filepath. Do this as follows:
import json
import os
# Function to import settings from settings.json
def get_project_settings(importFilepath):
# Test the filepath to sure it exists
if os.path.exists(importFilepath):
# Open the file
f = open(importFilepath, "r")
# Get the information from file
project_settings = json.load(f)
# Close the file
f.close()
# Return project settings to program
return project_settings
else:
return ImportError
Check Your Connection
Finally, you can check if your connection works using this simple function:
from binance.spot import Spot
# Function to query Binance account
def query_account(api_key, secret_key):
return Spot(key=api_key, secret=secret_key).account()
If you’re connected, the function will return a connection string.
Say Hi!
I love hearing from my readers, so feel free to reach out. It means a ton to me when you clap for my articles or drop a friendly comment — it helps me know that my content is helping.
❤