Install
openclaw skills install mt5-trading-assistantAutomates MetaTrader 5 trading: connect, monitor accounts, execute buy/sell orders with SL/TP, retrieve market data, and manage positions via scripts.
openclaw skills install mt5-trading-assistantComplete automation suite for MetaTrader 5 trading platforms. Provides tools for account monitoring, trade execution, market analysis, and risk management.
Important: This skill contains example scripts with hardcoded credentials. You MUST modify the configuration before use.
Python 3.7+ with MetaTrader5 package:
pip install MetaTrader5
MT5 Desktop Client running and logged into your account
AutoTrading enabled in MT5 (press F7 or click traffic light icon)
python scripts/mt5_check.py
# IMPORTANT: First modify scripts/mt5_buy.py with your account details
python scripts/mt5_buy.py 0.01
python scripts/mt5_check.py
python scripts/mt5_snapshot.py
# Buy 0.01 lots at market price
python scripts/mt5_buy.py 0.01
# Sell 0.02 lots at specified price 5040.00
python scripts/mt5_sell.py 0.02 5040.00
# Buy with stop loss and take profit
python scripts/mt5_buy.py 0.01 0 5030 5050
# Close all script-managed positions
python scripts/mt5_close_all.py
# Close all positions for a symbol
python scripts/mt5_close_all.py all
# Close specific position by ticket
python scripts/mt5_close_all.py 12345678
python scripts/test_mt5_kline.py
mt5_buy.py - Buy Order Executionpython scripts/mt5_buy.py <volume> [price] [stop_loss] [take_profit]
Parameters:
volume: Lot size (e.g., 0.01 for micro lot)price: Optional execution price (0 for market price)stop_loss: Optional stop loss pricetake_profit: Optional take profit priceExamples:
# Market buy 0.01 lot
python scripts/mt5_buy.py 0.01
# Limit buy at 5040.00 with SL 5030, TP 5050
python scripts/mt5_buy.py 0.05 5040.00 5030.00 5050.00
mt5_sell.py - Sell Order Executionpython 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 Managementpython scripts/mt5_close_all.py [command]
Commands:
all: Close all positions for configured symbol<ticket>: Close specific position by ticket numbermt5_check.py - Account Statuspython scripts/mt5_check.py
Output: Account information, positions, market data, system status.
mt5_snapshot.py - Market Snapshotpython scripts/mt5_snapshot.py
Output: Concise account and market status with trading commands.
test_mt5_kline.py - Data Validationpython scripts/test_mt5_kline.py
Purpose: Test MT5 connection and data retrieval capabilities.
⚠️ SECURITY WARNING: The example scripts contain hardcoded demo account credentials. You MUST modify these before using with your real account.
Edit the configuration section in each script file:
# In scripts/mt5_buy.py, scripts/mt5_sell.py, etc.
ACCOUNT_CONFIG = {
"login": YOUR_ACCOUNT_NUMBER, # CHANGE THIS
"password": "YOUR_PASSWORD", # CHANGE THIS
"server": "YOUR_SERVER_NAME", # CHANGE THIS
"symbol": "YOUR_SYMBOL", # e.g., "XAUUSD" or "XAUUSDm"
}
Create config.py from template:
cp references/config_template.py config.py
Edit config.py:
MT5_CONFIG = {
"login": 12345678, # YOUR MT5 account number
"password": "your_password", # YOUR MT5 password
"server": "YourServer", # YOUR MT5 server
"symbol": "XAUUSD", # Trading symbol
}
Uncomment import lines in scripts:
# Uncomment these lines in each script:
try:
from config import MT5_CONFIG
ACCOUNT_CONFIG.update(MT5_CONFIG)
except ImportError:
print("NOTE: config.py not found, using default configuration")
MT5_CONFIG = {
"login": 277528870,
"password": "your_password",
"server": "Exness-MT5Trial5", # Demo server
"symbol": "XAUUSDm", # Gold with 'm' suffix
}
MT5_CONFIG = {
"login": 12345678,
"password": "your_password",
"server": "ICMarkets-MT5",
"symbol": "XAUUSD", # Standard symbol
}
Error: Initialize failed or Login failed
Solution:
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
Slow execution: Reduce refresh intervals, close unused charts Connection drops: Check internet stability, restart MT5 client
Create strategy scripts by importing MT5 functions:
import MetaTrader5 as mt5
from config import MT5_CONFIG
def moving_average_strategy():
"""Simple moving average crossover strategy"""
# Initialize MT5
mt5.initialize()
mt5.login(MT5_CONFIG["login"], MT5_CONFIG["password"], server=MT5_CONFIG["server"])
# Get historical data
rates = mt5.copy_rates_from(MT5_CONFIG["symbol"], mt5.TIMEFRAME_H1, datetime.now(), 100)
# Calculate indicators
# ... strategy logic ...
# Execute trades
# ... order execution ...
mt5.shutdown()
from config import MT5_CONFIG
def calculate_position_size(risk_percent=0.02, stop_loss_pips=20):
"""Calculate position size based on risk"""
account = mt5.account_info()
risk_amount = account.balance * risk_percent
# Get point value
symbol_info = mt5.symbol_info(MT5_CONFIG["symbol"])
point_value = symbol_info.trade_tick_value
# Calculate lot size
risk_per_pip = risk_amount / stop_loss_pips
lot_size = risk_per_pip / point_value
return min(lot_size, MT5_CONFIG.get("max_lot_size", 1.0))
Create a simple monitoring script:
#!/usr/bin/env python3
"""
MT5 Trading Dashboard
Refreshes every 10 seconds with account status
"""
import time
from datetime import datetime
import MetaTrader5 as mt5
from config import MT5_CONFIG
def dashboard():
while True:
# Clear screen
print("\n" * 50)
# Get current time
print(f"MT5 Dashboard - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 60)
# Get account data
mt5.initialize()
mt5.login(MT5_CONFIG["login"], MT5_CONFIG["password"], server=MT5_CONFIG["server"])
# Display data
account = mt5.account_info()
if account:
print(f"Account: {account.login} | Equity: ${account.equity:.2f}")
print(f"Balance: ${account.balance:.2f} | Margin: ${account.margin:.2f}")
# Get positions
positions = mt5.positions_get(symbol=MT5_CONFIG["symbol"])
if positions:
print(f"\nPositions: {len(positions)}")
for pos in positions:
pnl = "+" if pos.profit > 0 else ""
print(f" {pos.ticket}: {pos.symbol} {pos.volume} lots | P&L: {pnl}${pos.profit:.2f}")
mt5.shutdown()
print("\n" + "=" * 60)
print("Next update in 10 seconds (Ctrl+C to stop)")
time.sleep(10)
if __name__ == "__main__":
try:
dashboard()
except KeyboardInterrupt:
print("\nDashboard stopped")
import os
MT5_CONFIG = {
"login": os.getenv("MT5_LOGIN"),
"password": os.getenv("MT5_PASSWORD"),
"server": os.getenv("MT5_SERVER"),
}
chmod 600 config.pyecho "config.py" >> .gitignorereferences/config_template.py - Configuration templatereferences/setup_guide.md - Complete setup instructionsFor issues:
references/setup_guide.md for troubleshootingpython scripts/test_mt5_kline.pyCommon solutions: