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

| Chiến lược Short-Term Scalping Python 1–5 phút

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

Chiến lược Short-Term Scalping Python 1–5 phút

Scalping là một chiến lược giao dịch ngắn hạn, nơi các nhà giao dịch mua và bán tài sản trong khoảng thời gian rất ngắn (từ vài giây đến vài phút) để kiếm lợi nhuận từ những biến động giá nhỏ. Với Python, chúng ta có thể tự động hóa chiến lược này để tận dụng các cơ hội giao dịch nhanh chóng.

Scalping là gì?

Scalping là một kỹ thuật giao dịch tốc độ cao, tập trung vào việc kiếm lợi nhuận từ những biến động giá nhỏ. Đặc điểm chính:

  • Thời gian giữ lệnh ngắn: 1-5 phút, thậm chí vài giây
  • Tần suất giao dịch cao: Nhiều lệnh trong một ngày
  • Lợi nhuận nhỏ mỗi lệnh: Nhưng tích lũy qua nhiều lệnh
  • Yêu cầu tốc độ: Cần phản ứng nhanh với thị trường

Tại sao sử dụng Python cho Scalping?

Python là công cụ lý tưởng cho scalping vì:

  1. Xử lý dữ liệu real-time: Thư viện như ccxt, websocket cho phép nhận dữ liệu giá real-time
  2. Tính toán nhanh: NumPy, Pandas xử lý dữ liệu hiệu quả
  3. Tự động hóa: Bot có thể giao dịch 24/7 không cần giám sát
  4. Backtesting: Kiểm tra chiến lược trên dữ liệu lịch sử

Chiến lược Scalping 1-5 phút

1. Chiến lược Mean Reversion (Hồi quy về trung bình)

Chiến lược này dựa trên giả định rằng giá sẽ quay trở lại mức trung bình sau khi biến động mạnh.

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

