Skip to main content

Kết nối Python với API Binance để lấy dữ liệu realtime

· 4 min read
admin

Binance là một trong những sàn giao dịch tiền điện tử lớn nhất thế giới, cung cấp API mạnh mẽ cho phép các nhà phát triển xây dựng các ứng dụng giao dịch tự động. Bài viết này sẽ hướng dẫn bạn cách kết nối Python với API Binance để lấy dữ liệu realtime và thực hiện các giao dịch.

Kết nối Python với API Binance

1. Cài đặt thư viện cần thiết

Đầu tiên, chúng ta cần cài đặt thư viện python-binance:

pip install python-binance

2. Tạo API Key và Secret Key

  1. Đăng nhập vào tài khoản Binance
  2. Vào phần API Management
  3. Tạo API Key mới
  4. Lưu lại API Key và Secret Key

3. Kết nối với API Binance

from binance.client import Client
from binance.enums import *

# Khởi tạo client
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_API_SECRET'
client = Client(api_key, api_secret)

# Kiểm tra kết nối
print(client.get_system_status())

4. Lấy dữ liệu thị trường

4.1. Lấy giá hiện tại

# Lấy giá hiện tại của BTC/USDT
btc_price = client.get_symbol_ticker(symbol="BTCUSDT")
print(f"Giá BTC/USDT: {btc_price['price']}")

REST API - Lấy dữ liệu lịch sử

4.2. Lấy dữ liệu lịch sử

# Lấy dữ liệu kline/candlestick
klines = client.get_klines(
symbol='BTCUSDT',
interval=Client.KLINE_INTERVAL_1HOUR,
limit=100
)

# Chuyển đổi dữ liệu thành DataFrame
import pandas as pd
df = pd.DataFrame(klines, columns=[
'timestamp', 'open', 'high', 'low', 'close', 'volume',
'close_time', 'quote_asset_volume', 'number_of_trades',
'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore'
])

Kline/Candlestick Data

5. Sử dụng WebSocket để lấy dữ liệu realtime

from binance.websockets import BinanceSocketManager
from binance.client import Client

def process_message(msg):
print(f"Giá mới: {msg['p']}")

# Khởi tạo WebSocket
bm = BinanceSocketManager(client)
conn_key = bm.start_symbol_ticker_socket('BTCUSDT', process_message)
bm.start()

WebSocket - Dữ liệu realtime

6. Lấy thông tin Order Book

# Lấy order book
depth = client.get_order_book(symbol='BTCUSDT', limit=5)
print("Bids (Lệnh mua):")
for bid in depth['bids']:
print(f"Giá: {bid[0]}, Số lượng: {bid[1]}")
print("\nAsks (Lệnh bán):")
for ask in depth['asks']:
print(f"Giá: {ask[0]}, Số lượng: {ask[1]}")

Order Book

7. Thực hiện giao dịch

7.1. Đặt lệnh thị trường

# Đặt lệnh mua thị trường
order = client.create_order(
symbol='BTCUSDT',
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=0.001
)

7.2. Đặt lệnh giới hạn

# Đặt lệnh mua giới hạn
order = client.create_order(
symbol='BTCUSDT',
side=SIDE_BUY,
type=ORDER_TYPE_LIMIT,
timeInForce=TIME_IN_FORCE_GTC,
quantity=0.001,
price='30000'
)

Order Types

8. Quản lý tài khoản

8.1. Lấy thông tin tài khoản

# Lấy thông tin tài khoản
account = client.get_account()
for balance in account['balances']:
if float(balance['free']) > 0 or float(balance['locked']) > 0:
print(f"Asset: {balance['asset']}")
print(f"Free: {balance['free']}")
print(f"Locked: {balance['locked']}")

Account Balance

8.2. Lấy lịch sử giao dịch

# Lấy lịch sử giao dịch
trades = client.get_my_trades(symbol='BTCUSDT')
for trade in trades:
print(f"Time: {trade['time']}")
print(f"Price: {trade['price']}")
print(f"Quantity: {trade['qty']}")
print(f"Side: {trade['isBuyer']}")

Trading Volume

9. Xử lý lỗi và Rate Limits

9.1. Xử lý lỗi

from binance.exceptions import BinanceAPIException

try:
# Thực hiện request
client.get_account()
except BinanceAPIException as e:
print(f"Lỗi API: {e.status_code} - {e.message}")

Error Handling

9.2. Rate Limits

# Kiểm tra rate limits
rate_limits = client.get_exchange_info()
for limit in rate_limits['rateLimits']:
print(f"Limit Type: {limit['rateLimitType']}")
print(f"Interval: {limit['interval']}")
print(f"Limit: {limit['limit']}")

API Rate Limits

10. Ví dụ hoàn chỉnh: Bot giao dịch đơn giản

from binance.client import Client
from binance.enums import *
import time

def trading_bot():
# Khởi tạo client
client = Client(api_key, api_secret)

while True:
try:
# Lấy giá hiện tại
ticker = client.get_symbol_ticker(symbol="BTCUSDT")
current_price = float(ticker['price'])

# Lấy dữ liệu kline
klines = client.get_klines(
symbol='BTCUSDT',
interval=Client.KLINE_INTERVAL_1HOUR,
limit=100
)

# Tính toán chỉ báo (ví dụ: SMA)
closes = [float(k[4]) for k in klines]
sma20 = sum(closes[-20:]) / 20

# Logic giao dịch đơn giản
if current_price > sma20:
# Đặt lệnh mua
order = client.create_order(
symbol='BTCUSDT',
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=0.001
)
elif current_price < sma20:
# Đặt lệnh bán
order = client.create_order(
symbol='BTCUSDT',
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=0.001
)

# Đợi 1 phút
time.sleep(60)

except Exception as e:
print(f"Lỗi: {e}")
time.sleep(60)

if __name__ == "__main__":
trading_bot()

Kết luận

Trong bài viết này, chúng ta đã học cách:

  1. Cài đặt và cấu hình python-binance
  2. Lấy dữ liệu thị trường qua REST API
  3. Sử dụng WebSocket để lấy dữ liệu realtime
  4. Thực hiện các giao dịch
  5. Quản lý tài khoản
  6. Xử lý lỗi và rate limits
  7. Xây dựng bot giao dịch đơn giản

Lưu ý quan trọng:

  • Luôn bảo vệ API Key và Secret Key
  • Tuân thủ rate limits của Binance
  • Test kỹ trên tài khoản testnet trước khi giao dịch thật
  • Xử lý lỗi một cách cẩn thận
  • Không nên đầu tư quá nhiều vào một chiến lược giao dịch

Tài liệu tham khảo