Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro
| 1 | """MetaTrader 5 broker integration (works with Headway accounts).""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | from dataclasses import dataclass |
| 6 | from datetime import datetime |
| 7 | from typing import Any |
| 8 | |
| 9 | import pandas as pd |
| 10 | |
| 11 | |
| 12 | def _load_mt5() -> Any: |
| 13 | """Import the MetaTrader5 package lazily with a helpful error.""" |
| 14 | try: |
| 15 | from importlib import import_module |
| 16 | |
| 17 | return import_module("MetaTrader5") |
| 18 | except ImportError as exc: |
| 19 | raise RuntimeError( |
| 20 | "The MetaTrader5 package is not installed or not supported on this " |
| 21 | "platform. It officially supports Windows only. Install the Headway " |
| 22 | "MT5 terminal on Windows (or a Windows VPS / Wine), then run " |
| 23 | "'pip install MetaTrader5'. Original error: " |
| 24 | f"{exc}" |
| 25 | ) from exc |
| 26 | |
| 27 | |
| 28 | @dataclass |
| 29 | class MT5AccountInfo: |
| 30 | """Account information from MT5.""" |
| 31 | |
| 32 | login: int |
| 33 | balance: float |
| 34 | equity: float |
| 35 | margin: float |
| 36 | free_margin: float |
| 37 | margin_level: float |
| 38 | currency: str |
| 39 | leverage: int |
| 40 | trade_allowed: bool |
| 41 | trade_expert: bool |
| 42 | connected: bool |
| 43 | |
| 44 | |
| 45 | @dataclass |
| 46 | class MT5Position: |
| 47 | """Position information from MT5.""" |
| 48 | |
| 49 | ticket: int |
| 50 | symbol: str |
| 51 | type: int # 0 for buy, 1 for sell |
| 52 | volume: float |
| 53 | price_open: float |
| 54 | price_current: float |
| 55 | profit: float |
| 56 | swap: float |
| 57 | commission: float |
| 58 | comment: str |
| 59 | |
| 60 | |
| 61 | class MT5Broker: |
| 62 | """MetaTrader 5 broker interface (incl. Headway servers).""" |
| 63 | |
| 64 | def __init__( |
| 65 | self, |
| 66 | login: int | None = None, |
| 67 | password: str | None = None, |
| 68 | server: str | None = None, |
| 69 | timeout: int = 60000, |
| 70 | terminal_path: str | None = None, |
| 71 | ) -> None: |
| 72 | """Initialize MT5 broker connection. |
| 73 | |
| 74 | Args: |
| 75 | login: MT5 account login (if None, attaches to the open terminal). |
| 76 | password: MT5 account password. |
| 77 | server: MT5 server name, e.g. Headway-Demo or Headway-Real. |
| 78 | timeout: Connection timeout in milliseconds. |
| 79 | terminal_path: Optional path to terminal64.exe (useful under Wine). |
| 80 | """ |
| 81 | self.login = login |
| 82 | self.password = password |
| 83 | self.server = server |
| 84 | self.timeout = timeout |
| 85 | self.terminal_path = terminal_path |
| 86 | self.connected = False |
| 87 | self.account_info: MT5AccountInfo | None = None |
| 88 | |
| 89 | def connect(self) -> bool: |
| 90 | """Initialize connection to the MT5 terminal. |
| 91 | |
| 92 | Returns: |
| 93 | True if connection succeeded, False otherwise. |
| 94 | """ |
| 95 | mt5 = _load_mt5() |
| 96 | kwargs: dict[str, Any] = {"timeout": self.timeout} |
| 97 | if self.terminal_path: |
| 98 | kwargs["path"] = self.terminal_path |
| 99 | if self.login is not None: |
| 100 | kwargs["login"] = self.login |
| 101 | if self.password is not None: |
| 102 | kwargs["password"] = self.password |
| 103 | if self.server is not None: |
| 104 | kwargs["server"] = self.server |
| 105 | if not mt5.initialize(**kwargs): |
| 106 | print(f"MT5 initialize() failed, error code = {mt5.last_error()}") |
| 107 | print("Check: MT5 terminal installed, login/password/server correct.") |
| 108 | return False |
| 109 | |
| 110 | self.connected = True |
| 111 | self.account_info = self._get_account_info() |
| 112 | print(f"Connected to MT5 account #{self.account_info.login}") |
| 113 | return True |
| 114 | |
| 115 | def disconnect(self) -> None: |
| 116 | """Disconnect from the MT5 terminal.""" |
| 117 | if not self.connected: |
| 118 | return |
| 119 | mt5 = _load_mt5() |
| 120 | mt5.shutdown() |
| 121 | self.connected = False |
| 122 | print("Disconnected from MT5") |
| 123 | |
| 124 | def _require_connected(self) -> Any: |
| 125 | if not self.connected: |
| 126 | raise ConnectionError("Not connected to MT5. Call connect() first.") |
| 127 | return _load_mt5() |
| 128 | |
| 129 | def _get_account_info(self) -> MT5AccountInfo: |
| 130 | """Fetch account information from MT5.""" |
| 131 | mt5 = self._require_connected() |
| 132 | info = mt5.account_info() |
| 133 | if info is None: |
| 134 | raise RuntimeError(f"Failed to get account info: {mt5.last_error()}") |
| 135 | return MT5AccountInfo( |
| 136 | login=int(info.login), |
| 137 | balance=float(info.balance), |
| 138 | equity=float(info.equity), |
| 139 | margin=float(info.margin), |
| 140 | free_margin=float(info.margin_free), |
| 141 | margin_level=float(info.margin_level), |
| 142 | currency=str(info.currency), |
| 143 | leverage=int(info.leverage), |
| 144 | trade_allowed=bool(info.trade_allowed), |
| 145 | trade_expert=bool(info.trade_expert), |
| 146 | connected=True, |
| 147 | ) |
| 148 | |
| 149 | def get_account_info(self) -> MT5AccountInfo: |
| 150 | """Return current account information.""" |
| 151 | return self._get_account_info() |
| 152 | |
| 153 | def get_symbol_info(self, symbol: str) -> dict[str, Any]: |
| 154 | """Return symbol info, selecting the symbol in MarketWatch if needed.""" |
| 155 | mt5 = self._require_connected() |
| 156 | info = mt5.symbol_info(symbol) |
| 157 | if info is None: |
| 158 | if not mt5.symbol_select(symbol, True): |
| 159 | raise ValueError(f"Symbol {symbol} not found: {mt5.last_error()}") |
| 160 | info = mt5.symbol_info(symbol) |
| 161 | if info is None: |
| 162 | raise RuntimeError(f"Failed to get symbol info for {symbol}") |
| 163 | result: dict[str, Any] = dict(info._asdict()) |
| 164 | return result |
| 165 | |
| 166 | def get_rates(self, symbol: str, timeframe: int, count: int = 1000) -> pd.DataFrame: |
| 167 | """Return recent OHLCV bars as a DataFrame indexed by time.""" |
| 168 | mt5 = self._require_connected() |
| 169 | self.get_symbol_info(symbol) |
| 170 | rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, count) |
| 171 | if rates is None: |
| 172 | raise RuntimeError(f"Failed to get rates for {symbol}: {mt5.last_error()}") |
| 173 | return _rates_to_frame(rates) |
| 174 | |
| 175 | def get_historical_data( |
| 176 | self, |
| 177 | symbol: str, |
| 178 | timeframe: str, |
| 179 | start_date: datetime, |
| 180 | end_date: datetime, |
| 181 | ) -> pd.DataFrame: |
| 182 | """Return OHLCV data between two dates (for backtesting).""" |
| 183 | mt5 = self._require_connected() |
| 184 | timeframe_map = { |
| 185 | "1M": mt5.TIMEFRAME_M1, |
| 186 | "5M": mt5.TIMEFRAME_M5, |
| 187 | "15M": mt5.TIMEFRAME_M15, |
| 188 | "30M": mt5.TIMEFRAME_M30, |
| 189 | "1H": mt5.TIMEFRAME_H1, |
| 190 | "4H": mt5.TIMEFRAME_H4, |
| 191 | "1D": mt5.TIMEFRAME_D1, |
| 192 | "1W": mt5.TIMEFRAME_W1, |
| 193 | "1MN": mt5.TIMEFRAME_MN1, |
| 194 | } |
| 195 | if timeframe not in timeframe_map: |
| 196 | raise ValueError(f"Unsupported timeframe: {timeframe}") |
| 197 | self.get_symbol_info(symbol) |
| 198 | rates = mt5.copy_rates_range(symbol, timeframe_map[timeframe], start_date, end_date) |
| 199 | if rates is None: |
| 200 | raise RuntimeError(f"Failed to get historical data for {symbol}") |
| 201 | df = _rates_to_frame(rates) |
| 202 | mask = (df.index >= start_date) & (df.index <= end_date) |
| 203 | return df.loc[mask] |
| 204 | |
| 205 | def get_positions(self, symbol: str | None = None) -> list[MT5Position]: |
| 206 | """Return open positions, optionally filtered by symbol.""" |
| 207 | mt5 = self._require_connected() |
| 208 | positions = mt5.positions_get(symbol=symbol) if symbol else mt5.positions_get() |
| 209 | if positions is None: |
| 210 | return [] |
| 211 | return [ |
| 212 | MT5Position( |
| 213 | ticket=int(pos.ticket), |
| 214 | symbol=str(pos.symbol), |
| 215 | type=int(pos.type), |
| 216 | volume=float(pos.volume), |
| 217 | price_open=float(pos.price_open), |
| 218 | price_current=float(pos.price_current), |
| 219 | profit=float(pos.profit), |
| 220 | swap=float(pos.swap), |
| 221 | commission=float(pos.commission), |
| 222 | comment=str(pos.comment), |
| 223 | ) |
| 224 | for pos in positions |
| 225 | ] |
| 226 | |
| 227 | def place_order( |
| 228 | self, |
| 229 | symbol: str, |
| 230 | order_type: int, |
| 231 | volume: float, |
| 232 | price: float = 0.0, |
| 233 | sl: float = 0.0, |
| 234 | tp: float = 0.0, |
| 235 | comment: str = "Alice Bot", |
| 236 | deviation: int = 10, |
| 237 | ) -> bool: |
| 238 | """Place a market deal order.""" |
| 239 | mt5 = self._require_connected() |
| 240 | symbol_info = self.get_symbol_info(symbol) |
| 241 | tick = mt5.symbol_info_tick(symbol) |
| 242 | if tick is None: |
| 243 | raise RuntimeError(f"No tick data for {symbol}") |
| 244 | if price <= 0.0: |
| 245 | is_buy = order_type == mt5.ORDER_TYPE_BUY |
| 246 | price = float(tick.ask if is_buy else tick.bid) |
| 247 | request: dict[str, Any] = { |
| 248 | "action": mt5.TRADE_ACTION_DEAL, |
| 249 | "symbol": symbol, |
| 250 | "volume": volume, |
| 251 | "type": order_type, |
| 252 | "price": price, |
| 253 | "sl": sl, |
| 254 | "tp": tp, |
| 255 | "deviation": deviation, |
| 256 | "magic": 234000, |
| 257 | "comment": comment, |
| 258 | "type_time": mt5.ORDER_TIME_GTC, |
| 259 | "type_filling": symbol_info.get("filling_mode", mt5.ORDER_FILLING_IOC), |
| 260 | } |
| 261 | result = mt5.order_send(request) |
| 262 | if result is None or result.retcode != mt5.TRADE_RETCODE_DONE: |
| 263 | code = result.retcode if result is not None else mt5.last_error() |
| 264 | print(f"Order send failed, retcode={code}") |
| 265 | return False |
| 266 | print(f"Order placed successfully: {result.order}") |
| 267 | return True |
| 268 | |
| 269 | def buy( |
| 270 | self, |
| 271 | symbol: str, |
| 272 | volume: float, |
| 273 | sl: float = 0.0, |
| 274 | tp: float = 0.0, |
| 275 | comment: str = "Alice Bot", |
| 276 | ) -> bool: |
| 277 | """Place a market buy order.""" |
| 278 | mt5 = self._require_connected() |
| 279 | return self.place_order( |
| 280 | symbol=symbol, |
| 281 | order_type=mt5.ORDER_TYPE_BUY, |
| 282 | volume=volume, |
| 283 | sl=sl, |
| 284 | tp=tp, |
| 285 | comment=comment, |
| 286 | ) |
| 287 | |
| 288 | def sell( |
| 289 | self, |
| 290 | symbol: str, |
| 291 | volume: float, |
| 292 | sl: float = 0.0, |
| 293 | tp: float = 0.0, |
| 294 | comment: str = "Alice Bot", |
| 295 | ) -> bool: |
| 296 | """Place a market sell order.""" |
| 297 | mt5 = self._require_connected() |
| 298 | return self.place_order( |
| 299 | symbol=symbol, |
| 300 | order_type=mt5.ORDER_TYPE_SELL, |
| 301 | volume=volume, |
| 302 | sl=sl, |
| 303 | tp=tp, |
| 304 | comment=comment, |
| 305 | ) |
| 306 | |
| 307 | def close_position(self, ticket: int) -> bool: |
| 308 | """Close an open position by ticket.""" |
| 309 | mt5 = self._require_connected() |
| 310 | positions = mt5.positions_get(ticket=ticket) |
| 311 | if not positions: |
| 312 | print(f"Position {ticket} not found") |
| 313 | return False |
| 314 | pos = positions[0] |
| 315 | tick = mt5.symbol_info_tick(pos.symbol) |
| 316 | if tick is None: |
| 317 | raise RuntimeError(f"No tick data for {pos.symbol}") |
| 318 | is_long = pos.type == mt5.ORDER_TYPE_BUY |
| 319 | request: dict[str, Any] = { |
| 320 | "action": mt5.TRADE_ACTION_DEAL, |
| 321 | "position": ticket, |
| 322 | "symbol": pos.symbol, |
| 323 | "volume": pos.volume, |
| 324 | "type": mt5.ORDER_TYPE_SELL if is_long else mt5.ORDER_TYPE_BUY, |
| 325 | "price": float(tick.bid if is_long else tick.ask), |
| 326 | "deviation": 10, |
| 327 | "magic": 234000, |
| 328 | "comment": "Alice Bot Close", |
| 329 | "type_time": mt5.ORDER_TIME_GTC, |
| 330 | "type_filling": mt5.ORDER_FILLING_IOC, |
| 331 | } |
| 332 | result = mt5.order_send(request) |
| 333 | if result is None or result.retcode != mt5.TRADE_RETCODE_DONE: |
| 334 | code = result.retcode if result is not None else mt5.last_error() |
| 335 | print(f"Position close failed, retcode={code}") |
| 336 | return False |
| 337 | print(f"Position {ticket} closed successfully") |
| 338 | return True |
| 339 | |
| 340 | |
| 341 | def _rates_to_frame(rates: Any) -> pd.DataFrame: |
| 342 | """Convert MT5 rates array to an OHLCV DataFrame.""" |
| 343 | df = pd.DataFrame(rates) |
| 344 | df["time"] = pd.to_datetime(df["time"], unit="s") |
| 345 | df = df.set_index("time") |
| 346 | df = df.rename( |
| 347 | columns={ |
| 348 | "open": "Open", |
| 349 | "high": "High", |
| 350 | "low": "Low", |
| 351 | "close": "Close", |
| 352 | "tick_volume": "Volume", |
| 353 | } |
| 354 | ) |
| 355 | return df |