Bài viết gần đây
-
Lộ Trình Học AI Trading Cho Người Đã Biết Bot Hedging (A–Z)
Tháng 9 8, 2026 -
Reinforcement Learning Cho Bot DCA: Dạy Bot Biết Khi Nào Nên Nín
Tháng 9 8, 2026
| Cách Viết Hàm Để Lấy Thông Tin Tài Khoản MT5 Bằng Python
Được viết bởi Đặng Trí Thanh vào ngày 15/11/2025 lúc 21:33 | 304 lượt xem
Hướng dẫn chi tiết cách viết hàm để lấy thông tin tài khoản MetaTrader 5 bằng Python sử dụng thư viện MetaTrader5.
Cách Viết Hàm Để Lấy Thông Tin Tài Khoản MT5 Bằng Python
Python có thể kết nối với MetaTrader 5 thông qua thư viện MetaTrader5 để lấy thông tin tài khoản, quản lý lệnh và tự động hóa giao dịch. Bài viết này sẽ hướng dẫn bạn cách viết các hàm để lấy thông tin tài khoản MT5 bằng Python.
Cài Đặt Thư Viện
Trước tiên, cần cài đặt thư viện MetaTrader5:
pip install MetaTrader5
Kết Nối Với MT5
Hàm Kết Nối Cơ Bản
import MetaTrader5 as mt5
def connect_mt5(login=None, password=None, server=None, path=None):
"""
Kết nối với MetaTrader 5
Args:
login: Số tài khoản (None nếu dùng tài khoản đã đăng nhập)
password: Mật khẩu (None nếu dùng tài khoản đã đăng nhập)
server: Tên server (None nếu dùng server mặc định)
path: Đường dẫn đến MT5 (None nếu dùng đường dẫn mặc định)
Returns:
bool: True nếu kết nối thành công, False nếu thất bại
"""
# Khởi tạo MT5
if not mt5.initialize(path=path):
print("Khởi tạo MT5 thất bại, error code =", mt5.last_error())
return False
# Đăng nhập nếu có thông tin
if login and password and server:
authorized = mt5.login(login, password=password, server=server)
if not authorized:
print("Đăng nhập thất bại, error code =", mt5.last_error())
mt5.shutdown()
return False
print(f"Đăng nhập thành công vào tài khoản {login}")
else:
# Sử dụng tài khoản đã đăng nhập trong MT5
account_info = mt5.account_info()
if account_info is None:
print("Không thể lấy thông tin tài khoản, error code =", mt5.last_error())
mt5.shutdown()
return False
print(f"Đã kết nối với tài khoản {account_info.login}")
return True
# Sử dụng
if connect_mt5():
print("Kết nối MT5 thành công!")
else:
print("Kết nối MT5 thất bại!")
Hàm Ngắt Kết Nối
def disconnect_mt5():
"""Ngắt kết nối với MT5"""
mt5.shutdown()
print("Đã ngắt kết nối MT5")
Lấy Thông Tin Tài Khoản
Hàm Lấy Tất Cả Thông Tin Tài Khoản
def get_account_info():
"""
Lấy tất cả thông tin tài khoản
Returns:
dict: Dictionary chứa thông tin tài khoản hoặc None nếu lỗi
"""
account_info = mt5.account_info()
if account_info is None:
print("Không thể lấy thông tin tài khoản, error code =", mt5.last_error())
return None
# Chuyển đổi sang dictionary
account_dict = {
'login': account_info.login,
'trade_mode': account_info.trade_mode,
'leverage': account_info.leverage,
'limit_orders': account_info.limit_orders,
'margin_so_mode': account_info.margin_so_mode,
'trade_allowed': account_info.trade_allowed,
'trade_expert': account_info.trade_expert,
'margin_mode': account_info.margin_mode,
'currency_digits': account_info.currency_digits,
'fifo_close': account_info.fifo_close,
'balance': account_info.balance,
'credit': account_info.credit,
'profit': account_info.profit,
'equity': account_info.equity,
'margin': account_info.margin,
'margin_free': account_info.margin_free,
'margin_level': account_info.margin_level,
'margin_so_call': account_info.margin_so_call,
'margin_so_so': account_info.margin_so_so,
'margin_initial': account_info.margin_initial,
'margin_maintenance': account_info.margin_maintenance,
'assets': account_info.assets,
'liabilities': account_info.liabilities,
'commission_blocked': account_info.commission_blocked,
'name': account_info.name,
'server': account_info.server,
'currency': account_info.currency,
'company': account_info.company
}
return account_dict
Hàm Lấy Số Dư (Balance)
def get_balance():
"""
Lấy số dư tài khoản
Returns:
float: Số dư tài khoản hoặc None nếu lỗi
"""
account_info = mt5.account_info()
if account_info is None:
print("Không thể lấy thông tin tài khoản, error code =", mt5.last_error())
return None
return account_info.balance
Hàm Lấy Equity
def get_equity():
"""
Lấy equity (tài sản ròng) của tài khoản
Equity = Balance + Credit + Profit
Returns:
float: Equity hoặc None nếu lỗi
"""
account_info = mt5.account_info()
if account_info is None:
print("Không thể lấy thông tin tài khoản, error code =", mt5.last_error())
return None
return account_info.equity
Hàm Lấy Margin
def get_margin():
"""
Lấy margin đã sử dụng
Returns:
float: Margin đã sử dụng hoặc None nếu lỗi
"""
account_info = mt5.account_info()
if account_info is None:
print("Không thể lấy thông tin tài khoản, error code =", mt5.last_error())
return None
return account_info.margin
Hàm Lấy Margin Free
def get_margin_free():
"""
Lấy margin còn lại (có thể sử dụng)
Margin Free = Equity - Margin
Returns:
float: Margin free hoặc None nếu lỗi
"""
account_info = mt5.account_info()
if account_info is None:
print("Không thể lấy thông tin tài khoản, error code =", mt5.last_error())
return None
return account_info.margin_free
Hàm Lấy Margin Level
def get_margin_level():
"""
Lấy margin level (tỷ lệ margin)
Margin Level = (Equity / Margin) * 100
Returns:
float: Margin level (%) hoặc None nếu lỗi
"""
account_info = mt5.account_info()
if account_info is None:
print("Không thể lấy thông tin tài khoản, error code =", mt5.last_error())
return None
return account_info.margin_level
Hàm Lấy Profit
def get_profit():
"""
Lấy lợi nhuận/thua lỗ hiện tại của tất cả các lệnh mở
Returns:
float: Profit (dương = lợi nhuận, âm = thua lỗ) hoặc None nếu lỗi
"""
account_info = mt5.account_info()
if account_info is None:
print("Không thể lấy thông tin tài khoản, error code =", mt5.last_error())
return None
return account_info.profit
Hàm Tổng Hợp
Hàm Hiển Thị Tất Cả Thông Tin
def display_account_info():
"""Hiển thị tất cả thông tin tài khoản"""
account_info = mt5.account_info()
if account_info is None:
print("Không thể lấy thông tin tài khoản, error code =", mt5.last_error())
return
print("=" * 50)
print("THÔNG TIN TÀI KHOẢN MT5")
print("=" * 50)
print(f"Login: {account_info.login}")
print(f"Tên: {account_info.name}")
print(f"Server: {account_info.server}")
print(f"Company: {account_info.company}")
print(f"Currency: {account_info.currency}")
print(f"Leverage: 1:{account_info.leverage}")
print("-" * 50)
print("SỐ DƯ VÀ TÀI SẢN")
print("-" * 50)
print(f"Balance: {account_info.balance:.2f} {account_info.currency}")
print(f"Credit: {account_info.credit:.2f} {account_info.currency}")
print(f"Profit: {account_info.profit:.2f} {account_info.currency}")
print(f"Equity: {account_info.equity:.2f} {account_info.currency}")
print("-" * 50)
print("MARGIN")
print("-" * 50)
print(f"Margin: {account_info.margin:.2f} {account_info.currency}")
print(f"Margin Free: {account_info.margin_free:.2f} {account_info.currency}")
print(f"Margin Level: {account_info.margin_level:.2f}%")
print(f"Margin Initial: {account_info.margin_initial:.2f} {account_info.currency}")
print(f"Margin Maintenance: {account_info.margin_maintenance:.2f} {account_info.currency}")
print("-" * 50)
print("TRẠNG THÁI")
print("-" * 50)
print(f"Trade Allowed: {account_info.trade_allowed}")
print(f"Trade Expert: {account_info.trade_expert}")
print(f"Trade Mode: {account_info.trade_mode}")
print(f"Margin Mode: {account_info.margin_mode}")
print("=" * 50)
# Sử dụng
if connect_mt5():
display_account_info()
disconnect_mt5()
Hàm Kiểm Tra Điều Kiện Giao Dịch
def can_trade():
"""
Kiểm tra xem có thể giao dịch không
Returns:
dict: Dictionary chứa các điều kiện giao dịch
"""
account_info = mt5.account_info()
if account_info is None:
return {
'can_trade': False,
'reason': 'Không thể lấy thông tin tài khoản'
}
conditions = {
'can_trade': True,
'trade_allowed': account_info.trade_allowed,
'trade_expert': account_info.trade_expert,
'margin_free': account_info.margin_free,
'margin_level': account_info.margin_level,
'reasons': []
}
# Kiểm tra các điều kiện
if not account_info.trade_allowed:
conditions['can_trade'] = False
conditions['reasons'].append('Giao dịch không được phép')
if not account_info.trade_expert:
conditions['can_trade'] = False
conditions['reasons'].append('Expert Advisor không được phép')
if account_info.margin_free <= 0:
conditions['can_trade'] = False
conditions['reasons'].append('Không còn margin free')
if account_info.margin_level < 100:
conditions['can_trade'] = False
conditions['reasons'].append(f'Margin level thấp: {account_info.margin_level:.2f}%')
return conditions
# Sử dụng
if connect_mt5():
conditions = can_trade()
if conditions['can_trade']:
print("Có thể giao dịch")
else:
print("Không thể giao dịch:")
for reason in conditions['reasons']:
print(f" - {reason}")
disconnect_mt5()
Lấy Thông Tin Chi Tiết
Hàm Lấy Thông Tin Theo Từng Trường
def get_account_field(field_name):
"""
Lấy thông tin tài khoản theo tên trường
Args:
field_name: Tên trường cần lấy (balance, equity, margin, etc.)
Returns:
Giá trị của trường hoặc None nếu lỗi
"""
account_info = mt5.account_info()
if account_info is None:
print("Không thể lấy thông tin tài khoản, error code =", mt5.last_error())
return None
# Dictionary mapping tên trường
field_mapping = {
'login': account_info.login,
'balance': account_info.balance,
'equity': account_info.equity,
'margin': account_info.margin,
'margin_free': account_info.margin_free,
'margin_level': account_info.margin_level,
'profit': account_info.profit,
'credit': account_info.credit,
'leverage': account_info.leverage,
'currency': account_info.currency,
'server': account_info.server,
'name': account_info.name,
'company': account_info.company
}
return field_mapping.get(field_name.lower(), None)
# Sử dụng
if connect_mt5():
balance = get_account_field('balance')
equity = get_account_field('equity')
margin = get_account_field('margin')
print(f"Balance: {balance}")
print(f"Equity: {equity}")
print(f"Margin: {margin}")
disconnect_mt5()
Class Quản Lý Tài Khoản
Class MT5Account
import MetaTrader5 as mt5
from typing import Optional, Dict
class MT5Account:
"""Class quản lý tài khoản MT5"""
def __init__(self, login=None, password=None, server=None, path=None):
"""
Khởi tạo và kết nối với MT5
Args:
login: Số tài khoản
password: Mật khẩu
server: Tên server
path: Đường dẫn đến MT5
"""
self.login = login
self.password = password
self.server = server
self.path = path
self.connected = False
if self.connect():
self.connected = True
def connect(self) -> bool:
"""Kết nối với MT5"""
if not mt5.initialize(path=self.path):
print("Khởi tạo MT5 thất bại, error code =", mt5.last_error())
return False
if self.login and self.password and self.server:
authorized = mt5.login(self.login, password=self.password, server=self.server)
if not authorized:
print("Đăng nhập thất bại, error code =", mt5.last_error())
mt5.shutdown()
return False
return True
def disconnect(self):
"""Ngắt kết nối với MT5"""
mt5.shutdown()
self.connected = False
def get_info(self) -> Optional[Dict]:
"""Lấy tất cả thông tin tài khoản"""
if not self.connected:
print("Chưa kết nối với MT5")
return None
account_info = mt5.account_info()
if account_info is None:
print("Không thể lấy thông tin tài khoản, error code =", mt5.last_error())
return None
return {
'login': account_info.login,
'balance': account_info.balance,
'equity': account_info.equity,
'margin': account_info.margin,
'margin_free': account_info.margin_free,
'margin_level': account_info.margin_level,
'profit': account_info.profit,
'credit': account_info.credit,
'leverage': account_info.leverage,
'currency': account_info.currency,
'server': account_info.server,
'name': account_info.name,
'company': account_info.company,
'trade_allowed': account_info.trade_allowed,
'trade_expert': account_info.trade_expert
}
def get_balance(self) -> Optional[float]:
"""Lấy số dư tài khoản"""
info = self.get_info()
return info['balance'] if info else None
def get_equity(self) -> Optional[float]:
"""Lấy equity"""
info = self.get_info()
return info['equity'] if info else None
def get_margin(self) -> Optional[float]:
"""Lấy margin đã sử dụng"""
info = self.get_info()
return info['margin'] if info else None
def get_margin_free(self) -> Optional[float]:
"""Lấy margin free"""
info = self.get_info()
return info['margin_free'] if info else None
def get_margin_level(self) -> Optional[float]:
"""Lấy margin level"""
info = self.get_info()
return info['margin_level'] if info else None
def get_profit(self) -> Optional[float]:
"""Lấy profit"""
info = self.get_info()
return info['profit'] if info else None
def can_trade(self) -> bool:
"""Kiểm tra có thể giao dịch không"""
info = self.get_info()
if not info:
return False
return (info['trade_allowed'] and
info['trade_expert'] and
info['margin_free'] > 0 and
info['margin_level'] >= 100)
def display_info(self):
"""Hiển thị thông tin tài khoản"""
info = self.get_info()
if not info:
return
print("=" * 50)
print("THÔNG TIN TÀI KHOẢN MT5")
print("=" * 50)
print(f"Login: {info['login']}")
print(f"Tên: {info['name']}")
print(f"Server: {info['server']}")
print(f"Company: {info['company']}")
print(f"Currency: {info['currency']}")
print(f"Leverage: 1:{info['leverage']}")
print("-" * 50)
print(f"Balance: {info['balance']:.2f} {info['currency']}")
print(f"Equity: {info['equity']:.2f} {info['currency']}")
print(f"Margin: {info['margin']:.2f} {info['currency']}")
print(f"Margin Free: {info['margin_free']:.2f} {info['currency']}")
print(f"Margin Level: {info['margin_level']:.2f}%")
print(f"Profit: {info['profit']:.2f} {info['currency']}")
print("-" * 50)
print(f"Trade Allowed: {info['trade_allowed']}")
print(f"Trade Expert: {info['trade_expert']}")
print(f"Can Trade: {self.can_trade()}")
print("=" * 50)
def __enter__(self):
"""Context manager entry"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit"""
self.disconnect()
# Sử dụng class
if __name__ == "__main__":
# Sử dụng với context manager
with MT5Account() as account:
account.display_info()
print(f"nBalance: {account.get_balance()}")
print(f"Equity: {account.get_equity()}")
print(f"Can Trade: {account.can_trade()}")
Ví Dụ Sử Dụng Thực Tế
Script Kiểm Tra Tài Khoản
import MetaTrader5 as mt5
from datetime import datetime
def check_account_status():
"""Kiểm tra trạng thái tài khoản"""
if not mt5.initialize():
print("Không thể khởi tạo MT5")
return
account_info = mt5.account_info()
if account_info is None:
print("Không thể lấy thông tin tài khoản")
mt5.shutdown()
return
print(f"n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]")
print(f"Tài khoản: {account_info.login}")
print(f"Balance: {account_info.balance:.2f} {account_info.currency}")
print(f"Equity: {account_info.equity:.2f} {account_info.currency}")
print(f"Margin Level: {account_info.margin_level:.2f}%")
print(f"Profit: {account_info.profit:.2f} {account_info.currency}")
# Cảnh báo nếu margin level thấp
if account_info.margin_level < 200:
print("⚠️ CẢNH BÁO: Margin level thấp!")
mt5.shutdown()
# Chạy kiểm tra
check_account_status()
Script Monitor Tài Khoản
import MetaTrader5 as mt5
import time
from datetime import datetime
def monitor_account(interval=60):
"""
Monitor tài khoản liên tục
Args:
interval: Khoảng thời gian giữa các lần kiểm tra (giây)
"""
if not mt5.initialize():
print("Không thể khởi tạo MT5")
return
print("Bắt đầu monitor tài khoản...")
print("Nhấn Ctrl+C để dừngn")
try:
while True:
account_info = mt5.account_info()
if account_info:
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] "
f"Balance: {account_info.balance:.2f} | "
f"Equity: {account_info.equity:.2f} | "
f"Margin Level: {account_info.margin_level:.2f}% | "
f"Profit: {account_info.profit:.2f}")
time.sleep(interval)
except KeyboardInterrupt:
print("nDừng monitor...")
finally:
mt5.shutdown()
# Chạy monitor (kiểm tra mỗi 60 giây)
# monitor_account(60)
Kết Luận
Bài viết đã hướng dẫn cách viết các hàm để lấy thông tin tài khoản MT5 bằng Python. Các hàm này giúp bạn:
- Kết nối và quản lý kết nối với MT5
- Lấy các thông tin cơ bản: balance, equity, margin
- Kiểm tra điều kiện giao dịch
- Monitor tài khoản liên tục
- Sử dụng class để quản lý code tốt hơn
Lưu ý quan trọng:
- Luôn kiểm tra kết quả trả về từ các hàm MT5
- Xử lý lỗi đúng cách
- Đóng kết nối khi không sử dụng
- Sử dụng context manager để đảm bảo đóng kết nối
Tài Liệu Tham Khảo
- MetaTrader5 Python Documentation
- MT5 Python API Reference
- Xây Dựng Bot Auto Trading Cho Forex MT5
- Python Kết Nối MT5
Bài viết được biên soạn bởi CoinGetMarket – Nền tảng giáo dục về crypto và trading bot.
Bài lab liên quan
Đọc thêm
- Cách Viết Code Review Chuẩn Hóa Theo Tiêu Chuẩn PEP 8
- Cách Viết Hàm Gửi Tin Nhắn Văn Bản Đơn Giản Từ Python Tới Telegram
- Thiết Lập Hệ Thống Mô Phỏng Lệnh Capital Position Trades Trong Python
- Học Python Tài Chính: Power BI Và Python Kết Hợp Thế Nào?
Tổng quan về cách viết hàm lấy
Cách Viết Hàm Lấy là chủ đề được nhiều người quan tâm trong cộng đồng đầu tư và lập trình. Hiểu đúng bản chất giúp bạn áp dụng hiệu quả vào công việc và đầu tư.
Bài viết này tổng hợp kiến thức về cách viết hàm lấy: khái niệm, các bước thực hiện, ví dụ minh họa và câu hỏi thường gặp.
Các khái niệm cần nắm
| Khái niệm | Giải thích | Ví dụ |
|---|---|---|
| Khái niệm 1 | Nền tảng của chủ đề | Áp dụng thực tế |
| Khái niệm 2 | Mở rộng kiến thức | Tình huống cụ thể |
| Khái niệm 3 | Ứng dụng nâng cao | Kết hợp nhiều yếu tố |
Các bước thực hiện chi tiết
Bắt đầu từ việc xác định mục tiêu rõ ràng, sau đó chia nhỏ công việc thành từng bước có thể kiểm tra được. Ghi chép lại quá trình để rút kinh nghiệm.
def main():
# bước 1: xác định mục tiêu
# bước 2: thu thập thông tin
# bước 3: thực hiện và kiểm tra
print('Hoàn thành')
if __name__ == '__main__':
main()
Lưu ý và lỗi thường gặp
Lỗi phổ biến là làm tắt các bước quan trọng dẫn đến kết quả sai. Hãy kiểm tra từng giai đoạn và sẵn sàng quay lại điều chỉnh khi cần.
Câu hỏi thường gặp về cách viết hàm lấy
Tôi nên bắt đầu học cách viết hàm lấy từ đâu?
Hãy bắt đầu từ khái niệm cơ bản, làm theo ví dụ, rồi tự áp dụng vào một bài toán nhỏ của riêng bạn.
Cần bao lâu để thành thạo?
Tùy vào thời gian đầu tư, nhưng với thực hành đều đặn vài tuần bạn sẽ nắm được phần cốt lõi và tiếp tục phát triển.
Có tài liệu nào nên đọc không?
Ưu tiên tài liệu chính thức và các khóa học có bài tập thực hành, kết hợp với việc tự xây dựng dự án nhỏ.
Kết luận
Cách Viết Hàm Lấy là hành trình cần sự kiên trì và thực hành. Hãy đặt mục tiêu nhỏ, hoàn thành từng bước và không ngừng cải thiện để đạt kết quả tốt nhất.
Mẹo và thực hành tốt nhất với cách viết hàm lấy
Áp dụng cách viết hàm lấy đúng cách sẽ giúp bạn tiết kiệm thời gian và tránh những sai lầm tốn kém. Dưới đây là những thực hành tốt nhất đúc kết từ kinh nghiệm thực tế.
Trước hết, hãy giữ mọi thứ đơn giản. Bắt đầu với phương án đơn giản nhất đạt được mục tiêu, sau đó mới tối ưu. Sự phức tạp chỉ nên đến khi cần thiết.
Thứ hai, luôn đo lường. Nếu bạn không đo lường được, bạn không thể cải thiện. Hãy xác định các chỉ số chính ngay từ đầu và theo dõi chúng đều đặn.
Thứ ba, xây dựng thói quen kiểm tra định kỳ. Dành thời gian mỗi tuần để rà soát lại kết quả, phát hiện sớm những bất thường trước khi chúng trở thành vấn đề lớn.
| Thực hành | Lợi ích | Mức độ ưu tiên |
|---|---|---|
| Giữ đơn giản | Dễ hiểu, dễ bảo trì | Cao |
| Đo lường kết quả | Cải thiện liên tục | Cao |
| Kiểm tra định kỳ | Phát hiện sớm rủi ro | Cao |
| Ghi chép lại | Học hỏi từ quá khứ | Trung bình |
| Tự động hóa dần | Tiết kiệm thời gian | Trung bình |
Những sai lầm phổ biến khi áp dụng cách viết hàm lấy
Nhiều người gặp thất bại khi áp dụng cách viết hàm lấy không phải vì phương pháp sai, mà vì những sai lầm trong quá trình thực hiện. Nhận diện sớm các sai lầm này giúp bạn tránh được những tổn thất không đáng có.
| Sai lầm | Hậu quả | Cách khắc phục |
|---|---|---|
| Thiếu kế hoạch rõ ràng | Đi sai hướng, lãng phí thời gian | Lập kế hoạch và mục tiêu cụ thể |
| Bỏ qua dữ liệu gốc | Kết luận sai lệch | Kiểm tra nguồn dữ liệu kỹ lưỡng |
| Quá phức tạp ban đầu | Khó vận hành, dễ nản | Bắt đầu tối giản |
| Không kiểm tra định kỳ | Rủi ro âm thầm tăng | Đặt lịch kiểm tra đều đặn |
| Kỳ vọng phi thực tế | Thất vọng, bỏ cuộc | Đặt mục tiêu thực tế, dài hạn |
| Sao chép máy móc | Không phù hợp hoàn cảnh | Điều chỉnh theo bối cảnh |
Cách xử lý khi gặp sai lầm
Khi phát hiện sai lầm, đừng hoảng loạn. Hãy dừng lại, xác định nguyên nhân gốc, khắc phục và rút kinh nghiệm. Ghi chép lại bài học để không lặp lại trong tương lai. Thất bại nhỏ và sớm luôn rẻ hơn thất bại lớn và muộn.
Đặng Trí Thanh
Giám đốc Công nghệ · DNT Digital · Giảng viên HNDL Hướng Nghiệp Dữ LiệuĐặng Trí Thanh — Founder & CTO · Hướng Nghiệp Dữ Liệu - DNT Digital. Chuyên đào tạo và triển khai thực chiến Python, MT5 và hệ thống bot auto trading / IB cho học viên và doanh nghiệp.