| Python Crypto: Lấy Dữ Liệu Binance, Tính Chỉ Báo, Backtest Chiến Lược BTCUSDT

Thị trường crypto mở 24/7 — con người không thể theo dõi liên tục, nhưng Python thì có thể. Bài viết này hướng dẫn bạn kết nối Binance API bằng Python, lấy dữ liệu BTCUSDT và backtest chiến lược trading crypto.

Cài Đặt

pip install python-binance pandas numpy matplotlib

Kết Nối Binance API

from binance.client import Client

# Lấy API key tại: Binance → Profile → API Management
API_KEY    = "your_api_key"
API_SECRET = "your_api_secret"

client = Client(API_KEY, API_SECRET)

# Test kết nối
info = client.get_server_time()
print(f"Kết nối thành công! Server time: {info}")

# Xem số dư tài khoản
account = client.get_account()
balances = [b for b in account['balances'] if float(b['free']) > 0]
for b in balances:
    print(f"{b['asset']}: {b['free']}")

Lấy Dữ Liệu Lịch Sử BTCUSDT

import pandas as pd
from datetime import datetime

def get_binance_data(symbol, interval, start_str, end_str=None):
    klines = client.get_historical_klines(symbol, interval, start_str, end_str)
    df = pd.DataFrame(klines, columns=[
        'timestamp', 'open', 'high', 'low', 'close', 'volume',
        'close_time', 'quote_vol', 'trades', 'taker_buy_base',
        'taker_buy_quote', 'ignore'
    ])
    df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
    df.set_index('timestamp', inplace=True)
    for col in ['open', 'high', 'low', 'close', 'volume']:
        df[col] = df[col].astype(float)
    return df[['open', 'high', 'low', 'close', 'volume']]

# Dữ liệu BTCUSDT khung 1 ngày từ 2023
df = get_binance_data(
    symbol="BTCUSDT",
    interval=Client.KLINE_INTERVAL_1DAY,
    start_str="2023-01-01",
    end_str="2026-06-01"
)
print(f"Tải {len(df)} nến ngày")
print(df.tail())

Tính Chỉ Báo Kỹ Thuật

import numpy as np

# RSI 14
delta = df['close'].diff()
gain  = delta.clip(lower=0).rolling(14).mean()
loss  = (-delta.clip(upper=0)).rolling(14).mean()
df['RSI'] = 100 - (100 / (1 + gain/loss))

# MACD (12, 26, 9)
ema12 = df['close'].ewm(span=12).mean()
ema26 = df['close'].ewm(span=26).mean()
df['MACD']        = ema12 - ema26
df['MACD_signal'] = df['MACD'].ewm(span=9).mean()
df['MACD_hist']   = df['MACD'] - df['MACD_signal']

# Bollinger Bands (20, 2)
df['BB_mid']   = df['close'].rolling(20).mean()
bb_std         = df['close'].rolling(20).std()
df['BB_upper'] = df['BB_mid'] + 2 * bb_std
df['BB_lower'] = df['BB_mid'] - 2 * bb_std

print(df[['close', 'RSI', 'MACD', 'BB_upper', 'BB_lower']].tail(5))

Chiến Lược: MACD Crossover

# Mua khi MACD cắt lên Signal Line
# Bán khi MACD cắt xuống Signal Line
df['signal'] = 0
df.loc[
    (df['MACD'] > df['MACD_signal']) &
    (df['MACD'].shift(1) <= df['MACD_signal'].shift(1)),
    'signal'
] = 1   # MUA

df.loc[
    (df['MACD'] = df['MACD_signal'].shift(1)),
    'signal'
] = -1  # BÁN

Backtest

initial_usdt = 1000  # $1,000
capital      = initial_usdt
position     = 0
trades       = []

for i in range(len(df)):
    price = df['close'].iloc[i]
    sig   = df['signal'].iloc[i]

    if sig == 1 and position == 0:   # Mua
        position = capital / price
        capital  = 0

    elif sig == -1 and position > 0:  # Bán
        capital = position * price
        trades.append(capital)
        position = 0

# Đóng vị thế cuối
if position > 0:
    capital = position * df['close'].iloc[-1]

profit_pct = (capital - initial_usdt) / initial_usdt * 100
print(f"n=== Kết quả Backtest BTCUSDT MACD ===")
print(f"Vốn ban đầu:  ${initial_usdt:,.0f}")
print(f"Vốn cuối:     ${capital:,.0f}")
print(f"Lợi nhuận:    {profit_pct:.1f}%")
print(f"Buy & Hold:   {(df['close'].iloc[-1]/df['close'].iloc[0] - 1)*100:.1f}%")

Theo Dõi Giá Thời Gian Thực

import time

while True:
    ticker = client.get_symbol_ticker(symbol="BTCUSDT")
    price  = float(ticker['price'])
    print(f"BTC: ${price:,.2f}", end='
')
    time.sleep(5)  # cập nhật mỗi 5 giây

Kết Luận

Binance API + Python = bộ công cụ hoàn chỉnh để phân tích và giao dịch crypto. Bước tiếp theo: thêm module quản lý rủi ro (stop-loss, take-profit) và kết nối với Telegram bot để nhận thông báo tín hiệu.


📌 Muốn ứng dụng Python vào phân tích và giao dịch tài chính thực chiến?
Khóa Python Fintech — Phân Tích Dữ Liệu Lớn & Tự Động Hóa Giao Dịch tại Hướng Nghiệp Dữ Liệu giúp bạn thực hành với dữ liệu VnIndex, Binance API thật — không dạy lý thuyết hàn lâm.
📞 Hotline/Zalo: 0927 909 257

admin

admin

Biên tập viên, Hướng Nghiệp Dữ Liệu
724 Bài viết
15.4k Người theo dõi
120k+ Lượt đọc

Biên tập viên nội dung tại Hướng Nghiệp Dữ Liệu, phụ trách tổng hợp và biên soạn các bài viết về lập trình Python, dữ liệu và công nghệ.