ZetCode

Python Binance

last modified November 19, 2026 Python 3.15

In this article we show how to work with the Binance cryptocurrency exchange in Python using the python-binance library.

python-binance

Binance is one of the largest cryptocurrency exchanges. It offers a REST API and websocket streams. Market data (prices, order books, trades, candlesticks) is public; account data and trading are private and need an API key and secret.

python-binance is an unofficial Python wrapper for the Binance API. It has a synchronous Client and an asynchronous AsyncClient with the same methods. The responses are the JSON data from Binance converted to dictionaries and lists. The examples use python-binance 1.0.37. They query the live exchange, so the numbers in the outputs differ on every run.

$ pip install python-binance

Server time

The simplest calls check the connection to the exchange.

server_time.py
from datetime import datetime, UTC

from binance import Client

client = Client()

res = client.get_server_time()
print(res)

server = datetime.fromtimestamp(res['serverTime'] / 1000, UTC)
print(f'server time: {server:%Y-%m-%d %H:%M:%S} UTC')
print(client.ping())
client.close_connection()

Creating a Client without keys gives access to the public endpoints. The get_server_time method returns the server time in milliseconds since the epoch; Binance uses milliseconds for all timestamps. We convert it to an aware datetime in UTC. The ping method returns an empty dictionary when the server is reachable. The close_connection method closes the HTTP session.

$ python server_time.py
{'serverTime': 1795095074233}
server time: 2026-11-19 13:31:14 UTC
{}

Current price

The get_symbol_ticker method returns the latest price of a symbol. A symbol is a trading pair; in BTCUSDT, BTC is the base asset and USDT (a US dollar stablecoin) is the quote asset.

price.py
from decimal import Decimal

from binance import Client

client = Client()

res = client.get_symbol_ticker(symbol='BTCUSDT')
print(res)

price = Decimal(res['price'])
print(f'1 BTC = {price:,.2f} USDT')
print(f'100 USDT = {Decimal(100) / price:.8f} BTC')
client.close_connection()

Binance sends prices and quantities as strings with eight decimal places, so that no precision is lost. We convert them to Decimal rather than float, which is the safe choice for money. The price tells how many USDT one bitcoin costs; dividing gives the amount of BTC we get for 100 USDT.

$ python price.py
{'symbol': 'BTCUSDT', 'price': '63757.67000000'}
1 BTC = 63,757.67 USDT
100 USDT = 0.00156844 BTC

All prices

Without the symbol parameter, the ticker endpoint returns the prices of all symbols. python-binance has the get_all_tickers method for it.

all_prices.py
from decimal import Decimal

from binance import Client

client = Client()
prices = client.get_all_tickers()
print(f'{len(prices)} prices')

wanted = {'BTCUSDT', 'ETHUSDT', 'SOLUSDT', 'ETHBTC'}
for p in prices:
    if p['symbol'] in wanted:
        print(f"{p['symbol']:8} {Decimal(p['price']).normalize()}")

client.close_connection()

One request returns several thousand prices, so it is better than one request per symbol when we need many of them. We print four of them. The normalize method removes the trailing zeros. Note that ETHBTC is priced in bitcoin, not in dollars.

$ python all_prices.py
3753 prices
ETHBTC   0.02832
BTCUSDT  63762
ETHUSDT  1805.84
SOLUSDT  74.89

Exchange information

The get_exchange_info method returns the rate limits of the API and the list of all symbols with their properties.

symbols.py
from collections import Counter

from binance import Client

client = Client()
info = client.get_exchange_info()
symbols = info['symbols']

trading = [s for s in symbols if s['status'] == 'TRADING']
print(f'{len(symbols)} symbols, {len(trading)} trading')

quotes = Counter(s['quoteAsset'] for s in trading)
for asset, n in quotes.most_common(5):
    print(f'{asset:6} {n}')

eth = [s['symbol'] for s in trading if s['baseAsset'] == 'ETH']
print(sorted(eth))
client.close_connection()

The list also contains delisted symbols, so we keep only those with the TRADING status. A Counter shows the most common quote assets, and the last line lists all markets where ether is the base asset.