class ScalpingBot:
    def __init__(self, exchange_name, api_key, api_secret):
        """
        Khởi tạo bot scalping

        Args:
            exchange_name: Tên sàn (binance, okx, etc.)
            api_key: API key
            api_secret: API secret
        """
        self.exchange = getattr(ccxt, exchange_name)({
            'apiKey': api_key,
            'secret': api_secret,
            'enableRateLimit': True,
        })
        self.symbol = 'BTC/USDT'
        self.timeframe = '1m'  # Khung thời gian 1 phút

    def get_ohlcv_data(self, limit=100):
        """Lấy dữ liệu OHLCV (Open, High, Low, Close, Volume)"""
        ohlcv = self.exchange.fetch_ohlcv(self.symbol, self.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

    def calculate_indicators(self, df):
        """Tính toán các chỉ báo kỹ thuật"""
        # Bollinger Bands
        df['sma_20'] = df['close'].rolling(window=20).mean()
        df['std_20'] = df['close'].rolling(window=20).std()
        df['bb_upper'] = df['sma_20'] + (df['std_20'] * 2)
        df['bb_lower'] = df['sma_20'] - (df['std_20'] * 2)

        # RSI (Relative Strength Index)
        delta = df['close'].diff()
        gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
        loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
        rs = gain / loss
        df['rsi'] = 100 - (100 / (1 + rs))

        # EMA (Exponential Moving Average)
        df['ema_9'] = df['close'].ewm(span=9, adjust=False).mean()
        df['ema_21'] = df['close'].ewm(span=21, adjust=False).mean()

        return df

    def mean_reversion_signal(self, df):
        """
        Tín hiệu Mean Reversion:
        - Mua khi giá chạm dưới Bollinger Lower Band và RSI < 30
        - Bán khi giá chạm trên Bollinger Upper Band và RSI > 70
        """
        latest = df.iloc[-1]
        prev = df.iloc[-2]

        # Tín hiệu mua
        buy_signal = (
            latest['close'] < latest['bb_lower'] and
            latest['rsi'] < 30 and
            prev['rsi'] >= 30  # RSI vừa vượt qua ngưỡng oversold
        )

        # Tín hiệu bán
        sell_signal = (
            latest['close'] > latest['bb_upper'] and
            latest['rsi'] > 70 and
            prev['rsi'] <= 70  # RSI vừa vượt qua ngưỡng overbought
        )

        return buy_signal, sell_signal

    def execute_trade(self, signal_type, amount):
        """Thực hiện giao dịch"""
        try:
            if signal_type == 'buy':
                order = self.exchange.create_market_buy_order(self.symbol, amount)
                print(f"[BUY] {datetime.now()} - Price: {order['price']}, Amount: {amount}")
                return order
            elif signal_type == 'sell':
                order = self.exchange.create_market_sell_order(self.symbol, amount)
                print(f"[SELL] {datetime.now()} - Price: {order['price']}, Amount: {amount}")
                return order
        except Exception as e:
            print(f"Error executing trade: {e}")
            return None

    def run(self):
        """Chạy bot scalping"""
        print("Starting Scalping Bot...")

        while True:
            try:
                # Lấy dữ liệu mới nhất
                df = self.get_ohlcv_data(limit=100)
                df = self.calculate_indicators(df)

                # Kiểm tra tín hiệu
                buy_signal, sell_signal = self.mean_reversion_signal(df)

                # Kiểm tra vị thế hiện tại
                balance = self.exchange.fetch_balance()
                btc_balance = balance['BTC']['free']
                usdt_balance = balance['USDT']['free']

                if buy_signal and usdt_balance > 10:
                    # Mua với 50% số tiền có sẵn
                    amount = (usdt_balance * 0.5) / df.iloc[-1]['close']
                    self.execute_trade('buy', amount)

                elif sell_signal and btc_balance > 0.0001:
                    # Bán toàn bộ BTC
                    self.execute_trade('sell', btc_balance)

                # Chờ 10 giây trước khi kiểm tra lại
                time.sleep(10)

            except Exception as e:
                print(f"Error in main loop: {e}")
                time.sleep(5)

# Sử dụng bot
if __name__ == "__main__":
    # LƯU Ý: Thay thế bằng API key thật của bạn
    bot = ScalpingBot(
        exchange_name='binance',
        api_key='YOUR_API_KEY',
        api_secret='YOUR_API_SECRET'
    )

    # Chạy bot
    # bot.run()

2. Chiến lược Breakout (Phá vỡ)

Chiến lược này tìm kiếm các điểm phá vỡ kháng cự/hỗ trợ để vào lệnh.

class BreakoutScalpingBot(ScalpingBot):
    """Bot scalping sử dụng chiến lược Breakout"""

    def identify_support_resistance(self, df, window=20):
        """Xác định mức hỗ trợ và kháng cự"""
        # Hỗ trợ: giá thấp nhất trong window
        df['support'] = df['low'].rolling(window=window).min()

        # Kháng cự: giá cao nhất trong window
        df['resistance'] = df['high'].rolling(window=window).max()

        return df

    def breakout_signal(self, df):
        """
        Tín hiệu Breakout:
        - Mua khi giá phá vỡ kháng cự với volume tăng
        - Bán khi giá phá vỡ hỗ trợ với volume tăng
        """
        latest = df.iloc[-1]
        prev = df.iloc[-2]

        # Volume trung bình
        avg_volume = df['volume'].rolling(window=20).mean().iloc[-1]

        # Tín hiệu mua: Phá vỡ kháng cự
        buy_signal = (
            latest['close'] > prev['resistance'] and
            latest['volume'] > avg_volume * 1.5 and  # Volume tăng mạnh
            latest['rsi'] < 70  # Không quá overbought
        )

        # Tín hiệu bán: Phá vỡ hỗ trợ
        sell_signal = (
            latest['close'] < prev['support'] and
            latest['volume'] > avg_volume * 1.5 and  # Volume tăng mạnh
            latest['rsi'] > 30  # Không quá oversold
        )

        return buy_signal, sell_signal

3. Chiến lược Momentum (Đà tăng/giảm)

Chiến lược này tận dụng đà tăng/giảm của giá.

class MomentumScalpingBot(ScalpingBot):
    """Bot scalping sử dụng chiến lược Momentum"""

    def momentum_signal(self, df):
        """
        Tín hiệu Momentum:
        - Mua khi EMA ngắn cắt lên EMA dài và RSI > 50
        - Bán khi EMA ngắn cắt xuống EMA dài và RSI < 50
        """
        latest = df.iloc[-1]
        prev = df.iloc[-2]

        # Golden Cross: EMA 9 cắt lên EMA 21
        golden_cross = (
            latest['ema_9'] > latest['ema_21'] and
            prev['ema_9'] <= prev['ema_21']
        )

        # Death Cross: EMA 9 cắt xuống EMA 21
        death_cross = (
            latest['ema_9'] < latest['ema_21'] and
            prev['ema_9'] >= prev['ema_21']
        )

        # Tín hiệu mua
        buy_signal = golden_cross and latest['rsi'] > 50

        # Tín hiệu bán
        sell_signal = death_cross and latest['rsi'] < 50

        return buy_signal, sell_signal

Quản lý rủi ro cho Scalping

Scalping có rủi ro cao, cần quản lý rủi ro chặt chẽ:

1. Stop Loss và Take Profit

class RiskManager:
    """Quản lý rủi ro cho scalping"""

    def __init__(self, stop_loss_pct=0.5, take_profit_pct=1.0):
        """
        Args:
            stop_loss_pct: Dừng lỗ khi giá giảm % (ví dụ: 0.5% = 0.5%)
            take_profit_pct: Chốt lời khi giá tăng % (ví dụ: 1.0% = 1%)
        """
        self.stop_loss_pct = stop_loss_pct
        self.take_profit_pct = take_profit_pct
        self.positions = {}  # Lưu trữ các vị thế đang mở

    def check_stop_loss_take_profit(self, current_price, position):
        """
        Kiểm tra điều kiện stop loss và take profit

        Args:
            current_price: Giá hiện tại
            position: Vị thế {'type': 'buy'/'sell', 'price': entry_price, 'amount': amount}
        """
        entry_price = position['price']

        if position['type'] == 'buy':
            # Vị thế mua
            profit_pct = ((current_price - entry_price) / entry_price) * 100

            if profit_pct <= -self.stop_loss_pct:
                return 'stop_loss'
            elif profit_pct >= self.take_profit_pct:
                return 'take_profit'

        elif position['type'] == 'sell':
            # Vị thế bán (short)
            profit_pct = ((entry_price - current_price) / entry_price) * 100

            if profit_pct <= -self.stop_loss_pct:
                return 'stop_loss'
            elif profit_pct >= self.take_profit_pct:
                return 'take_profit'

        return None

    def calculate_position_size(self, balance, risk_pct=1.0):
        """
        Tính toán kích thước vị thế dựa trên rủi ro

        Args:
            balance: Số dư tài khoản
            risk_pct: % rủi ro cho mỗi lệnh (ví dụ: 1.0% = 1%)
        """
        risk_amount = balance * (risk_pct / 100)
        return risk_amount

2. Giới hạn số lệnh mỗi ngày

class TradeLimiter:
    """Giới hạn số lệnh giao dịch"""

    def __init__(self, max_trades_per_day=50):
        self.max_trades = max_trades_per_day
        self.trades_today = 0
        self.last_reset_date = datetime.now().date()

    def can_trade(self):
        """Kiểm tra xem có thể giao dịch không"""
        today = datetime.now().date()

        # Reset counter mỗi ngày
        if today != self.last_reset_date:
            self.trades_today = 0
            self.last_reset_date = today

        return self.trades_today < self.max_trades

    def record_trade(self):
        """Ghi nhận một lệnh giao dịch"""
        self.trades_today += 1

Best Practices cho Scalping Bot

1. Sử dụng WebSocket cho dữ liệu real-time

import websocket
import json
import threading

class RealTimePriceFeed:
    """Nhận dữ liệu giá real-time qua WebSocket"""

    def __init__(self, symbol, callback):
        """
        Args:
            symbol: Cặp giao dịch (ví dụ: 'btcusdt')
            callback: Hàm xử lý khi nhận được giá mới
        """
        self.symbol = symbol.lower()
        self.callback = callback
        self.ws_url = f"wss://stream.binance.com:9443/ws/{self.symbol}@ticker"

    def on_message(self, ws, message):
        """Xử lý message từ WebSocket"""
        data = json.loads(message)
        current_price = float(data['c'])  # Giá đóng cửa hiện tại
        self.callback(current_price)

    def on_error(self, ws, error):
        print(f"WebSocket error: {error}")

    def on_close(self, ws):
        print("WebSocket closed")

    def start(self):
        """Bắt đầu kết nối WebSocket"""
        ws = websocket.WebSocketApp(
            self.ws_url,
            on_message=self.on_message,
            on_error=self.on_error,
            on_close=self.on_close
        )
        ws.run_forever()

# Sử dụng
def handle_price_update(price):
    print(f"Current price: {price}")

feed = RealTimePriceFeed('btcusdt', handle_price_update)
# feed.start()  # Chạy trong thread riêng

2. Tối ưu hóa tốc độ thực thi

# Sử dụng asyncio cho xử lý bất đồng bộ
import asyncio
import ccxt.async_support as ccxt_async

class AsyncScalpingBot:
    """Bot scalping sử dụng async để tăng tốc độ"""

    def __init__(self, exchange_name, api_key, api_secret):
        self.exchange = getattr(ccxt_async, exchange_name)({
            'apiKey': api_key,
            'secret': api_secret,
        })

    async def get_price_async(self):
        """Lấy giá bất đồng bộ"""
        ticker = await self.exchange.fetch_ticker('BTC/USDT')
        return ticker['last']

    async def execute_trade_async(self, side, amount):
        """Thực hiện giao dịch bất đồng bộ"""
        if side == 'buy':
            order = await self.exchange.create_market_buy_order('BTC/USDT', amount)
        else:
            order = await self.exchange.create_market_sell_order('BTC/USDT', amount)
        return order

    async def run_async(self):
        """Chạy bot bất đồng bộ"""
        while True:
            price = await self.get_price_async()
            # Logic xử lý...
            await asyncio.sleep(1)

3. Logging và Monitoring

import logging
from datetime import datetime

# Cấu hình logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(f'scalping_bot_{datetime.now().strftime("%Y%m%d")}.log'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger('ScalpingBot')

class LoggedScalpingBot(ScalpingBot):
    """Bot scalping với logging đầy đủ"""

    def execute_trade(self, signal_type, amount):
        """Thực hiện giao dịch với logging"""
        try:
            logger.info(f"Attempting {signal_type} order for {amount} {self.symbol}")
            order = super().execute_trade(signal_type, amount)

            if order:
                logger.info(f"Order executed: {order['id']} at price {order['price']}")
            else:
                logger.warning(f"Order failed: {signal_type}")

            return order
        except Exception as e:
            logger.error(f"Error executing trade: {e}", exc_info=True)
            return None

Kết luận

Scalping với Python là một chiến lược phức tạp nhưng có tiềm năng lợi nhuận cao. Điểm quan trọng:

  1. Tốc độ: Sử dụng WebSocket và async để phản ứng nhanh
  2. Quản lý rủi ro: Luôn đặt stop loss và take profit
  3. Backtesting: Kiểm tra chiến lược trên dữ liệu lịch sử trước khi giao dịch thật
  4. Monitoring: Theo dõi bot liên tục và điều chỉnh khi cần

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

  1. Tạo bot scalping đơn giản: Sử dụng chiến lược Mean Reversion với Bollinger Bands
  2. Backtesting: Kiểm tra chiến lược trên dữ liệu lịch sử 1 tháng
  3. Tối ưu hóa: Điều chỉnh các tham số (RSI threshold, Bollinger Bands period) để tối đa hóa lợi nhuận
  4. Thêm quản lý rủi ro: Implement stop loss và take profit tự động

Lưu ý quan trọng

⚠️ Cảnh báo rủi ro: Scalping là chiến lược rủi ro cao, có thể dẫn đến thua lỗ đáng kể. Luôn:

  • Bắt đầu với số tiền nhỏ
  • Test kỹ trên paper trading trước
  • Hiểu rõ rủi ro trước khi đầu tư
  • Không đầu tư nhiều hơn số tiền bạn có thể mất

Tác giả: Hướng Nghiệp Lập Trình
Ngày đăng: 15/03/2025
Chuyên mục: Lập trình Bot Auto Trading, Python Nâng cao