Skip to Content

Ngày 43 Python 365 ngày | Phân tích dữ liệu giao dịch từ API Binance

🐍 Ngày 43 Python 365 ngày | Phân tích dữ liệu giao dịch từ API Binance

🗓 Ngày 43: Phân tích dữ liệu giao dịch từ API Binance

Hôm nay, bạn sẽ học cách thu thập dữ liệu giao dịch từ Binance và thực hiện phân tích cơ bản với Python.

🎯 Mục tiêu

  • Hiểu cấu trúc dữ liệu giao dịch từ Binance.
  • Trích xuất dữ liệu giao dịch (trades).
  • Phân tích khối lượng, giá trung bình và thời gian giao dịch.

🧰 Cài đặt công cụ

pip install python-binance pandas

🔌 Lấy dữ liệu giao dịch

from binance.client import Client
import pandas as pd

api_key = "your_api_key"
api_secret = "your_api_secret"

client = Client(api_key, api_secret)

trades = client.get_recent_trades(symbol='BTCUSDT')
df = pd.DataFrame(trades)
print(df.head())

📊 Phân tích dữ liệu

df['price'] = df['price'].astype(float)
df['qty'] = df['qty'].astype(float)

# Tính tổng khối lượng
total_volume = df['qty'].sum()

# Giá trung bình
avg_price = (df['price'] * df['qty']).sum() / total_volume

print("Tổng khối lượng:", total_volume)
print("Giá trung bình:", round(avg_price, 2))

📈 Vẽ biểu đồ giá và khối lượng

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 4))
plt.plot(df['price'], label='Giá BTC')
plt.xlabel('Lệnh giao dịch')
plt.ylabel('Giá')
plt.title('Biến động giá BTC - gần nhất')
plt.legend()
plt.grid(True)
plt.show()

📌 Bài tập gợi ý

  • Vẽ biểu đồ giá và khối lượng theo thời gian.
  • So sánh giá trung bình giữa BTCUSDT và ETHUSDT.
  • Lưu dữ liệu về file .csv để huấn luyện mô hình sau này.

Phân tích dữ liệu là bước đầu tiên để hiểu thị trường và phát triển chiến lược giao dịch hiệu quả hơn!

/* Tối ưu font, khoảng cách và màu chủ đạo */ body { font-family: 'Inter', sans-serif; color: #2e3a59; } h1, h2, h3 { color: #2a7a4d; /* màu xanh giống Docusaurus */ font-weight: 700; } a { color: #2a7a4d; text-decoration: none; } a:hover { text-decoration: underline; } /* Bo tròn và đổ bóng cho khối nội dung */ .card, .oe_structure { border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); padding: 1.5rem; }