File size: 13,351 Bytes
d8bad25 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | """
MT5 MCP Bridge β wraps the MetaTrader5 Python SDK into clean tool functions
for the AI agent to call. Supports both demo and live accounts.
Falls back to simulated data when MT5 is not available.
"""
import os
import time
import random
import math
from datetime import datetime, timedelta
from typing import Optional
from dotenv import load_dotenv
load_dotenv()
# Try to import MetaTrader5; if unavailable, use simulation mode
try:
import MetaTrader5 as mt5
MT5_AVAILABLE = True
except ImportError:
MT5_AVAILABLE = False
if os.getenv("FORCE_MT5_DATA", "false").lower() == "true":
raise ImportError("CRITICAL: MetaTrader5 package not found and FORCE_MT5_DATA=true")
print("[MT5] MetaTrader5 package not available β running in SIMULATION mode")
try:
import pandas as pd
PANDAS_AVAILABLE = True
except ImportError:
PANDAS_AVAILABLE = False
class MT5Bridge:
"""Bridge to MetaTrader 5 via the official Python SDK."""
TIMEFRAME_MAP = {
"M1": mt5.TIMEFRAME_M1 if MT5_AVAILABLE else 1,
"M5": mt5.TIMEFRAME_M5 if MT5_AVAILABLE else 5,
"M15": mt5.TIMEFRAME_M15 if MT5_AVAILABLE else 15,
"M30": mt5.TIMEFRAME_M30 if MT5_AVAILABLE else 30,
"H1": mt5.TIMEFRAME_H1 if MT5_AVAILABLE else 60,
"H4": mt5.TIMEFRAME_H4 if MT5_AVAILABLE else 240,
"D1": mt5.TIMEFRAME_D1 if MT5_AVAILABLE else 1440,
}
def __init__(self):
self.connected = False
self.simulation_mode = not MT5_AVAILABLE
self.symbol = os.getenv("TRADING_SYMBOL", "XAUUSDm")
self._sim_base_price = 2650.0
self._sim_positions = []
self._sim_ticket_counter = 1000
def initialize(self) -> dict:
"""Connect to the MT5 terminal."""
if self.simulation_mode:
if os.getenv("FORCE_MT5_DATA", "false").lower() == "true":
return {
"success": False,
"message": "CRITICAL: MT5 not available but FORCE_MT5_DATA is true. Exiting."
}
self.connected = True
return {
"success": True,
"message": "Running in SIMULATION mode (MT5 not available)",
"mode": "simulation"
}
mt5_path = os.getenv("MT5_PATH")
login = int(os.getenv("MT5_LOGIN", "0"))
password = os.getenv("MT5_PASSWORD", "")
server = os.getenv("MT5_SERVER", "")
init_kwargs = {}
if mt5_path:
init_kwargs["path"] = mt5_path
if not mt5.initialize(**init_kwargs):
err_code = mt5.last_error()
if os.getenv("FORCE_MT5_DATA", "false").lower() == "true":
return {"success": False, "message": f"CRITICAL: MT5 init failed: {err_code}"}
return {"success": False, "message": f"MT5 init failed: {err_code}"}
if login and password and server:
authorized = mt5.login(login=login, password=password, server=server)
if not authorized:
return {"success": False, "message": f"MT5 login failed: {mt5.last_error()}"}
self.connected = True
account = mt5.account_info()
mode = "demo" if account.trade_mode == 0 else "live"
return {
"success": True,
"message": f"Connected to MT5 ({mode}) β Account #{account.login}",
"mode": mode
}
def shutdown(self):
"""Disconnect from MT5."""
if not self.simulation_mode and MT5_AVAILABLE:
mt5.shutdown()
self.connected = False
def get_account_info(self) -> dict:
"""Get trading account information."""
if self.simulation_mode:
return {
"login": 12345678,
"balance": 10000.00,
"equity": 10000.00 + sum(p.get("profit", 0) for p in self._sim_positions),
"margin": sum(p.get("volume", 0) * 1000 for p in self._sim_positions),
"free_margin": 10000.00 - sum(p.get("volume", 0) * 1000 for p in self._sim_positions),
"margin_level": 0.0,
"profit": sum(p.get("profit", 0) for p in self._sim_positions),
"server": "SimulationServer",
"currency": "USD",
"trade_mode": os.getenv("ACCOUNT_MODE", "demo")
}
account = mt5.account_info()
if account is None:
return {"error": "Failed to get account info"}
return {
"login": account.login,
"balance": account.balance,
"equity": account.equity,
"margin": account.margin,
"free_margin": account.margin_free,
"margin_level": account.margin_level,
"profit": account.profit,
"server": account.server,
"currency": account.currency,
"trade_mode": "demo" if account.trade_mode == 0 else "live"
}
def get_rates(self, symbol: Optional[str] = None, timeframe: str = "M5", count: int = 200) -> list:
"""Fetch OHLCV candle data."""
symbol = symbol or self.symbol
if self.simulation_mode:
return self._simulate_candles(count, timeframe)
tf = self.TIMEFRAME_MAP.get(timeframe, mt5.TIMEFRAME_M5)
rates = mt5.copy_rates_from_pos(symbol, tf, 0, count)
if rates is None or len(rates) == 0:
return []
candles = []
for r in rates:
candles.append({
"time": int(r["time"]),
"open": float(r["open"]),
"high": float(r["high"]),
"low": float(r["low"]),
"close": float(r["close"]),
"volume": float(r["tick_volume"]),
})
return candles
def get_tick(self, symbol: Optional[str] = None) -> dict:
"""Get latest tick (bid/ask)."""
symbol = symbol or self.symbol
if self.simulation_mode:
price = self._sim_base_price + random.uniform(-5, 5)
spread = random.uniform(0.1, 0.5)
return {
"bid": round(price, 2),
"ask": round(price + spread, 2),
"time": int(time.time()),
"symbol": symbol
}
tick = mt5.symbol_info_tick(symbol)
if tick is None:
return {"error": f"No tick data for {symbol}"}
return {
"bid": tick.bid,
"ask": tick.ask,
"time": tick.time,
"symbol": symbol
}
def get_positions(self, symbol: Optional[str] = None) -> list:
"""List open positions."""
symbol = symbol or self.symbol
if self.simulation_mode:
tick = self.get_tick(symbol)
for p in self._sim_positions:
if p["type"] == "buy":
p["price_current"] = tick["bid"]
p["profit"] = round((tick["bid"] - p["price_open"]) * p["volume"] * 100, 2)
else:
p["price_current"] = tick["ask"]
p["profit"] = round((p["price_open"] - tick["ask"]) * p["volume"] * 100, 2)
return self._sim_positions
positions = mt5.positions_get(symbol=symbol)
if positions is None:
return []
result = []
for p in positions:
result.append({
"ticket": p.ticket,
"symbol": p.symbol,
"type": "buy" if p.type == 0 else "sell",
"volume": p.volume,
"price_open": p.price_open,
"price_current": p.price_current,
"sl": p.sl,
"tp": p.tp,
"profit": p.profit,
"time": p.time,
})
return result
def place_order(self, action: str, symbol: Optional[str] = None,
volume: float = 0.01, sl: float = 0.0, tp: float = 0.0) -> dict:
"""Place a market order (buy or sell)."""
symbol = symbol or self.symbol
if self.simulation_mode:
if os.getenv("FORCE_MT5_DATA", "false").lower() == "true":
return {"success": False, "message": "Cannot place mock order in STRICT MT5 mode."}
tick = self.get_tick(symbol)
price = tick["ask"] if action.lower() == "buy" else tick["bid"]
self._sim_ticket_counter += 1
pos = {
"ticket": self._sim_ticket_counter,
"symbol": symbol,
"type": action.lower(),
"volume": volume,
"price_open": price,
"price_current": price,
"sl": sl,
"tp": tp,
"profit": 0.0,
"time": int(time.time()),
}
self._sim_positions.append(pos)
return {"success": True, "ticket": pos["ticket"], "price": price, "action": action}
# Real MT5 order
tick = mt5.symbol_info_tick(symbol)
if tick is None:
return {"success": False, "message": f"Cannot get tick for {symbol}"}
order_type = mt5.ORDER_TYPE_BUY if action.lower() == "buy" else mt5.ORDER_TYPE_SELL
price = tick.ask if action.lower() == "buy" else tick.bid
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": volume,
"type": order_type,
"price": price,
"deviation": 20,
"magic": 3000000,
"comment": "Gemini3Flash-Agent",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_IOC,
}
if sl > 0:
request["sl"] = sl
if tp > 0:
request["tp"] = tp
result = mt5.order_send(request)
if result is None or result.retcode != mt5.TRADE_RETCODE_DONE:
error_msg = result.comment if result else "Unknown error"
return {"success": False, "message": error_msg}
return {
"success": True,
"ticket": result.order,
"price": result.price,
"action": action
}
def close_position(self, ticket: int) -> dict:
"""Close a specific position by ticket."""
if self.simulation_mode:
for i, p in enumerate(self._sim_positions):
if p["ticket"] == ticket:
closed = self._sim_positions.pop(i)
return {"success": True, "ticket": ticket, "profit": closed["profit"]}
return {"success": False, "message": f"Position {ticket} not found"}
positions = mt5.positions_get(ticket=ticket)
if not positions:
return {"success": False, "message": f"Position {ticket} not found"}
pos = positions[0]
close_type = mt5.ORDER_TYPE_SELL if pos.type == 0 else mt5.ORDER_TYPE_BUY
tick = mt5.symbol_info_tick(pos.symbol)
price = tick.bid if pos.type == 0 else tick.ask
request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": pos.symbol,
"volume": pos.volume,
"type": close_type,
"position": ticket,
"price": price,
"deviation": 20,
"magic": 3000000,
"comment": "Gemini3Flash-Close",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_IOC,
}
result = mt5.order_send(request)
if result is None or result.retcode != mt5.TRADE_RETCODE_DONE:
error_msg = result.comment if result else "Unknown error"
return {"success": False, "message": error_msg}
return {"success": True, "ticket": ticket, "profit": pos.profit}
# ββ Simulation helpers ββββββββββββββββββββββββββββββββββββββββββ
def _simulate_candles(self, count: int, timeframe: str = "M5") -> list:
"""Generate realistic-looking simulated gold candle data."""
tf_minutes = {
"M1": 1, "M5": 5, "M15": 15, "M30": 30,
"H1": 60, "H4": 240, "D1": 1440
}.get(timeframe, 5)
candles = []
now = int(time.time())
price = self._sim_base_price
for i in range(count):
t = now - (count - i) * tf_minutes * 60
change = random.gauss(0, 2.5)
o = round(price, 2)
c = round(price + change, 2)
h = round(max(o, c) + abs(random.gauss(0, 1.5)), 2)
low = round(min(o, c) - abs(random.gauss(0, 1.5)), 2)
vol = random.randint(50, 500)
candles.append({
"time": t,
"open": o,
"high": h,
"low": low,
"close": c,
"volume": vol,
})
price = c
self._sim_base_price = c
return candles
|