This document explains how SignalTrader integrates with MetaTrader 5 (MT5) for automated trading execution, position management, and market data access.
The MetaTrader integration provides a complete bridge between Telegram signal processing and live trading execution. It handles order placement, position monitoring, risk management, and profit taking strategies.
- MetaTrader 5 terminal installed
- Trading account with broker
- Algorithmic trading enabled in MT5
- Terminal path correctly configured in
settings.json
"MetaTrader": {
"path": "C:/Program Files/MetaTrader 5/terminal64.exe",
"server": "YourBroker-Server",
"username": 123456,
"password": "YourPassword"
}- Login: Establishes connection to MT5 terminal
- Symbol Selection: Ensures trading symbols are available in Market Watch
- Connection Monitoring: Automatic reconnection on failures
- Market Orders: Immediate execution at current market price
- Pending Orders: Limit and stop orders with expiration
- Order Types: Buy/Sell, Buy Limit/Stop, Sell Limit/Stop
- Open Positions: Track and modify existing positions
- Partial Closures: Close portions of positions for profit taking
- Stop Loss/Take Profit: Dynamic adjustment of risk levels
mt = MetaTrader(
path="path/to/terminal64.exe",
server="broker-server",
user=123456,
password="password"
)Login(): Connect to MT5 terminalCheckSymbol(symbol): Verify symbol availabilityGetSymbols(): Retrieve all available symbols
OpenPosition(): Place new ordersclose_position(): Close positions or cancel ordersupdate_stop_loss(): Modify stop loss levelsclose_half_position(): Partial position closure
get_current_price(): Get bid/ask pricesget_open_positions(): List active positionsget_pending_orders(): List pending orders
The system automatically determines order types based on entry price vs. current market price:
- Market Order: When entry price is at current market level (± threshold)
- Limit Order: When entry price is better than current market
- Stop Order: When entry price is worse than current market
For certain symbols (especially XAUUSD), prices are validated and adjusted to match broker requirements:
- Corrects decimal places
- Handles broker-specific formatting
- Prevents invalid price submissions
Supports both fixed and percentage-based position sizing:
# Percentage of account balance
lot = "2%" # 2% of account balance
# Fixed lot size
lot = 0.01 # Fixed 0.01 lots- Automatic SL adjustment for trailing stops
- Validation against broker tick sizes
- Support for both position and pending order SL
- Multiple TP levels supported
- Partial profit taking at each level
- Configurable profit saving percentages
- Real-time position tracking
- Automatic trailing stop adjustments
- Profit level detection and execution
Automatically adjusts stop loss as profits increase:
- Monitors position profit levels
- Moves SL to next TP level when reached
- Closes partial positions for profit locking
Configurable partial closures:
"SaveProfits": [25, 25, 25, 25]- Takes 25% profit at each TP level
- Reduces position size progressively
High-risk mode with two entry levels:
- Primary entry at signal price
- Secondary entry for averaging
- Separate risk calculation for each
- Invalid Price: Price too close/far from market
- No Connection: MT5 terminal not running
- Symbol Not Found: Symbol not available with broker
- Insufficient Funds: Account balance too low
MT5 returns specific error codes:
10004: Invalid request10006: Invalid price10013: Invalid volume10015: Invalid price (too close to market)10016: Invalid stops10027: Auto trading disabled
Signals and positions are stored in SQLite:
- Signals Table: Stores parsed signal data
- Positions Table: Links MT5 tickets to signals
- Query Methods: Retrieve positions by signal ID, update SL/TP
- Continuous position checking
- Pending order management
- Automatic cleanup of expired orders
- All trading actions logged with timestamps
- MT5 server time included in logs
- Error details captured for debugging
- Full documentation: https://www.mql5.com/en/docs/python_metatrader5
- Order sending:
mt5.order_send() - Position queries:
mt5.positions_get() - Symbol info:
mt5.symbol_info()
- Price validation for specific symbols
- Automatic order type determination
- Risk-based lot size calculation
- Advanced position management
- Verify MT5 terminal is running
- Check terminal path in settings
- Ensure algorithmic trading is enabled
- Confirm broker server details
- Check account balance
- Verify symbol availability
- Review price validation logic
- Check for duplicate positions
- Monitor CPU usage during high-frequency trading
- Adjust monitoring intervals if needed
- Consider broker-specific limitations