7. The Binance API and keeping your keys safe
Level 3: Market Data and APIs
Alongside ccxt, Binance offers its own official Python library, python-binance, with more direct access to functions specific to that particular exchange — useful when ccxt does not cover something Binance-specific that you need.
Using it takes four steps. First, create a Binance account. Second, generate an API key from your account's API management panel — that key (and its associated secret) is, in practice, a password that gives your code permission to trade on your behalf. Third, install the library:
pip install python-binanceAnd fourth — the step people skip most often, and the one that costs the most when something goes wrong — protect those keys properly. The correct approach is NOT to write them directly inside the code, nor to upload them to a GitHub repository, nor to share them through any channel that is not strictly private. If an API key with trading permissions leaks, anyone who finds it can trade on your real account.
The standard practice is to store them as operating system environment variables, outside the source code itself:
# in the terminal, before running your script (Windows):
# set BINANCE_API_KEY=your_key_here
# set BINANCE_API_SECRET=your_secret_here
# on macOS or Linux:
# export BINANCE_API_KEY="your_key_here"
# export BINANCE_API_SECRET="your_secret_here"
import os
from binance.client import Client
api_key = os.environ.get("BINANCE_API_KEY")
api_secret = os.environ.get("BINANCE_API_SECRET")
client = Client(api_key, api_secret, tld="us")With this, the code reads the keys from the environment at run time, but the code itself — the file you might share, push to a repository or show in a course — never contains a real key. It is exactly the same logic you should never break in any real project: code gets shared, secrets do not.
With the client connected, querying market information is straightforward:
depth = client.get_order_book(symbol="BNBBTC") # order book
prices = client.get_all_tickers() # current price of every pair
candles = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC")These three calls are read-only: they risk no capital, so they are a good starting point for getting familiar with the API before touching any function that places real orders.