$ python symbols.py
3750 symbols, 1380 trading
USDT   525
TRY    310
USDC   255
U      48
USD1   31
['ETHARS', 'ETHBRL', 'ETHBTC', 'ETHEUR', 'ETHFDUSD', 'ETHIDR', 'ETHJPY', 'ETHMXN', 'ETHTHB', 'ETHTRY', 'ETHU', 'ETHUSD', 'ETHUSD1', 'ETHUSDC', 'ETHUSDS', 'ETHUSDT']

Trading rules

Each symbol has filters that an order must satisfy. The get_symbol_info method returns the information about one symbol.

symbol_rules.py
from binance import Client

client = Client()
info = client.get_symbol_info('BTCUSDT')

print(info['baseAsset'], info['quoteAsset'], info['status'])
print(info['orderTypes'])

filters = {f['filterType']: f for f in info['filters']}
print('tick size:', filters['PRICE_FILTER']['tickSize'])
print('step size:', filters['LOT_SIZE']['stepSize'])
print('min qty:  ', filters['LOT_SIZE']['minQty'])
print('min order:', filters['NOTIONAL']['minNotional'], info['quoteAsset'])
client.close_connection()

We turn the list of filters into a dictionary keyed by the filter type. The PRICE_FILTER gives the tick size, the smallest price step. The LOT_SIZE filter gives the step and the minimum of the quantity, and the NOTIONAL filter the minimum value of an order in the quote asset. An order that breaks a filter is rejected by the exchange.

$ python symbol_rules.py
BTC USDT TRADING
['LIMIT', 'LIMIT_MAKER', 'MARKET', 'STOP_LOSS', 'STOP_LOSS_LIMIT', 'TAKE_PROFIT', 'TAKE_PROFIT_LIMIT']
tick size: 0.01000000
step size: 0.00001000
min qty:   0.00001000
min order: 5.00000000 USDT

24-hour statistics

The get_ticker method returns statistics for a rolling 24-hour window.

ticker_24h.py
from decimal import Decimal

from binance import Client

client = Client()
t = client.get_ticker(symbol='ETHUSDT')

print(sorted(t))
print()

d = {k: Decimal(t[k]) for k in ('lastPrice', 'openPrice', 'highPrice',
                                 'lowPrice', 'priceChangePercent', 'quoteVolume')}
print(f"last:   {d['lastPrice']:>12,.2f}")
print(f"open:   {d['openPrice']:>12,.2f}")
print(f"high:   {d['highPrice']:>12,.2f}")
print(f"low:    {d['lowPrice']:>12,.2f}")
print(f"change: {d['priceChangePercent']:>+11.2f} %")
print(f"volume: {d['quoteVolume'] / 1_000_000:>12,.1f} M USDT")
print(f"trades: {t['count']:>12,}")
client.close_connection()

First we print the keys of the response. Then we convert the interesting values to Decimal and print them aligned. The quoteVolume is the traded volume in USDT, and count, the number of trades, is already an integer.

$ python ticker_24h.py
['askPrice', 'askQty', 'bidPrice', 'bidQty', 'closeTime', 'count', 'firstId', 'highPrice', 'lastId', 'lastPrice', 'lastQty', 'lowPrice', 'openPrice', 'openTime', 'prevClosePrice', 'priceChange', 'priceChangePercent', 'quoteVolume', 'symbol', 'volume', 'weightedAvgPrice']

last:       1,806.01
open:       1,794.79
high:       1,813.59
low:        1,732.83
change:       +0.62 %
volume:        555.2 M USDT
trades:    2,351,864

Order book

The order book lists the open buy orders (bids) and sell orders (asks). The get_order_book method returns the best price levels.

order_book.py
from decimal import Decimal

from binance import Client

client = Client()
book = client.get_order_book(symbol='BTCUSDT', limit=5)

print('     price        qty   (asks)')
for price, qty in reversed(book['asks']):
    print(f'{Decimal(price):>10.2f} {Decimal(qty):>10.5f}')
print('-' * 22)
for price, qty in book['bids']:
    print(f'{Decimal(price):>10.2f} {Decimal(qty):>10.5f}')
print('     price        qty   (bids)')

best_bid = Decimal(book['bids'][0][0])
best_ask = Decimal(book['asks'][0][0])
print(f'spread: {best_ask - best_bid:.2f} USDT')
client.close_connection()

Each level is a pair of price and quantity strings. Asks are sorted from the lowest price and bids from the highest, so we reverse the asks to print the book as a ladder with the best prices in the middle. The difference between the best ask and the best bid is the spread; for a liquid market like BTCUSDT, it is usually one tick.

$ python order_book.py
     price        qty   (asks)
  63776.93    0.00012
  63776.50    0.01902
  63776.16    0.00009
  63776.02    0.00600
  63776.01    2.23989
----------------------
  63776.00    0.35708
  63775.66    0.00018
  63775.65    0.39242
  63775.53    0.15547
  63775.31    0.00008
     price        qty   (bids)
spread: 0.01 USDT

Recent trades

The get_recent_trades method returns the latest executed trades of a symbol.

recent_trades.py
from datetime import datetime, UTC
from decimal import Decimal

from binance import Client

client = Client()
trades = client.get_recent_trades(symbol='BTCUSDT', limit=8)

for t in trades:
    when = datetime.fromtimestamp(t['time'] / 1000, UTC)
    side = 'sell' if t['isBuyerMaker'] else 'buy'
    stamp = when.strftime('%H:%M:%S.%f')[:-3]
    qty, price = Decimal(t['qty']), Decimal(t['price'])
    print(f'{stamp} {side:4} {qty:.5f} BTC at {price:.2f}')

client.close_connection()

The isBuyerMaker field tells which side was waiting in the book. If the buyer was the maker, the trade was triggered by a seller, so we label it as a sell. We format the trade time with milliseconds by cutting the last three digits of the microseconds.

$ python recent_trades.py
13:31:22.345 sell 0.02300 BTC at 63774.97
13:31:22.345 sell 0.01300 BTC at 63774.97
13:31:22.346 sell 0.01300 BTC at 63774.97
13:31:22.365 sell 0.01300 BTC at 63774.97
13:31:22.365 sell 0.01300 BTC at 63774.97
13:31:22.365 sell 0.02300 BTC at 63774.97
13:31:22.365 sell 0.01300 BTC at 63774.97
13:31:22.367 sell 0.00011 BTC at 63774.97

Candlesticks

Candlesticks, also called klines, summarize trading in fixed intervals: the open, high, low, and close price and the volume. They are returned by the get_klines method.

klines.py
from datetime import datetime, UTC
from decimal import Decimal

from binance import Client

client = Client()
klines = client.get_klines(symbol='BTCUSDT',
                           interval=Client.KLINE_INTERVAL_1DAY, limit=7)

print(f"{'date':10} {'open':>10} {'high':>10} {'low':>10} {'close':>10} {'volume':>10}")
for k in klines:
    day = datetime.fromtimestamp(k[0] / 1000, UTC).date()
    o, h, l, c, v = (Decimal(x) for x in k[1:6])
    print(f'{day} {o:>10.2f} {h:>10.2f} {l:>10.2f} {c:>10.2f} {v:>10.1f}')

client.close_connection()

Each kline is a list; the first item is the open time in milliseconds and the next five are the open, high, low, close, and volume. The interval is given by a constant such as KLINE_INTERVAL_1DAY (the string '1d'). The last candle is the current day, which is not closed yet.

$ python klines.py
date             open       high        low      close     volume
2026-11-13   71460.00   71514.01   67568.00   68314.00    29648.8
2026-11-14   68314.01   68446.21   63320.00   64150.00    32674.8
2026-11-15   64150.01   66132.01   62006.00   65351.05    29231.2
2026-11-16   65351.05   65696.16   63905.01   64882.87    21929.2
2026-11-17   64882.88   65447.00   63336.00   64947.35    28316.8
2026-11-18   64947.36   65002.00   62062.97   63068.22    18699.7
2026-11-19   63068.21   64080.80   62388.72   63774.98     8444.7

Historical data

One klines request returns at most 1000 candles. The get_historical_klines method takes a date range, makes as many requests as needed, and joins the results.

historical.py
from datetime import datetime, UTC
from decimal import Decimal

from binance import Client

client = Client()
klines = client.get_historical_klines('ETHUSDT', Client.KLINE_INTERVAL_1DAY,
                                      '2026-01-01', '2026-11-01')
