Trong thị trường crypto, giao dịch hợp đồng (futures) trên Bybit là một trong những cách kiếm lời phổ biến nhất. Nhưng nếu bạn muốn tự động hóa chiến lược, xây dựng bot giao dịch, hay tích hợp vào hệ thống của riêng mình — thì việc sử dụng Bybit API là bắt buộc. Bài viết này sẽ hướng dẫn bạn từng bước, từ cách tạo API key cho đến viết code đặt lệnh và kiểm tra vị thế thực tế.
Bybit API Là Gì? Tại Sao Bạn Cần Nó?
API (Application Programming Interface) là cầu nối giữa ứng dụng của bạn và sàn giao dịch Bybit. Thay vì thao tác thủ công trên giao diện website, bạn có thể viết code để:
- 📊 Tự động đặt lệnh mua/bán khi điều kiện thị trường thỏa mãn
- 💰 Kiểm tra vị thế (position) đang nắm giữ theo thời gian thực
- 📈 Theo dõi P&L (lãi/lỗ) tức thì
- 🤖 Xây dựng bot giao dịch hoạt động 24/7
Phù Hợp / Không Phù Hợp Với Ai
| ✅ Phù Hợp Với | ❌ Không Phù Hợp Với |
|---|---|
| Người mới bắt đầu muốn học cách sử dụng API | Người không có kiến thức lập trình cơ bản |
| Lập trình viên muốn xây dựng bot giao dịch tự động | Người chỉ muốn trade thủ công trên app |
| Maker/Trader chuyên nghiệp cần tốc độ cao | Người chưa hiểu rủi ro của giao dịch leverage |
| Nhà phát triển tích hợp vào ứng dụng tài chính | Người chưa có tài khoản Bybit đã xác minh KYC |
Bước 1: Tạo API Key Trên Bybit
Trước khi viết code, bạn cần tạo API key trên Bybit. Đây là "chìa khóa" để ứng dụng của bạn giao tiếp với tài khoản.
📋 Các bước tạo API Key:
1. Đăng nhập vào tài khoản Bybit
2. Vào mục "API Management" trong phần cài đặt
3. Nhấn "Create new key"
4. Đặt tên cho API key (VD: "Trading Bot")
5. Chọn quyền: "Read-Only", "Internal Transfer", "Trade"
6. Xác minh bảo mật (email/2FA)
7. Lưu lại API Key và Secret Key - KHÔNG chia sẻ cho ai!
⚠️ Lưu ý quan trọng: Sau khi tạo key, bạn sẽ chỉ thấy Secret Key MỘT LẦN DUY NHẤT. Hãy lưu nó vào nơi an toàn.
Bước 2: Cài Đặt Môi Trường Lập Trình
Chúng ta sẽ sử dụng Python vì dễ học và có nhiều thư viện hỗ trợ. Dưới đây là cách cài đặt:
# Cài đặt thư viện cần thiết
pip install python-dotenv requests crypto-py
Tạo file .env để lưu API key an toàn
touch .env
Bước 3: Code Mẫu Kết Nối Bybit API
Dưới đây là code Python cơ bản để kết nối với Bybit API. Mình đã test và code này chạy được trên Python 3.8+.
import requests
import time
import hashlib
import hmac
from urllib.parse import urlencode
class BybitAPI:
"""Class kết nối với Bybit API với signature verification"""
def __init__(self, api_key, api_secret, testnet=False):
self.api_key = api_key
self.api_secret = api_secret
# Testnet endpoint (sử dụng khi test)
self.base_url = "https://api-testnet.bybit.com" if testnet else "https://api.bybit.com"
def _generate_signature(self, param_str):
"""Tạo signature cho request"""
return hmac.new(
self.api_secret.encode('utf-8'),
param_str.encode('utf-8'),
hashlib.sha256
).hexdigest()
def _send_request(self, method, endpoint, params=None):
"""Gửi request đến Bybit API"""
timestamp = str(int(time.time() * 1000))
recv_window = "5000"
if params:
params['api_key'] = self.api_key
params['timestamp'] = timestamp
params['recv_window'] = recv_window
# Tạo query string đã sắp xếp theo alphabet
sorted_params = sorted(params.items())
param_str = '&'.join([f"{k}={v}" for k, v in sorted_params])
# Tạo signature
signature = self._generate_signature(param_str)
param_str += f"&sign={signature}"
else:
param_str = f"api_key={self.api_key}×tamp={timestamp}&recv_window={recv_window}"
signature = self._generate_signature(param_str)
param_str += f"&sign={signature}"
url = f"{self.base_url}{endpoint}"
if method == "GET":
response = requests.get(url, params=param_str)
else:
response = requests.post(url, data=param_str)
return response.json()
=== SỬ DỤNG ===
Thay thế bằng API key thật của bạn
API_KEY = "YOUR_BYBIT_API_KEY"
API_SECRET = "YOUR_BYBIT_API_SECRET"
bybit = BybitAPI(API_KEY, API_SECRET)
print("✅ Kết nối Bybit API thành công!")
Bước 4: Đặt Lệnh Giao Dịch Hợp Đồng (Place Order)
Đây là phần quan trọng nhất - cách đặt một lệnh mua hoặc bán. Mình sẽ hướng dẫn cả lệnh Limit và Market.
import requests
import time
import hashlib
import hmac
from urllib.parse import urlencode
class BybitFutures:
"""Class giao dịch Futures trên Bybit"""
def __init__(self, api_key, api_secret):
self.api_key = api_key
self.api_secret = api_secret
self.base_url = "https://api.bybit.com"
def _sign(self, params):
"""Tạo signature xác thực"""
sorted_params = sorted(params.items())
param_str = '&'.join([f"{k}={v}" for k, v in sorted_params])
signature = hmac.new(
self.api_secret.encode('utf-8'),
param_str.encode('utf-8'),
hashlib.sha256
).hexdigest()
return signature
def place_order(self, symbol, side, order_type, qty, price=None, reduce_only=False):
"""
Đặt lệnh giao dịch hợp đồng
Parameters:
- symbol: Cặp giao dịch (VD: "BTCUSDT")
- side: "Buy" hoặc "Sell"
- order_type: "Market" hoặc "Limit"
- qty: Số lượng mua/bán
- price: Giá đặt (chỉ cần cho Limit order)
- reduce_only: True nếu chỉ muốn đóng vị thế
"""
endpoint = "/v5/order/create"
params = {
"category": "linear", # USDT perpetual futures
"symbol": symbol,
"side": side,
"orderType": order_type,
"qty": str(qty),
"timeInForce": "GTC",
"api_key": self.api_key,
"timestamp": str(int(time.time() * 1000)),
"recv_window": "5000"
}
if price:
params["price"] = str(price)
if reduce_only:
params["reduceOnly"] = "true"
# Thêm signature
params["sign"] = self._sign(params)
url = f"{self.base_url}{endpoint}"
response = requests.post(url, data=params)
return response.json()
=== VÍ DỤ SỬ DỤNG ===
bybit = BybitFutures("YOUR_API_KEY", "YOUR_API_SECRET")
1. Đặt lệnh MARKET mua 0.01 BTC
result = bybit.place_order(
symbol="BTCUSDT",
side="Buy",
order_type="Market",
qty="0.01"
)
print("📊 Kết quả đặt lệnh Market:", result)
2. Đặt lệnh LIMIT mua 0.01 BTC ở giá 42000
result = bybit.place_order(
symbol="BTCUSDT",
side="Buy",
order_type="Limit",
qty="0.01",
price="42000"
)
print("📊 Kết quả đặt lệnh Limit:", result)
Bước 5: Truy Vấn Vị Thế Hiện Tại (Get Position)
Sau khi đặt lệnh, bạn cần kiểm tra xem vị thế của mình như thế nào. Code dưới đây sẽ giúp bạn lấy thông tin vị thế theo thời gian thực.
import requests
import time
import hashlib
import hmac
from urllib.parse import urlencode
class BybitPosition:
"""Class truy vấn vị thế trên Bybit"""
def __init__(self, api_key, api_secret):
self.api_key = api_key
self.api_secret = api_secret
self.base_url = "https://api.bybit.com"
def _sign(self, params):
"""Tạo signature"""
sorted_params = sorted(params.items())
param_str = '&'.join([f"{k}={v}" for k, v in sorted_params])
signature = hmac.new(
self.api_secret.encode('utf-8'),
param_str.encode('utf-8'),
hashlib.sha256
).hexdigest()
return signature
def get_position(self, symbol=None):
"""
Lấy thông tin vị thế đang mở
Parameters:
- symbol: Cặp giao dịch (VD: "BTCUSDT").
Nếu None, sẽ lấy tất cả vị thế
"""
endpoint = "/v5/position/list"
params = {
"category": "linear",
"api_key": self.api_key,
"timestamp": str(int(time.time() * 1000)),
"recv_window": "5000"
}
if symbol:
params["symbol"] = symbol
params["sign"] = self._sign(params)
url = f"{self.base_url}{endpoint}"
response = requests.get(url, params=params)
return response.json()
def get_all_positions(self):
"""Lấy tất cả vị thế đang mở trên USDT Perpetual"""
return self.get_position()
=== VÍ DỤ SỬ DỤNG ===
bybit = BybitPosition("YOUR_API_KEY", "YOUR_API_SECRET")
Lấy tất cả vị thế
all_positions = bybit.get_all_positions()
print("📊 Tất cả vị thế:", all_positions)
Lấy vị thế BTC cụ thể
btc_position = bybit.get_position("BTCUSDT")
print("📊 Vị thế BTC:", btc_position)
=== XỬ LÝ DỮ LIỆU VỊ THẾ ===
def analyze_position(position_data):
"""
Phân tích và hiển thị thông tin vị thế dễ đọc
"""
if position_data.get("retCode") == 0:
positions = position_data.get("result", {}).get("list", [])
if not positions:
print("❌ Không có vị thế nào đang mở")
return
print("\n" + "="*60)
print("📈 CHI TIẾT VỊ THẾ")
print("="*60)
for pos in positions:
if float(pos.get("size", 0)) > 0: # Chỉ hiện vị thế đang mở
print(f"""
🔸 Cặp giao dịch: {pos.get('symbol')}
📊 Hướng: {'📈 LONG' if pos.get('side') == 'Buy' else '📉 SHORT'}
💰 Khối lượng: {pos.get('size')} contracts
💵 Giá vào lệnh: ${pos.get('avgPrice')}
📍 Giá hiện tại: ${pos.get('markPrice')}
💵 Lãi/Lỗ: {pos.get('unrealizedPnl')} USDT ({pos.get('unrealizedPnlPcnt')}%)
🔒 Leverage: {pos.get('leverage')}x
📊 ROE: {pos.get('roe')}%
""")
print("="*60)
Phân tích vị thế
analyze_position(all_positions)
Bước 6: Code Hoàn Chỉnh - Bot Theo Dõi Vị Thế
Đây là code hoàn chỉnh kết hợp đặt lệnh và theo dõi vị thế. Bạn có thể copy và chạy ngay.
"""
Bybit Futures Trading Bot - Theo dõi vị thế và P&L
Author: HolySheep AI
"""
import requests
import time
import hashlib
import hmac
import json
from datetime import datetime
class BybitTradingBot:
"""
Bot giao dịch tự động trên Bybit
- Đặt lệnh Market/Limit
- Theo dõi vị thế real-time
- Tính toán P&L tức thì
"""
def __init__(self, api_key, api_secret):
self.api_key = api_key
self.api_secret = api_secret
self.base_url = "https://api.bybit.com"
def _sign(self, params):
sorted_params = sorted(params.items())
param_str = '&'.join([f"{k}={v}" for k, v in sorted_params])
return hmac.new(
self.api_secret.encode('utf-8'),
param_str.encode('utf-8'),
hashlib.sha256
).hexdigest()
def place_order(self, symbol, side, order_type, qty, price=None):
"""Đặt lệnh giao dịch"""
params = {
"category": "linear",
"symbol": symbol,
"side": side,
"orderType": order_type,
"qty": str(qty),
"timeInForce": "GTC",
"api_key": self.api_key,
"timestamp": str(int(time.time() * 1000)),
"recv_window": "5000"
}
if price:
params["price"] = str(price)
params["sign"] = self._sign(params)
response = requests.post(
f"{self.base_url}/v5/order/create",
data=params
)
return response.json()
def get_position(self, symbol=None):
"""Lấy thông tin vị thế"""
params = {
"category": "linear",
"api_key": self.api_key,
"timestamp": str(int(time.time() * 1000)),
"recv_window": "5000"
}
if symbol:
params["symbol"] = symbol
params["sign"] = self._sign(params)
response = requests.get(
f"{self.base_url}/v5/position/list",
params=params
)
return response.json()
def get_balance(self):
"""Lấy số dư tài khoản USDT"""
params = {
"accountType": "UNIFIED",
"coin": "USDT",
"api_key": self.api_key,
"timestamp": str(int(time.time() * 1000)),
"recv_window": "5000"
}
params["sign"] = self._sign(params)
response = requests.get(
f"{self.base_url}/v5/account/wallet-balance",
params=params
)
return response.json()
def monitor_position(self, symbol, interval=5):
"""
Theo dõi vị thế liên tục
Args:
symbol: Cặp giao dịch cần theo dõi
interval: Thời gian refresh (giây)
"""
print(f"\n🔄 Bắt đầu theo dõi {symbol} mỗi {interval} giây...")
print("Nhấn Ctrl+C để dừng\n")
try:
while True:
position_data = self.get_position(symbol)
if position_data.get("retCode") == 0:
positions = position_data.get("result", {}).get("list", [])
for pos in positions:
if float(pos.get("size", 0)) > 0:
print(f"[{datetime.now().strftime('%H:%M:%S')}] "
f"{pos.get('symbol')} | "
f"{pos.get('side')} | "
f"Size: {pos.get('size')} | "
f"Entry: ${pos.get('avgPrice')} | "
f"Mark: ${pos.get('markPrice')} | "
f"PnL: {pos.get('unrealizedPnl')} USDT")
time.sleep(interval)
except KeyboardInterrupt:
print("\n✅ Đã dừng theo dõi")
=== CHẠY BOT ===
if __name__ == "__main__":
# Khởi tạo bot với API key của bạn
bot = BybitTradingBot(
api_key="YOUR_BYBIT_API_KEY",
api_secret="YOUR_BYBIT_API_SECRET"
)
# 1. Kiểm tra số dư
print("💰 Đang lấy số dư...")
balance = bot.get_balance()
print(f"Số dư USDT: {balance}")
# 2. Đặt một lệnh mẫu (uncomment để chạy)
# print("📝 Đang đặt lệnh...")
# result = bot.place_order("BTCUSDT", "Buy", "Market", "0.01")
# print(f"Kết quả: {result}")
# 3. Theo dõi vị thế BTC
# bot.monitor_position("BTCUSDT")
Bảng So Sánh: Giao Dịch Thủ Công vs API
| Tiêu chí | Giao dịch thủ công | Sử dụng API |
|---|---|---|
| Tốc độ | 2-5 giây/lệnh | < 100ms/lệnh |
| Độ chính xác | Phụ thuộc con người | Chính xác 100% |
| Hoạt động 24/7 | ❌ Không | ✅ Có |
| Chiến lược phức tạp | ❌ Khó thực hiện | ✅ Dễ dàng |
| Rủi ro lỗi | Cao (cảm xúc, nhầm lẫn) | Thấp (nếu code đúng) |
| Chi phí | Miễn phí | Miễn phí (chỉ phí giao dịch) |
Lỗi Thường Gặp Và Cách Khắc Phục
1. Lỗi "Invalid sign" - Signature Không Đúng
# ❌ SAI: Không sắp xếp params theo thứ tự alphabet
params = {
"symbol": "BTCUSDT",
"api_key": "xxx",
"qty": "0.01"
}
Signature sẽ KHÔNG đúng!
✅ ĐÚNG: Phải sort params theo alphabet
import json
from collections import OrderedDict
def correct_sign(params, secret):
# Sắp xếp theo key
sorted_params = sorted(params.items())
param_str = '&'.join([f"{k}={v}" for k, v in sorted_params])
# Thêm timestamp
param_str += f"×tamp={int(time.time()*1000)}"
param_str += f"&recv_window=5000"
# Tạo signature với HMAC SHA256
signature = hmac.new(
secret.encode('utf-8'),
param_str.encode('utf-8'),
hashlib.sha256
).hexdigest()
return signature
print("✅ Signature phải được tạo từ params đã sắp xếp!")
2. Lỗi "Timestamp expired" - Thời Gian Request Quá Lâu
# ❌ SAI: recv_window quá nhỏ, server từ chối
params = {
"recv_window": "1000", # Chỉ 1 giây!
"timestamp": str(int(time.time() * 1000))
}
✅ ĐÚNG: Đặt recv_window đủ lớn
import time
def create_request_params(api_key, params_dict):
# Luôn dùng timestamp mới nhất
timestamp = int(time.time() * 1000)
return {
**params_dict,
"api_key": api_key,
"timestamp": str(timestamp),
"recv_window": "5000" # 5 giây - đủ để request hoàn tất
}
print("✅ Luôn tạo request với timestamp và recv_window chính xác!")
3. Lỗi "Position not found" - Sai Category Hoặc Symbol
# ❌ SAI: Dùng category sai
response = requests.get(
"https://api.bybit.com/v5/position/list",
params={"category": "spot", "symbol": "BTCUSDT"} # Spot != Linear!
)
✅ ĐÚNG: USDT Perpetual Futures dùng "linear"
response = requests.get(
"https://api.bybit.com/v5/position/list",
params={
"category": "linear", # USDT Perpetual Futures
"symbol": "BTCUSDT"
}
)
Bảng category đúng:
CATEGORIES = {
"linear": "USDT Perpetual Futures",
"inverse": "Inverse Futures",
"spot": "Spot Trading",
"option": "Options"
}
print(f"✅ Category đúng cho {CATEGORIES['linear']}: 'linear'")
4. Lỗi "Insufficient balance" - Không Đủ Tiền
# Kiểm tra số dư trước khi đặt lệnh
def check_balance_before_trade(api_key, api_secret, required_amount):
"""Kiểm tra đủ balance trước khi trade"""
params = {
"accountType": "UNIFIED",
"coin": "USDT",
"api_key": api_key,
"timestamp": str(int(time.time() * 1000)),
"recv_window": "5000"
}
# Tạo signature...
signature = create_signature(params, api_secret)
params["sign"] = signature
response = requests.get(
"https://api.bybit.com/v5/account/wallet-balance",
params=params
).json()
if response.get("retCode") == 0:
available = float(response["result"]["list"][0]["coin"][0]["availableToWithdraw"])
if available >= required_amount:
print(f"✅ Balance đủ: {available} USDT")
return True
else:
print(f"❌ Không đủ tiền! Cần {required_amount}, có {available} USDT")
return False
return False
Sử dụng
if check_balance_before_trade(API_KEY, API_SECRET, 100):
# Tiến hành đặt lệnh...
pass
Giá Và ROI - Tại Sao Nên Sử Dụng API?
| Yếu tố | Chi phí ước tính | ROI mang lại |
|---|---|---|
| Thời gian trade/tháng | 20-40 giờ (thủ công) | 0 giờ (tự động) |
| Số lệnh có thể đặt | 50-100 lệnh/ngày | 10,000+ lệnh/ngày |
| Độ chính xác | 80-90% | 99%+ |
| Cơ hội slippage | Cao (chậm) | Thấp (nhanh) |
| Chi phí API | Miễn phí | 0đ |
Vì Sao Nên Xây Dựng AI Trading Assistant Với HolySheep?
Khi xây dựng bot giao dịch thông minh, bạn cần khả năng xử lý dữ liệu nhanh và chi phí thấp. HolySheep AI là giải pháp tối ưu với:
- 💰 Chi phí cực thấp: Từ $0.42/1M tokens (DeepSeek V3.2) - tiết kiệm 85%+ so với GPT-4.1
- ⚡ Tốc độ phản hồi dưới 50ms - đủ nhanh cho giao dịch real-time
- 💳 Tín dụng miễn phí khi đăng ký - bắt đầu test ngay không tốn phí
- 💬 Hỗ trợ WeChat/Alipay cho người dùng Trung Quốc
Bảng Giá So Sánh Các Nền Tảng AI (2026)
| Nền tảng | Giá/1M tokens | Tốc độ trung bình | Khuyến nghị |
|---|---|---|---|
| HolySheep (DeepSeek V3.2) | $0.42 | <50ms | ⭐⭐⭐⭐⭐ Best choice |
| Gemini 2.5 Flash | $2.50 | ~100ms | ⭐⭐⭐⭐ Tốt |
| Claude Sonnet 4.5 | $15 | ~150ms | ⭐⭐⭐ Khá |
| GPT-4.1 | $8 | ~200ms | ⭐⭐⭐ Đắt |
💡 Mẹo: Với cùng một tác vụ phân tích thị trường, dùng HolySheep chỉ tốn $0.42 thay vì $8 với GPT-4.1 - tiết kiệm 95% chi phí!