| Quản Lý Risk Trong Backend FastAPI Cho Bot Auto Trading

Được viết bởi thanhdt vào ngày 09/12/2025 lúc 16:47 | 131 lượt xem

Quản Lý Risk (TP/SL, Drawdown…) Trong Backend FastAPI Cho Bot Auto Trading

https://d1rwhvwstyk9gu.cloudfront.net/2022/07/Architecture-for-Algorithmic-Trading-1.png?utm_source=chatgpt.com
https://d1rwhvwstyk9gu.cloudfront.net/2024/03/backtestdiagram2.jpeg?utm_source=chatgpt.com
https://www.solulab.com/wp-content/uploads/2024/10/How-to-Create-Crypto-Trading-Bot.jpg?utm_source=chatgpt.com

Trong một hệ thống Bot Auto Trading (Forex – Crypto – Chứng khoán), quản lý rủi ro (Risk Management) là yếu tố quan trọng nhất quyết định sự sống còn của tài khoản.
Ngay cả chiến lược tốt nhất cũng sẽ thua nếu backend không có cơ chế:

  • Tự động đóng lệnh khi đạt TP/SL
  • Kiểm soát drawdown tài khoản
  • Giới hạn số lệnh
  • Kiểm tra vị thế
  • Chống mở lệnh trùng
  • Ngăn bot chạy trong vùng rủi ro

Backend FastAPI chính là nơi tất cả logic risk được xử lý, đảm bảo bot chạy an toàn, chính xác và không vượt “giới hạn rủi ro” mà trader đã đặt ra.


1. Tại sao Risk Management phải nằm ở Backend FastAPI?

https://www.researchgate.net/profile/Stefano-Pinardi/publication/221450971/figure/fig1/AS%3A669093661270026%401536535768507/Risk-Management-Architecture.jpg?utm_source=chatgpt.com

Hãy nhớ:

Bot Auto Trading không được phép dựa 100% vào tín hiệu.
Backend phải kiểm soát mọi nguy cơ có thể gây cháy tài khoản.

Vì sao backend FastAPI phải gánh phần risk?

  • Webhook TradingView chỉ gửi tín hiệu — không biết trạng thái tài khoản
  • Thuật toán phân tích (AI / indicator / SMC) không biết drawdown
  • Các lệnh trên sàn có thể bị:
    • Từ chối
    • Trượt giá
    • Không set được TP/SL qua API
    • Lệch chế độ position mode (Hedge/OneWay)

Chỉ có backend FastAPI mới có khả năng:

  • Kiểm tra trạng thái tài khoản thật
  • Quản lý TP/SL
  • Tự động đóng lệnh nếu đạt điều kiện
  • Chặn lệnh nguy hiểm
  • Kiểm tra lịch sử lệnh
  • Sync trạng thái bot — server — exchange

2. TP/SL – Cách Backend FastAPI xử lý lệnh an toàn

Cấp độ 1 – Gửi TP/SL trực tiếp qua API sàn

Ví dụ với ccxt:

@app.post("/order")
async def create_order(symbol: str, side: str, amount: float, tp: float, sl: float):
    order = await exchange.create_order(
        symbol,
        "market",
        side,
        amount
    )

    # Gắn TP/SL nếu sàn hỗ trợ đặt ngay
    await exchange.create_order(symbol, "takeProfit", "sell", amount, tp)
    await exchange.create_order(symbol, "stopLoss", "sell", amount, sl)

    return {"order": order}

Ưu điểm: đơn giản, nhanh
Nhược điểm: nhiều sàn từ chối TP/SL offline hoặc API lỗi
→ bot phải có cơ chế fallback.


Cấp độ 2 – Polling tự động kiểm tra TP/SL

Khi API không đặt được TP/SL (Bitget thường báo lỗi):

“The V1 API has been decommissioned. Bot sẽ tự động kiểm tra TP/SL bằng polling…”

FastAPI xử lý:

@app.on_event("startup")
async def start_background_tasks():
    asyncio.create_task(watch_positions())

async def watch_positions():
    while True:
        positions = await exchange.fetch_positions()
        for pos in positions:
            if pos["unrealizedPnl"] >= TARGET_PROFIT:
                await exchange.close_position(pos["symbol"])
            if pos["unrealizedPnl"] <= -MAX_LOSS:
                await exchange.close_position(pos["symbol"])
        await asyncio.sleep(5)

Bot đảm bảo không để lệnh chạy vượt quá mức rủi ro.

https://altrady-strapi.s3.eu-west-1.amazonaws.com/SL_and_TP_levels_72d924f0bf.png?utm_source=chatgpt.com
https://www.researchgate.net/publication/336337716/figure/fig1/AS%3A811717189713920%401570539867494/Trading-strategy-flowchart.png?utm_source=chatgpt.com

3. Quản lý Drawdown – Nền tảng sống còn của Bot

Drawdown gồm 2 loại:

  1. Daily Drawdown – giảm % trong ngày
  2. Total Drawdown – giảm % từ vốn ban đầu

Backend FastAPI phải tự động:

  • Theo dõi số dư tài khoản
  • So sánh với ngưỡng DD
  • Dừng bot nếu vượt ngưỡng
  • Gửi cảnh báo (Telegram/Zalo/Email)
  • Chặn mọi lệnh mới

Ví dụ kiểm tra Daily Drawdown