print(f'{len(klines)} daily candles')

closes = [(datetime.fromtimestamp(k[0] / 1000, UTC).date(), Decimal(k[4]))
          for k in klines]

low = min(closes, key=lambda c: c[1])
high = max(closes, key=lambda c: c[1])
print(f'first close:   {closes[0][0]} {closes[0][1]:.2f}')
print(f'lowest close:  {low[0]} {low[1]:.2f}')
print(f'highest close: {high[0]} {high[1]:.2f}')
print(f'last close:    {closes[-1][0]} {closes[-1][1]:.2f}')
client.close_connection()

We download the daily candles of ETHUSDT from January 1 to November 1, 2026, both days included. The start and end may also be given in a relative form such as '1 week ago UTC'. Since the range lies in the past, the output of this example does not change.

$ python historical.py
305 daily candles
first close:   2026-01-01 3004.19
lowest close:  2026-06-25 1567.84
highest close: 2026-01-14 3354.92
last close:    2026-11-01 2275.31

Errors

When Binance rejects a request, python-binance raises BinanceAPIException. It carries the HTTP status code and the Binance error code and message.

api_errors.py
from binance import Client
from binance.exceptions import BinanceAPIException

client = Client()

requests = [
    ('get_symbol_ticker', {'symbol': 'BTCEUR'}),
    ('get_symbol_ticker', {'symbol': 'BTCXYZ'}),
    ('get_order_book', {'symbol': 'BTCUSDT', 'limit': 0}),
    ('get_klines', {'symbol': 'BTCUSDT', 'interval': '2d'}),
]

for name, params in requests:
    try:
        res = getattr(client, name)(**params)
        print('ok:', res)
    except BinanceAPIException as e:
        print(f'{e.status_code} code={e.code}: {e.message}')

client.close_connection()

The first request is valid. The other three fail with an unknown symbol, an invalid limit, and an invalid interval. The error codes are documented in the Binance API documentation. Network problems raise exceptions of the underlying HTTP library instead, and exceeding the rate limits gives HTTP status 429.

$ python api_errors.py
ok: {'symbol': 'BTCEUR', 'price': '57927.79000000'}
400 code=-1121: Invalid symbol.
400 code=-1102: Mandatory parameter 'limit' was not sent, was empty/null, or malformed.
400 code=-1120: Invalid interval.

Asynchronous client

The AsyncClient has the same methods as Client, but they are coroutines. With asyncio.gather, several requests run concurrently.

async_prices.py
import asyncio
from decimal import Decimal

from binance import AsyncClient

SYMBOLS = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT', 'SOLUSDT', 'XRPUSDT']

async def main():
    client = await AsyncClient.create()
    try:
        tasks = [client.get_ticker(symbol=s) for s in SYMBOLS]
        tickers = await asyncio.gather(*tasks)
    finally:
        await client.close_connection()

    for t in tickers:
        last = Decimal(t['lastPrice'])
        change = Decimal(t['priceChangePercent'])
        print(f"{t['symbol']:8} {last:>12,.4f} {change:>+7.2f} %")

asyncio.run(main())

An AsyncClient is created with the create coroutine. We start five ticker requests at once and wait for all of them; gather returns the results in the order of the tasks. The finally clause closes the session even when a request fails.

$ python async_prices.py
BTCUSDT   63,772.0000   -0.55 %
ETHUSDT    1,806.0700   +0.58 %
BNBUSDT      592.6600   +0.50 %
SOLUSDT       74.9000   +0.88 %
XRPUSDT        0.9898   +0.41 %

Websocket streams

Polling the REST API is not the right way to follow the market in real time. Binance pushes trades, tickers, and order book updates through websocket streams; python-binance reads them with BinanceSocketManager.

trade_stream.py
import asyncio
from datetime import datetime, UTC
from decimal import Decimal

from binance import AsyncClient, BinanceSocketManager

async def main():
    client = await AsyncClient.create()
    manager = BinanceSocketManager(client)

    async with manager.trade_socket('BTCUSDT') as stream:
        for _ in range(6):
            msg = await stream.recv()
            when = datetime.fromtimestamp(msg['T'] / 1000, UTC)
            side = 'sell' if msg['m'] else 'buy'
            print(f"{when:%H:%M:%S} {msg['s']} {side:4} "
                  f"{Decimal(msg['q']):.5f} at {Decimal(msg['p']):.2f}")

    await client.close_connection()

