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

| Biến và Hàm trong Python – Ứng dụng trong Bot Auto Trading

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


Biến và Hàm trong Python – Ứng dụng trong Bot Auto Trading

Python là một ngôn ngữ lập trình mạnh mẽ, đặc biệt phù hợp cho việc xây dựng các ứng dụng tài chính và bot tự động giao dịch. Trong bài viết này, chúng ta sẽ tìm hiểu về biếnhàm trong Python, và cách áp dụng chúng vào việc xây dựng bot auto trading.

1. Biến trong Python

1.1. Khái niệm về biến

Biến trong Python là một tên được sử dụng để lưu trữ dữ liệu. Khác với nhiều ngôn ngữ lập trình khác, Python không yêu cầu khai báo kiểu dữ liệu trước khi sử dụng.

# Khai báo biến đơn giản
symbol = "BTCUSDT"  # Chuỗi ký tự
price = 45000.50    # Số thực
quantity = 0.1      # Số thực
is_active = True    # Boolean

1.2. Các kiểu dữ liệu cơ bản

Trong bot trading, chúng ta thường làm việc với các kiểu dữ liệu sau:

# String - Tên cặp giao dịch
trading_pair = "ETHUSDT"

# Float - Giá cả, số lượng
current_price = 2500.75
order_amount = 0.5

# Integer - Số lượng đơn hàng
order_count = 10

# Boolean - Trạng thái bot
bot_running = True
auto_trade_enabled = False

# List - Danh sách các lệnh
pending_orders = ["order1", "order2", "order3"]

# Dictionary - Thông tin đơn hàng
order_info = {
    "symbol": "BTCUSDT",
    "price": 45000,
    "quantity": 0.1,
    "side": "BUY"
}

1.3. Ứng dụng biến trong Bot Trading

Trong bot auto trading, biến được sử dụng để lưu trữ:

  • Thông tin giao dịch: Giá, khối lượng, cặp giao dịch
  • Cấu hình bot: API keys, tham số chiến lược
  • Trạng thái: Bot đang chạy hay dừng, số lệnh đang chờ
# Cấu hình bot
API_KEY = "your_api_key"
API_SECRET = "your_api_secret"
BASE_URL = "https://api.binance.com"

# Tham số chiến lược
MAX_POSITION_SIZE = 1000.0  # USD
STOP_LOSS_PERCENT = 2.0     # 2%
TAKE_PROFIT_PERCENT = 5.0   # 5%

# Trạng thái bot
bot_status = "running"
total_trades = 0
profit_loss = 0.0

2. Hàm trong Python

2.1. Khái niệm về hàm

Hàm (function) là một khối code có thể tái sử dụng, giúp tổ chức code tốt hơn và tránh lặp lại.

def calculate_profit(entry_price, exit_price, quantity):
    """Tính toán lợi nhuận từ một giao dịch"""
    profit = (exit_price - entry_price) * quantity
    return profit

# Sử dụng hàm
profit = calculate_profit(45000, 46000, 0.1)
print(f"Lợi nhuận: ${profit}")

2.2. Cấu trúc hàm

def function_name(parameters):
    """
    Docstring - Mô tả hàm
    """
    # Code thực thi
    return result

2.3. Các loại hàm trong Bot Trading

Hàm tính toán

def calculate_position_size(balance, risk_percent):
    """Tính toán kích thước vị thế dựa trên số dư và % rủi ro"""
    position_size = balance * (risk_percent / 100)
    return position_size

def calculate_stop_loss_price(entry_price, stop_loss_percent):
    """Tính giá stop loss"""
    stop_loss = entry_price * (1 - stop_loss_percent / 100)
    return stop_loss

def calculate_take_profit_price(entry_price, take_profit_percent):
    """Tính giá take profit"""
    take_profit = entry_price * (1 + take_profit_percent / 100)
    return take_profit

Hàm xử lý dữ liệu

