| CÁCH XÂY DỰNG BOT AUTO TRADING BINANCE SPOT/FUTURES BẰNG PYTHON

Được viết bởi thanhdt vào ngày 27/11/2025 lúc 16:04 | 152 lượt xem

CÁCH XÂY DỰNG BOT AUTO TRADING BINANCE SPOT/FUTURES BẰNG PYTHON

(Kỹ thuật chuyên sâu cho trader & developer)

Bot Auto Trading trên Binance (Spot/Futures) là một trong những ứng dụng mạnh nhất của Python trong giao dịch tài chính. Để xây dựng một bot hiệu quả, bạn cần nắm rõ: API, xử lý dữ liệu, khung chiến lược, quản lý rủi ro, và cách vận hành trên VPS.

Bài viết này hướng dẫn đầy đủ từ A → Z.


1. Kiến trúc chuẩn của một Bot Auto Trading

https://miro.medium.com/1%2AkPMKD2UISQHd_nlSdpHw7A.png

Một bot chuẩn gồm 5 lớp:

1) Data Layer – Lấy dữ liệu thị trường

  • Binance REST API
  • Binance Websocket
  • CCXT (thư viện Python đa sàn)

2) Indicator Layer – Tính toán tín hiệu

  • MA, EMA, MACD, RSI
  • ATR
  • Mô hình nến

3) Strategy Layer – Thuật toán giao dịch

  • Breakout
  • Trend-following
  • Long/Short Futures
  • Grid Trading
  • DCA

4) Risk Management – Quản trị rủi ro

  • Stop-loss
  • Take-profit
  • Position size
  • Max drawdown

5) Execution Layer – Gửi lệnh

  • Market order
  • Limit order
  • Futures long/short
  • Reduce-only

2. Chuẩn bị môi trường Python

pip install ccxt
pip install python-binance
pip install pandas numpy
pip install python-dotenv

Lời khuyên: Nên dùng Python 3.10.11 để tránh lỗi TA-Lib, pandas, numpy.


3. Lấy dữ liệu từ Binance (Spot & Futures)

3.1. Dữ liệu Spot bằng CCXT

import ccxt

binance = ccxt.binance()
ohlcv = binance.fetch_ohlcv('BTC/USDT', timeframe='1m', limit=100)
print(ohlcv[:3])

3.2. Dữ liệu Futures (USDT-M Futures)

binance_f = ccxt.binance({
    'options': { 'defaultType': 'future' }
})

data = binance_f.fetch_ohlcv('BTC/USDT', '5m', limit=200)
print(data[:3])

4. Tính MA, MACD, RSI bằng Python

import pandas as pd

df = pd.DataFrame(ohlcv, columns=['time','open','high','low','close','volume'])
df['MA20'] = df['close'].rolling(20).mean()
df['MA50'] = df['close'].rolling(50).mean()

MACD:

df['EMA12'] = df['close'].ewm(span=12).mean()
df['EMA26'] = df['close'].ewm(span=26).mean()
df['MACD'] = df['EMA12'] - df['EMA26']
df['Signal'] = df['MACD'].ewm(span=9).mean()

5. Xây chiến lược Trend Following (Spot/Futures)

Chiến lược MA20 cắt MA50:

BUY  khi MA20 > MA50 và giá trên MA20
SELL khi MA20 < MA50 và giá dưới MA20

Code:

if df['MA20'].iloc[-1] > df['MA50'].iloc[-1]:
    signal = "BUY"
else:
    signal = "SELL"

print("Signal:", signal)

6. Gửi lệnh SPOT bằng Binance API

https://cdn.shortpixel.ai/spai/q_lossy%2Bw_949%2Bto_webp%2Bret_img/algotrading101.com/learn/wp-content/uploads/2020/06/create_api.jpg
https://cdn.shortpixel.ai/spai/q_lossy%2Bw_949%2Bto_webp%2Bret_img/algotrading101.com/learn/wp-content/uploads/2020/06/exchange_info-1.jpg
from binance.client import Client
from dotenv import load_dotenv
import os

load_dotenv()

api_key = os.getenv("BINANCE_KEY")
api_secret = os.getenv("BINANCE_SECRET")

client = Client(api_key, api_secret)

order = client.order_market_buy(
    symbol='BTCUSDT',
    quantity=0.001
)

print(order)

7. Gửi lệnh FUTURES (Long/Short)

Lệnh Long Futures:

client.futures_create_order(
    symbol='BTCUSDT',
    side='BUY',
    type='MARKET',
    quantity=0.01
)

Lệnh Short Futures:

client.futures_create_order(
    symbol='BTCUSDT',
    side='SELL',
    type='MARKET',
    quantity=0.01
)

Lệnh đặt Stop-loss (Futures)

client.futures_create_order(
    symbol='BTCUSDT',
    side='SELL',
    type='STOP_MARKET',
    stopPrice=27000,
    closePosition=True
)

8. Thêm quản trị rủi ro (bắt buộc)

Winrate không quan trọng — Quan trọng là Risk/Reward

Quy tắc chuẩn:

  • TP/SL ≥ 2:1
  • Tối đa rủi ro mỗi lệnh: 1–2% tài khoản
  • Mỗi chiến lược chỉ chạy 1 vị thế duy nhất

9. Chạy bot liên tục với vòng loop

import time

while True:
    try:
        # lấy data
        ohlcv = binance.fetch_ohlcv('BTC/USDT', '1m', limit=100)
        # tính toán
        # tạo tín hiệu
        # vào lệnh
    except Exception as e:
        print("Error:", e)

    time.sleep(10)

10. Deploy Bot lên VPS (Chạy 24/7)

https://repository-images.githubusercontent.com/697748599/a9de4cf4-b622-464b-9f03-2a920ac9802d
https://www.bluehost.com/blog/wp-content/uploads/2025/06/Set_crypto_trading-1024x683.webp

Hướng dẫn nhanh:

  1. Thuê VPS (Ubuntu 22.04)
  2. Cài Python 3.10
  3. Upload bot qua SCP/Git
  4. Chạy bot bằng: nohup python bot.py &
  5. Kiểm tra log: tail -f nohup.out

11. Bảo mật API Key đúng chuẩn

Không bao giờ ghi API trực tiếp vào code.

Dùng .env:

BINANCE_KEY=xxxx
BINANCE_SECRET=xxxx

KẾT LUẬN

Sau bài này, anh đã có đầy đủ:

  • Kiến trúc bot
  • Cách lấy dữ liệu Spot/Futures
  • Indicator + chiến lược mẫu
  • Cách gửi lệnh Spot & Futures
  • Quản trị rủi ro
  • Cách chạy bot 24/7
Thành ĐT

Thành ĐT

Founder & Chief Technology Officer, HNDL
1.321 Bài viết
15.4k Người theo dõi
120k+ Lượt đọc

Chuyên gia với hơn 10 năm kinh nghiệm trong phát triển hệ thống giao dịch tự động (Trading Bot), Fintech, Mobile App và phân tích dữ liệu tài chính (Quantitative Analysis). Người sáng lập và trực tiếp dẫn dắt các khóa học thực chiến tại Hướng Nghiệp Dữ Liệu.