asyncio.run(main())

The trade_socket method opens the trade stream of a symbol. In the async with block, each recv call waits for the next message. Stream messages use short keys: T is the trade time, p the price, q the quantity, and m whether the buyer was the maker. We stop after six trades.

$ python trade_stream.py
13:31:31 BTCUSDT buy  0.00009 at 63772.01
13:31:31 BTCUSDT buy  0.00010 at 63772.01
13:31:31 BTCUSDT buy  0.10000 at 63772.01
13:31:31 BTCUSDT buy  0.00629 at 63772.01
13:31:31 BTCUSDT buy  0.00010 at 63772.01
13:31:31 BTCUSDT buy  0.00009 at 63772.01

Account data

Private endpoints need an API key and secret, which are created in the account settings on Binance. For experiments, use the spot test network at testnet.binance.vision, which has its own keys and test funds.

account.py
import os
import sys
from decimal import Decimal

from binance import Client
from binance.exceptions import BinanceAPIException

api_key = os.environ.get('BINANCE_API_KEY')
api_secret = os.environ.get('BINANCE_API_SECRET')
if not api_key or not api_secret:
    sys.exit('set BINANCE_API_KEY and BINANCE_API_SECRET')

client = Client(api_key, api_secret, testnet=True)

try:
    account = client.get_account()
except BinanceAPIException as e:
    sys.exit(f'error {e.code}: {e.message}')
finally:
    client.close_connection()

for b in account['balances']:
    total = Decimal(b['free']) + Decimal(b['locked'])
    if total:
        print(f"{b['asset']:6} {total.normalize()}")

Keys must never be written into the source code; we read them from environment variables. With testnet=True, the client talks to the test network. The get_account method returns the balances of all assets, and we print those that are not zero; locked is the amount held by open orders. Here the variables are not set, so the program stops. With invalid keys, Binance answers with error -2014, "API-key format invalid". Calling a private method on a client without keys fails in python-binance itself, before any request is sent.

$ python account.py
set BINANCE_API_KEY and BINANCE_API_SECRET

Moving average crossover

The last program combines candlesticks with a simple analysis. A simple moving average (SMA) is the mean of the last n closing prices. When the short average crosses above the long one, it is called a golden cross; when it crosses below, a death cross.

moving_average.py
from datetime import datetime, UTC
from decimal import Decimal
from statistics import fmean

from binance import Client

SHORT, LONG = 7, 25

client = Client()
klines = client.get_klines(symbol='BTCUSDT',
                           interval=Client.KLINE_INTERVAL_1DAY, limit=90)
client.close_connection()

days = [datetime.fromtimestamp(k[0] / 1000, UTC).date() for k in klines]
closes = [float(Decimal(k[4])) for k in klines]

def sma(values, n, i):
    return fmean(values[i - n + 1:i + 1])

prev = None
for i in range(LONG - 1, len(closes)):
    above = sma(closes, SHORT, i) > sma(closes, LONG, i)
    if prev is not None and above != prev:
        kind = 'golden cross (up)' if above else 'death cross (down)'
        print(f'{days[i]} {kind:20} close {closes[i]:,.2f}')
    prev = above

i = len(closes) - 1
print(f'today: SMA{SHORT} {sma(closes, SHORT, i):,.2f}, '
      f'SMA{LONG} {sma(closes, LONG, i):,.2f}')

We download 90 daily candles and compute the 7-day and 25-day averages for every day that has enough history. The sma function averages a slice of the closing prices with statistics.fmean; for analysis, floats are good enough. Whenever the relation of the two averages changes, we print the day and the kind of cross. This is an illustration of working with the data, not trading advice.

$ python moving_average.py
2026-09-20 golden cross (up)    close 81,178.00
2026-10-12 death cross (down)   close 81,850.00
today: SMA7 64,928.50, SMA25 73,610.58

Source

python-binance documentation

Binance Spot API documentation

In this article we have worked with the Binance API in Python. See also Python ccxt, which supports many exchanges with one API, Python asyncio, and Python Decimal.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.