Connect to Binance API using Python
Do you want to run some trading strategies on the cryptocurrency market? Look no further! This post shows you how to connect to the Binance API using Python.
First thing that needs to be done is to log in to your Binance account https://www.binance.com/en
Under the account drop down, click on API Management. Create an API and note down your API Key and Secret Key.
To connect to Binance using your newly generated API keys, the ccxt library will be used: https://github.com/ccxt/ccxt
The ccxt library is a powerful library, which allows you to connect to multiple cryptocurrency exchanges including Binance, Coinbase and Coinbase Pro. The following code allows you to connect to your Binance account:
import ccxt
import configbinance_api_key = "*********"
binance_secret_key = "*******"exchange = ccxt.binance({
"apiKey": config.binance_api_key, "secret": config.binance_secret_key})balance = exchange.fetch_balance()print(balance)
The code above allows you to print the balance from your own account.
Looking at the documentation from the ccxt GitHub page, the call below allows us to get the price for a specific symbol.
exchange.fetch_ohlcv()
To store the prices in for a certain cryptocurrency symbol, the code below converts the output from a dictionary into a pandas dataframe. The example below is for the cryptocurrency pair BTC/USDT.
bars = exchange.fetch_ohlcv('BTC/USDT', timeframe='1m', limit=100)df = pd.DataFrame(bars[:-1], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')print(df.head())
Thank you for reading this post! If you liked this post, please follow me on Medium.
Link to my GitHub repository: https://github.com/Hishok
Connect with me on LinkedIn.