MT5 Trading Assistant
Complete automation suite for MetaTrader 5 trading platforms. Provides tools for account monitoring, trade execution, market analysis, and risk management.
Quick Start
Important: This skill contains example scripts with hardcoded credentials. You MUST modify the configuration before use.
Prerequisites
- 1. Python 3.7+ with
MetaTrader5 package:
CODEBLOCK0
- 2. MT5 Desktop Client running and logged into your account
- AutoTrading enabled in MT5 (press F7 or click traffic light icon)
Basic Usage Example
Check Account Status
CODEBLOCK1
Execute Test Trade
CODEBLOCK2
Basic Usage
Check Account Status
CODEBLOCK3
Get Market Snapshot
CODEBLOCK4
Execute Trades
CODEBLOCK5
Close Positions
CODEBLOCK6
Test K-line Data
CODEBLOCK7
Core Features
1. Account Monitoring
- - Real-time balance and equity tracking
- Position monitoring with P&L calculation
- Margin and leverage information
- Connection status verification
2. Trade Execution
- - Market orders (BUY/SELL)
- Position closing (full/partial)
- Stop loss and take profit management
- Order modification capabilities
3. Market Data
- - Real-time bid/ask quotes
- Historical K-line data (M1, M5, H1, D1, etc.)
- Spread monitoring
- Price change calculations
4. Risk Management
- - Position size calculation
- Stop loss automation
- Risk percentage limits
- Daily loss limits
Script Reference
mt5_buy.py - Buy Order Execution
python scripts/mt5_buy.py <volume> [price] [stop_loss] [take_profit]
Parameters:
- -
volume: Lot size (e.g., 0.01 for micro lot) - INLINECODE3 : Optional execution price (0 for market price)
- INLINECODE4 : Optional stop loss price
- INLINECODE5 : Optional take profit price
Examples:
CODEBLOCK9
mt5_sell.py - Sell Order Execution
python scripts/mt5_sell.py <volume> [price] [stop_loss] [take_profit]
Usage: Same as
mt5_buy.py but for sell orders.
mt5_close_all.py - Position Management
python scripts/mt5_close_all.py [command]
Commands:
- - No argument: Close script-managed positions (magic 100001/100002)
- INLINECODE9 : Close all positions for configured symbol
- INLINECODE10 : Close specific position by ticket number
mt5_check.py - Account Status
python scripts/mt5_check.py
Output: Account information, positions, market data, system status.
mt5_snapshot.py - Market Snapshot
python scripts/mt5_snapshot.py
Output: Concise account and market status with trading commands.
test_mt5_kline.py - Data Validation
python scripts/test_mt5_kline.py
Purpose: Test MT5 connection and data retrieval capabilities.
Configuration - MUST MODIFY BEFORE USE
⚠️ SECURITY WARNING: The example scripts contain hardcoded demo account credentials. You MUST modify these before using with your real account.
Configuration Options
Option 1: Direct Script Modification (Quick)
Edit the configuration section in each script file:
CODEBLOCK15
Option 2: Configuration File (Recommended)
- 1. Create
config.py from template:
CODEBLOCK16
- 2. Edit
config.py:
CODEBLOCK17
- 3. Uncomment import lines in scripts:
CODEBLOCK18
Broker-Specific Settings
Exness
CODEBLOCK19
IC Markets
CODEBLOCK20
Common Issues & Solutions
Connection Problems
Error:
Initialize failed or
Login failed
Solution:
- 1. Ensure MT5 desktop client is running and logged in
- Verify account credentials in config.py
- Check server name matches MT5 client
- Enable AutoTrading in MT5 (F7 key)
Trading Issues
Error:
AutoTrading disabled by client
Solution: Click the AutoTrading button (traffic light) in MT5 toolbar
Error: Invalid symbol
Solution: Check symbol name in MT5 client, note broker-specific suffixes
Performance Issues
Slow execution: Reduce refresh intervals, close unused charts
Connection drops: Check internet stability, restart MT5 client
Advanced Usage
Custom Strategies
Create strategy scripts by importing MT5 functions:
CODEBLOCK21
Risk Management Integration
CODEBLOCK22
Monitoring Dashboard
Create a simple monitoring script:
CODEBLOCK23
Security Best Practices
- 1. Never hardcode passwords - Use config.py or environment variables
- Use environment variables for production:
import os
MT5_CONFIG = {
"login": os.getenv("MT5_LOGIN"),
"password": os.getenv("MT5_PASSWORD"),
"server": os.getenv("MT5_SERVER"),
}
- 3. Set file permissions: INLINECODE20
- Add to .gitignore: INLINECODE21
- Regular password rotation: Change passwords every 30-90 days
Resources
Reference Files
- -
references/config_template.py - Configuration template - INLINECODE23 - Complete setup instructions
External Resources
Support
For issues:
- 1. Check
references/setup_guide.md for troubleshooting - Verify MT5 client is running with AutoTrading enabled
- Test connection with INLINECODE25
- Check account credentials in config.py
Common solutions:
- - Restart MT5 client
- Re-enable AutoTrading (F7)
- Verify internet connection
- Check broker server status
MT5 交易助手
MetaTrader 5 交易平台的完整自动化套件。提供账户监控、交易执行、市场分析和风险管理工具。
快速开始
重要提示:此技能包含带有硬编码凭据的示例脚本。使用前必须修改配置。
前提条件
- 1. Python 3.7+ 并安装 MetaTrader5 包:
bash
pip install MetaTrader5
- 2. MT5 桌面客户端 正在运行并已登录您的账户
- 在 MT5 中启用自动交易(按 F7 或点击交通灯图标)
基本使用示例
检查账户状态
bash
python scripts/mt5_check.py
执行测试交易
bash
重要提示:首先修改 scripts/mt5_buy.py 中的账户信息
python scripts/mt5_buy.py 0.01
基本用法
检查账户状态
bash
python scripts/mt5_check.py
获取市场快照
bash
python scripts/mt5_snapshot.py
执行交易
bash
市价买入 0.01 手
python scripts/mt5_buy.py 0.01
以指定价格 5040.00 卖出 0.02 手
python scripts/mt5_sell.py 0.02 5040.00
带止损和止盈买入
python scripts/mt5_buy.py 0.01 0 5030 5050
平仓
bash
关闭所有脚本管理的持仓
python scripts/mt5
closeall.py
关闭某个品种的所有持仓
python scripts/mt5
closeall.py all
按订单号关闭特定持仓
python scripts/mt5
closeall.py 12345678
测试 K 线数据
bash
python scripts/test
mt5kline.py
核心功能
1. 账户监控
- - 实时余额和净值跟踪
- 持仓监控及盈亏计算
- 保证金和杠杆信息
- 连接状态验证
2. 交易执行
- - 市价单(买入/卖出)
- 平仓(全部/部分)
- 止损和止盈管理
- 订单修改功能
3. 市场数据
- - 实时买/卖报价
- 历史 K 线数据(M1、M5、H1、D1 等)
- 点差监控
- 价格变动计算
4. 风险管理
- - 持仓规模计算
- 止损自动化
- 风险百分比限制
- 每日亏损限额
脚本参考
mt5_buy.py - 买入订单执行
bash
python scripts/mt5_buy.py <手数> [价格] [止损] [止盈]
参数:
- - 手数:交易量(例如 0.01 为微型手)
- 价格:可选执行价格(0 表示市价)
- 止损:可选止损价格
- 止盈:可选止盈价格
示例:
bash
市价买入 0.01 手
python scripts/mt5_buy.py 0.01
限价买入 5040.00,止损 5030,止盈 5050
python scripts/mt5_buy.py 0.05 5040.00 5030.00 5050.00
mt5_sell.py - 卖出订单执行
bash
python scripts/mt5_sell.py <手数> [价格] [止损] [止盈]
用法:与 mt5_buy.py 相同,但用于卖出订单。
mt5closeall.py - 持仓管理
bash
python scripts/mt5
closeall.py [命令]
命令:
- - 无参数:关闭脚本管理的持仓(魔法编号 100001/100002)
- all:关闭配置品种的所有持仓
- <订单号>:按订单号关闭特定持仓
mt5_check.py - 账户状态
bash
python scripts/mt5_check.py
输出:账户信息、持仓、市场数据、系统状态。
mt5_snapshot.py - 市场快照
bash
python scripts/mt5_snapshot.py
输出:简洁的账户和市场状态,附带交易命令。
testmt5kline.py - 数据验证
bash
python scripts/test
mt5kline.py
用途:测试 MT5 连接和数据检索功能。
配置 - 使用前必须修改
⚠️ 安全警告:示例脚本包含硬编码的模拟账户凭据。使用真实账户前必须修改。
配置选项
选项 1:直接修改脚本(快速)
编辑每个脚本文件中的配置部分:
python
在 scripts/mt5buy.py、scripts/mt5sell.py 等文件中
ACCOUNT_CONFIG = {
login: 您的账户号码, # 修改此项
password: 您的密码, # 修改此项
server: 您的服务器名称, # 修改此项
symbol: 您的交易品种, # 例如 XAUUSD 或 XAUUSDm
}
选项 2:配置文件(推荐)
- 1. 从模板创建 config.py:
bash
cp references/config_template.py config.py
- 2. 编辑 config.py:
python
MT5_CONFIG = {
login: 12345678, # 您的 MT5 账户号码
password: 您的密码, # 您的 MT5 密码
server: 您的服务器, # 您的 MT5 服务器
symbol: XAUUSD, # 交易品种
}
- 3. 取消脚本中的导入行注释:
python
# 在每个脚本中取消注释这些行:
try:
from config import MT5_CONFIG
ACCOUNT
CONFIG.update(MT5CONFIG)
except ImportError:
print(注意:未找到 config.py,使用默认配置)
经纪商特定设置
Exness
python
MT5_CONFIG = {
login: 277528870,
password: 您的密码,
server: Exness-MT5Trial5, # 模拟服务器
symbol: XAUUSDm, # 黄金带 m 后缀
}
IC Markets
python
MT5_CONFIG = {
login: 12345678,
password: 您的密码,
server: ICMarkets-MT5,
symbol: XAUUSD, # 标准品种
}
常见问题及解决方案
连接问题
错误:初始化失败 或 登录失败
解决方案:
- 1. 确保 MT5 桌面客户端正在运行并已登录
- 验证 config.py 中的账户凭据
- 检查服务器名称是否与 MT5 客户端匹配
- 在 MT5 中启用自动交易(F7 键)
交易问题
错误:客户端禁用自动交易
解决方案:点击 MT5 工具栏中的自动交易按钮(交通灯)
错误:无效品种
解决方案:检查 MT5 客户端中的品种名称,注意经纪商特定的后缀
性能问题
执行缓慢:减少刷新间隔,关闭未使用的图表
连接断开:检查网络稳定性,重启 MT5 客户端
高级用法
自定义策略
通过导入 MT5 函数创建策略脚本:
python
import MetaTrader5 as mt5
from config import MT5_CONFIG
def movingaveragestrategy():
简单移动平均线交叉策略
# 初始化 MT5
mt5.initialize()
mt5.login(MT5CONFIG[login], MT5CONFIG[password], server=MT5_CONFIG[server])
# 获取历史数据
rates = mt5.copyratesfrom(MT5CONFIG[symbol], mt5.TIMEFRAMEH1, datetime.now(), 100)
# 计算指标
# ... 策略逻辑 ...
# 执行交易
# ... 订单执行 ...
mt5.shutdown()
风险管理集成
python
from config import MT5_CONFIG
def calculatepositionsize(riskpercent=0.02, stoploss_pips=20):
根据风险计算持仓规模
account = mt5.account_info()
riskamount = account.balance * riskpercent
# 获取点值
symbolinfo = mt5.symbolinfo(MT5_CONFIG[symbol])
pointvalue = symbolinfo.tradetickvalue
# 计算手数
risk