CryptoBinance APIPythonCCXTBot Crypto
Được viết bởithanhdtvà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 toàn diện kết nối Binance API bằng Python với thư viện CCXT và python-binance: lấy dữ liệu real-time, đặt lệnh, quản lý portfolio và xây dựng bot 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 → AccountAPI 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.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.