Bài viết gần đây

| Phân tích chênh lệch giá tiền điện tử giữa các sàn giao dịch với Python

Được viết bởi thanhdt vào ngày 13/11/2025 lúc 06:12 | 6 lượt xem

Phân tích chênh lệch giá tiền điện tử giữa các sàn giao dịch với Python

Giới thiệu

Chênh lệch giá (Arbitrage) là một chiến lược giao dịch phổ biến trong thị trường tiền điện tử. Trong bài viết này, chúng ta sẽ học cách sử dụng Python và CCXT để phân tích chênh lệch giá giữa các sàn giao dịch khác nhau.

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

1.1. Cài đặt thư viện

pip install ccxt pandas numpy plotly

1.2. Khởi tạo kết nối với các sàn

import ccxt
import pandas as pd
import numpy as np
from datetime import datetime

# Khởi tạo các sàn giao dịch
exchanges = {
    'binance': ccxt.binance(),
    'coinbase': ccxt.coinbase(),
    'kraken': ccxt.kraken(),
    'kucoin': ccxt.kucoin()
}

# Cấu hình chung
for exchange in exchanges.values():
    exchange.enableRateLimit = True

2. Lấy dữ liệu giá từ nhiều sàn

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

def get_current_prices(symbol, exchanges):
    """
    Lấy giá hiện tại của một cặp giao dịch từ nhiều sàn

    Parameters:
    - symbol: Cặp giao dịch (ví dụ: 'BTC/USDT')
    - exchanges: Dictionary chứa các exchange objects
    """
    prices = {}
    for name, exchange in exchanges.items():
        try:
            ticker = exchange.fetch_ticker(symbol)
            prices[name] = {
                'bid': ticker['bid'],
                'ask': ticker['ask'],
                'last': ticker['last'],
                'timestamp': datetime.fromtimestamp(ticker['timestamp']/1000)
            }
        except Exception as e:
            print(f"Error fetching {symbol} from {name}: {e}")
    return prices

# Ví dụ sử dụng
symbol = 'BTC/USDT'
prices = get_current_prices(symbol, exchanges)

2.2. Tính toán chênh lệch giá

def calculate_arbitrage_opportunities(prices):
    """
    Tính toán cơ hội arbitrage giữa các sàn
    """
    opportunities = []

    # Tạo ma trận chênh lệch
    exchanges = list(prices.keys())
    for i in range(len(exchanges)):
        for j in range(i+1, len(exchanges)):
            exchange1 = exchanges[i]
            exchange2 = exchanges[j]

            # Tính chênh lệch mua-bán
            spread1 = prices[exchange1]['ask'] - prices[exchange2]['bid']
            spread2 = prices[exchange2]['ask'] - prices[exchange1]['bid']

            # Tính phần trăm chênh lệch
            spread1_pct = (spread1 / prices[exchange2]['bid']) * 100
            spread2_pct = (spread2 / prices[exchange1]['bid']) * 100

            opportunities.append({
                'exchange1': exchange1,
                'exchange2': exchange2,
                'spread1': spread1,
                'spread2': spread2,
                'spread1_pct': spread1_pct,
                'spread2_pct': spread2_pct,
                'timestamp': datetime.now()
            })

    return pd.DataFrame(opportunities)

# Tính toán cơ hội arbitrage
arbitrage_df = calculate_arbitrage_opportunities(prices)

3. Phân tích và Trực quan hóa

3.1. Phân tích chênh lệch

def analyze_arbitrage(arbitrage_df, min_spread_pct=0.5):
    """
    Phân tích cơ hội arbitrage

    Parameters:
    - arbitrage_df: DataFrame chứa dữ liệu chênh lệch
    - min_spread_pct: Phần trăm chênh lệch tối thiểu để xem xét
    """
    # Lọc các cơ hội có chênh lệch đáng kể
    significant_opportunities = arbitrage_df[
        (arbitrage_df['spread1_pct'] > min_spread_pct) |
        (arbitrage_df['spread2_pct'] > min_spread_pct)
    ]

    # Sắp xếp theo chênh lệch
    significant_opportunities = significant_opportunities.sort_values(
        by=['spread1_pct', 'spread2_pct'],
        ascending=False
    )

    return significant_opportunities

# Phân tích cơ hội
opportunities = analyze_arbitrage(arbitrage_df)
print(opportunities)

3.2. Trực quan hóa chênh lệch