async def check_drawdown():
    balance = await get_balance()
    loss_percent = (balance - START_BALANCE) / START_BALANCE * 100

    if loss_percent <= -MAX_DD_DAILY:
        await disable_all_bots()
        return {"status": "STOP", "reason": "Daily drawdown exceeded"}

    return {"status": "OK"}
https://cptmarkets.com/static/images/trade/academy/articles/article6.2.jpg?utm_source=chatgpt.com
https://4proptrader.com/c/files/image-20250930110000-2.jpeg?utm_source=chatgpt.com

4. Giới hạn số lệnh – Chống overtrade / spam lệnh

Một bot rủi ro nhất là bot spam lệnh liên tục.

Backend FastAPI phải kiểm tra:

  • Số lệnh mở hiện tại
  • Số lệnh trong khung thời gian (1H, 4H, 1D)
  • Chặn nếu đã vượt giới hạn
async def check_order_limits():
    open_orders = await exchange.fetch_open_orders()
    if len(open_orders) >= MAX_ORDERS:
        return False
    return True

5. Kiểm tra vị thế – Chống mở lệnh trùng / đảo vị thế sai

Ví dụ nguy hiểm:

  • Bot LONG khi đã có LONG
  • Bot SHORT khi đang ở chế độ OneWay
  • Bot mở liên tục vì nhận nhiều webhook trùng nhau

Backend FastAPI cần:

async def can_open(symbol, side):
    pos = await get_position(symbol)
    if pos and pos["contracts"] > 0:
        # Hedge Mode thì cho phép mở ngược
        if POSITION_MODE == "hedge":  
            return True
        # OneWay thì chặn hoàn toàn
        return False  
    return True
https://bitmart.zendesk.com/hc/article_attachments/35719317560475?utm_source=chatgpt.com
https://www.researchgate.net/publication/359061294/figure/fig1/AS%3A1131016886464512%401646666847674/Flow-chart-of-the-analysis-process.png?utm_source=chatgpt.com

6. Quản lý rủi ro bằng Queue (Chống race-condition)

Trong bot forex/crypto, đôi khi bạn nhận nhiều tín hiệu cùng lúc.

→ Nếu không có Queue → backend đặt đồng thời nhiều lệnh, gây:

  • Double order
  • Sai vị thế
  • TP/SL sai
  • Cháy tài khoản nhanh

Giải pháp: Redis Queue hoặc Python asyncio Queue.

order_queue = asyncio.Queue()

async def worker():
    while True:
        task = await order_queue.get()
        await process_order(task)
        order_queue.task_done()

7. Thêm cảnh báo realtime – Telegram / Zalo OA / Email

Khi bot vượt ngưỡng rủi ro:

  • Drawdown vượt mức
  • TP/SL không đặt được
  • Không khớp lệnh
  • API timeout
  • Lệch position mode
  • Gọi vốn vượt maximum size

Backend FastAPI gửi cảnh báo:

https://i.ytimg.com/vi/tkMhCdN8Wzo/maxresdefault.jpg?utm_source=chatgpt.com
https://assets.bytebytego.com/diagrams/0042-design-a-notification-push-system.png?utm_source=chatgpt.com
https://www.researchgate.net/publication/45706056/figure/fig1/AS%3A670708908707846%401536920873290/Real-time-alert-clustering-and-classification-system-architecture.ppm?utm_source=chatgpt.com
async def send_alert(msg):
    async with httpx.AsyncClient() as client:
        await client.post(TELEGRAM_URL, json={"text": msg})

8. Kiến trúc Backend FastAPI chuẩn cho Risk Management

https://user-images.githubusercontent.com/86808206/220212075-a10fa8a6-fc07-4726-b82b-fd58e3aeb63f.png?utm_source=chatgpt.com
https://d1rwhvwstyk9gu.cloudfront.net/2022/07/Architecture-for-Algorithmic-Trading-1.png?utm_source=chatgpt.com
https://miro.medium.com/1%2AITe5wGqey-Z0aGJmndhgiQ.png?utm_source=chatgpt.com

Một mô hình đầy đủ bao gồm:

1. Risk Engine Service

  • Kiểm tra vị thế
  • Giới hạn số lệnh
  • Check drawdown
  • Set TP/SL

2. Account Service

  • Theo dõi balance / equity
  • Lấy funding / commission

3. Execution Service

  • Đặt lệnh an toàn
  • Retry nếu API lỗi
  • Xử lý slippage

4. Webhook Service

  • Nhận tín hiệu / validate / queue

5. Monitor Service

  • Log
  • Dashboard
  • Alerts

6. Database

  • Lệnh
  • Nhật ký bot
  • Cấu hình rủi ro

Kết luận

Risk Management không phải là “phần phụ”, mà chính là hệ thống bảo hiểm toàn bộ tài khoản trading.
Backend FastAPI giúp xây dựng Risk Engine mạnh mẽ nhờ:

  • Async hiệu năng cao
  • Kiểm soát vị thế realtime
  • Đặt TP/SL thông minh
  • Chặn lệnh nguy hiểm
  • Tự động dừng bot khi vượt drawdown
  • Giới hạn số lệnh
  • Tự động khôi phục / cảnh báo

Nếu chiến lược là “trái tim của bot”, thì FastAPI Risk Engine chính là bộ não giúp bot sống sót trên thị trường.