Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro

fix/nan-prices-cli-demo-mode
py 397 lines 13.5 KB
Raw
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 self._demo_identity: tuple[int, str] | None = None
89
90 def connect(self) -> bool:
91 """Initialize connection to the MT5 terminal.
92
93 Returns:
94 True if connection succeeded, False otherwise.
95 """
96 mt5 = _load_mt5()
97 kwargs: dict[str, Any] = {"timeout": self.timeout}
98 if self.terminal_path:
99 kwargs["path"] = self.terminal_path
100 if self.login is not None:
101 kwargs["login"] = self.login
102 if self.password is not None:
103 kwargs["password"] = self.password
104 if self.server is not None:
105 kwargs["server"] = self.server
106 if not mt5.initialize(**kwargs):
107 print(f"MT5 initialize() failed, error code = {mt5.last_error()}")
108 print("Check: MT5 terminal installed, login/password/server correct.")
109 return False
110
111 self.connected = True
112 try:
113 self._assert_demo_account(pin=True)
114 self.account_info = self._get_account_info()
115 except Exception:
116 self.disconnect()
117 raise
118 print(f"Connected to MT5 account #{self.account_info.login}")
119 return True
120
121 def disconnect(self) -> None:
122 """Disconnect from the MT5 terminal."""
123 if not self.connected:
124 return
125 mt5 = _load_mt5()
126 mt5.shutdown()
127 self.connected = False
128 self._demo_identity = None
129 self.account_info = None
130 print("Disconnected from MT5")
131
132 def _require_connected(self) -> Any:
133 if not self.connected:
134 raise ConnectionError("Not connected to MT5. Call connect() first.")
135 return _load_mt5()
136
137 def _assert_demo_account(self, *, pin: bool = False) -> None:
138 """Fail closed on real/unknown accounts and terminal account switches.
139
140 This build supports demo accounts only. Server names and CLI flags are
141 not evidence of account type. Re-read immediately before every send.
142 """
143 mt5 = self._require_connected()
144 info = mt5.account_info()
145 mode = getattr(info, "trade_mode", None)
146 demo_mode = getattr(mt5, "ACCOUNT_TRADE_MODE_DEMO", None)
147 login = getattr(info, "login", None)
148 server = getattr(info, "server", None)
149 if (
150 type(mode) is not int
151 or type(demo_mode) is not int
152 or mode != demo_mode
153 or type(login) is not int
154 or login <= 0
155 or not isinstance(server, str)
156 or not server
157 ):
158 raise RuntimeError("Demo-only safety: account type or identity is not verified demo")
159 identity = (login, server)
160 if self.login is not None and login != self.login:
161 raise RuntimeError("Demo-only safety: login does not match requested account")
162 if self.server is not None and server != self.server:
163 raise RuntimeError("Demo-only safety: server does not match requested account")
164 if pin:
165 self._demo_identity = identity
166 elif self._demo_identity is None or identity != self._demo_identity:
167 raise RuntimeError("Demo-only safety: terminal account changed; reconnect required")
168
169 def _get_account_info(self) -> MT5AccountInfo:
170 """Fetch account information from MT5."""
171 mt5 = self._require_connected()
172 info = mt5.account_info()
173 if info is None:
174 raise RuntimeError(f"Failed to get account info: {mt5.last_error()}")
175 return MT5AccountInfo(
176 login=int(info.login),
177 balance=float(info.balance),
178 equity=float(info.equity),
179 margin=float(info.margin),
180 free_margin=float(info.margin_free),
181 margin_level=float(info.margin_level),
182 currency=str(info.currency),
183 leverage=int(info.leverage),
184 trade_allowed=bool(info.trade_allowed),
185 trade_expert=bool(info.trade_expert),
186 connected=True,
187 )
188
189 def get_account_info(self) -> MT5AccountInfo:
190 """Return current account information."""
191 return self._get_account_info()
192
193 def get_symbol_info(self, symbol: str) -> dict[str, Any]:
194 """Return symbol info, selecting the symbol in MarketWatch if needed."""
195 mt5 = self._require_connected()
196 info = mt5.symbol_info(symbol)
197 if info is None:
198 if not mt5.symbol_select(symbol, True):
199 raise ValueError(f"Symbol {symbol} not found: {mt5.last_error()}")
200 info = mt5.symbol_info(symbol)
201 if info is None:
202 raise RuntimeError(f"Failed to get symbol info for {symbol}")
203 result: dict[str, Any] = dict(info._asdict())
204 return result
205
206 def get_rates(self, symbol: str, timeframe: int, count: int = 1000) -> pd.DataFrame:
207 """Return recent OHLCV bars as a DataFrame indexed by time."""
208 mt5 = self._require_connected()
209 self.get_symbol_info(symbol)
210 rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, count)
211 if rates is None:
212 raise RuntimeError(f"Failed to get rates for {symbol}: {mt5.last_error()}")
213 return _rates_to_frame(rates)
214
215 def get_historical_data(
216 self,
217 symbol: str,
218 timeframe: str,
219 start_date: datetime,
220 end_date: datetime,
221 ) -> pd.DataFrame:
222 """Return OHLCV data between two dates (for backtesting)."""
223 mt5 = self._require_connected()
224 timeframe_map = {
225 "1M": mt5.TIMEFRAME_M1,
226 "5M": mt5.TIMEFRAME_M5,
227 "15M": mt5.TIMEFRAME_M15,
228 "30M": mt5.TIMEFRAME_M30,
229 "1H": mt5.TIMEFRAME_H1,
230 "4H": mt5.TIMEFRAME_H4,
231 "1D": mt5.TIMEFRAME_D1,
232 "1W": mt5.TIMEFRAME_W1,
233 "1MN": mt5.TIMEFRAME_MN1,
234 }
235 if timeframe not in timeframe_map:
236 raise ValueError(f"Unsupported timeframe: {timeframe}")
237 self.get_symbol_info(symbol)
238 rates = mt5.copy_rates_range(symbol, timeframe_map[timeframe], start_date, end_date)
239 if rates is None:
240 raise RuntimeError(f"Failed to get historical data for {symbol}")
241 df = _rates_to_frame(rates)
242 mask = (df.index >= start_date) & (df.index <= end_date)
243 return df.loc[mask]
244
245 def get_positions(self, symbol: str | None = None) -> list[MT5Position]:
246 """Return open positions, optionally filtered by symbol."""
247 mt5 = self._require_connected()
248 positions = mt5.positions_get(symbol=symbol) if symbol else mt5.positions_get()
249 if positions is None:
250 return []
251 return [
252 MT5Position(
253 ticket=int(pos.ticket),
254 symbol=str(pos.symbol),
255 type=int(pos.type),
256 volume=float(pos.volume),
257 price_open=float(pos.price_open),
258 price_current=float(pos.price_current),
259 profit=float(pos.profit),
260 swap=float(pos.swap),
261 commission=float(pos.commission),
262 comment=str(pos.comment),
263 )
264 for pos in positions
265 ]
266
267 def place_order(
268 self,
269 symbol: str,
270 order_type: int,
271 volume: float,
272 price: float = 0.0,
273 sl: float = 0.0,
274 tp: float = 0.0,
275 comment: str = "Alice Bot",
276 deviation: int = 10,
277 ) -> bool:
278 """Place a market deal order."""
279 mt5 = self._require_connected()
280 symbol_info = self.get_symbol_info(symbol)
281 tick = mt5.symbol_info_tick(symbol)
282 if tick is None:
283 raise RuntimeError(f"No tick data for {symbol}")
284 if price <= 0.0:
285 is_buy = order_type == mt5.ORDER_TYPE_BUY
286 price = float(tick.ask if is_buy else tick.bid)
287 request: dict[str, Any] = {
288 "action": mt5.TRADE_ACTION_DEAL,
289 "symbol": symbol,
290 "volume": volume,
291 "type": order_type,
292 "price": price,
293 "sl": sl,
294 "tp": tp,
295 "deviation": deviation,
296 "magic": 234000,
297 "comment": comment,
298 "type_time": mt5.ORDER_TIME_GTC,
299 "type_filling": symbol_info.get("filling_mode", mt5.ORDER_FILLING_IOC),
300 }
301 self._assert_demo_account()
302 result = mt5.order_send(request)
303 if result is None or result.retcode != mt5.TRADE_RETCODE_DONE:
304 code = result.retcode if result is not None else mt5.last_error()
305 print(f"Order send failed, retcode={code}")
306 return False
307 print(f"Order placed successfully: {result.order}")
308 return True
309
310 def buy(
311 self,
312 symbol: str,
313 volume: float,
314 sl: float = 0.0,
315 tp: float = 0.0,
316 comment: str = "Alice Bot",
317 ) -> bool:
318 """Place a market buy order."""
319 mt5 = self._require_connected()
320 return self.place_order(
321 symbol=symbol,
322 order_type=mt5.ORDER_TYPE_BUY,
323 volume=volume,
324 sl=sl,
325 tp=tp,
326 comment=comment,
327 )
328
329 def sell(
330 self,
331 symbol: str,
332 volume: float,
333 sl: float = 0.0,
334 tp: float = 0.0,
335 comment: str = "Alice Bot",
336 ) -> bool:
337 """Place a market sell order."""
338 mt5 = self._require_connected()
339 return self.place_order(
340 symbol=symbol,
341 order_type=mt5.ORDER_TYPE_SELL,
342 volume=volume,
343 sl=sl,
344 tp=tp,
345 comment=comment,
346 )
347
348 def close_position(self, ticket: int) -> bool:
349 """Close an open position by ticket."""
350 mt5 = self._require_connected()
351 positions = mt5.positions_get(ticket=ticket)
352 if not positions:
353 print(f"Position {ticket} not found")
354 return False
355 pos = positions[0]
356 tick = mt5.symbol_info_tick(pos.symbol)
357 if tick is None:
358 raise RuntimeError(f"No tick data for {pos.symbol}")
359 is_long = pos.type == mt5.ORDER_TYPE_BUY
360 request: dict[str, Any] = {
361 "action": mt5.TRADE_ACTION_DEAL,
362 "position": ticket,
363 "symbol": pos.symbol,
364 "volume": pos.volume,
365 "type": mt5.ORDER_TYPE_SELL if is_long else mt5.ORDER_TYPE_BUY,
366 "price": float(tick.bid if is_long else tick.ask),
367 "deviation": 10,
368 "magic": 234000,
369 "comment": "Alice Bot Close",
370 "type_time": mt5.ORDER_TIME_GTC,
371 "type_filling": mt5.ORDER_FILLING_IOC,
372 }
373 self._assert_demo_account()
374 result = mt5.order_send(request)
375 if result is None or result.retcode != mt5.TRADE_RETCODE_DONE:
376 code = result.retcode if result is not None else mt5.last_error()
377 print(f"Position close failed, retcode={code}")
378 return False
379 print(f"Position {ticket} closed successfully")
380 return True
381
382
383 def _rates_to_frame(rates: Any) -> pd.DataFrame:
384 """Convert MT5 rates array to an OHLCV DataFrame."""
385 df = pd.DataFrame(rates)
386 df["time"] = pd.to_datetime(df["time"], unit="s")
387 df = df.set_index("time")
388 df = df.rename(
389 columns={
390 "open": "Open",
391 "high": "High",
392 "low": "Low",
393 "close": "Close",
394 "tick_volume": "Volume",
395 }
396 )
397 return df