@devries-cameron20 / open-alice / commits / 5828743
Fork 0

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

Add Headway MT5 login: broker presets, saved credentials, broker CLI

Camo67 committed Oct 12, 2026 at 16:56 UTC 582874365b06e922c6f4ec0b36dcc17dfb9c7ea5
11 files changed +1128 -12
.env.example new
+6
@@ -0,0 +1,6 @@
1 +# Copy to ~/.config/open-alice/mt5.env (or let `alice broker login` create it).
2 +# File is chmod 600. Prefer `alice broker login` over editing by hand.
3 +MT5_LOGIN=12345678
4 +MT5_PASSWORD=change-me
5 +MT5_SERVER=Headway-Demo
6 +# Real account alternative: MT5_SERVER=Headway-Real
README.md
+26 -4
@@ -8,6 +8,8 @@
8 - **Strategy engine** — pluggable strategies with backtesting
9 - **Risk management** — position sizing, stop-loss, take-profit
10 - **Paper trading** — test without real money
11 +- **Live trading** — connect to MetaTrader 5 for execution
12 +- **Signal integration** — receive signals from TradingView and other platforms via webhooks
13 - **CLI interface** — simple command-line controls
14
15 ## Quick Start
@@ -16,11 +18,20 @@
18 # Install
19 pip install -e .
20
21 +# For webhook server functionality
22 +pip install -e ".[web]"
23 +
24 # Run paper trading
25 alice paper --strategy sma_crossover --symbol AAPL
26
27 # Backtest
23 -alice backtest --strategy sma_crossover --symbol AAPL --start 2024-01-01 --end 2025-01-01
28 +alice backtest --strategy sma_crossover --symbol AAPL --period 1y
29 +
30 +# Live trading (requires MetaTrader 5 terminal running)
31 +alice live --symbol EURUSD --strategy sma_crossover --login 12345678 --password your_password --server your_server
32 +
33 +# Start webhook server for signals (e.g., from TradingView)
34 +alice serve --host 0.0.0.0 --port 5000
35 ```
36
37 ## Project Structure
@@ -31,14 +42,25 @@ open-alice/
42 │ └── open_alice/
43 │ ├── __init__.py
44 │ ├── __main__.py
45 +│ ├── broker/ # Broker integrations
46 +│ │ ├── __init__.py
47 +│ │ └── mt5.py # MetaTrader 5 integration
48 │ ├── cli.py # CLI entry point
49 │ ├── data.py # Market data fetching
36 -│ ├── strategies/ # Trading strategies
50 │ ├── engine/ # Backtesting & execution engine
51 +│ ├── signals/ # Signal reception
52 +│ │ ├── __init__.py
53 +│ │ └── webhook.py # Webhook signal receiver
54 +│ ├── strategies/ # Trading strategies
55 │ └── risk/ # Risk management
39 -└── tests/
56 +├── tests/
57 +├── .github/
58 +│ └── workflows/
59 +│ └── ci.yml # GitHub Actions CI
60 +├── Dockerfile # Container build instructions
61 +└── docker-compose.yml # Easy deployment configuration
62 ```
63
64 ## License
65
44 -AGPL-3.0
66 +AGPL-3.0
\ No newline at end of file
pyproject.toml
+8 -2
@@ -20,9 +20,15 @@ dev = [
20 "mypy>=1.8",
21 "pandas-stubs>=2.0",
22 ]
23 +web = [
24 + "flask>=2.0",
25 +]
26 +mt5 = [
27 + "MetaTrader5>=5.0.45; sys_platform == 'win32'",
28 +]
29
30 [[tool.mypy.overrides]]
25 -module = ["yfinance.*"]
31 +module = ["yfinance.*", "MetaTrader5", "flask.*"]
32 ignore_missing_imports = true
33
34 [tool.ruff]
@@ -34,4 +40,4 @@ select = ["E", "F", "I", "N", "UP", "B", "SIM"]
40
41 [tool.mypy]
42 python_version = "3.11"
37 -strict = true
43 +strict = true
\ No newline at end of file
src/open_alice/broker/__init__.py new
+25
@@ -0,0 +1,25 @@
1 +"""Broker integrations (MetaTrader 5 / Headway)."""
2 +
3 +from open_alice.broker.config import (
4 + clear_credentials,
5 + get_credentials_path,
6 + load_credentials,
7 + save_credentials,
8 +)
9 +from open_alice.broker.headway import (
10 + list_headway_servers,
11 + resolve_headway_server,
12 +)
13 +from open_alice.broker.mt5 import MT5AccountInfo, MT5Broker, MT5Position
14 +
15 +__all__ = [
16 + "MT5Broker",
17 + "MT5AccountInfo",
18 + "MT5Position",
19 + "list_headway_servers",
20 + "resolve_headway_server",
21 + "load_credentials",
22 + "save_credentials",
23 + "clear_credentials",
24 + "get_credentials_path",
25 +]
src/open_alice/broker/config.py new
+74
@@ -0,0 +1,74 @@
1 +"""Local storage for MT5 / Headway credentials (file-based, chmod 600)."""
2 +
3 +from __future__ import annotations
4 +
5 +import os
6 +from pathlib import Path
7 +
8 +
9 +def get_config_dir() -> Path:
10 + """Return the per-user config directory for open-alice."""
11 + base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
12 + return Path(base) / "open-alice"
13 +
14 +
15 +def get_credentials_path() -> Path:
16 + """Return the path of the saved MT5 credentials file."""
17 + return get_config_dir() / "mt5.env"
18 +
19 +
20 +def save_credentials(login: int, password: str, server: str) -> Path:
21 + """Save MT5 credentials to a user-only readable file.
22 +
23 + Args:
24 + login: MT5 account number.
25 + password: MT5 password (trade password, not investor-only if trading).
26 + server: MT5 server name (e.g. Headway-Demo).
27 +
28 + Returns:
29 + Path of the written file.
30 + """
31 + path = get_credentials_path()
32 + path.parent.mkdir(parents=True, exist_ok=True)
33 + # Minimal .env format without extra dependencies.
34 + content = f'MT5_LOGIN={login}\nMT5_PASSWORD={password}\nMT5_SERVER={server}\n'
35 + path.write_text(content, encoding="utf-8")
36 + try:
37 + os.chmod(path, 0o600)
38 + except OSError:
39 + pass
40 + return path
41 +
42 +
43 +def load_credentials() -> dict[str, str] | None:
44 + """Load saved MT5 credentials, checking file then environment.
45 +
46 + Returns:
47 + Dict with login/password/server, or None when nothing is stored.
48 + """
49 + path = get_credentials_path()
50 + data: dict[str, str] = {}
51 + if path.is_file():
52 + for line in path.read_text(encoding="utf-8").splitlines():
53 + line = line.strip()
54 + if not line or line.startswith("#") or "=" not in line:
55 + continue
56 + key, _, value = line.partition("=")
57 + data[key.strip()] = value.strip().strip('"').strip("'")
58 +
59 + # Environment variables act as fallback / override when file is absent.
60 + login = data.get("MT5_LOGIN") or os.environ.get("MT5_LOGIN", "")
61 + password = data.get("MT5_PASSWORD") or os.environ.get("MT5_PASSWORD", "")
62 + server = data.get("MT5_SERVER") or os.environ.get("MT5_SERVER", "")
63 + if not login or not password or not server:
64 + return None
65 + return {"login": login, "password": password, "server": server}
66 +
67 +
68 +def clear_credentials() -> bool:
69 + """Delete the saved credentials file. Returns True if something was removed."""
70 + path = get_credentials_path()
71 + if path.is_file():
72 + path.unlink()
73 + return True
74 + return False
src/open_alice/broker/headway.py new
+49
@@ -0,0 +1,49 @@
1 +"""Headway broker presets for MetaTrader 5."""
2 +
3 +from __future__ import annotations
4 +
5 +# Official Headway MT5 servers (from Headway support docs).
6 +# Demo: Headway-Demo (mt5.demo.trade-hw.online)
7 +# Real: Headway-Real (mt5.real.trade-hw.online)
8 +HEADWAY_DEMO_SERVERS: tuple[str, ...] = (
9 + "Headway-Demo",
10 + "mt5.demo.trade-hw.online",
11 +)
12 +
13 +HEADWAY_REAL_SERVERS: tuple[str, ...] = (
14 + "Headway-Real",
15 + "mt5.real.trade-hw.online",
16 +)
17 +
18 +DEFAULT_DEMO_SERVER = "Headway-Demo"
19 +DEFAULT_REAL_SERVER = "Headway-Real"
20 +
21 +
22 +def list_headway_servers() -> dict[str, tuple[str, ...]]:
23 + """Return known Headway servers grouped by account type."""
24 + return {"demo": HEADWAY_DEMO_SERVERS, "real": HEADWAY_REAL_SERVERS}
25 +
26 +
27 +def resolve_headway_server(server: str | None, demo: bool = False) -> str:
28 + """Resolve a user-supplied server value to a concrete Headway server name.
29 +
30 + Args:
31 + server: Raw server string, or None to use the default.
32 + demo: If True and server is None, return the demo server.
33 +
34 + Returns:
35 + Concrete server name to pass to MT5 login.
36 + """
37 + if server is None or not server.strip():
38 + return DEFAULT_DEMO_SERVER if demo else DEFAULT_REAL_SERVER
39 +
40 + cleaned = server.strip()
41 + lowered = cleaned.lower()
42 +
43 + # Accept shortcuts like "demo", "real", "headway-demo", "headway-real".
44 + if lowered in {"demo", "headway-demo", "headway demo"}:
45 + return DEFAULT_DEMO_SERVER
46 + if lowered in {"real", "headway-real", "headway real"}:
47 + return DEFAULT_REAL_SERVER
48 +
49 + return cleaned
src/open_alice/broker/mt5.py new
+354
@@ -0,0 +1,354 @@
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, Optional
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 + import MetaTrader5 as mt5 # type: ignore[import-untyped]
16 + except ImportError as exc:
17 + raise RuntimeError(
18 + "The MetaTrader5 package is not installed or not supported on this "
19 + "platform. It officially supports Windows only. Install the Headway "
20 + "MT5 terminal on Windows (or a Windows VPS / Wine), then run "
21 + "'pip install MetaTrader5'. Original error: "
22 + f"{exc}"
23 + ) from exc
24 + return mt5
25 +
26 +
27 +@dataclass
28 +class MT5AccountInfo:
29 + """Account information from MT5."""
30 +
31 + login: int
32 + balance: float
33 + equity: float
34 + margin: float
35 + free_margin: float
36 + margin_level: float
37 + currency: str
38 + leverage: int
39 + trade_allowed: bool
40 + trade_expert: bool
41 + connected: bool
42 +
43 +
44 +@dataclass
45 +class MT5Position:
46 + """Position information from MT5."""
47 +
48 + ticket: int
49 + symbol: str
50 + type: int # 0 for buy, 1 for sell
51 + volume: float
52 + price_open: float
53 + price_current: float
54 + profit: float
55 + swap: float
56 + commission: float
57 + comment: str
58 +
59 +
60 +class MT5Broker:
61 + """MetaTrader 5 broker interface (incl. Headway servers)."""
62 +
63 + def __init__(
64 + self,
65 + login: Optional[int] = None,
66 + password: Optional[str] = None,
67 + server: Optional[str] = None,
68 + timeout: int = 60000,
69 + terminal_path: Optional[str] = None,
70 + ) -> None:
71 + """Initialize MT5 broker connection.
72 +
73 + Args:
74 + login: MT5 account login (if None, attaches to the open terminal).
75 + password: MT5 account password.
76 + server: MT5 server name, e.g. Headway-Demo or Headway-Real.
77 + timeout: Connection timeout in milliseconds.
78 + terminal_path: Optional path to terminal64.exe (useful under Wine).
79 + """
80 + self.login = login
81 + self.password = password
82 + self.server = server
83 + self.timeout = timeout
84 + self.terminal_path = terminal_path
85 + self.connected = False
86 + self.account_info: MT5AccountInfo | None = None
87 +
88 + def connect(self) -> bool:
89 + """Initialize connection to the MT5 terminal.
90 +
91 + Returns:
92 + True if connection succeeded, False otherwise.
93 + """
94 + mt5 = _load_mt5()
95 + kwargs: dict[str, Any] = {"timeout": self.timeout}
96 + if self.terminal_path:
97 + kwargs["path"] = self.terminal_path
98 + if self.login is not None:
99 + kwargs["login"] = self.login
100 + if self.password is not None:
101 + kwargs["password"] = self.password
102 + if self.server is not None:
103 + kwargs["server"] = self.server
104 + if not mt5.initialize(**kwargs):
105 + print(f"MT5 initialize() failed, error code = {mt5.last_error()}")
106 + print("Check: MT5 terminal installed, login/password/server correct.")
107 + return False
108 +
109 + self.connected = True
110 + self.account_info = self._get_account_info()
111 + print(f"Connected to MT5 account #{self.account_info.login}")
112 + return True
113 +
114 + def disconnect(self) -> None:
115 + """Disconnect from the MT5 terminal."""
116 + if not self.connected:
117 + return
118 + mt5 = _load_mt5()
119 + mt5.shutdown()
120 + self.connected = False
121 + print("Disconnected from MT5")
122 +
123 + def _require_connected(self) -> Any:
124 + if not self.connected:
125 + raise ConnectionError("Not connected to MT5. Call connect() first.")
126 + return _load_mt5()
127 +
128 + def _get_account_info(self) -> MT5AccountInfo:
129 + """Fetch account information from MT5."""
130 + mt5 = self._require_connected()
131 + info = mt5.account_info()
132 + if info is None:
133 + raise RuntimeError(f"Failed to get account info: {mt5.last_error()}")
134 + return MT5AccountInfo(
135 + login=int(info.login),
136 + balance=float(info.balance),
137 + equity=float(info.equity),
138 + margin=float(info.margin),
139 + free_margin=float(info.margin_free),
140 + margin_level=float(info.margin_level),
141 + currency=str(info.currency),
142 + leverage=int(info.leverage),
143 + trade_allowed=bool(info.trade_allowed),
144 + trade_expert=bool(info.trade_expert),
145 + connected=True,
146 + )
147 +
148 + def get_account_info(self) -> MT5AccountInfo:
149 + """Return current account information."""
150 + return self._get_account_info()
151 +
152 + def get_symbol_info(self, symbol: str) -> dict[str, Any]:
153 + """Return symbol info, selecting the symbol in MarketWatch if needed."""
154 + mt5 = self._require_connected()
155 + info = mt5.symbol_info(symbol)
156 + if info is None:
157 + if not mt5.symbol_select(symbol, True):
158 + raise ValueError(f"Symbol {symbol} not found: {mt5.last_error()}")
159 + info = mt5.symbol_info(symbol)
160 + if info is None:
161 + raise RuntimeError(f"Failed to get symbol info for {symbol}")
162 + result: dict[str, Any] = dict(info._asdict())
163 + return result
164 +
165 + def get_rates(self, symbol: str, timeframe: int, count: int = 1000) -> pd.DataFrame:
166 + """Return recent OHLCV bars as a DataFrame indexed by time."""
167 + mt5 = self._require_connected()
168 + self.get_symbol_info(symbol)
169 + rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, count)
170 + if rates is None:
171 + raise RuntimeError(f"Failed to get rates for {symbol}: {mt5.last_error()}")
172 + return _rates_to_frame(rates)
173 +
174 + def get_historical_data(
175 + self,
176 + symbol: str,
177 + timeframe: str,
178 + start_date: datetime,
179 + end_date: datetime,
180 + ) -> pd.DataFrame:
181 + """Return OHLCV data between two dates (for backtesting)."""
182 + mt5 = self._require_connected()
183 + timeframe_map = {
184 + "1M": mt5.TIMEFRAME_M1,
185 + "5M": mt5.TIMEFRAME_M5,
186 + "15M": mt5.TIMEFRAME_M15,
187 + "30M": mt5.TIMEFRAME_M30,
188 + "1H": mt5.TIMEFRAME_H1,
189 + "4H": mt5.TIMEFRAME_H4,
190 + "1D": mt5.TIMEFRAME_D1,
191 + "1W": mt5.TIMEFRAME_W1,
192 + "1MN": mt5.TIMEFRAME_MN1,
193 + }
194 + if timeframe not in timeframe_map:
195 + raise ValueError(f"Unsupported timeframe: {timeframe}")
196 + self.get_symbol_info(symbol)
197 + rates = mt5.copy_rates_range(symbol, timeframe_map[timeframe], start_date, end_date)
198 + if rates is None:
199 + raise RuntimeError(f"Failed to get historical data for {symbol}")
200 + df = _rates_to_frame(rates)
201 + mask = (df.index >= start_date) & (df.index <= end_date)
202 + return df.loc[mask]
203 +
204 + def get_positions(self, symbol: Optional[str] = None) -> list[MT5Position]:
205 + """Return open positions, optionally filtered by symbol."""
206 + mt5 = self._require_connected()
207 + positions = mt5.positions_get(symbol=symbol) if symbol else mt5.positions_get()
208 + if positions is None:
209 + return []
210 + return [
211 + MT5Position(
212 + ticket=int(pos.ticket),
213 + symbol=str(pos.symbol),
214 + type=int(pos.type),
215 + volume=float(pos.volume),
216 + price_open=float(pos.price_open),
217 + price_current=float(pos.price_current),
218 + profit=float(pos.profit),
219 + swap=float(pos.swap),
220 + commission=float(pos.commission),
221 + comment=str(pos.comment),
222 + )
223 + for pos in positions
224 + ]
225 +
226 + def place_order(
227 + self,
228 + symbol: str,
229 + order_type: int,
230 + volume: float,
231 + price: float = 0.0,
232 + sl: float = 0.0,
233 + tp: float = 0.0,
234 + comment: str = "Alice Bot",
235 + deviation: int = 10,
236 + ) -> bool:
237 + """Place a market deal order."""
238 + mt5 = self._require_connected()
239 + symbol_info = self.get_symbol_info(symbol)
240 + tick = mt5.symbol_info_tick(symbol)
241 + if tick is None:
242 + raise RuntimeError(f"No tick data for {symbol}")
243 + if price <= 0.0:
244 + is_buy = order_type == mt5.ORDER_TYPE_BUY
245 + price = float(tick.ask if is_buy else tick.bid)
246 + request: dict[str, Any] = {
247 + "action": mt5.TRADE_ACTION_DEAL,
248 + "symbol": symbol,
249 + "volume": volume,
250 + "type": order_type,
251 + "price": price,
252 + "sl": sl,
253 + "tp": tp,
254 + "deviation": deviation,
255 + "magic": 234000,
256 + "comment": comment,
257 + "type_time": mt5.ORDER_TIME_GTC,
258 + "type_filling": symbol_info.get("filling_mode", mt5.ORDER_FILLING_IOC),
259 + }
260 + result = mt5.order_send(request)
261 + if result is None or result.retcode != mt5.TRADE_RETCODE_DONE:
262 + code = result.retcode if result is not None else mt5.last_error()
263 + print(f"Order send failed, retcode={code}")
264 + return False
265 + print(f"Order placed successfully: {result.order}")
266 + return True
267 +
268 + def buy(
269 + self,
270 + symbol: str,
271 + volume: float,
272 + sl: float = 0.0,
273 + tp: float = 0.0,
274 + comment: str = "Alice Bot",
275 + ) -> bool:
276 + """Place a market buy order."""
277 + mt5 = self._require_connected()
278 + return self.place_order(
279 + symbol=symbol,
280 + order_type=mt5.ORDER_TYPE_BUY,
281 + volume=volume,
282 + sl=sl,
283 + tp=tp,
284 + comment=comment,
285 + )
286 +
287 + def sell(
288 + self,
289 + symbol: str,
290 + volume: float,
291 + sl: float = 0.0,
292 + tp: float = 0.0,
293 + comment: str = "Alice Bot",
294 + ) -> bool:
295 + """Place a market sell order."""
296 + mt5 = self._require_connected()
297 + return self.place_order(
298 + symbol=symbol,
299 + order_type=mt5.ORDER_TYPE_SELL,
300 + volume=volume,
301 + sl=sl,
302 + tp=tp,
303 + comment=comment,
304 + )
305 +
306 + def close_position(self, ticket: int) -> bool:
307 + """Close an open position by ticket."""
308 + mt5 = self._require_connected()
309 + positions = mt5.positions_get(ticket=ticket)
310 + if not positions:
311 + print(f"Position {ticket} not found")
312 + return False
313 + pos = positions[0]
314 + tick = mt5.symbol_info_tick(pos.symbol)
315 + if tick is None:
316 + raise RuntimeError(f"No tick data for {pos.symbol}")
317 + is_long = pos.type == mt5.ORDER_TYPE_BUY
318 + request: dict[str, Any] = {
319 + "action": mt5.TRADE_ACTION_DEAL,
320 + "position": ticket,
321 + "symbol": pos.symbol,
322 + "volume": pos.volume,
323 + "type": mt5.ORDER_TYPE_SELL if is_long else mt5.ORDER_TYPE_BUY,
324 + "price": float(tick.bid if is_long else tick.ask),
325 + "deviation": 10,
326 + "magic": 234000,
327 + "comment": "Alice Bot Close",
328 + "type_time": mt5.ORDER_TIME_GTC,
329 + "type_filling": mt5.ORDER_FILLING_IOC,
330 + }
331 + result = mt5.order_send(request)
332 + if result is None or result.retcode != mt5.TRADE_RETCODE_DONE:
333 + code = result.retcode if result is not None else mt5.last_error()
334 + print(f"Position close failed, retcode={code}")
335 + return False
336 + print(f"Position {ticket} closed successfully")
337 + return True
338 +
339 +
340 +def _rates_to_frame(rates: Any) -> pd.DataFrame:
341 + """Convert MT5 rates array to an OHLCV DataFrame."""
342 + df = pd.DataFrame(rates)
343 + df["time"] = pd.to_datetime(df["time"], unit="s")
344 + df = df.set_index("time")
345 + df = df.rename(
346 + columns={
347 + "open": "Open",
348 + "high": "High",
349 + "low": "Low",
350 + "close": "Close",
351 + "tick_volume": "Volume",
352 + }
353 + )
354 + return df
src/open_alice/cli.py
+374 -6
@@ -3,9 +3,21 @@
3 from __future__ import annotations
4
5 import argparse
6 +import getpass
7 +import sys
8
9 +from open_alice.broker import (
10 + clear_credentials,
11 + get_credentials_path,
12 + list_headway_servers,
13 + load_credentials,
14 + resolve_headway_server,
15 + save_credentials,
16 +)
17 +from open_alice.broker.mt5 import MT5Broker
18 from open_alice.data import add_returns, fetch_ohlcv
19 from open_alice.engine import run_backtest, run_paper
20 +from open_alice.signals.webhook import TradingViewSignalReceiver, create_webhook_app
21 from open_alice.strategies import (
22 BollingerStrategy,
23 MacdStrategy,
@@ -37,6 +49,7 @@ def main() -> None:
49 bt.add_argument("--capital", type=float, default=100_000, help="Initial capital")
50 bt.add_argument("--fast", type=int, default=20, help="Fast SMA period")
51 bt.add_argument("--slow", type=int, default=50, help="Slow SMA period")
52 + bt.add_argument("--use-mt5", action="store_true", help="Use MT5 for data")
53
54 # Paper trading command
55 paper = subparsers.add_parser("paper", help="Run paper trading simulation")
@@ -45,6 +58,40 @@ def main() -> None:
58 paper.add_argument("--period", default="1y", help="Data period")
59 paper.add_argument("--capital", type=float, default=100_000, help="Initial capital")
60 paper.add_argument("--risk", type=float, default=0.02, help="Risk per trade")
61 + paper.add_argument("--use-mt5", action="store_true", help="Use MT5 for data")
62 +
63 + # Live trading command (Headway via MT5)
64 + live = subparsers.add_parser("live", help="Run live trading with MT5/Headway")
65 + live.add_argument("--symbol", default="EURUSD", help="Ticker symbol")
66 + live.add_argument("--strategy", default="sma_crossover", choices=STRATEGIES.keys())
67 + live.add_argument("--fast", type=int, default=20, help="Fast SMA period")
68 + live.add_argument("--slow", type=int, default=50, help="Slow SMA period")
69 + live.add_argument("--login", type=int, help="MT5 login (defaults to saved)")
70 + live.add_argument("--password", type=str, help="MT5 password (defaults to saved)")
71 + live.add_argument("--server", type=str, help="MT5 server (defaults to saved)")
72 + live.add_argument("--demo", action="store_true", help="Use Headway demo server")
73 + live.add_argument("--risk", type=float, default=0.02, help="Risk per trade")
74 + live.add_argument("--interval", type=int, default=60, help="Check interval (seconds)")
75 + live.add_argument("--execute", action="store_true", help="Actually place orders")
76 +
77 + # Broker account management (Headway via MT5)
78 + broker = subparsers.add_parser("broker", help="Manage MT5 / Headway login")
79 + broker_sub = broker.add_subparsers(dest="broker_command", required=True)
80 +
81 + b_login = broker_sub.add_parser("login", help="Save Headway MT5 credentials")
82 + b_login.add_argument("--login", type=int, help="MT5 account number")
83 + b_login.add_argument("--server", type=str, help="MT5 server or 'demo'/'real'")
84 + b_login.add_argument("--demo", action="store_true", help="Shortcut for Headway demo")
85 + b_login.add_argument("--terminal-path", type=str, help="Path to terminal64.exe")
86 +
87 + broker_sub.add_parser("status", help="Show saved login and test connection")
88 + broker_sub.add_parser("logout", help="Delete saved MT5 credentials")
89 +
90 + # Webhook server command
91 + webhook = subparsers.add_parser("serve", help="Start webhook server for signals")
92 + webhook.add_argument("--host", default="0.0.0.0", help="Host to bind to")
93 + webhook.add_argument("--port", type=int, default=5000, help="Port to bind to")
94 + webhook.add_argument("--secret", type=str, help="Secret for request validation")
95
96 args = parser.parse_args()
97
@@ -52,21 +99,67 @@ def main() -> None:
99 _run_backtest(args)
100 elif args.command == "paper":
101 _run_paper(args)
102 + elif args.command == "live":
103 + _run_live(args)
104 + elif args.command == "broker":
105 + _run_broker(args)
106 + elif args.command == "serve":
107 + _run_webhook(args)
108
109
110 def _build_strategy(name: str, args: argparse.Namespace) -> Strategy:
111 if name == "sma_crossover":
59 - return SmaCrossover(fast=args.fast, slow=args.slow)
60 - return STRATEGIES[name]()
112 + fast = int(getattr(args, "fast", 20))
113 + slow = int(getattr(args, "slow", 50))
114 + return SmaCrossover(fast=fast, slow=slow)
115 + factory = STRATEGIES[name]
116 + return factory()
117 +
118 +
119 +def _mt5_login_from_args(args: argparse.Namespace) -> tuple[int | None, str | None, str | None]:
120 + """Resolve MT5 credentials from flags, then saved file, then env."""
121 + login = getattr(args, "login", None)
122 + password = getattr(args, "password", None)
123 + server = getattr(args, "server", None)
124 + if login is not None and password is not None and server is not None:
125 + return int(login), str(password), str(server)
126 + saved = load_credentials()
127 + if saved is not None:
128 + return int(saved["login"]), saved["password"], saved["server"]
129 + return None, None, None
130
131
132 def _run_backtest(args: argparse.Namespace) -> None:
133 + use_mt5 = bool(getattr(args, "use_mt5", False))
134 print(f"\n{'='*60}")
135 print(f" Alice Backtest — {args.symbol}")
136 print(f" Strategy: {args.strategy} | Period: {args.period} | Capital: ${args.capital:,.0f}")
137 + print(f" Data Source: {'MT5' if use_mt5 else 'Yahoo Finance'}")
138 print(f"{'='*60}\n")
139
69 - df = fetch_ohlcv(args.symbol, period=args.period)
140 + if use_mt5:
141 + import datetime
142 +
143 + login, password, server = _mt5_login_from_args(args)
144 + broker = MT5Broker(login=login, password=password, server=server)
145 + try:
146 + if broker.connect():
147 + end_date = datetime.datetime.now()
148 + start_date = end_date - datetime.timedelta(days=365)
149 + df = broker.get_historical_data(args.symbol, "1D", start_date, end_date)
150 + broker.disconnect()
151 + if df.empty:
152 + print("Warning: MT5 returned no data, falling back to Yahoo Finance")
153 + df = fetch_ohlcv(args.symbol, period=args.period)
154 + else:
155 + print("Warning: MT5 connect failed, falling back to Yahoo Finance")
156 + df = fetch_ohlcv(args.symbol, period=args.period)
157 + except Exception as exc:
158 + print(f"Warning: MT5 error ({exc}), falling back to Yahoo Finance")
159 + df = fetch_ohlcv(args.symbol, period=args.period)
160 + else:
161 + df = fetch_ohlcv(args.symbol, period=args.period)
162 +
163 df = add_returns(df)
164
165 strategy = _build_strategy(args.strategy, args)
@@ -83,18 +176,44 @@ def _run_backtest(args: argparse.Namespace) -> None:
176
177
178 def _run_paper(args: argparse.Namespace) -> None:
179 + use_mt5 = bool(getattr(args, "use_mt5", False))
180 print(f"\n{'='*60}")
181 print(f" Alice Paper Trading — {args.symbol}")
182 print(f" Strategy: {args.strategy} | Period: {args.period} | Capital: ${args.capital:,.0f}")
183 + print(f" Data Source: {'MT5' if use_mt5 else 'Yahoo Finance'}")
184 print(f"{'='*60}\n")
185
91 - df = fetch_ohlcv(args.symbol, period=args.period)
186 + if use_mt5:
187 + login, password, server = _mt5_login_from_args(args)
188 + broker = MT5Broker(login=login, password=password, server=server)
189 + try:
190 + from typing import Any
191 +
192 + mt5: Any = __import__("MetaTrader5")
193 + if broker.connect():
194 + df = broker.get_rates(args.symbol, mt5.TIMEFRAME_D1, 100)
195 + broker.disconnect()
196 + if df.empty:
197 + print("Warning: MT5 returned no data, falling back to Yahoo Finance")
198 + df = fetch_ohlcv(args.symbol, period=args.period)
199 + else:
200 + print("Warning: MT5 connect failed, falling back to Yahoo Finance")
201 + df = fetch_ohlcv(args.symbol, period=args.period)
202 + except Exception as exc:
203 + print(f"Warning: MT5 error ({exc}), falling back to Yahoo Finance")
204 + df = fetch_ohlcv(args.symbol, period=args.period)
205 + else:
206 + df = fetch_ohlcv(args.symbol, period=args.period)
207 +
208 df = add_returns(df)
209
210 strategy = _build_strategy(args.strategy, args)
211 portfolio = run_paper(
96 - df, strategy, args.symbol,
97 - initial_capital=args.capital, risk_per_trade=args.risk,
212 + df,
213 + strategy,
214 + args.symbol,
215 + initial_capital=args.capital,
216 + risk_per_trade=args.risk,
217 )
218
219 print(f" Final Equity: ${portfolio.equity:>10,.2f}")
@@ -120,5 +239,254 @@ def _run_paper(args: argparse.Namespace) -> None:
239 print(f"\n{'='*60}\n")
240
241
242 +def _run_broker(args: argparse.Namespace) -> None:
243 + action = getattr(args, "broker_command", None)
244 + if action == "login":
245 + _broker_login(args)
246 + elif action == "status":
247 + _broker_status()
248 + elif action == "logout":
249 + if clear_credentials():
250 + print("Saved MT5 credentials deleted.")
251 + else:
252 + print("No saved MT5 credentials found.")
253 +
254 +
255 +def _broker_login(args: argparse.Namespace) -> None:
256 + servers = list_headway_servers()
257 + print("\n Headway MT5 servers:")
258 + print(f" Demo: {', '.join(servers['demo'])}")
259 + print(f" Real: {', '.join(servers['real'])}")
260 + print(" Tip: install MT5 from Headway so these servers are preloaded.\n")
261 +
262 + raw_login = getattr(args, "login", None)
263 + if raw_login is None:
264 + entered = input(" MT5 login (account number): ").strip()
265 + if not entered:
266 + print(" Login cancelled.")
267 + return
268 + raw_login = int(entered)
269 +
270 + raw_server = getattr(args, "server", None)
271 + demo = bool(getattr(args, "demo", False))
272 + if raw_server is None:
273 + if not demo:
274 + entered = input(" MT5 server [Headway-Demo / Headway-Real]: ").strip()
275 + raw_server = entered or None
276 + server = resolve_headway_server(raw_server, demo=demo)
277 +
278 + password = getpass.getpass(f" MT5 password for {raw_login} on {server}: ")
279 + if not password:
280 + print(" Login cancelled (empty password).")
281 + return
282 +
283 + terminal_path = getattr(args, "terminal_path", None)
284 + broker = MT5Broker(login=int(raw_login), password=password, server=server)
285 + if terminal_path:
286 + broker.terminal_path = terminal_path
287 + print(f"\n Connecting to {server} as {raw_login} ...")
288 + try:
289 + ok = broker.connect()
290 + except RuntimeError as exc:
291 + print(f"\n {exc}")
292 + return
293 + if not ok:
294 + print(" Login failed. Check login / password / server and retry.")
295 + return
296 + try:
297 + info = broker.get_account_info()
298 + print(f" Connected! Balance: {info.balance:.2f} {info.currency} "
299 + f"Equity: {info.equity:.2f}")
300 + finally:
301 + broker.disconnect()
302 + path = save_credentials(int(raw_login), password, server)
303 + print(f" Credentials saved to {path} (mode 600).")
304 + print(" Future commands (live/backtest/paper --use-mt5) will reuse them.\n")
305 +
306 +
307 +def _broker_status() -> None:
308 + saved = load_credentials()
309 + if saved is None:
310 + print(f"No saved credentials ({get_credentials_path()}).")
311 + print("Run: alice broker login --demo (or --server Headway-Real)")
312 + return
313 + print(f"Saved login: {saved['login']} server: {saved['server']}")
314 + print(f"File: {get_credentials_path()}")
315 + print("Testing connection ...")
316 + broker = MT5Broker(
317 + login=int(saved["login"]),
318 + password=saved["password"],
319 + server=saved["server"],
320 + )
321 + try:
322 + if not broker.connect():
323 + print("Connection failed. Re-run 'alice broker login'.")
324 + return
325 + info = broker.get_account_info()
326 + print(f"OK: balance={info.balance:.2f} {info.currency} equity={info.equity:.2f} "
327 + f"leverage=1:{info.leverage} trade_allowed={info.trade_allowed}")
328 + positions = broker.get_positions()
329 + print(f"Open positions: {len(positions)}")
330 + for pos in positions[:10]:
331 + side = "BUY" if pos.type == 0 else "SELL"
332 + print(f" #{pos.ticket} {side} {pos.symbol} {pos.volume} "
333 + f"open={pos.price_open} now={pos.price_current} pnl={pos.profit:.2f}")
334 + except RuntimeError as exc:
335 + print(f"{exc}")
336 + finally:
337 + if broker.connected:
338 + broker.disconnect()
339 +
340 +
341 +def _run_live(args: argparse.Namespace) -> None:
342 + print(f"\n{'='*60}")
343 + print(f" Alice Live Trading — {args.symbol}")
344 + print(f" Strategy: {args.strategy}")
345 + print(f"{'='*60}\n")
346 +
347 + try:
348 + from typing import Any
349 +
350 + mt5: Any = __import__("MetaTrader5")
351 + except ImportError:
352 + print("Error: MetaTrader5 package not installed (Windows only).")
353 + print("Run on Windows / a Windows VPS with Headway MT5 installed:")
354 + print(" pip install MetaTrader5")
355 + sys.exit(1)
356 +
357 + demo = bool(getattr(args, "demo", False))
358 + raw_server = getattr(args, "server", None)
359 + login = getattr(args, "login", None)
360 + password = getattr(args, "password", None)
361 + if login is None or password is None or raw_server is None:
362 + saved = load_credentials()
363 + if saved is not None:
364 + if login is None:
365 + login = int(saved["login"])
366 + if password is None:
367 + password = saved["password"]
368 + if raw_server is None:
369 + raw_server = saved["server"]
370 + server = resolve_headway_server(raw_server, demo=demo)
371 + if login is None or password is None:
372 + print("No MT5 credentials. Run first:")
373 + print(" alice broker login --demo # or --server Headway-Real")
374 + sys.exit(1)
375 +
376 + broker = MT5Broker(login=int(login), password=password, server=server)
377 + if not broker.connect():
378 + print("Failed to connect. Check credentials and that MT5 is installed.")
379 + sys.exit(1)
380 +
381 + execute = bool(getattr(args, "execute", False))
382 + try:
383 + strategy = _build_strategy(args.strategy, args)
384 +
385 + print(f"Connected to MT5 account #{broker.get_account_info().login} ({server})")
386 + print(f"Trading {args.symbol} with {args.strategy} "
387 + f"(risk={args.risk*100:.1f}%, every {args.interval}s)")
388 + print(f"Mode: {'LIVE ORDERS' if execute else 'SIGNALS ONLY (dry run)'}")
389 + print("Press Ctrl+C to stop\n")
390 +
391 + import datetime
392 + import time
393 +
394 + while True:
395 + try:
396 + df = broker.get_rates(args.symbol, mt5.TIMEFRAME_H1, 100)
397 + df = add_returns(df)
398 + df = strategy.generate_signals(df)
399 +
400 + latest = df.iloc[-1]
401 + prev = df.iloc[-2] if len(df) > 1 else latest
402 + price = float(latest["Close"])
403 +
404 + if latest["Signal"] == 1 and prev["Signal"] != 1:
405 + print(f"[{datetime.datetime.now()}] BUY signal {args.symbol} @ {price:.5f}")
406 + _handle_signal(broker, args.symbol, True, price, args.risk, execute)
407 + elif latest["Signal"] == -1 and prev["Signal"] != -1:
408 + print(f"[{datetime.datetime.now()}] SELL signal {args.symbol} @ {price:.5f}")
409 + _handle_signal(broker, args.symbol, False, price, args.risk, execute)
410 +
411 + positions = broker.get_positions(args.symbol)
412 + for pos in positions:
413 + if pos.type == 0 and latest["Signal"] == -1:
414 + print(f"[{datetime.datetime.now()}] Opposite signal: "
415 + f"close LONG #{pos.ticket}")
416 + if execute:
417 + broker.close_position(pos.ticket)
418 + elif pos.type == 1 and latest["Signal"] == 1:
419 + print(f"[{datetime.datetime.now()}] Opposite signal: "
420 + f"close SHORT #{pos.ticket}")
421 + if execute:
422 + broker.close_position(pos.ticket)
423 +
424 + time.sleep(args.interval)
425 +
426 + except KeyboardInterrupt:
427 + print("\nStopping live trading...")
428 + break
429 + except Exception as exc:
430 + print(f"Error in trading loop: {exc} (retrying)")
431 + import time as _time
432 +
433 + _time.sleep(args.interval)
434 +
435 + finally:
436 + broker.disconnect()
437 + print("Disconnected from MT5")
438 +
439 +
440 +def _handle_signal(
441 + broker: MT5Broker,
442 + symbol: str,
443 + is_buy: bool,
444 + price: float,
445 + risk: float,
446 + execute: bool,
447 +) -> None:
448 + """Size a position from equity risk and optionally submit it."""
449 + account = broker.get_account_info()
450 + risk_amount = account.equity * risk
451 + stop_distance = price * 0.02 # simplified 2% stop
452 + if stop_distance <= 0:
453 + return
454 + lots = max(0.01, round(risk_amount / (stop_distance * 100000), 2))
455 + side = "BUY" if is_buy else "SELL"
456 + stop = price * (0.98 if is_buy else 1.02)
457 + target = price * (1.04 if is_buy else 0.96)
458 + print(f" {side} {lots} lots @ {price:.5f} SL={stop:.5f} TP={target:.5f}")
459 + if not execute:
460 + print(" Dry run: add --execute to place the order.")
461 + return
462 + if is_buy:
463 + broker.buy(symbol, lots, stop, target, "Alice Bot Signal")
464 + else:
465 + broker.sell(symbol, lots, stop, target, "Alice Bot Signal")
466 +
467 +
468 +def _run_webhook(args: argparse.Namespace) -> None:
469 + print(f"\n{'='*60}")
470 + print(" Alice Webhook Server")
471 + print(f" Host: {args.host}")
472 + print(f" Port: {args.port}")
473 + print(f"{'='*60}\n")
474 +
475 + receiver = TradingViewSignalReceiver(secret=args.secret)
476 + app = create_webhook_app(receiver, args.host, args.port)
477 +
478 + if app is None:
479 + print("Error: Flask not installed. Install with: pip install -e '.[web]'")
480 + sys.exit(1)
481 +
482 + try:
483 + import os
484 +
485 + os.environ["FLASK_ENV"] = "development"
486 + app.run(host=args.host, port=args.port, debug=True)
487 + except KeyboardInterrupt:
488 + print("\nShutting down webhook server...")
489 +
490 +
491 if __name__ == "__main__":
492 main()
src/open_alice/signals/__init__.py
src/open_alice/signals/webhook.py new
+178
@@ -0,0 +1,178 @@
1 +"""Webhook receiver for trading signals (e.g., TradingView alerts)."""
2 +
3 +from __future__ import annotations
4 +
5 +from dataclasses import dataclass
6 +from datetime import datetime
7 +from typing import Optional, Dict, Any
8 +from enum import Enum
9 +
10 +import logging
11 +
12 +logger = logging.getLogger(__name__)
13 +
14 +
15 +class SignalType(Enum):
16 + """Types of trading signals."""
17 + BUY = "buy"
18 + SELL = "sell"
19 + CLOSE = "close"
20 +
21 +
22 +@dataclass
23 +class TradingSignal:
24 + """Represents a trading signal received from external source."""
25 + symbol: str
26 + signal_type: SignalType
27 + price: Optional[float] = None
28 + timestamp: Optional[datetime] = None
29 + strength: Optional[float] = None # Signal strength 0-1
30 + stop_loss: Optional[float] = None
31 + take_profit: Optional[float] = None
32 + comment: Optional[str] = None
33 + raw_data: Optional[Dict[str, Any]] = None
34 +
35 +
36 +class SignalReceiver:
37 + """Base class for signal receivers."""
38 +
39 + def parse_signal(self, raw_data: Dict[str, Any]) -> Optional[TradingSignal]:
40 + """Parse raw data into a TradingSignal.
41 +
42 + Args:
43 + raw_data: Raw data received from external source
44 +
45 + Returns:
46 + TradingSignal or None if parsing failed
47 + """
48 + raise NotImplementedError
49 +
50 +
51 +class TradingViewSignalReceiver(SignalReceiver):
52 + """Receiver for TradingView webhook alerts."""
53 +
54 + def __init__(self, secret: Optional[str] = None):
55 + """Initialize TradingView signal receiver.
56 +
57 + Args:
58 + secret: Optional secret for validating requests
59 + """
60 + self.secret = secret
61 +
62 + def parse_signal(self, raw_data: Dict[str, Any]) -> Optional[TradingSignal]:
63 + """Parse TradingView webhook alert into TradingSignal.
64 +
65 + Expected TradingView alert format:
66 + {
67 + "symbol": "AAPL",
68 + "action": "buy",
69 + "price": 150.00,
70 + "time": "2023-01-01T10:30:00Z",
71 + "strength": 0.8,
72 + "stop_loss": 145.00,
73 + "take_profit": 160.00,
74 + "comment": "My strategy signal"
75 + }
76 +
77 + Args:
78 + raw_data: Raw webhook data from TradingView
79 +
80 + Returns:
81 + TradingSignal or None if parsing failed
82 + """
83 + try:
84 + # Validate required fields
85 + if "symbol" not in raw_data or "action" not in raw_data:
86 + logger.warning("Missing required fields in TradingView signal")
87 + return None
88 +
89 + symbol = raw_data["symbol"].upper()
90 + action = raw_data["action"].lower()
91 +
92 + # Map action to signal type
93 + if action in ["buy", "long"]:
94 + signal_type = SignalType.BUY
95 + elif action in ["sell", "short"]:
96 + signal_type = SignalType.SELL
97 + elif action in ["close", "exit"]:
98 + signal_type = SignalType.CLOSE
99 + else:
100 + logger.warning(f"Unknown action in TradingView signal: {action}")
101 + return None
102 +
103 + # Parse optional fields
104 + price = float(raw_data["price"]) if "price" in raw_data and raw_data["price"] is not None else None
105 + strength = float(raw_data["strength"]) if "strength" in raw_data and raw_data["strength"] is not None else None
106 + stop_loss = float(raw_data["stop_loss"]) if "stop_loss" in raw_data and raw_data["stop_loss"] is not None else None
107 + take_profit = float(raw_data["take_profit"]) if "take_profit" in raw_data and raw_data["take_profit"] is not None else None
108 + comment = str(raw_data["comment"]) if "comment" in raw_data and raw_data["comment"] is not None else None
109 +
110 + # Parse timestamp
111 + timestamp = None
112 + if "time" in raw_data and raw_data["time"] is not None:
113 + try:
114 + timestamp = datetime.fromisoformat(raw_data["time"].replace("Z", "+00:00"))
115 + except ValueError:
116 + logger.warning(f"Could not parse timestamp: {raw_data['time']}")
117 + timestamp = datetime.now()
118 + else:
119 + timestamp = datetime.now()
120 +
121 + return TradingSignal(
122 + symbol=symbol,
123 + signal_type=signal_type,
124 + price=price,
125 + timestamp=timestamp,
126 + strength=strength,
127 + stop_loss=stop_loss,
128 + take_profit=take_profit,
129 + comment=comment,
130 + raw_data=raw_data
131 + )
132 +
133 + except Exception as e:
134 + logger.error(f"Error parsing TradingView signal: {e}")
135 + return None
136 +
137 +
138 +# Simple HTTP server for receiving webhooks (optional)
139 +def create_webhook_app(receiver: SignalReceiver, host: str = "0.0.0.0", port: int = 5000):
140 + """Create a simple Flask app for receiving webhook signals.
141 +
142 + Args:
143 + receiver: SignalReceiver instance to use for parsing
144 + host: Host to bind to
145 + port: Port to bind to
146 +
147 + Returns:
148 + Flask app instance
149 + """
150 + try:
151 + from flask import Flask, request, jsonify
152 +
153 + app = Flask(__name__)
154 +
155 + @app.route('/webhook', methods=['POST'])
156 + def webhook():
157 + if not request.is_json:
158 + return jsonify({"error": "Expected JSON"}), 400
159 +
160 + data = request.get_json()
161 + signal = receiver.parse_signal(data)
162 +
163 + if signal is None:
164 + return jsonify({"error": "Failed to parse signal"}), 400
165 +
166 + # In a real implementation, this would queue the signal for processing
167 + logger.info(f"Received signal: {signal}")
168 + return jsonify({"status": "received", "signal": signal.__dict__}), 200
169 +
170 + @app.route('/health', methods=['GET'])
171 + def health():
172 + return jsonify({"status": "healthy"}), 200
173 +
174 + return app
175 +
176 + except ImportError:
177 + logger.warning("Flask not installed. Webhook server not available.")
178 + return None
\ No newline at end of file
tests/test_broker_headway.py new
+34
@@ -0,0 +1,34 @@
1 +"""Tests for Headway presets and credential storage."""
2 +
3 +from open_alice.broker.config import (
4 + clear_credentials,
5 + load_credentials,
6 + save_credentials,
7 +)
8 +from open_alice.broker.headway import list_headway_servers, resolve_headway_server
9 +
10 +
11 +def test_list_headway_servers() -> None:
12 + servers = list_headway_servers()
13 + assert "Headway-Demo" in servers["demo"]
14 + assert "Headway-Real" in servers["real"]
15 +
16 +
17 +def test_resolve_headway_server_defaults() -> None:
18 + assert resolve_headway_server(None, demo=True) == "Headway-Demo"
19 + assert resolve_headway_server(None, demo=False) == "Headway-Real"
20 + assert resolve_headway_server("demo") == "Headway-Demo"
21 + assert resolve_headway_server("real") == "Headway-Real"
22 + assert resolve_headway_server("Headway-Demo") == "Headway-Demo"
23 +
24 +
25 +def test_save_and_load_credentials(tmp_path, monkeypatch) -> None:
26 + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
27 + save_credentials(12345678, "secret-pass", "Headway-Demo")
28 + loaded = load_credentials()
29 + assert loaded is not None
30 + assert loaded["login"] == "12345678"
31 + assert loaded["password"] == "secret-pass"
32 + assert loaded["server"] == "Headway-Demo"
33 + assert clear_credentials() is True
34 + assert load_credentials() is None