def plot_arbitrage_opportunities(arbitrage_df):
    """
    Vẽ biểu đồ chênh lệch giá
    """
    import plotly.graph_objects as go

    # Tạo biểu đồ
    fig = go.Figure()

    # Thêm các cột cho spread1 và spread2
    fig.add_trace(go.Bar(
        name='Spread 1',
        x=arbitrage_df['exchange1'] + ' vs ' + arbitrage_df['exchange2'],
        y=arbitrage_df['spread1_pct'],
        text=arbitrage_df['spread1_pct'].round(2),
        textposition='auto',
    ))

    fig.add_trace(go.Bar(
        name='Spread 2',
        x=arbitrage_df['exchange1'] + ' vs ' + arbitrage_df['exchange2'],
        y=arbitrage_df['spread2_pct'],
        text=arbitrage_df['spread2_pct'].round(2),
        textposition='auto',
    ))

    # Cập nhật layout
    fig.update_layout(
        title='Arbitrage Opportunities Between Exchanges',
        xaxis_title='Exchange Pairs',
        yaxis_title='Spread Percentage (%)',
        barmode='group',
        template='plotly_dark'
    )

    return fig

# Vẽ biểu đồ
fig = plot_arbitrage_opportunities(arbitrage_df)
fig.show()

4. Theo dõi chênh lệch theo thời gian thực

def monitor_arbitrage(symbol, exchanges, interval=60, duration=3600):
    """
    Theo dõi chênh lệch giá theo thời gian thực

    Parameters:
    - symbol: Cặp giao dịch
    - exchanges: Dictionary chứa các exchange objects
    - interval: Khoảng thời gian giữa các lần kiểm tra (giây)
    - duration: Thời gian theo dõi (giây)
    """
    import time
    from datetime import datetime, timedelta

    end_time = datetime.now() + timedelta(seconds=duration)
    opportunities_history = []

    while datetime.now() < end_time:
        try:
            # Lấy giá hiện tại
            prices = get_current_prices(symbol, exchanges)

            # Tính toán cơ hội arbitrage
            arbitrage_df = calculate_arbitrage_opportunities(prices)

            # Phân tích cơ hội
            opportunities = analyze_arbitrage(arbitrage_df)

            # Lưu vào lịch sử
            opportunities_history.append({
                'timestamp': datetime.now(),
                'opportunities': opportunities
            })

            # In thông tin
            print(f"nTime: {datetime.now()}")
            print(opportunities)

            # Đợi đến lần kiểm tra tiếp theo
            time.sleep(interval)

        except Exception as e:
            print(f"Error in monitoring: {e}")
            time.sleep(interval)

    return pd.DataFrame(opportunities_history)

# Bắt đầu theo dõi
# monitor_arbitrage('BTC/USDT', exchanges)

5. Tính toán lợi nhuận tiềm năng

def calculate_potential_profit(opportunity, amount=1.0):
    """
    Tính toán lợi nhuận tiềm năng từ cơ hội arbitrage

    Parameters:
    - opportunity: Dictionary chứa thông tin cơ hội arbitrage
    - amount: Số lượng coin giao dịch
    """
    # Tính lợi nhuận cho cả hai hướng
    profit1 = amount * opportunity['spread1']
    profit2 = amount * opportunity['spread2']

    # Tính phí giao dịch (ước tính)
    fee_rate = 0.001  # 0.1%
    fees = amount * fee_rate * 2  # Phí mua và bán

    # Lợi nhuận thực tế
    net_profit1 = profit1 - fees
    net_profit2 = profit2 - fees

    return {
        'gross_profit1': profit1,
        'gross_profit2': profit2,
        'fees': fees,
        'net_profit1': net_profit1,
        'net_profit2': net_profit2
    }

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 nhiều sàn giao dịch qua CCXT
  2. Lấy và so sánh giá từ các sàn khác nhau
  3. Tính toán cơ hội arbitrage
  4. Trực quan hóa chênh lệch giá
  5. Theo dõi chênh lệch theo thời gian thực

Lưu ý quan trọng:

  • Cần tính đến phí giao dịch và phí rút tiền
  • Xem xét thời gian xử lý giao dịch
  • Kiểm tra giới hạn giao dịch của các sàn
  • Đảm bảo đủ số dư trên các sàn

Tài liệu tham khảo

  1. CCXT Documentation
  2. Binance API Documentation
  3. Coinbase API Documentation
  4. Kraken API 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ệ: