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

fix/nan-prices-cli-demo-mode
py 73 lines 2.45 KB
Raw
1 """Local storage for MT5 / Headway credentials (file-based, chmod 600)."""
2
3 from __future__ import annotations
4
5 import contextlib
6 import os
7 from pathlib import Path
8
9
10 def get_config_dir() -> Path:
11 """Return the per-user config directory for open-alice."""
12 base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
13 return Path(base) / "open-alice"
14
15
16 def get_credentials_path() -> Path:
17 """Return the path of the saved MT5 credentials file."""
18 return get_config_dir() / "mt5.env"
19
20
21 def save_credentials(login: int, password: str, server: str) -> Path:
22 """Save MT5 credentials to a user-only readable file.
23
24 Args:
25 login: MT5 account number.
26 password: MT5 password (trade password, not investor-only if trading).
27 server: MT5 server name (e.g. Headway-Demo).
28
29 Returns:
30 Path of the written file.
31 """
32 path = get_credentials_path()
33 path.parent.mkdir(parents=True, exist_ok=True)
34 # Minimal .env format without extra dependencies.
35 content = f'MT5_LOGIN={login}\nMT5_PASSWORD={password}\nMT5_SERVER={server}\n'
36 path.write_text(content, encoding="utf-8")
37 with contextlib.suppress(OSError):
38 os.chmod(path, 0o600)
39 return path
40
41
42 def load_credentials() -> dict[str, str] | None:
43 """Load saved MT5 credentials, checking file then environment.
44
45 Returns:
46 Dict with login/password/server, or None when nothing is stored.
47 """
48 path = get_credentials_path()
49 data: dict[str, str] = {}
50 if path.is_file():
51 for line in path.read_text(encoding="utf-8").splitlines():
52 line = line.strip()
53 if not line or line.startswith("#") or "=" not in line:
54 continue
55 key, _, value = line.partition("=")
56 data[key.strip()] = value.strip().strip('"').strip("'")
57
58 # Environment variables act as fallback / override when file is absent.
59 login = data.get("MT5_LOGIN") or os.environ.get("MT5_LOGIN", "")
60 password = data.get("MT5_PASSWORD") or os.environ.get("MT5_PASSWORD", "")
61 server = data.get("MT5_SERVER") or os.environ.get("MT5_SERVER", "")
62 if not login or not password or not server:
63 return None
64 return {"login": login, "password": password, "server": server}
65
66
67 def clear_credentials() -> bool:
68 """Delete the saved credentials file. Returns True if something was removed."""
69 path = get_credentials_path()
70 if path.is_file():
71 path.unlink()
72 return True
73 return False