Skip to main content

One post tagged with "forex"

View All Tags

Hướng Dẫn Các Bước Xây Dựng Auto Trading Robot MT5 với Python

· 3 min read

1. Giới Thiệu

MetaTrader 5 (MT5) là một nền tảng giao dịch phổ biến hỗ trợ lập trình bot tự động bằng ngôn ngữ MQL5 và Python. Trong bài viết này, chúng ta sẽ xây dựng một robot giao dịch tự động (Auto Trading Bot) bằng Python kết nối với MT5.

2. Cài Đặt Môi Trường

Trước tiên, cài đặt thư viện MetaTrader5 để kết nối với nền tảng MT5:

pip install MetaTrader5 pandas numpy

3. Kết Nối Python Với MT5

import MetaTrader5 as mt5

# Kết nối đến MT5
if not mt5.initialize():
print("Kết nối thất bại!")
mt5.shutdown()

# Lấy thông tin tài khoản
account_info = mt5.account_info()
print(account_info)

4. Lấy Dữ Liệu Thị Trường

import pandas as pd
from datetime import datetime

symbol = "EURUSD"

# Lấy dữ liệu nến từ MT5
rates = mt5.copy_rates_from_pos(symbol, mt5.TIMEFRAME_M1, 0, 100)

# Chuyển dữ liệu thành DataFrame
rates_frame = pd.DataFrame(rates)
rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')
print(rates_frame.head())

5. Gửi Lệnh Mua/Bán

def place_order(symbol, order_type, lot_size, sl=None, tp=None):
order = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": lot_size,
"type": mt5.ORDER_TYPE_BUY if order_type == "buy" else mt5.ORDER_TYPE_SELL,
"price": mt5.symbol_info_tick(symbol).ask if order_type == "buy" else mt5.symbol_info_tick(symbol).bid,
"deviation": 10,
"magic": 0,
"comment": "Python Bot",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_IOC
}
if sl:
order["sl"] = sl
if tp:
order["tp"] = tp
result = mt5.order_send(order)
return result

# Đặt lệnh mua 0.1 lot EURUSD
place_order("EURUSD", "buy", 0.1)

6. Xây Dựng Chiến Lược Giao Dịch Đơn Giản

Một chiến lược đơn giản sử dụng Chỉ báo Trung bình Động (SMA):

def moving_average_strategy(symbol, short_window=10, long_window=50):
rates = mt5.copy_rates_from_pos(symbol, mt5.TIMEFRAME_M1, 0, long_window)
df = pd.DataFrame(rates)
df['SMA_Short'] = df['close'].rolling(window=short_window).mean()
df['SMA_Long'] = df['close'].rolling(window=long_window).mean()

if df['SMA_Short'].iloc[-1] > df['SMA_Long'].iloc[-1]:
place_order(symbol, "buy", 0.1)
elif df['SMA_Short'].iloc[-1] < df['SMA_Long'].iloc[-1]:
place_order(symbol, "sell", 0.1)

# Chạy chiến lược giao dịch
moving_average_strategy("EURUSD")

7. Đóng Lệnh Giao Dịch

def close_positions(symbol):
positions = mt5.positions_get(symbol=symbol)
if positions:
for pos in positions:
close_order = {
"action": mt5.TRADE_ACTION_DEAL,
"position": pos.ticket,
"symbol": pos.symbol,
"volume": pos.volume,
"type": mt5.ORDER_TYPE_SELL if pos.type == 0 else mt5.ORDER_TYPE_BUY,
"price": mt5.symbol_info_tick(pos.symbol).bid if pos.type == 0 else mt5.symbol_info_tick(pos.symbol).ask,
"deviation": 10,
"magic": 0,
"comment": "Closing position",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_IOC
}
mt5.order_send(close_order)

# Đóng tất cả lệnh của EURUSD
close_positions("EURUSD")

8. Đánh Giá Hiệu Suất Giao Dịch

def analyze_trades():
history = mt5.history_deals_get(datetime(2024, 1, 1), datetime.now())
df = pd.DataFrame(list(history), columns=["symbol", "type", "volume", "price", "profit", "time"])
print(df.groupby("symbol")["profit"].sum())

analyze_trades()

9. Tổng Kết

Việc xây dựng bot giao dịch tự động với Python trên MT5 giúp bạn có thể giao dịch nhanh chóng và chính xác hơn. Bạn có thể tiếp tục phát triển bot bằng các thuật toán Machine Learning để tối ưu hóa kết quả giao dịch! 🚀