In this comprehensive guide, we'll explore how to interact with Binance cryptocurrency exchange using Python and the powerful python-binance library. Whether you're looking to retrieve market data, manage your assets, or execute trades programmatically, this tutorial covers all essential aspects.
Getting Started with python-binance
The python-binance library is an unofficial Python wrapper for Binance's REST API v3. Binance remains one of the most popular cryptocurrency exchanges globally, offering both public and private APIs for developers.
Installation
pip install python-binanceThis command installs the necessary library to begin working with Binance's API.
Retrieving Exchange Information
The get_exchange_info function provides crucial details about the exchange, including rate limits and available trading pairs (symbols).
#!/usr/bin/python
import asyncio
from binance import AsyncClient
async def main():
client = await AsyncClient.create()
res = await client.get_exchange_info()
print(f'Number of symbols: {len(res["symbols"])}')
for sym in res['symbols']:
print(f"{sym['symbol']}: base {sym['baseAsset']}, quote {sym['quoteAsset']}")
await client.close_connection()
asyncio.run(main())Key points:
- Symbols represent trading pairs (e.g., BTCBUSD = Bitcoin vs. BUSD stablecoin)
- The response includes base and quote assets for each pair
- The API provides current information about all available markets
Accessing Market Data
Retrieving Ticker Information
Tickers provide real-time price information for specific cryptocurrency pairs:
#!/usr/bin/python
import asyncio
import json
from binance import AsyncClient
async def main():
client = await AsyncClient.create()
res = await client.get_ticker(symbol='LTCBUSD')
print(json.dumps(res, indent=2))
await client.close_connection()
asyncio.run(main())This returns comprehensive data including:
- Current price and price changes
- Trading volume
- High/low prices for the period
- Opening and closing prices
Managing Your Binance Account
Accessing Deposit Addresses
To receive cryptocurrency into your Binance account:
#!/usr/bin/python
import asyncio
import os
from binance import AsyncClient
async def main():
api_key = os.getenv('BINANCE_API_KEY')
api_secret = os.getenv('BINANCE_SECRET_KEY')
client = await AsyncClient.create(api_key, api_secret)
btc_address = await client.get_deposit_address(coin='BTC')
print(btc_address)
await client.close_connection()
asyncio.run(main())Important notes:
- Requires API keys for authentication
- Provides unique deposit addresses for each cryptocurrency
- Addresses are managed by Binance, not personally owned
Checking Asset Balances
Monitor your cryptocurrency holdings:
#!/usr/bin/python
import asyncio
import os
from binance import AsyncClient
async def main():
api_key = os.getenv('BINANCE_API_KEY')
api_secret = os.getenv('BINANCE_SECRET_KEY')
client = await AsyncClient.create(api_key, api_secret)
balance = await client.get_asset_balance(asset='LTC')
print(f"Asset: {balance['asset']}")
print(f"Available: {balance['free']}")
print(f"Locked: {balance['locked']}")
await client.close_connection()
asyncio.run(main())👉 For secure cryptocurrency trading, explore advanced exchange features
Trade Management
Viewing Trade History
Analyze your past trades for specific pairs:
#!/usr/bin/python
import asyncio
import os
from datetime import datetime
from binance import AsyncClient
from rich import box
from rich.console import Console
from rich.table import Table
async def main():
api_key = os.getenv('BINANCE_API_KEY')
api_secret = os.getenv('BINANCE_SECRET_KEY')
client = await AsyncClient.create(api_key, api_secret)
trades = await client.get_my_trades(symbol='SHIBBUSD')
# Create formatted table output
table = Table(title='Trade History', box=box.ASCII)
table.add_column('Time', justify='center')
table.add_column('Price', justify='right')
table.add_column('Quantity', justify='right')
table.add_column('Total Value', justify='right')
for trade in trades:
time = datetime.utcfromtimestamp(trade['time']/1000.0)
table.add_row(
f"{time:%Y-%m-%d %H:%M}",
f"{float(trade['price']):.8f}",
f"{float(trade['qty'])}",
f"{float(trade['quoteQty']):.8f}"
)
Console().print(table)
await client.close_connection()
asyncio.run(main())Managing Fiat Transactions
Track your fiat-to-crypto purchases:
#!/usr/bin/python
import asyncio
import os
from binance import AsyncClient
from binance.helpers import date_to_milliseconds
from datetime import datetime
from rich.console import Console
from rich.table import Table
async def main():
api_key = os.getenv('BINANCE_API_KEY')
api_secret = os.getenv('BINANCE_SECRET_KEY')
client = await AsyncClient.create(api_key, api_secret)
start = date_to_milliseconds('2023/01/01')
end = date_to_milliseconds('March 31, 2023')
payments = await client.get_fiat_payments_history(
transactionType=0, # 0 for buys
beginTime=start,
endTime=end
)
table = Table(title='Fiat Payments')
table.add_column('Date')
table.add_column('Fiat Amount')
table.add_column('Crypto Received')
for payment in payments['data']:
date = datetime.utcfromtimestamp(payment['createTime']/1000.0)
table.add_row(
f"{date:%Y-%m-%d}",
f"{payment['sourceAmount']} {payment['fiatCurrency']}",
f"{payment['obtainAmount']} {payment['cryptoCurrency']}"
)
Console().print(table)
await client.close_connection()
asyncio.run(main())👉 Discover more about cryptocurrency trading and APIs
FAQ Section
What is python-binance?
python-binance is an unofficial Python wrapper for Binance's REST API v3, allowing developers to interact programmatically with Binance's cryptocurrency exchange.
How do I get API keys for Binance?
API keys can be generated in your Binance account settings under the API Management section. Remember to keep your secret key secure and never share it publicly.
What's the difference between base and quote assets?
In a trading pair like BTC/USDT, BTC is the base asset (the cryptocurrency being bought/sold), while USDT is the quote asset (the currency used to price the base asset).
Can I trade automatically with python-binance?
Yes, python-binance supports all trading functionalities available through Binance's API, including market orders, limit orders, and more advanced trading options.
Is python-binance suitable for high-frequency trading?
While python-binance can be used for automated trading, Binance has strict rate limits. For high-frequency trading, consider using Binance's WebSocket API for real-time updates.
Conclusion
The python-binance library provides comprehensive access to Binance's cryptocurrency exchange through Python. From retrieving market data to executing trades and managing your portfolio, this guide has covered the essential functionality you need to automate your cryptocurrency operations.
For more advanced trading strategies and features, consider exploring additional resources and documentation. Always remember to implement proper risk management when trading cryptocurrencies programmatically.