CryptoBinance APIPythonCCXTBot Crypto
Được viết bởiĐặng Trí Thanhvào ngày 06/07/2026

Binance API Python: Hướng Dẫn Xây Dựng Bot Giao Dịch Crypto Từ Đầu

Hướng dẫn kết nối Binance API bằng Python với CCXT và python-binance: lấy dữ liệu real-time, đặt lệnh và xây dựng bot crypto hoàn chỉnh.

Binance API Python: Hướng Dẫn Xây Dựng Bot Giao Dịch Crypto Từ Đầu

Binance là sàn giao dịch crypto lớn nhất thế giới với API REST và WebSocket đầy đủ, miễn phí và tài liệu chi tiết. Đây là nền tảng lý tưởng để xây dựng bot giao dịch crypto bằng Python.

Chuẩn Bị: Tạo API Key Binance

  1. Đăng nhập Binance → Account → API Management
  2. Tạo API key mới, đặt tên dễ nhớ
  3. CHỈ bật quyền cần thiết: Enable Reading + Enable Spot & Margin Trading
  4. KHÔNG bật Enable Withdrawals (bảo mật)
  5. Whitelist IP của VPS nếu bot chạy trên server

Lưu API Key và Secret vào file .env:

BINANCE_API_KEY=your_api_key
BINANCE_SECRET=your_secret_key

Cách 1: Dùng Thư Viện CCXT (Khuyến Nghị)

CCXT hỗ trợ 100+ sàn với API thống nhất — viết code một lần dùng được nhiều sàn:

pip install ccxt python-dotenv
import ccxt
import os
from dotenv import load_dotenv

load_dotenv()

exchange = ccxt.binance({
    'apiKey': os.getenv('BINANCE_API_KEY'),
    'secret': os.getenv('BINANCE_SECRET'),
    'options': {'defaultType': 'spot'},  # 'future' cho futures
})

# Kiểm tra kết nối
balance = exchange.fetch_balance()
print(f"USDT balance: {balance['USDT']['free']:.2f}")

# Lấy giá hiện tại
ticker = exchange.fetch_ticker('BTC/USDT')
print(f"BTC price: ${ticker['last']:,.2f}")

# Lấy dữ liệu OHLCV (nến)
ohlcv = exchange.fetch_ohlcv('BTC/USDT', '1h', limit=100)
import pandas as pd
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
print(df.tail())

Đặt Lệnh Giao Dịch

# Lệnh Market (khớp ngay theo giá thị trường)
order = exchange.create_market_buy_order('BTC/USDT', 0.001)  # Mua 0.001 BTC

# Lệnh Limit (đặt giá cố định)
order = exchange.create_limit_buy_order('BTC/USDT', 0.001, 60000)  # Mua 0.001 BTC ở $60,000

# Lệnh Stop Loss
order = exchange.create_order(
    symbol='BTC/USDT',
    type='STOP_LOSS_LIMIT',
    side='sell',
    amount=0.001,
    price=58000,        # Giá bán khi chạm stop
    params={'stopPrice': 58500}  # Giá kích hoạt stop
)

# Hủy lệnh
exchange.cancel_order(order['id'], 'BTC/USDT')

Cách 2: WebSocket Cho Dữ Liệu Real-time

import asyncio
import ccxt.pro as ccxtpro  # pip install ccxt[pro]

async def watch_price():
    exchange = ccxtpro.binance()

    while True:
        ticker = await exchange.watch_ticker('BTC/USDT')
        print(f"BTC: ${ticker['last']:,.2f} | Change: {ticker['percentage']:.2f}%")

asyncio.run(watch_price())

Bot RSI Hoàn Chỉnh

import pandas as pd
import numpy as np
import time

def calculate_rsi(series, period=14):
    delta = series.diff()
    gain = delta.clip(lower=0).rolling(period).mean()
    loss = (-delta.clip(upper=0)).rolling(period).mean()
    rs = gain / loss
    return 100 - (100 / (1 + rs))

def run_rsi_bot(symbol='BTC/USDT', timeframe='1h',
                rsi_period=14, oversold=30, overbought=70):
    position = 0

    while True:
        try:
            ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=100)
            df = pd.DataFrame(ohlcv,
                              columns=['ts', 'open', 'high', 'low', 'close', 'vol'])
            df['rsi'] = calculate_rsi(df['close'], rsi_period)

            current_rsi = df['rsi'].iloc[-1]
            current_price = df['close'].iloc[-1]

            if current_rsi < oversold and position == 0:
                qty = 10 / current_price  # $10 mỗi lệnh
                exchange.create_market_buy_order(symbol, round(qty, 6))
                position = 1
                print(f"BUY @ ${current_price:.2f} | RSI: {current_rsi:.1f}")

            elif current_rsi > overbought and position == 1:
                # Lấy số lượng đang hold
                bal = exchange.fetch_balance()['BTC']['free']
                exchange.create_market_sell_order(symbol, bal)
                position = 0
                print(f"SELL @ ${current_price:.2f} | RSI: {current_rsi:.1f}")

        except Exception as e:
            print(f"Error: {e}")

        time.sleep(60)  # Kiểm tra mỗi phút

run_rsi_bot()

Lưu Ý Bảo Mật Tuyệt Đối

  • Không bao giờ commit API key lên GitHub — dùng .env và .gitignore
  • Whitelist IP cho API key — nếu key bị lộ, kẻ xấu cũng không dùng được từ IP khác
  • Không enable withdrawal permission cho trading bot
  • Test trên Binance Testnet trước khi chạy thật: exchange.set_sandbox_mode(True)

Học xây dựng bot crypto hoàn chỉnh với dashboard và Telegram alerts tại Hướng Nghiệp Dữ Liệu.

Câu hỏi thường gặp

Nên dùng CCXT hay python-binance?

CCXT phù hợp nếu bạn muốn code chạy được trên nhiều sàn khác nhau vì cùng một API cho Binance, Bybit, OKX. python-binance phù hợp nếu bạn chỉ làm việc với Binance và cần các tính năng riêng của sàn như WebSocket stream chuyên dụng hoặc quản lý sub-account.

Làm sao bảo mật API key Binance khi chạy bot?

Luôn giới hạn IP cho API key, chỉ bật quyền đọc và giao dịch spot, tuyệt đối không bật quyền rút tiền. Lưu key trong biến môi trường hoặc file .env nằm trong .gitignore, không bao giờ hard-code trong source hoặc đẩy lên GitHub.

Bot crypto chạy trên VPS hay máy cá nhân?

VPS là lựa chọn đúng cho bot chạy liên tục vì crypto giao dịch 24/7. Máy cá nhân chỉ phù hợp để phát triển và thử nghiệm. Chọn VPS ở cùng khu vực địa lý với server sàn (thường là Tokyo hoặc Singapore cho Binance) để giảm độ trễ.