def get_current_price(symbol):
    """Lấy giá hiện tại của cặp giao dịch"""
    # Giả lập API call
    # Trong thực tế, bạn sẽ gọi API của sàn giao dịch
    prices = {
        "BTCUSDT": 45000.50,
        "ETHUSDT": 2500.75
    }
    return prices.get(symbol, 0)

def format_order_info(order):
    """Định dạng thông tin đơn hàng"""
    return f"Symbol: {order['symbol']}, Price: ${order['price']}, Quantity: {order['quantity']}"

Hàm kiểm tra điều kiện

def should_buy(current_price, ma_20, ma_50):
    """Kiểm tra điều kiện mua (ví dụ: MA20 cắt lên MA50)"""
    if ma_20 > ma_50 and current_price > ma_20:
        return True
    return False

def should_sell(current_price, entry_price, stop_loss, take_profit):
    """Kiểm tra điều kiện bán"""
    if current_price <= stop_loss:
        return "STOP_LOSS"
    elif current_price >= take_profit:
        return "TAKE_PROFIT"
    return None

3. Ứng dụng thực tế: Xây dựng Bot Trading đơn giản

3.1. Cấu trúc Bot cơ bản

# Biến toàn cục
BALANCE = 1000.0  # Số dư ban đầu (USD)
RISK_PERCENT = 2.0  # Rủi ro mỗi lệnh (%)
STOP_LOSS_PERCENT = 2.0  # Stop loss (%)
TAKE_PROFIT_PERCENT = 5.0  # Take profit (%)

# Hàm tính toán
def calculate_order_size(balance, risk_percent, entry_price):
    """Tính kích thước lệnh"""
    risk_amount = balance * (risk_percent / 100)
    quantity = risk_amount / entry_price
    return round(quantity, 4)

def calculate_stop_loss(entry_price, percent):
    """Tính giá stop loss"""
    return entry_price * (1 - percent / 100)

def calculate_take_profit(entry_price, percent):
    """Tính giá take profit"""
    return entry_price * (1 + percent / 100)

# Hàm giao dịch
def place_buy_order(symbol, price, quantity):
    """Đặt lệnh mua"""
    order = {
        "symbol": symbol,
        "side": "BUY",
        "price": price,
        "quantity": quantity,
        "status": "FILLED"
    }
    print(f"✅ Đã mua {quantity} {symbol} ở giá ${price}")
    return order

def place_sell_order(symbol, price, quantity):
    """Đặt lệnh bán"""
    order = {
        "symbol": symbol,
        "side": "SELL",
        "price": price,
        "quantity": quantity,
        "status": "FILLED"
    }
    print(f"✅ Đã bán {quantity} {symbol} ở giá ${price}")
    return order

# Hàm quản lý giao dịch
def execute_trade(symbol, entry_price, balance):
    """Thực hiện một giao dịch hoàn chỉnh"""
    # Tính toán kích thước lệnh
    quantity = calculate_order_size(balance, RISK_PERCENT, entry_price)

    # Tính stop loss và take profit
    stop_loss = calculate_stop_loss(entry_price, STOP_LOSS_PERCENT)
    take_profit = calculate_take_profit(entry_price, TAKE_PROFIT_PERCENT)

    # Đặt lệnh mua
    buy_order = place_buy_order(symbol, entry_price, quantity)

    # Giả lập giá thay đổi
    current_price = entry_price * 1.06  # Giá tăng 6%

    # Kiểm tra điều kiện bán
    if current_price >= take_profit:
        sell_order = place_sell_order(symbol, take_profit, quantity)
        profit = (take_profit - entry_price) * quantity
        print(f"💰 Lợi nhuận: ${profit:.2f}")
        return profit
    elif current_price <= stop_loss:
        sell_order = place_sell_order(symbol, stop_loss, quantity)
        loss = (stop_loss - entry_price) * quantity
        print(f"📉 Lỗ: ${loss:.2f}")
        return loss

    return 0

# Chương trình chính
if __name__ == "__main__":
    # Thông tin giao dịch
    symbol = "BTCUSDT"
    entry_price = 45000.0
    balance = BALANCE

    # Thực hiện giao dịch
    result = execute_trade(symbol, entry_price, balance)

    # Cập nhật số dư
    new_balance = balance + result
    print(f"\n📊 Số dư ban đầu: ${balance}")
    print(f"📊 Số dư mới: ${new_balance:.2f}")
    print(f"📊 Thay đổi: ${result:.2f} ({result/balance*100:.2f}%)")

3.2. Bot với nhiều giao dịch

def run_trading_bot(symbols, initial_balance):
    """Chạy bot trading cho nhiều cặp giao dịch"""
    balance = initial_balance
    trades = []

    for symbol in symbols:
        # Lấy giá hiện tại (giả lập)
        current_price = get_current_price(symbol)

        # Kiểm tra điều kiện mua
        if should_buy(current_price, current_price * 0.99, current_price * 0.98):
            result = execute_trade(symbol, current_price, balance)
            trades.append({
                "symbol": symbol,
                "result": result
            })
            balance += result

    # Tổng kết
    total_profit = sum(t["result"] for t in trades)
    print(f"\n📈 Tổng số giao dịch: {len(trades)}")
    print(f"💰 Tổng lợi nhuận: ${total_profit:.2f}")
    print(f"📊 Số dư cuối: ${balance:.2f}")

    return balance

# Sử dụng
symbols = ["BTCUSDT", "ETHUSDT", "BNBUSDT"]
final_balance = run_trading_bot(symbols, 1000.0)

4. Best Practices

4.1. Đặt tên biến rõ ràng

# ❌ Tệ
x = 45000
y = 0.1
z = True

# ✅ Tốt
btc_price = 45000
order_quantity = 0.1
is_trading_active = True

4.2. Sử dụng hàm để tái sử dụng code

# ❌ Tệ - Lặp lại code
profit1 = (46000 - 45000) * 0.1
profit2 = (2500 - 2400) * 1.0
profit3 = (300 - 290) * 10.0

# ✅ Tốt - Dùng hàm
def calculate_profit(entry, exit, quantity):
    return (exit - entry) * quantity

profit1 = calculate_profit(45000, 46000, 0.1)
profit2 = calculate_profit(2400, 2500, 1.0)
profit3 = calculate_profit(290, 300, 10.0)

4.3. Sử dụng docstring

def calculate_risk_reward_ratio(entry_price, stop_loss, take_profit):
    """
    Tính tỷ lệ Risk/Reward

    Args:
        entry_price: Giá vào lệnh
        stop_loss: Giá stop loss
        take_profit: Giá take profit

    Returns:
        Tỷ lệ Risk/Reward (float)
    """
    risk = entry_price - stop_loss
    reward = take_profit - entry_price
    return reward / risk if risk > 0 else 0

5. Kết luận

Biến và hàm là những khái niệm cơ bản nhưng cực kỳ quan trọng trong Python. Trong bot auto trading:

  • Biến giúp lưu trữ và quản lý dữ liệu giao dịch
  • Hàm giúp tổ chức code, tái sử dụng logic, và dễ bảo trì

Việc nắm vững biến và hàm sẽ giúp bạn xây dựng các bot trading phức tạp và hiệu quả hơn.

6. Bài tập thực hành

  1. Viết hàm tính toán số lượng coin có thể mua với số tiền cho trước
  2. Viết hàm kiểm tra điều kiện vào lệnh dựa trên giá và moving average
  3. Xây dựng một bot đơn giản có thể tự động mua/bán dựa trên điều kiện bạn đặt ra

Lưu ý: Bài viết này chỉ mang tính chất giáo dục. Giao dịch tài chính có rủi ro, hãy luôn thận trọng và chỉ đầu tư số tiền bạn có thể chấp nhận mất.