Skip to main content

2 posts tagged with "Binance"

View All Tags

Tự động lấy và trực quan hóa dữ liệu giá tiền điện tử từ Binance với Python

· 5 min read

Giới thiệu

Trong bài viết này, chúng ta sẽ học cách sử dụng Python và thư viện CCXT để lấy dữ liệu giá tiền điện tử từ sàn Binance, sau đó phân tích và trực quan hóa dữ liệu này. Đây là kỹ năng quan trọng cho các nhà giao dịch và phân tích thị trường tiền điện tử.

1. Cài đặt và Cấu hình

1.1. Cài đặt các thư viện cần thiết

pip install ccxt pandas numpy plotly openpyxl

1.2. Kết nối với Binance qua CCXT

import ccxt
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime

# Khởi tạo exchange
exchange = ccxt.binance({
'enableRateLimit': True, # Tự động xử lý rate limit
'options': {
'defaultType': 'spot' # Sử dụng spot trading
}
})

# Kiểm tra kết nối
print(f"Exchange: {exchange.name}")
print(f"Markets: {len(exchange.markets)}")

2. Lấy dữ liệu OHLCV (Candlestick)

2.1. Lấy dữ liệu theo timeframe

def fetch_ohlcv(symbol, timeframe='1h', limit=1000):
"""
Lấy dữ liệu OHLCV từ Binance

Parameters:
- symbol: Cặp giao dịch (ví dụ: 'BTC/USDT')
- timeframe: Khung thời gian ('1m', '5m', '1h', '4h', '1d')
- limit: Số lượng nến muốn lấy (tối đa 1000)
"""
try:
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
return df
except Exception as e:
print(f"Error fetching data: {e}")
return None

# Ví dụ sử dụng
btc_data = fetch_ohlcv('BTC/USDT', '1h', 1000)
print(btc_data.head())

2.2. Lấy nhiều hơn 1000 nến

def fetch_multiple_ohlcv(symbol, timeframe='1h', since=None, limit=1000):
"""
Lấy nhiều hơn 1000 nến bằng cách sử dụng since parameter
"""
all_ohlcv = []
while True:
try:
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, since=since, limit=limit)
if len(ohlcv) == 0:
break
all_ohlcv.extend(ohlcv)
since = ohlcv[-1][0] + 1
except Exception as e:
print(f"Error: {e}")
break
return pd.DataFrame(all_ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])

3. Xử lý và Lưu trữ Dữ liệu

3.1. Xử lý dữ liệu với Pandas

def process_ohlcv_data(df):
"""
Xử lý dữ liệu OHLCV
"""
# Chuyển đổi timestamp
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')

# Tính toán các chỉ báo
df['returns'] = df['close'].pct_change()
df['volatility'] = df['returns'].rolling(window=20).std()

# Tính toán SMA
df['SMA20'] = df['close'].rolling(window=20).mean()
df['SMA50'] = df['close'].rolling(window=50).mean()

return df

# Xử lý dữ liệu
btc_data = process_ohlcv_data(btc_data)

3.2. Lưu trữ dữ liệu

def save_data(df, filename, format='csv'):
"""
Lưu dữ liệu ra file
"""
if format == 'csv':
df.to_csv(f"{filename}.csv", index=False)
elif format == 'excel':
df.to_excel(f"{filename}.xlsx", index=False)
elif format == 'html':
df.to_html(f"{filename}.html", index=False)
else:
print("Unsupported format")

# Ví dụ lưu dữ liệu
save_data(btc_data, 'btc_data', 'csv')
save_data(btc_data, 'btc_data', 'excel')

4. Trực quan hóa dữ liệu với Plotly

4.1. Vẽ biểu đồ nến (Candlestick)

def plot_candlestick(df, title='BTC/USDT Price'):
"""
Vẽ biểu đồ nến với Plotly
"""
fig = go.Figure(data=[go.Candlestick(
x=df['timestamp'],
open=df['open'],
high=df['high'],
low=df['low'],
close=df['close']
)])

# Thêm SMA
fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['SMA20'],
name='SMA20',
line=dict(color='blue')
))

fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['SMA50'],
name='SMA50',
line=dict(color='red')
))

# Cập nhật layout
fig.update_layout(
title=title,
yaxis_title='Price (USDT)',
xaxis_title='Date',
template='plotly_dark'
)

return fig

# Vẽ và hiển thị biểu đồ
fig = plot_candlestick(btc_data)
fig.show()

4.2. Vẽ biểu đồ volume

def plot_volume(df, title='BTC/USDT Volume'):
"""
Vẽ biểu đồ volume
"""
fig = go.Figure(data=[go.Bar(
x=df['timestamp'],
y=df['volume'],
name='Volume'
)])

fig.update_layout(
title=title,
yaxis_title='Volume',
xaxis_title='Date',
template='plotly_dark'
)

return fig

# Vẽ và hiển thị biểu đồ volume
volume_fig = plot_volume(btc_data)
volume_fig.show()

5. Lấy giá hiện tại (Ticker)

def get_current_price(symbol):
"""
Lấy giá hiện tại của một cặp giao dịch
"""
try:
ticker = exchange.fetch_ticker(symbol)
return {
'symbol': symbol,
'last': ticker['last'],
'bid': ticker['bid'],
'ask': ticker['ask'],
'volume': ticker['baseVolume'],
'timestamp': datetime.fromtimestamp(ticker['timestamp']/1000)
}
except Exception as e:
print(f"Error fetching ticker: {e}")
return None

# Ví dụ lấy giá BTC/USDT
btc_ticker = get_current_price('BTC/USDT')
print(btc_ticker)

6. Mở rộng: Các tính năng nâng cao

6.1. Lấy dữ liệu từ nhiều cặp giao dịch

def fetch_multiple_symbols(symbols, timeframe='1h', limit=1000):
"""
Lấy dữ liệu từ nhiều cặp giao dịch
"""
data = {}
for symbol in symbols:
data[symbol] = fetch_ohlcv(symbol, timeframe, limit)
return data

# Ví dụ lấy dữ liệu nhiều cặp
symbols = ['BTC/USDT', 'ETH/USDT', 'BNB/USDT']
multi_data = fetch_multiple_symbols(symbols)

6.2. Tính toán tương quan giữa các cặp

def calculate_correlation(data_dict):
"""
Tính toán tương quan giữa các cặp giao dịch
"""
# Tạo DataFrame với giá đóng cửa của các cặp
closes = pd.DataFrame()
for symbol, df in data_dict.items():
closes[symbol] = df['close']

# Tính toán ma trận tương quan
correlation = closes.corr()
return correlation

# Tính và hiển thị tương quan
correlation = calculate_correlation(multi_data)
print(correlation)

Kết luận

Trong bài viết này, chúng ta đã học cách:

  1. Kết nối với Binance qua CCXT
  2. Lấy và xử lý dữ liệu OHLCV
  3. Lưu trữ dữ liệu dưới nhiều định dạng
  4. Trực quan hóa dữ liệu với Plotly
  5. Thực hiện các phân tích nâng cao

Đây là nền tảng cơ bản để bạn có thể tự động hóa việc phân tích dữ liệu tiền điện tử. Bạn có thể mở rộng thêm bằng cách:

  • Thêm các chỉ báo kỹ thuật
  • Tạo chiến lược giao dịch tự động
  • Phân tích sentiment từ social media
  • Tích hợp với các nguồn dữ liệu khác

Tài liệu tham khảo

  1. CCXT Documentation
  2. Binance API Documentation
  3. Pandas Documentation
  4. Plotly Documentation

Liên hệ

Nếu bạn có thắc mắc hoặc cần hỗ trợ thêm, hãy liên hệ:

Kết nối Python với API Binance để lấy dữ liệu realtime

· 4 min read
admin

Binance là một trong những sàn giao dịch tiền điện tử lớn nhất thế giới, cung cấp API mạnh mẽ cho phép các nhà phát triển xây dựng các ứng dụng giao dịch tự động. Bài viết này sẽ hướng dẫn bạn cách kết nối Python với API Binance để lấy dữ liệu realtime và thực hiện các giao dịch.

Kết nối Python với API Binance

1. Cài đặt thư viện cần thiết

Đầu tiên, chúng ta cần cài đặt thư viện python-binance:

pip install python-binance

2. Tạo API Key và Secret Key

  1. Đăng nhập vào tài khoản Binance
  2. Vào phần API Management
  3. Tạo API Key mới
  4. Lưu lại API Key và Secret Key

3. Kết nối với API Binance

from binance.client import Client
from binance.enums import *

# Khởi tạo client
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_API_SECRET'
client = Client(api_key, api_secret)

# Kiểm tra kết nối
print(client.get_system_status())

4. Lấy dữ liệu thị trường

4.1. Lấy giá hiện tại

# Lấy giá hiện tại của BTC/USDT
btc_price = client.get_symbol_ticker(symbol="BTCUSDT")
print(f"Giá BTC/USDT: {btc_price['price']}")

REST API - Lấy dữ liệu lịch sử

4.2. Lấy dữ liệu lịch sử

# Lấy dữ liệu kline/candlestick
klines = client.get_klines(
symbol='BTCUSDT',
interval=Client.KLINE_INTERVAL_1HOUR,
limit=100
)

# Chuyển đổi dữ liệu thành DataFrame
import pandas as pd
df = pd.DataFrame(klines, columns=[
'timestamp', 'open', 'high', 'low', 'close', 'volume',
'close_time', 'quote_asset_volume', 'number_of_trades',
'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore'
])

Kline/Candlestick Data

5. Sử dụng WebSocket để lấy dữ liệu realtime

from binance.websockets import BinanceSocketManager
from binance.client import Client

def process_message(msg):
print(f"Giá mới: {msg['p']}")

# Khởi tạo WebSocket
bm = BinanceSocketManager(client)
conn_key = bm.start_symbol_ticker_socket('BTCUSDT', process_message)
bm.start()

WebSocket - Dữ liệu realtime

6. Lấy thông tin Order Book

# Lấy order book
depth = client.get_order_book(symbol='BTCUSDT', limit=5)
print("Bids (Lệnh mua):")
for bid in depth['bids']:
print(f"Giá: {bid[0]}, Số lượng: {bid[1]}")
print("\nAsks (Lệnh bán):")
for ask in depth['asks']:
print(f"Giá: {ask[0]}, Số lượng: {ask[1]}")

Order Book

7. Thực hiện giao dịch

7.1. Đặt lệnh thị trường

# Đặt lệnh mua thị trường
order = client.create_order(
symbol='BTCUSDT',
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=0.001
)

7.2. Đặt lệnh giới hạn

# Đặt lệnh mua giới hạn
order = client.create_order(
symbol='BTCUSDT',
side=SIDE_BUY,
type=ORDER_TYPE_LIMIT,
timeInForce=TIME_IN_FORCE_GTC,
quantity=0.001,
price='30000'
)

Order Types

8. Quản lý tài khoản

8.1. Lấy thông tin tài khoản

# Lấy thông tin tài khoản
account = client.get_account()
for balance in account['balances']:
if float(balance['free']) > 0 or float(balance['locked']) > 0:
print(f"Asset: {balance['asset']}")
print(f"Free: {balance['free']}")
print(f"Locked: {balance['locked']}")

Account Balance

8.2. Lấy lịch sử giao dịch

# Lấy lịch sử giao dịch
trades = client.get_my_trades(symbol='BTCUSDT')
for trade in trades:
print(f"Time: {trade['time']}")
print(f"Price: {trade['price']}")
print(f"Quantity: {trade['qty']}")
print(f"Side: {trade['isBuyer']}")

Trading Volume

9. Xử lý lỗi và Rate Limits

9.1. Xử lý lỗi

from binance.exceptions import BinanceAPIException

try:
# Thực hiện request
client.get_account()
except BinanceAPIException as e:
print(f"Lỗi API: {e.status_code} - {e.message}")

Error Handling

9.2. Rate Limits

# Kiểm tra rate limits
rate_limits = client.get_exchange_info()
for limit in rate_limits['rateLimits']:
print(f"Limit Type: {limit['rateLimitType']}")
print(f"Interval: {limit['interval']}")
print(f"Limit: {limit['limit']}")

API Rate Limits

10. Ví dụ hoàn chỉnh: Bot giao dịch đơn giản

from binance.client import Client
from binance.enums import *
import time

def trading_bot():
# Khởi tạo client
client = Client(api_key, api_secret)

while True:
try:
# Lấy giá hiện tại
ticker = client.get_symbol_ticker(symbol="BTCUSDT")
current_price = float(ticker['price'])

# Lấy dữ liệu kline
klines = client.get_klines(
symbol='BTCUSDT',
interval=Client.KLINE_INTERVAL_1HOUR,
limit=100
)

# Tính toán chỉ báo (ví dụ: SMA)
closes = [float(k[4]) for k in klines]
sma20 = sum(closes[-20:]) / 20

# Logic giao dịch đơn giản
if current_price > sma20:
# Đặt lệnh mua
order = client.create_order(
symbol='BTCUSDT',
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=0.001
)
elif current_price < sma20:
# Đặt lệnh bán
order = client.create_order(
symbol='BTCUSDT',
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=0.001
)

# Đợi 1 phút
time.sleep(60)

except Exception as e:
print(f"Lỗi: {e}")
time.sleep(60)

if __name__ == "__main__":
trading_bot()

Kết luận

Trong bài viết này, chúng ta đã học cách:

  1. Cài đặt và cấu hình python-binance
  2. Lấy dữ liệu thị trường qua REST API
  3. Sử dụng WebSocket để lấy dữ liệu realtime
  4. Thực hiện các giao dịch
  5. Quản lý tài khoản
  6. Xử lý lỗi và rate limits
  7. Xây dựng bot giao dịch đơn giản

Lưu ý quan trọng:

  • Luôn bảo vệ API Key và Secret Key
  • Tuân thủ rate limits của Binance
  • Test kỹ trên tài khoản testnet trước khi giao dịch thật
  • Xử lý lỗi một cách cẩn thận
  • Không nên đầu tư quá nhiều vào một chiến lược giao dịch

Tài liệu tham khảo